Commit d5cf4dc4 authored by Austin Tankiang's avatar Austin Tankiang Committed by Commit Bot

Remove unused DownloadHandler

Bug: 1003238
Change-Id: Icc3227b44ba58fcab17bd8eab959f0346a8a906d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1886133Reviewed-by: default avatarSam McNally <sammc@chromium.org>
Commit-Queue: Austin Tankiang <austinct@chromium.org>
Cr-Commit-Position: refs/heads/master@{#710238}
parent af56e43c
...@@ -883,8 +883,6 @@ source_set("chromeos") { ...@@ -883,8 +883,6 @@ source_set("chromeos") {
"display/quirks_manager_delegate_impl.h", "display/quirks_manager_delegate_impl.h",
"drive/debug_info_collector.cc", "drive/debug_info_collector.cc",
"drive/debug_info_collector.h", "drive/debug_info_collector.h",
"drive/download_handler.cc",
"drive/download_handler.h",
"drive/drive_integration_service.cc", "drive/drive_integration_service.cc",
"drive/drive_integration_service.h", "drive/drive_integration_service.h",
"drive/file_system_util.cc", "drive/file_system_util.cc",
...@@ -2581,7 +2579,6 @@ source_set("unit_tests") { ...@@ -2581,7 +2579,6 @@ source_set("unit_tests") {
"cryptauth/client_app_metadata_provider_service_unittest.cc", "cryptauth/client_app_metadata_provider_service_unittest.cc",
"customization/customization_document_unittest.cc", "customization/customization_document_unittest.cc",
"dbus/proxy_resolution_service_provider_unittest.cc", "dbus/proxy_resolution_service_provider_unittest.cc",
"drive/download_handler_unittest.cc",
"drive/drive_integration_service_unittest.cc", "drive/drive_integration_service_unittest.cc",
"drive/file_system_util_unittest.cc", "drive/file_system_util_unittest.cc",
"drive/write_on_cache_file_unittest.cc", "drive/write_on_cache_file_unittest.cc",
......
// 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 <memory>
#include <utility>
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/supports_user_data.h"
#include "base/task/post_task.h"
#include "base/threading/thread_task_runner_handle.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 "components/drive/chromeos/file_system_interface.h"
#include "components/drive/drive.pb.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/download_item_utils.h"
using content::BrowserThread;
using download::DownloadItem;
using content::DownloadManager;
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* const 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 int kFreeDiskSpaceDelayInSeconds = 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 = default;
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(
content::CheckForFileExistenceCallback callback,
FileError error,
std::unique_ptr<ResourceEntry> entry) {
std::move(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;
return download->GetDownloadCreationType() ==
download::DownloadItem::TYPE_HISTORY_IMPORT;
}
// 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 < base::size(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_(
base::TimeDelta::FromSeconds(kFreeDiskSpaceDelayInSeconds)) {}
DownloadHandler::~DownloadHandler() = default;
// static
DownloadHandler* DownloadHandler::GetForProfile(Profile* profile) {
DriveIntegrationService* service =
DriveIntegrationServiceFactory::FindForProfile(profile);
if (!service || !service->IsMounted())
return nullptr;
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_ = std::make_unique<download::AllDownloadItemNotifier>(
download_manager, this);
// Remove any persisted Drive DownloadItem. crbug.com/171384
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_ = std::make_unique<download::AllDownloadItemNotifier>(
download_manager, this);
}
void DownloadHandler::SubstituteDriveDownloadPath(
const base::FilePath& drive_path,
download::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,
std::make_unique<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, nullptr);
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) != nullptr;
}
void DownloadHandler::CheckForFileExistence(
const DownloadItem* download,
content::CheckForFileExistenceCallback callback) {
file_system_->GetResourceEntry(
util::ExtractDrivePath(GetTargetPath(download)),
base::BindOnce(&ContinueCheckingForFileExistence, std::move(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::BindOnce(&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.
base::PostTask(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&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, nullptr);
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(
FROM_HERE, {base::ThreadPool(), base::MayBlock()},
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 nullptr;
}
} // namespace drive
// 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.
#ifndef CHROME_BROWSER_CHROMEOS_DRIVE_DOWNLOAD_HANDLER_H_
#define CHROME_BROWSER_CHROMEOS_DRIVE_DOWNLOAD_HANDLER_H_
#include <stdint.h>
#include "base/callback_forward.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "components/download/content/public/all_download_item_notifier.h"
#include "components/drive/file_errors.h"
#include "content/public/browser/download_manager_delegate.h"
class Profile;
namespace content {
class DownloadManager;
}
namespace download {
class DownloadItem;
}
namespace drive {
class FileSystemInterface;
// Observes downloads to temporary local drive folder. Schedules these
// downloads for upload to drive service.
class DownloadHandler : public download::AllDownloadItemNotifier::Observer {
public:
explicit DownloadHandler(FileSystemInterface* file_system);
~DownloadHandler() override;
// Utility method to get DownloadHandler with profile.
static DownloadHandler* GetForProfile(Profile* profile);
// Become an observer of DownloadManager.
void Initialize(content::DownloadManager* download_manager,
const base::FilePath& drive_tmp_download_path);
// In addition to the DownloadManager passed to Initialize(), observe another
// download manager. This should be called only for the DownloadManager of the
// incognito version of the profile where |file_system_| resides.
void ObserveIncognitoDownloadManager(
content::DownloadManager* download_manager);
// Callback used to return results from SubstituteDriveDownloadPath.
// TODO(hashimoto): Report error with a FileError. crbug.com/171345
typedef base::Callback<void(const base::FilePath&)>
SubstituteDriveDownloadPathCallback;
void SubstituteDriveDownloadPath(
const base::FilePath& drive_path,
download::DownloadItem* download,
const SubstituteDriveDownloadPathCallback& callback);
// Sets drive path, for example, '/special/drive/MyFolder/MyFile',
// to external data in |download|. Also sets display name and
// makes |download| a temporary.
void SetDownloadParams(const base::FilePath& drive_path,
download::DownloadItem* download);
// Gets the target drive path from external data in |download|.
base::FilePath GetTargetPath(const download::DownloadItem* download);
// Gets the downloaded drive cache file path from external data in |download|.
base::FilePath GetCacheFilePath(const download::DownloadItem* download);
// Checks if there is a Drive upload associated with |download|
bool IsDriveDownload(const download::DownloadItem* download);
// Checks a file corresponding to the download item exists in Drive.
void CheckForFileExistence(const download::DownloadItem* download,
content::CheckForFileExistenceCallback callback);
// Calculates request space for |downloads|.
int64_t CalculateRequestSpace(
const content::DownloadManager::DownloadVector& downloads);
// Checks available storage space and free disk space if necessary. Actual
// execution is delayed and rate limited.
void FreeDiskSpaceIfNeeded();
// Checks available storage space and free disk space if necessary. This is
// executed immediately.
void FreeDiskSpaceIfNeededImmediately();
// Sets free disk space delay for testing.
void SetFreeDiskSpaceDelayForTesting(const base::TimeDelta& delay);
private:
// AllDownloadItemNotifier::Observer overrides:
void OnDownloadCreated(content::DownloadManager* manager,
download::DownloadItem* download) override;
void OnDownloadUpdated(content::DownloadManager* manager,
download::DownloadItem* download) override;
// Removes the download.
void RemoveDownload(void* manager_id, int id);
// Callback for FileSystem::CreateDirectory().
// Used to implement SubstituteDriveDownloadPath().
void OnCreateDirectory(const SubstituteDriveDownloadPathCallback& callback,
FileError error);
// Starts the upload of a downloaded/downloading file.
void UploadDownloadItem(content::DownloadManager* manager,
download::DownloadItem* download);
// Sets |cache_file_path| as user data of the download item specified by |id|.
void SetCacheFilePath(void* manager_id,
int id,
const base::FilePath* cache_file_path,
FileError error);
// Gets a download manager, given a |manager_id| casted from the pointer to
// the manager. This is used to validate the manager that may be deleted while
// asynchronous task posting. Returns NULL if the manager is already gone.
content::DownloadManager* GetDownloadManager(void* manager_id);
FileSystemInterface* file_system_; // Owned by DriveIntegrationService.
// Observe the DownloadManager for new downloads.
std::unique_ptr<download::AllDownloadItemNotifier> notifier_;
std::unique_ptr<download::AllDownloadItemNotifier> notifier_incognito_;
// Temporary download location directory.
base::FilePath drive_tmp_download_path_;
// True if there is pending FreeDiskSpaceIfNeeded call.
bool has_pending_free_disk_space_;
base::TimeDelta free_disk_space_delay_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DownloadHandler> weak_ptr_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DownloadHandler);
};
} // namespace drive
#endif // CHROME_BROWSER_CHROMEOS_DRIVE_DOWNLOAD_HANDLER_H_
// Copyright (c) 2013 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 <stdint.h>
#include <memory>
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/test/base/testing_profile.h"
#include "components/download/public/common/mock_download_item.h"
#include "components/drive/chromeos/dummy_file_system.h"
#include "components/drive/file_system_core_util.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_download_manager.h"
#include "content/public/test/test_utils.h"
#include "google_apis/drive/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace {
// Test file system for verifying the behavior of DownloadHandler, by simulating
// various responses from FileSystem.
class DownloadHandlerTestFileSystem : public DummyFileSystem {
public:
DownloadHandlerTestFileSystem() : error_(FILE_ERROR_FAILED) {}
void set_error(FileError error) { error_ = error; }
// FileSystemInterface overrides.
void GetResourceEntry(const base::FilePath& file_path,
GetResourceEntryCallback callback) override {
std::move(callback).Run(
error_, std::unique_ptr<ResourceEntry>(
error_ == FILE_ERROR_OK ? new ResourceEntry : nullptr));
}
void CreateDirectory(const base::FilePath& directory_path,
bool is_exclusive,
bool is_recursive,
const FileOperationCallback& callback) override {
callback.Run(error_);
}
void FreeDiskSpaceIfNeededFor(
int64_t num_bytes,
const FreeDiskSpaceCallback& callback) override {
free_disk_space_if_needed_for_num_bytes_.push_back(num_bytes);
callback.Run(true);
}
std::vector<int64_t> free_disk_space_if_needed_for_num_bytes_;
private:
FileError error_;
};
class DownloadHandlerTestDownloadManager : public content::MockDownloadManager {
public:
void GetAllDownloads(
content::DownloadManager::DownloadVector* downloads) override {
for (auto* test_download : test_downloads_) {
downloads->push_back(test_download);
}
}
content::DownloadManager::DownloadVector test_downloads_;
};
class DownloadHandlerTestDownloadItem : public download::MockDownloadItem {
public:
bool IsDone() const override { return is_done_; }
int64_t GetTotalBytes() const override { return total_bytes_; }
int64_t GetReceivedBytes() const override { return received_bytes_; }
bool is_done_ = false;
int64_t total_bytes_ = 0;
int64_t received_bytes_ = 0;
};
} // namespace
class DownloadHandlerTest : public testing::Test {
public:
DownloadHandlerTest()
: download_manager_(new DownloadHandlerTestDownloadManager) {}
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
// Set expectations for download item.
EXPECT_CALL(download_item_, GetState())
.WillRepeatedly(testing::Return(download::DownloadItem::IN_PROGRESS));
download_handler_ = std::make_unique<DownloadHandler>(&test_file_system_);
download_handler_->Initialize(download_manager_.get(), temp_dir_.GetPath());
download_handler_->SetFreeDiskSpaceDelayForTesting(
base::TimeDelta::FromMilliseconds(0));
}
protected:
base::ScopedTempDir temp_dir_;
content::BrowserTaskEnvironment task_environment_;
TestingProfile profile_;
std::unique_ptr<DownloadHandlerTestDownloadManager> download_manager_;
std::unique_ptr<DownloadHandlerTestDownloadManager>
incognito_download_manager_;
DownloadHandlerTestFileSystem test_file_system_;
std::unique_ptr<DownloadHandler> download_handler_;
download::MockDownloadItem download_item_;
};
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathNonDrivePath) {
const base::FilePath non_drive_path(FILE_PATH_LITERAL("/foo/bar"));
ASSERT_FALSE(util::IsUnderDriveMountPoint(non_drive_path));
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
non_drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_EQ(non_drive_path, substituted_path);
EXPECT_FALSE(download_handler_->IsDriveDownload(&download_item_));
}
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPath) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Test the case that the download target directory already exists.
test_file_system_.set_error(FILE_ERROR_OK);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(temp_dir_.GetPath().IsParent(substituted_path));
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
}
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathGetEntryFailure) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Test the case that access to the download target directory failed for some
// reason.
test_file_system_.set_error(FILE_ERROR_FAILED);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(substituted_path.empty());
}
// content::SavePackage calls SubstituteDriveDownloadPath before creating
// DownloadItem.
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathForSavePackage) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
test_file_system_.set_error(FILE_ERROR_OK);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
nullptr, // DownloadItem is not available at this moment.
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result of SubstituteDriveDownloadPath().
EXPECT_TRUE(temp_dir_.GetPath().IsParent(substituted_path));
// |download_item_| is not a drive download yet.
EXPECT_FALSE(download_handler_->IsDriveDownload(&download_item_));
// Call SetDownloadParams().
download_handler_->SetDownloadParams(drive_path, &download_item_);
// |download_item_| is a drive download now.
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
}
TEST_F(DownloadHandlerTest, CheckForFileExistence) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Make |download_item_| a drive download.
download_handler_->SetDownloadParams(drive_path, &download_item_);
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
// Test for the case when the path exists.
test_file_system_.set_error(FILE_ERROR_OK);
// Call CheckForFileExistence.
bool file_exists = false;
download_handler_->CheckForFileExistence(
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&file_exists));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(file_exists);
// Test for the case when the path does not exist.
test_file_system_.set_error(FILE_ERROR_NOT_FOUND);
// Call CheckForFileExistence again.
download_handler_->CheckForFileExistence(
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&file_exists));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_FALSE(file_exists);
}
TEST_F(DownloadHandlerTest, FreeDiskSpace) {
// Add a download item to download manager.
DownloadHandlerTestDownloadItem download_item_a;
download_item_a.is_done_ = false;
download_item_a.total_bytes_ = 100;
download_item_a.received_bytes_ = 10;
download_manager_->test_downloads_.push_back(&download_item_a);
// Free disk space for download_item_a.
download_handler_->FreeDiskSpaceIfNeededImmediately();
ASSERT_EQ(1u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[0]);
// Confirm that FreeDiskSpaceIfNeeded is rate limited by calling it twice.
download_handler_->FreeDiskSpaceIfNeeded();
download_handler_->FreeDiskSpaceIfNeeded();
ASSERT_EQ(1u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
download_item_a.received_bytes_ = 20;
base::RunLoop().RunUntilIdle();
ASSERT_EQ(2u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[1]);
// Observe incognito download manager and add another download item.
// FreeDiskSpace should be called with considering both download items.
incognito_download_manager_ =
std::make_unique<DownloadHandlerTestDownloadManager>();
download_handler_->ObserveIncognitoDownloadManager(
incognito_download_manager_.get());
DownloadHandlerTestDownloadItem download_item_b;
download_item_b.is_done_ = false;
download_item_b.total_bytes_ = 200;
download_item_b.received_bytes_ = 0;
incognito_download_manager_->test_downloads_.push_back(&download_item_b);
download_item_a.received_bytes_ = 30;
download_handler_->FreeDiskSpaceIfNeededImmediately();
ASSERT_EQ(3u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[2]);
// Free disk space after making both items completed. In this case
// FreeDiskSpace should be called with 0 byte to keep
// drive::internal::kMinFreeSpaceInBytes.
download_item_a.is_done_ = true;
download_item_b.is_done_ = true;
download_handler_->FreeDiskSpaceIfNeeded();
base::RunLoop().RunUntilIdle();
ASSERT_EQ(4u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(0, test_file_system_.free_disk_space_if_needed_for_num_bytes_[3]);
}
TEST_F(DownloadHandlerTest, CalculateRequestSpace) {
DownloadHandlerTestDownloadItem download_item_a;
download_item_a.is_done_ = false;
download_item_a.total_bytes_ = 100;
download_item_a.received_bytes_ = 0;
DownloadHandlerTestDownloadItem download_item_b;
download_item_b.is_done_ = false;
download_item_b.total_bytes_ = 200;
download_item_b.received_bytes_ = 10;
content::DownloadManager::DownloadVector downloads;
downloads.push_back(&download_item_a);
downloads.push_back(&download_item_b);
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
download_item_a.received_bytes_ = 10;
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
download_item_b.is_done_ = true;
// Since download_item_b is completed, it shouldn't be counted.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
// Add unknown size download item.
DownloadHandlerTestDownloadItem download_item_c;
download_item_c.is_done_ = false;
download_item_c.total_bytes_ = 0;
downloads.push_back(&download_item_c);
// Unknown size download should be counted as 0 byte.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
// Add another unknown size download item.
DownloadHandlerTestDownloadItem download_item_d;
download_item_d.is_done_ = false;
download_item_d.total_bytes_ = 0;
downloads.push_back(&download_item_d);
// Unknown size downloads should be counted as 0 byte.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
}
} // namespace drive
...@@ -25,7 +25,6 @@ ...@@ -25,7 +25,6 @@
#include "base/unguessable_token.h" #include "base/unguessable_token.h"
#include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/drive/debug_info_collector.h" #include "chrome/browser/chromeos/drive/debug_info_collector.h"
#include "chrome/browser/chromeos/drive/download_handler.h"
#include "chrome/browser/chromeos/drive/file_system_util.h" #include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/file_manager/path_util.h" #include "chrome/browser/chromeos/file_manager/path_util.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h" #include "chrome/browser/chromeos/profiles/profile_helper.h"
...@@ -733,7 +732,6 @@ DriveIntegrationService::DriveIntegrationService( ...@@ -733,7 +732,6 @@ DriveIntegrationService::DriveIntegrationService(
logger_.get(), cache_.get(), scheduler_.get(), logger_.get(), cache_.get(), scheduler_.get(),
resource_metadata_.get(), blocking_task_runner_.get(), resource_metadata_.get(), blocking_task_runner_.get(),
cache_root_directory_.Append(kTemporaryFileDirectory))); cache_root_directory_.Append(kTemporaryFileDirectory)));
download_handler_ = std::make_unique<DownloadHandler>(file_system());
debug_info_collector_ = std::make_unique<DebugInfoCollector>( debug_info_collector_ = std::make_unique<DebugInfoCollector>(
resource_metadata_.get(), file_system(), blocking_task_runner_.get()); resource_metadata_.get(), file_system(), blocking_task_runner_.get());
...@@ -762,7 +760,6 @@ void DriveIntegrationService::Shutdown() { ...@@ -762,7 +760,6 @@ void DriveIntegrationService::Shutdown() {
RemoveDriveMountPoint(); RemoveDriveMountPoint();
notification_manager_.reset(); notification_manager_.reset();
debug_info_collector_.reset(); debug_info_collector_.reset();
download_handler_.reset();
file_system_.reset(); file_system_.reset();
scheduler_.reset(); scheduler_.reset();
drive_service_.reset(); drive_service_.reset();
...@@ -1167,25 +1164,6 @@ void DriveIntegrationService::InitializeAfterMetadataInitialized( ...@@ -1167,25 +1164,6 @@ void DriveIntegrationService::InitializeAfterMetadataInitialized(
// migrated and any dirty files are recovered whenever switching to DriveFS. // migrated and any dirty files are recovered whenever switching to DriveFS.
profile_->GetPrefs()->ClearPref(prefs::kDriveFsPinnedMigrated); profile_->GetPrefs()->ClearPref(prefs::kDriveFsPinnedMigrated);
// Initialize Download Handler for hooking downloads to the Drive folder.
content::DownloadManager* download_manager =
g_browser_process->download_status_updater()
? BrowserContext::GetDownloadManager(profile_)
: nullptr;
download_handler_->Initialize(
download_manager,
cache_root_directory_.Append(kTemporaryFileDirectory));
// Install the handler also to incognito profile.
if (g_browser_process->download_status_updater()) {
if (profile_->HasOffTheRecordProfile()) {
download_handler_->ObserveIncognitoDownloadManager(
BrowserContext::GetDownloadManager(
profile_->GetOffTheRecordProfile()));
}
observed_profiles_.Add(profile_);
}
// Register for Google Drive invalidation notifications. // Register for Google Drive invalidation notifications.
DriveNotificationManager* drive_notification_manager = DriveNotificationManager* drive_notification_manager =
DriveNotificationManagerFactory::GetForBrowserContext(profile_); DriveNotificationManagerFactory::GetForBrowserContext(profile_);
...@@ -1226,13 +1204,6 @@ bool DriveIntegrationService::DownloadDirectoryPreferenceIsInDrive() { ...@@ -1226,13 +1204,6 @@ bool DriveIntegrationService::DownloadDirectoryPreferenceIsInDrive() {
GetMountPointPath().IsParent(downloads_path); GetMountPointPath().IsParent(downloads_path);
} }
void DriveIntegrationService::OnOffTheRecordProfileCreated(
Profile* off_the_record) {
DCHECK_EQ(profile_, off_the_record->GetOriginalProfile());
download_handler_->ObserveIncognitoDownloadManager(
BrowserContext::GetDownloadManager(off_the_record));
}
void DriveIntegrationService::MigratePinnedFiles() { void DriveIntegrationService::MigratePinnedFiles() {
if (!metadata_storage_) if (!metadata_storage_)
return; return;
......
...@@ -16,7 +16,6 @@ ...@@ -16,7 +16,6 @@
#include "base/memory/weak_ptr.h" #include "base/memory/weak_ptr.h"
#include "base/observer_list.h" #include "base/observer_list.h"
#include "base/scoped_observer.h" #include "base/scoped_observer.h"
#include "chrome/browser/profiles/profile_observer.h"
#include "chromeos/components/drivefs/drivefs_host.h" #include "chromeos/components/drivefs/drivefs_host.h"
#include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/power/power_manager_client.h"
#include "components/drive/drive_notification_observer.h" #include "components/drive/drive_notification_observer.h"
...@@ -44,7 +43,6 @@ class DriveFs; ...@@ -44,7 +43,6 @@ class DriveFs;
namespace drive { namespace drive {
class DebugInfoCollector; class DebugInfoCollector;
class DownloadHandler;
class DriveServiceInterface; class DriveServiceInterface;
class EventLogger; class EventLogger;
class FileSystemInterface; class FileSystemInterface;
...@@ -103,7 +101,6 @@ class DriveIntegrationServiceObserver { ...@@ -103,7 +101,6 @@ class DriveIntegrationServiceObserver {
// created per-profile. // created per-profile.
class DriveIntegrationService : public KeyedService, class DriveIntegrationService : public KeyedService,
public DriveNotificationObserver, public DriveNotificationObserver,
public ProfileObserver,
public drivefs::DriveFsHost::MountObserver, public drivefs::DriveFsHost::MountObserver,
public chromeos::PowerManagerClient::Observer { public chromeos::PowerManagerClient::Observer {
public: public:
...@@ -175,7 +172,6 @@ class DriveIntegrationService : public KeyedService, ...@@ -175,7 +172,6 @@ class DriveIntegrationService : public KeyedService,
return debug_info_collector_.get(); return debug_info_collector_.get();
} }
FileSystemInterface* file_system() { return file_system_.get(); } FileSystemInterface* file_system() { return file_system_.get(); }
DownloadHandler* download_handler() { return download_handler_.get(); }
JobListInterface* job_list() { return scheduler_.get(); } JobListInterface* job_list() { return scheduler_.get(); }
// Clears all the local cache file, the local resource metadata, and // Clears all the local cache file, the local resource metadata, and
...@@ -248,9 +244,6 @@ class DriveIntegrationService : public KeyedService, ...@@ -248,9 +244,6 @@ class DriveIntegrationService : public KeyedService,
bool DownloadDirectoryPreferenceIsInDrive(); bool DownloadDirectoryPreferenceIsInDrive();
// ProfileObserver:
void OnOffTheRecordProfileCreated(Profile* off_the_record) override;
// Migrate pinned files from the old Drive integration to DriveFS. // Migrate pinned files from the old Drive integration to DriveFS.
void MigratePinnedFiles(); void MigratePinnedFiles();
...@@ -286,7 +279,6 @@ class DriveIntegrationService : public KeyedService, ...@@ -286,7 +279,6 @@ class DriveIntegrationService : public KeyedService,
std::unique_ptr<internal::ResourceMetadata, util::DestroyHelper> std::unique_ptr<internal::ResourceMetadata, util::DestroyHelper>
resource_metadata_; resource_metadata_;
std::unique_ptr<FileSystemInterface> file_system_; std::unique_ptr<FileSystemInterface> file_system_;
std::unique_ptr<DownloadHandler> download_handler_;
std::unique_ptr<DebugInfoCollector> debug_info_collector_; std::unique_ptr<DebugInfoCollector> debug_info_collector_;
base::ObserverList<DriveIntegrationServiceObserver>::Unchecked observers_; base::ObserverList<DriveIntegrationServiceObserver>::Unchecked observers_;
...@@ -303,7 +295,6 @@ class DriveIntegrationService : public KeyedService, ...@@ -303,7 +295,6 @@ class DriveIntegrationService : public KeyedService,
ScopedObserver<chromeos::PowerManagerClient, ScopedObserver<chromeos::PowerManagerClient,
chromeos::PowerManagerClient::Observer> chromeos::PowerManagerClient::Observer>
power_manager_observer_{this}; power_manager_observer_{this};
ScopedObserver<Profile, ProfileObserver> observed_profiles_{this};
// Note: This should remain the last member so it'll be destroyed and // Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed. // invalidate its weak pointers before any other members are destroyed.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment