summaryrefslogtreecommitdiffstats
path: root/chrome/browser/chromeos/drive/download_handler.cc
blob: 551e4af6e5b7d1f9ecf5fad517d2161e3ca0f077 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/drive/download_handler.h"

#include <stddef.h>

#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/strings/string_util.h"
#include "base/supports_user_data.h"
#include "base/thread_task_runner_handle.h"
#include "base/threading/sequenced_worker_pool.h"
#include "chrome/browser/chromeos/drive/drive_integration_service.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/drive/write_on_cache_file.h"
#include "chrome/browser/download/download_history.h"
#include "chrome/browser/download/download_service.h"
#include "chrome/browser/download/download_service_factory.h"
#include "components/drive/drive.pb.h"
#include "components/drive/file_system_interface.h"
#include "content/public/browser/browser_thread.h"

using content::BrowserThread;
using content::DownloadManager;
using content::DownloadItem;

namespace drive {
namespace {

// Key for base::SupportsUserData::Data.
const char kDrivePathKey[] = "DrivePath";

// Mime types that we better not trust. If the file was downloade with these
// mime types, while uploading to Drive we ignore it at guess by our own logic.
const char* kGenericMimeTypes[] = {"text/html", "text/plain",
                                   "application/octet-stream"};

// Longer is better. But at the same time, this value should be short enough as
// drive::internal::kMinFreeSpaceInBytes is not used up by file download in this
// interval.
const base::TimeDelta kFreeDiskSpaceDelay = base::TimeDelta::FromSeconds(3);

// User Data stored in DownloadItem for drive path.
class DriveUserData : public base::SupportsUserData::Data {
 public:
  explicit DriveUserData(const base::FilePath& path) : file_path_(path),
                                                       is_complete_(false) {}
  ~DriveUserData() override {}

  const base::FilePath& file_path() const { return file_path_; }
  const base::FilePath& cache_file_path() const { return cache_file_path_; }
  void set_cache_file_path(const base::FilePath& path) {
    cache_file_path_ = path;
  }
  bool is_complete() const { return is_complete_; }
  void set_complete() { is_complete_ = true; }

 private:
  const base::FilePath file_path_;
  base::FilePath cache_file_path_;
  bool is_complete_;
};

// Extracts DriveUserData* from |download|.
const DriveUserData* GetDriveUserData(const DownloadItem* download) {
  return static_cast<const DriveUserData*>(
      download->GetUserData(&kDrivePathKey));
}

DriveUserData* GetDriveUserData(DownloadItem* download) {
  return static_cast<DriveUserData*>(download->GetUserData(&kDrivePathKey));
}

// Creates a temporary file |drive_tmp_download_path| in
// |drive_tmp_download_dir|. Must be called on a thread that allows file
// operations.
base::FilePath GetDriveTempDownloadPath(
    const base::FilePath& drive_tmp_download_dir) {
  bool created = base::CreateDirectory(drive_tmp_download_dir);
  DCHECK(created) << "Can not create temp download directory at "
                  << drive_tmp_download_dir.value();
  base::FilePath drive_tmp_download_path;
  created = base::CreateTemporaryFileInDir(drive_tmp_download_dir,
                                           &drive_tmp_download_path);
  DCHECK(created) << "Temporary download file creation failed";
  return drive_tmp_download_path;
}

// Moves downloaded file to Drive.
void MoveDownloadedFile(const base::FilePath& downloaded_file,
                        base::FilePath* cache_file_path,
                        FileError error,
                        const base::FilePath& dest_path) {
  if (error != FILE_ERROR_OK ||
      !base::Move(downloaded_file, dest_path))
    return;
  *cache_file_path = dest_path;
}

// Used to implement CheckForFileExistence().
void ContinueCheckingForFileExistence(
    const content::CheckForFileExistenceCallback& callback,
    FileError error,
    scoped_ptr<ResourceEntry> entry) {
  callback.Run(error == FILE_ERROR_OK);
}

// Returns true if |download| is a Drive download created from data persisted
// on the download history DB.
bool IsPersistedDriveDownload(const base::FilePath& drive_tmp_download_path,
                              DownloadItem* download) {
  if (!drive_tmp_download_path.IsParent(download->GetTargetFilePath()))
    return false;

  DownloadService* download_service =
      DownloadServiceFactory::GetForBrowserContext(
          download->GetBrowserContext());
  DownloadHistory* download_history = download_service->GetDownloadHistory();

  return download_history && download_history->WasRestoredFromHistory(download);
}

// Returns an empty string |mime_type| was too generic that can be a result of
// 'default' fallback choice on the HTTP server. In such a case, we ignore the
// type so that our logic can guess by its own while uploading to Drive.
std::string FilterOutGenericMimeType(const std::string& mime_type) {
  for (size_t i = 0; i < arraysize(kGenericMimeTypes); ++i) {
    if (base::LowerCaseEqualsASCII(mime_type, kGenericMimeTypes[i]))
      return std::string();
  }
  return mime_type;
}

void IgnoreFreeDiskSpaceIfNeededForCallback(bool /*result*/) {}

}  // namespace

DownloadHandler::DownloadHandler(FileSystemInterface* file_system)
    : file_system_(file_system),
      has_pending_free_disk_space_(false),
      free_disk_space_delay_(kFreeDiskSpaceDelay),
      weak_ptr_factory_(this) {}

DownloadHandler::~DownloadHandler() {
}

// static
DownloadHandler* DownloadHandler::GetForProfile(Profile* profile) {
  DriveIntegrationService* service =
      DriveIntegrationServiceFactory::FindForProfile(profile);
  if (!service || !service->IsMounted())
    return NULL;
  return service->download_handler();
}

void DownloadHandler::Initialize(
    DownloadManager* download_manager,
    const base::FilePath& drive_tmp_download_path) {
  DCHECK(!drive_tmp_download_path.empty());

  drive_tmp_download_path_ = drive_tmp_download_path;

  if (download_manager) {
    notifier_.reset(new AllDownloadItemNotifier(download_manager, this));
    // Remove any persisted Drive DownloadItem. crbug.com/171384
    content::DownloadManager::DownloadVector downloads;
    download_manager->GetAllDownloads(&downloads);
    for (size_t i = 0; i < downloads.size(); ++i) {
      if (IsPersistedDriveDownload(drive_tmp_download_path_, downloads[i]))
        downloads[i]->Remove();
    }
  }
}

void DownloadHandler::ObserveIncognitoDownloadManager(
    DownloadManager* download_manager) {
  notifier_incognito_.reset(new AllDownloadItemNotifier(download_manager,
                                                        this));
}

void DownloadHandler::SubstituteDriveDownloadPath(
    const base::FilePath& drive_path,
    content::DownloadItem* download,
    const SubstituteDriveDownloadPathCallback& callback) {
  DVLOG(1) << "SubstituteDriveDownloadPath " << drive_path.value();

  SetDownloadParams(drive_path, download);

  if (util::IsUnderDriveMountPoint(drive_path)) {
    // Prepare the destination directory.
    const bool is_exclusive = false, is_recursive = true;
    file_system_->CreateDirectory(
        util::ExtractDrivePath(drive_path.DirName()),
        is_exclusive, is_recursive,
        base::Bind(&DownloadHandler::OnCreateDirectory,
                   weak_ptr_factory_.GetWeakPtr(),
                   callback));
  } else {
    callback.Run(drive_path);
  }
}

void DownloadHandler::SetDownloadParams(const base::FilePath& drive_path,
                                        DownloadItem* download) {
  if (!download || (download->GetState() != DownloadItem::IN_PROGRESS))
    return;

  if (util::IsUnderDriveMountPoint(drive_path)) {
    download->SetUserData(&kDrivePathKey, new DriveUserData(drive_path));
    download->SetDisplayName(drive_path.BaseName());
  } else if (IsDriveDownload(download)) {
    // This may have been previously set if the default download folder is
    // /drive, and the user has now changed the download target to a local
    // folder.
    download->SetUserData(&kDrivePathKey, NULL);
    download->SetDisplayName(base::FilePath());
  }
}

base::FilePath DownloadHandler::GetTargetPath(
    const DownloadItem* download) {
  const DriveUserData* data = GetDriveUserData(download);
  // If data is NULL, we've somehow lost the drive path selected by the file
  // picker.
  DCHECK(data);
  return data ? data->file_path() : base::FilePath();
}

base::FilePath DownloadHandler::GetCacheFilePath(const DownloadItem* download) {
  const DriveUserData* data = GetDriveUserData(download);
  return data ? data->cache_file_path() : base::FilePath();
}

bool DownloadHandler::IsDriveDownload(const DownloadItem* download) {
  // We use the existence of the DriveUserData object in download as a
  // signal that this is a download to Drive.
  return GetDriveUserData(download) != NULL;
}

void DownloadHandler::CheckForFileExistence(
    const DownloadItem* download,
    const content::CheckForFileExistenceCallback& callback) {
  file_system_->GetResourceEntry(
      util::ExtractDrivePath(GetTargetPath(download)),
      base::Bind(&ContinueCheckingForFileExistence,
                 callback));
}

void DownloadHandler::SetFreeDiskSpaceDelayForTesting(
    const base::TimeDelta& delay) {
  free_disk_space_delay_ = delay;
}

int64_t DownloadHandler::CalculateRequestSpace(
    const DownloadManager::DownloadVector& downloads) {
  int64_t request_space = 0;

  for (const auto* download : downloads) {
    if (download->IsDone())
      continue;

    const int64_t total_bytes = download->GetTotalBytes();
    // Skip unknown size download. Since drive cache tries to keep
    // drive::internal::kMinFreeSpaceInBytes, we can continue download with
    // using the space temporally.
    if (total_bytes == 0)
      continue;

    request_space += total_bytes - download->GetReceivedBytes();
  }

  return request_space;
}

void DownloadHandler::FreeDiskSpaceIfNeeded() {
  if (has_pending_free_disk_space_)
    return;

  base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
      FROM_HERE, base::Bind(&DownloadHandler::FreeDiskSpaceIfNeededImmediately,
                            weak_ptr_factory_.GetWeakPtr()),
      free_disk_space_delay_);

