1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chromeos/drive/drive_integration_service.h"
8 #include "base/files/file_util.h"
9 #include "base/prefs/pref_change_registrar.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/threading/sequenced_worker_pool.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/chromeos/drive/debug_info_collector.h"
16 #include "chrome/browser/chromeos/drive/download_handler.h"
17 #include "chrome/browser/chromeos/drive/file_system.h"
18 #include "chrome/browser/chromeos/drive/file_system_util.h"
19 #include "chrome/browser/chromeos/file_manager/path_util.h"
20 #include "chrome/browser/chromeos/profiles/profile_util.h"
21 #include "chrome/browser/download/download_prefs.h"
22 #include "chrome/browser/download/download_service.h"
23 #include "chrome/browser/download/download_service_factory.h"
24 #include "chrome/browser/drive/drive_notification_manager_factory.h"
25 #include "chrome/browser/profiles/incognito_helpers.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
28 #include "chrome/browser/signin/signin_manager_factory.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/grit/generated_resources.h"
31 #include "components/drive/drive_api_util.h"
32 #include "components/drive/drive_app_registry.h"
33 #include "components/drive/drive_notification_manager.h"
34 #include "components/drive/drive_pref_names.h"
35 #include "components/drive/event_logger.h"
36 #include "components/drive/file_cache.h"
37 #include "components/drive/job_scheduler.h"
38 #include "components/drive/resource_metadata.h"
39 #include "components/drive/resource_metadata_storage.h"
40 #include "components/drive/service/drive_api_service.h"
41 #include "components/keyed_service/content/browser_context_dependency_manager.h"
42 #include "components/signin/core/browser/profile_oauth2_token_service.h"
43 #include "components/signin/core/browser/signin_manager.h"
44 #include "components/version_info/version_info.h"
45 #include "content/public/browser/browser_context.h"
46 #include "content/public/browser/browser_thread.h"
47 #include "content/public/browser/notification_service.h"
48 #include "content/public/common/user_agent.h"
49 #include "google_apis/drive/auth_service.h"
50 #include "storage/browser/fileapi/external_mount_points.h"
51 #include "ui/base/l10n/l10n_util.h"
53 using content::BrowserContext
;
54 using content::BrowserThread
;
59 // Name of the directory used to store metadata.
60 const base::FilePath::CharType kMetadataDirectory
[] = FILE_PATH_LITERAL("meta");
62 // Name of the directory used to store cached files.
63 const base::FilePath::CharType kCacheFileDirectory
[] =
64 FILE_PATH_LITERAL("files");
66 // Name of the directory used to store temporary files.
67 const base::FilePath::CharType kTemporaryFileDirectory
[] =
68 FILE_PATH_LITERAL("tmp");
70 // Returns a user agent string used for communicating with the Drive backend,
71 // both WAPI and Drive API. The user agent looks like:
73 // chromedrive-<VERSION> chrome-cc/none (<OS_CPU_INFO>)
74 // chromedrive-24.0.1274.0 chrome-cc/none (CrOS x86_64 0.4.0)
76 // TODO(satorux): Move this function to somewhere else: crbug.com/151605
77 std::string
GetDriveUserAgent() {
78 const char kDriveClientName
[] = "chromedrive";
80 const std::string version
= version_info::GetVersionNumber();
82 // This part is <client_name>/<version>.
83 const char kLibraryInfo
[] = "chrome-cc/none";
85 const std::string os_cpu_info
= content::BuildOSCpuInfo();
87 // Add "gzip" to receive compressed data from the server.
88 // (see https://developers.google.com/drive/performance)
89 return base::StringPrintf("%s-%s %s (%s) (gzip)",
96 // Initializes FileCache and ResourceMetadata.
97 // Must be run on the same task runner used by |cache| and |resource_metadata|.
98 FileError
InitializeMetadata(
99 const base::FilePath
& cache_root_directory
,
100 internal::ResourceMetadataStorage
* metadata_storage
,
101 internal::FileCache
* cache
,
102 internal::ResourceMetadata
* resource_metadata
,
103 const base::FilePath
& downloads_directory
) {
104 // Files in temporary directory need not persist across sessions. Clean up
105 // the directory content while initialization.
106 base::DeleteFile(cache_root_directory
.Append(kTemporaryFileDirectory
),
108 if (!base::CreateDirectory(cache_root_directory
.Append(
109 kMetadataDirectory
)) ||
110 !base::CreateDirectory(cache_root_directory
.Append(
111 kCacheFileDirectory
)) ||
112 !base::CreateDirectory(cache_root_directory
.Append(
113 kTemporaryFileDirectory
))) {
114 LOG(WARNING
) << "Failed to create directories.";
115 return FILE_ERROR_FAILED
;
118 // Change permissions of cache file directory to u+rwx,og+x (711) in order to
119 // allow archive files in that directory to be mounted by cros-disks.
120 base::SetPosixFilePermissions(
121 cache_root_directory
.Append(kCacheFileDirectory
),
122 base::FILE_PERMISSION_USER_MASK
|
123 base::FILE_PERMISSION_EXECUTE_BY_GROUP
|
124 base::FILE_PERMISSION_EXECUTE_BY_OTHERS
);
126 internal::ResourceMetadataStorage::UpgradeOldDB(
127 metadata_storage
->directory_path());
129 if (!metadata_storage
->Initialize()) {
130 LOG(WARNING
) << "Failed to initialize the metadata storage.";
131 return FILE_ERROR_FAILED
;
134 if (!cache
->Initialize()) {
135 LOG(WARNING
) << "Failed to initialize the cache.";
136 return FILE_ERROR_FAILED
;
139 if (metadata_storage
->cache_file_scan_is_needed()) {
140 // Generate unique directory name.
141 const std::string
& dest_directory_name
= l10n_util::GetStringUTF8(
142 IDS_FILE_BROWSER_RECOVERED_FILES_FROM_GOOGLE_DRIVE_DIRECTORY_NAME
);
143 base::FilePath dest_directory
= downloads_directory
.Append(
144 base::FilePath::FromUTF8Unsafe(dest_directory_name
));
145 for (int uniquifier
= 1; base::PathExists(dest_directory
); ++uniquifier
) {
146 dest_directory
= downloads_directory
.Append(
147 base::FilePath::FromUTF8Unsafe(dest_directory_name
))
148 .InsertBeforeExtensionASCII(base::StringPrintf(" (%d)", uniquifier
));
151 internal::ResourceMetadataStorage::RecoveredCacheInfoMap
152 recovered_cache_info
;
153 metadata_storage
->RecoverCacheInfoFromTrashedResourceMap(
154 &recovered_cache_info
);
156 LOG_IF(WARNING
, !recovered_cache_info
.empty())
157 << "DB could not be opened for some reasons. "
158 << "Recovering cache files to " << dest_directory
.value();
159 if (!cache
->RecoverFilesFromCacheDirectory(dest_directory
,
160 recovered_cache_info
)) {
161 LOG(WARNING
) << "Failed to recover cache files.";
162 return FILE_ERROR_FAILED
;
166 FileError error
= resource_metadata
->Initialize();
167 LOG_IF(WARNING
, error
!= FILE_ERROR_OK
)
168 << "Failed to initialize resource metadata. " << FileErrorToString(error
);
174 // Observes drive disable Preference's change.
175 class DriveIntegrationService::PreferenceWatcher
{
177 explicit PreferenceWatcher(PrefService
* pref_service
)
178 : pref_service_(pref_service
),
179 integration_service_(NULL
),
180 weak_ptr_factory_(this) {
181 DCHECK(pref_service
);
182 pref_change_registrar_
.Init(pref_service
);
183 pref_change_registrar_
.Add(
184 prefs::kDisableDrive
,
185 base::Bind(&PreferenceWatcher::OnPreferenceChanged
,
186 weak_ptr_factory_
.GetWeakPtr()));
189 void set_integration_service(DriveIntegrationService
* integration_service
) {
190 integration_service_
= integration_service
;
194 void OnPreferenceChanged() {
195 DCHECK(integration_service_
);
196 integration_service_
->SetEnabled(
197 !pref_service_
->GetBoolean(prefs::kDisableDrive
));
200 PrefService
* pref_service_
;
201 PrefChangeRegistrar pref_change_registrar_
;
202 DriveIntegrationService
* integration_service_
;
204 base::WeakPtrFactory
<PreferenceWatcher
> weak_ptr_factory_
;
205 DISALLOW_COPY_AND_ASSIGN(PreferenceWatcher
);
208 DriveIntegrationService::DriveIntegrationService(
210 PreferenceWatcher
* preference_watcher
,
211 DriveServiceInterface
* test_drive_service
,
212 const std::string
& test_mount_point_name
,
213 const base::FilePath
& test_cache_root
,
214 FileSystemInterface
* test_file_system
)
216 state_(NOT_INITIALIZED
),
218 mount_point_name_(test_mount_point_name
),
219 cache_root_directory_(!test_cache_root
.empty() ?
220 test_cache_root
: util::GetCacheRootPath(profile
)),
221 weak_ptr_factory_(this) {
222 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
223 DCHECK(profile
&& !profile
->IsOffTheRecord());
225 logger_
.reset(new EventLogger
);
226 base::SequencedWorkerPool
* blocking_pool
= BrowserThread::GetBlockingPool();
227 blocking_task_runner_
= blocking_pool
->GetSequencedTaskRunner(
228 blocking_pool
->GetSequenceToken());
230 ProfileOAuth2TokenService
* oauth_service
=
231 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
233 if (test_drive_service
) {
234 drive_service_
.reset(test_drive_service
);
236 drive_service_
.reset(new DriveAPIService(
238 g_browser_process
->system_request_context(),
239 blocking_task_runner_
.get(),
240 GURL(google_apis::DriveApiUrlGenerator::kBaseUrlForProduction
),
241 GURL(google_apis::DriveApiUrlGenerator::kBaseDownloadUrlForProduction
),
242 GetDriveUserAgent()));
244 scheduler_
.reset(new JobScheduler(
245 profile_
->GetPrefs(),
247 drive_service_
.get(),
248 blocking_task_runner_
.get()));
249 metadata_storage_
.reset(new internal::ResourceMetadataStorage(
250 cache_root_directory_
.Append(kMetadataDirectory
),
251 blocking_task_runner_
.get()));
252 cache_
.reset(new internal::FileCache(
253 metadata_storage_
.get(),
254 cache_root_directory_
.Append(kCacheFileDirectory
),
255 blocking_task_runner_
.get(),
256 NULL
/* free_disk_space_getter */));
257 drive_app_registry_
.reset(new DriveAppRegistry(drive_service_
.get()));
259 resource_metadata_
.reset(new internal::ResourceMetadata(
260 metadata_storage_
.get(), cache_
.get(), blocking_task_runner_
));
263 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE);
268 profile_
->GetPrefs(), logger_
.get(), cache_
.get(),
269 scheduler_
.get(), resource_metadata_
.get(),
270 blocking_task_runner_
.get(), file_task_runner_
.get(),
271 cache_root_directory_
.Append(kTemporaryFileDirectory
)));
272 download_handler_
.reset(new DownloadHandler(file_system()));
273 debug_info_collector_
.reset(new DebugInfoCollector(
274 resource_metadata_
.get(), file_system(), blocking_task_runner_
.get()));
276 if (preference_watcher
) {
277 preference_watcher_
.reset(preference_watcher
);
278 preference_watcher
->set_integration_service(this);
281 SetEnabled(drive::util::IsDriveEnabledForProfile(profile
));
284 DriveIntegrationService::~DriveIntegrationService() {
285 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
288 void DriveIntegrationService::Shutdown() {
289 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
291 weak_ptr_factory_
.InvalidateWeakPtrs();
293 DriveNotificationManager
* drive_notification_manager
=
294 DriveNotificationManagerFactory::FindForBrowserContext(profile_
);
295 if (drive_notification_manager
)
296 drive_notification_manager
->RemoveObserver(this);
298 RemoveDriveMountPoint();
299 debug_info_collector_
.reset();
300 download_handler_
.reset();
301 file_system_
.reset();
302 drive_app_registry_
.reset();
304 drive_service_
.reset();
307 void DriveIntegrationService::SetEnabled(bool enabled
) {
308 // If Drive is being disabled, ensure the download destination preference to
309 // be out of Drive. Do this before "Do nothing if not changed." because we
310 // want to run the check for the first SetEnabled() called in the constructor,
311 // which may be a change from false to false.
313 AvoidDriveAsDownloadDirecotryPreference();
315 // Do nothing if not changed.
316 if (enabled_
== enabled
)
322 case NOT_INITIALIZED
:
323 // If the initialization is not yet done, trigger it.
329 // If the state is INITIALIZING or REMOUNTING, at the end of the
330 // process, it tries to mounting (with re-checking enabled state).
331 // Do nothing for now.
335 // The integration service is already initialized. Add the mount point.
336 AddDriveMountPoint();
341 RemoveDriveMountPoint();
346 bool DriveIntegrationService::IsMounted() const {
347 if (mount_point_name_
.empty())
350 // Look up the registered path, and just discard it.
351 // GetRegisteredPath() returns true if the path is available.
352 base::FilePath unused
;
353 storage::ExternalMountPoints
* const mount_points
=
354 storage::ExternalMountPoints::GetSystemInstance();
355 DCHECK(mount_points
);
356 return mount_points
->GetRegisteredPath(mount_point_name_
, &unused
);
359 void DriveIntegrationService::AddObserver(
360 DriveIntegrationServiceObserver
* observer
) {
361 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
362 observers_
.AddObserver(observer
);
365 void DriveIntegrationService::RemoveObserver(
366 DriveIntegrationServiceObserver
* observer
) {
367 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
368 observers_
.RemoveObserver(observer
);
371 void DriveIntegrationService::OnNotificationReceived() {
372 file_system_
->CheckForUpdates();
373 drive_app_registry_
->Update();
376 void DriveIntegrationService::OnPushNotificationEnabled(bool enabled
) {
378 drive_app_registry_
->Update();
380 const char* status
= (enabled
? "enabled" : "disabled");
381 logger_
->Log(logging::LOG_INFO
, "Push notification is %s", status
);
384 void DriveIntegrationService::ClearCacheAndRemountFileSystem(
385 const base::Callback
<void(bool)>& callback
) {
386 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
387 DCHECK(!callback
.is_null());
389 if (state_
!= INITIALIZED
) {
394 RemoveDriveMountPoint();
397 // Reloads the Drive app registry.
398 drive_app_registry_
->Update();
399 // Resetting the file system clears resource metadata and cache.
400 file_system_
->Reset(base::Bind(
401 &DriveIntegrationService::AddBackDriveMountPoint
,
402 weak_ptr_factory_
.GetWeakPtr(),
406 void DriveIntegrationService::AddBackDriveMountPoint(
407 const base::Callback
<void(bool)>& callback
,
409 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
410 DCHECK(!callback
.is_null());
412 state_
= error
== FILE_ERROR_OK
? INITIALIZED
: NOT_INITIALIZED
;
414 if (error
!= FILE_ERROR_OK
|| !enabled_
) {
415 // Failed to reset, or Drive was disabled during the reset.
420 AddDriveMountPoint();
424 void DriveIntegrationService::AddDriveMountPoint() {
425 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
426 DCHECK_EQ(INITIALIZED
, state_
);
429 const base::FilePath
& drive_mount_point
=
430 util::GetDriveMountPointPath(profile_
);
431 if (mount_point_name_
.empty())
432 mount_point_name_
= drive_mount_point
.BaseName().AsUTF8Unsafe();
433 storage::ExternalMountPoints
* const mount_points
=
434 storage::ExternalMountPoints::GetSystemInstance();
435 DCHECK(mount_points
);
438 mount_points
->RegisterFileSystem(mount_point_name_
,
439 storage::kFileSystemTypeDrive
,
440 storage::FileSystemMountOption(),
444 logger_
->Log(logging::LOG_INFO
, "Drive mount point is added");
445 FOR_EACH_OBSERVER(DriveIntegrationServiceObserver
, observers_
,
446 OnFileSystemMounted());
450 void DriveIntegrationService::RemoveDriveMountPoint() {
451 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
453 if (!mount_point_name_
.empty()) {
454 job_list()->CancelAllJobs();
456 FOR_EACH_OBSERVER(DriveIntegrationServiceObserver
, observers_
,
457 OnFileSystemBeingUnmounted());
459 storage::ExternalMountPoints
* const mount_points
=
460 storage::ExternalMountPoints::GetSystemInstance();
461 DCHECK(mount_points
);
463 mount_points
->RevokeFileSystem(mount_point_name_
);
464 logger_
->Log(logging::LOG_INFO
, "Drive mount point is removed");
468 void DriveIntegrationService::Initialize() {
469 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
470 DCHECK_EQ(NOT_INITIALIZED
, state_
);
473 state_
= INITIALIZING
;
475 base::PostTaskAndReplyWithResult(
476 blocking_task_runner_
.get(),
478 base::Bind(&InitializeMetadata
,
479 cache_root_directory_
,
480 metadata_storage_
.get(),
482 resource_metadata_
.get(),
483 file_manager::util::GetDownloadsFolderForProfile(profile_
)),
484 base::Bind(&DriveIntegrationService::InitializeAfterMetadataInitialized
,
485 weak_ptr_factory_
.GetWeakPtr()));
488 void DriveIntegrationService::InitializeAfterMetadataInitialized(
490 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
491 DCHECK_EQ(INITIALIZING
, state_
);
493 SigninManagerBase
* signin_manager
=
494 SigninManagerFactory::GetForProfile(profile_
);
495 drive_service_
->Initialize(signin_manager
->GetAuthenticatedAccountId());
497 if (error
!= FILE_ERROR_OK
) {
498 LOG(WARNING
) << "Failed to initialize: " << FileErrorToString(error
);
500 // Cannot used Drive. Set the download destination preference out of Drive.
501 AvoidDriveAsDownloadDirecotryPreference();
503 // Back to NOT_INITIALIZED state. Then, re-running Initialize() should
504 // work if the error is recoverable manually (such as out of disk space).
505 state_
= NOT_INITIALIZED
;
509 // Initialize Download Handler for hooking downloads to the Drive folder.
510 content::DownloadManager
* download_manager
=
511 g_browser_process
->download_status_updater() ?
512 BrowserContext::GetDownloadManager(profile_
) : NULL
;
513 download_handler_
->Initialize(
515 cache_root_directory_
.Append(kTemporaryFileDirectory
));
517 // Install the handler also to incognito profile.
518 if (g_browser_process
->download_status_updater()) {
519 if (profile_
->HasOffTheRecordProfile()) {
520 download_handler_
->ObserveIncognitoDownloadManager(
521 BrowserContext::GetDownloadManager(
522 profile_
->GetOffTheRecordProfile()));
524 profile_notification_registrar_
.reset(new content::NotificationRegistrar
);
525 profile_notification_registrar_
->Add(
527 chrome::NOTIFICATION_PROFILE_CREATED
,
528 content::NotificationService::AllSources());
531 // Register for Google Drive invalidation notifications.
532 DriveNotificationManager
* drive_notification_manager
=
533 DriveNotificationManagerFactory::GetForBrowserContext(profile_
);
534 if (drive_notification_manager
) {
535 drive_notification_manager
->AddObserver(this);
536 const bool registered
=
537 drive_notification_manager
->push_notification_registered();
538 const char* status
= (registered
? "registered" : "not registered");
539 logger_
->Log(logging::LOG_INFO
, "Push notification is %s", status
);
541 if (drive_notification_manager
->push_notification_enabled())
542 drive_app_registry_
->Update();
545 state_
= INITIALIZED
;
547 // Mount only when the drive is enabled. Initialize is triggered by
548 // SetEnabled(true), but there is a change to disable it again during
549 // the metadata initialization, so we need to look this up again here.
551 AddDriveMountPoint();
554 void DriveIntegrationService::AvoidDriveAsDownloadDirecotryPreference() {
555 PrefService
* pref_service
= profile_
->GetPrefs();
556 if (util::IsUnderDriveMountPoint(
557 pref_service
->GetFilePath(::prefs::kDownloadDefaultDirectory
))) {
558 pref_service
->SetFilePath(
559 ::prefs::kDownloadDefaultDirectory
,
560 file_manager::util::GetDownloadsFolderForProfile(profile_
));
564 void DriveIntegrationService::Observe(
566 const content::NotificationSource
& source
,
567 const content::NotificationDetails
& details
) {
568 if (type
== chrome::NOTIFICATION_PROFILE_CREATED
) {
569 Profile
* created_profile
= content::Source
<Profile
>(source
).ptr();
570 if (created_profile
->IsOffTheRecord() &&
571 created_profile
->IsSameProfile(profile_
)) {
572 download_handler_
->ObserveIncognitoDownloadManager(
573 BrowserContext::GetDownloadManager(created_profile
));
578 //===================== DriveIntegrationServiceFactory =======================
580 DriveIntegrationServiceFactory::FactoryCallback
*
581 DriveIntegrationServiceFactory::factory_for_test_
= NULL
;
583 DriveIntegrationServiceFactory::ScopedFactoryForTest::ScopedFactoryForTest(
584 FactoryCallback
* factory_for_test
) {
585 factory_for_test_
= factory_for_test
;
588 DriveIntegrationServiceFactory::ScopedFactoryForTest::~ScopedFactoryForTest() {
589 factory_for_test_
= NULL
;
593 DriveIntegrationService
* DriveIntegrationServiceFactory::GetForProfile(
595 return static_cast<DriveIntegrationService
*>(
596 GetInstance()->GetServiceForBrowserContext(profile
, true));
600 DriveIntegrationService
* DriveIntegrationServiceFactory::FindForProfile(
602 return static_cast<DriveIntegrationService
*>(
603 GetInstance()->GetServiceForBrowserContext(profile
, false));
607 DriveIntegrationServiceFactory
* DriveIntegrationServiceFactory::GetInstance() {
608 return Singleton
<DriveIntegrationServiceFactory
>::get();
611 DriveIntegrationServiceFactory::DriveIntegrationServiceFactory()
612 : BrowserContextKeyedServiceFactory(
613 "DriveIntegrationService",
614 BrowserContextDependencyManager::GetInstance()) {
615 DependsOn(ProfileOAuth2TokenServiceFactory::GetInstance());
616 DependsOn(DriveNotificationManagerFactory::GetInstance());
617 DependsOn(DownloadServiceFactory::GetInstance());
620 DriveIntegrationServiceFactory::~DriveIntegrationServiceFactory() {
623 content::BrowserContext
* DriveIntegrationServiceFactory::GetBrowserContextToUse(
624 content::BrowserContext
* context
) const {
625 return chrome::GetBrowserContextRedirectedInIncognito(context
);
628 KeyedService
* DriveIntegrationServiceFactory::BuildServiceInstanceFor(
629 content::BrowserContext
* context
) const {
630 Profile
* profile
= Profile::FromBrowserContext(context
);
632 DriveIntegrationService
* service
= NULL
;
633 if (!factory_for_test_
) {
634 DriveIntegrationService::PreferenceWatcher
* preference_watcher
= NULL
;
635 if (chromeos::IsProfileAssociatedWithGaiaAccount(profile
)) {
636 // Drive File System can be enabled.
638 new DriveIntegrationService::PreferenceWatcher(profile
->GetPrefs());
641 service
= new DriveIntegrationService(
642 profile
, preference_watcher
,
643 NULL
, std::string(), base::FilePath(), NULL
);
645 service
= factory_for_test_
->Run(profile
);