  has_pending_free_disk_space_ = true;
}

void DownloadHandler::FreeDiskSpaceIfNeededImmediately() {
  DownloadManager::DownloadVector downloads;

  // Get all downloads of current profile and its off-the-record profile.
  // TODO(yawano): support multi profiles.
  if (notifier_ && notifier_->GetManager()) {
    notifier_->GetManager()->GetAllDownloads(&downloads);
  }
  if (notifier_incognito_ && notifier_incognito_->GetManager()) {
    notifier_incognito_->GetManager()->GetAllDownloads(&downloads);
  }

  // Free disk space even if request size is 0 byte in order to make drive cache
  // keep drive::internal::kMinFreeSpaceInBytes.
  file_system_->FreeDiskSpaceIfNeededFor(
      CalculateRequestSpace(downloads),
      base::Bind(&IgnoreFreeDiskSpaceIfNeededForCallback));

  has_pending_free_disk_space_ = false;
}

void DownloadHandler::OnDownloadCreated(DownloadManager* manager,
                                        DownloadItem* download) {
  FreeDiskSpaceIfNeededImmediately();

  // Remove any persisted Drive DownloadItem. crbug.com/171384
  if (IsPersistedDriveDownload(drive_tmp_download_path_, download)) {
    // Remove download later, since doing it here results in a crash.
    BrowserThread::PostTask(BrowserThread::UI,
                            FROM_HERE,
                            base::Bind(&DownloadHandler::RemoveDownload,
                                       weak_ptr_factory_.GetWeakPtr(),
                                       static_cast<void*>(manager),
                                       download->GetId()));
  }
}

void DownloadHandler::RemoveDownload(void* manager_id, int id) {
  DownloadManager* manager = GetDownloadManager(manager_id);
  if (!manager)
    return;
  DownloadItem* download = manager->GetDownload(id);
  if (!download)
    return;
  download->Remove();
}

void DownloadHandler::OnDownloadUpdated(
    DownloadManager* manager, DownloadItem* download) {
  DCHECK_CURRENTLY_ON(BrowserThread::UI);

  FreeDiskSpaceIfNeeded();

  // Only accept downloads that have the Drive meta data associated with them.
  DriveUserData* data = GetDriveUserData(download);
  if (!drive_tmp_download_path_.IsParent(download->GetTargetFilePath()) ||
      !data ||
      data->is_complete())
    return;

  switch (download->GetState()) {
    case DownloadItem::IN_PROGRESS:
      break;

    case DownloadItem::COMPLETE:
      UploadDownloadItem(manager, download);
      data->set_complete();
      break;

    case DownloadItem::CANCELLED:
      download->SetUserData(&kDrivePathKey, NULL);
      break;

    case DownloadItem::INTERRUPTED:
      // Interrupted downloads can be resumed. Keep the Drive user data around
      // so that it can be used when the download resumes. The download is truly
      // done when it's complete, is cancelled or is removed.
      break;

    default:
      NOTREACHED();
  }
}

void DownloadHandler::OnCreateDirectory(
    const SubstituteDriveDownloadPathCallback& callback,
    FileError error) {
  DVLOG(1) << "OnCreateDirectory " << FileErrorToString(error);
  if (error == FILE_ERROR_OK) {
    base::PostTaskAndReplyWithResult(
        BrowserThread::GetBlockingPool(),
        FROM_HERE,
        base::Bind(&GetDriveTempDownloadPath, drive_tmp_download_path_),
        callback);
  } else {
    LOG(WARNING) << "Failed to create directory, error = "
                 << FileErrorToString(error);
    callback.Run(base::FilePath());
  }
}

void DownloadHandler::UploadDownloadItem(DownloadManager* manager,
                                         DownloadItem* download) {
  DCHECK_EQ(DownloadItem::COMPLETE, download->GetState());
  base::FilePath* cache_file_path = new base::FilePath;
  WriteOnCacheFileAndReply(
      file_system_, util::ExtractDrivePath(GetTargetPath(download)),
      FilterOutGenericMimeType(download->GetMimeType()),
      base::Bind(&MoveDownloadedFile, download->GetTargetFilePath(),
                 cache_file_path),
      base::Bind(&DownloadHandler::SetCacheFilePath,
                 weak_ptr_factory_.GetWeakPtr(), static_cast<void*>(manager),
                 download->GetId(), base::Owned(cache_file_path)));
}

void DownloadHandler::SetCacheFilePath(void* manager_id,
                                       int id,
                                       const base::FilePath* cache_file_path,
                                       FileError error) {
  if (error != FILE_ERROR_OK)
    return;
  DownloadManager* manager = GetDownloadManager(manager_id);
  if (!manager)
    return;
  DownloadItem* download = manager->GetDownload(id);
  if (!download)
    return;
  DriveUserData* data = GetDriveUserData(download);
  if (!data)
    return;
  data->set_cache_file_path(*cache_file_path);
}

DownloadManager* DownloadHandler::GetDownloadManager(void* manager_id) {
  if (manager_id == notifier_->GetManager())
    return notifier_->GetManager();
  if (notifier_incognito_ && manager_id == notifier_incognito_->GetManager())
    return notifier_incognito_->GetManager();
  return NULL;
}

}  // namespace drive