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/file_system_util.h"
9 #include "base/basictypes.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/file_util.h"
13 #include "base/files/file_path.h"
14 #include "base/i18n/icu_string_conversions.h"
15 #include "base/json/json_file_value_serializer.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/message_loop/message_loop_proxy.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/strings/string_number_conversions.h"
21 #include "base/strings/string_util.h"
22 #include "base/strings/stringprintf.h"
23 #include "base/threading/sequenced_worker_pool.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chromeos/drive/drive.pb.h"
26 #include "chrome/browser/chromeos/drive/drive_integration_service.h"
27 #include "chrome/browser/chromeos/drive/file_system_interface.h"
28 #include "chrome/browser/chromeos/drive/job_list.h"
29 #include "chrome/browser/chromeos/drive/write_on_cache_file.h"
30 #include "chrome/browser/chromeos/profiles/profile_helper.h"
31 #include "chrome/browser/chromeos/profiles/profile_util.h"
32 #include "chrome/browser/profiles/profile.h"
33 #include "chrome/browser/profiles/profile_manager.h"
34 #include "chrome/common/chrome_constants.h"
35 #include "chrome/common/chrome_paths_internal.h"
36 #include "chrome/common/pref_names.h"
37 #include "chrome/common/url_constants.h"
38 #include "chromeos/chromeos_constants.h"
39 #include "content/public/browser/browser_thread.h"
40 #include "google_apis/drive/gdata_wapi_parser.h"
41 #include "net/base/escape.h"
42 #include "webkit/browser/fileapi/file_system_url.h"
44 using content::BrowserThread;
51 const base::FilePath::CharType kSpecialMountPointRoot[] =
52 FILE_PATH_LITERAL("/special");
54 const char kDriveMountPointNameBase[] = "drive";
56 const base::FilePath::CharType kDriveMyDriveRootPath[] =
57 FILE_PATH_LITERAL("drive/root");
59 const base::FilePath::CharType kFileCacheVersionDir[] =
60 FILE_PATH_LITERAL("v1");
62 const char kSlash[] = "/";
63 const char kDot = '.';
64 const char kEscapedChars[] = "_";
66 std::string ReadStringFromGDocFile(const base::FilePath& file_path,
67 const std::string& key) {
68 const int64 kMaxGDocSize = 4096;
70 if (!base::GetFileSize(file_path, &file_size) ||
71 file_size > kMaxGDocSize) {
72 LOG(WARNING) << "File too large to be a GDoc file " << file_path.value();
76 JSONFileValueSerializer reader(file_path);
77 std::string error_message;
78 scoped_ptr<base::Value> root_value(reader.Deserialize(NULL, &error_message));
80 LOG(WARNING) << "Failed to parse " << file_path.value() << " as JSON."
81 << " error = " << error_message;
85 base::DictionaryValue* dictionary_value = NULL;
87 if (!root_value->GetAsDictionary(&dictionary_value) ||
88 !dictionary_value->GetString(key, &result)) {
89 LOG(WARNING) << "No value for the given key is stored in "
90 << file_path.value() << ". key = " << key;
97 // Returns DriveIntegrationService instance, if Drive is enabled.
99 DriveIntegrationService* GetIntegrationServiceByProfile(Profile* profile) {
100 DriveIntegrationService* service =
101 DriveIntegrationServiceFactory::FindForProfile(profile);
102 if (!service || !service->IsMounted())
107 void CheckDirectoryExistsAfterGetResourceEntry(
108 const FileOperationCallback& callback,
110 scoped_ptr<ResourceEntry> entry) {
111 if (error == FILE_ERROR_OK && !entry->file_info().is_directory())
112 error = FILE_ERROR_NOT_A_DIRECTORY;
118 const base::FilePath& GetDriveGrandRootPath() {
119 CR_DEFINE_STATIC_LOCAL(base::FilePath, grand_root_path,
120 (kDriveGrandRootDirName));
121 return grand_root_path;
124 const base::FilePath& GetDriveMyDriveRootPath() {
125 CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_root_path,
126 (kDriveMyDriveRootPath));
127 return drive_root_path;
130 base::FilePath GetDriveMountPointPathForUserIdHash(
131 const std::string user_id_hash) {
132 return base::FilePath(kSpecialMountPointRoot).AppendASCII(
133 net::EscapePath(kDriveMountPointNameBase +
134 (user_id_hash.empty() ? "" : "-" + user_id_hash)));
137 base::FilePath GetDriveMountPointPath(Profile* profile) {
138 std::string id = chromeos::ProfileHelper::GetUserIdHashFromProfile(profile);
139 if (id.empty() || id == chrome::kLegacyProfileDir) {
140 // ProfileHelper::GetUserIdHashFromProfile works only when multi-profile is
141 // enabled. In that case, we fall back to use UserManager (it basically just
142 // returns currently active users's hash in such a case.) I still try
143 // ProfileHelper first because it works better in tests.
144 chromeos::User* const user =
145 chromeos::UserManager::IsInitialized() ?
146 chromeos::UserManager::Get()->GetUserByProfile(
147 profile->GetOriginalProfile()) : NULL;
149 id = user->username_hash();
151 return GetDriveMountPointPathForUserIdHash(id);
154 FileSystemInterface* GetFileSystemByProfile(Profile* profile) {
155 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
157 DriveIntegrationService* integration_service =
158 GetIntegrationServiceByProfile(profile);
159 return integration_service ? integration_service->file_system() : NULL;
162 FileSystemInterface* GetFileSystemByProfileId(void* profile_id) {
163 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
165 // |profile_id| needs to be checked with ProfileManager::IsValidProfile
167 Profile* profile = reinterpret_cast<Profile*>(profile_id);
168 if (!g_browser_process->profile_manager()->IsValidProfile(profile))
170 return GetFileSystemByProfile(profile);
173 DriveAppRegistry* GetDriveAppRegistryByProfile(Profile* profile) {
174 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
176 DriveIntegrationService* integration_service =
177 GetIntegrationServiceByProfile(profile);
178 return integration_service ?
179 integration_service->drive_app_registry() :
183 DriveServiceInterface* GetDriveServiceByProfile(Profile* profile) {
184 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
186 DriveIntegrationService* integration_service =
187 GetIntegrationServiceByProfile(profile);
188 return integration_service ? integration_service->drive_service() : NULL;
191 GURL FilePathToDriveURL(const base::FilePath& path) {
192 std::string url(base::StringPrintf("%s:%s",
193 chrome::kDriveScheme,
194 path.AsUTF8Unsafe().c_str()));
198 base::FilePath DriveURLToFilePath(const GURL& url) {
199 if (!url.is_valid() || url.scheme() != chrome::kDriveScheme)
200 return base::FilePath();
201 std::string path_string = net::UnescapeURLComponent(
202 url.GetContent(), net::UnescapeRule::NORMAL);
203 return base::FilePath::FromUTF8Unsafe(path_string);
206 void MaybeSetDriveURL(Profile* profile, const base::FilePath& path, GURL* url) {
207 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
209 if (!IsUnderDriveMountPoint(path))
212 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
216 *url = FilePathToDriveURL(util::ExtractDrivePath(path));
219 bool IsUnderDriveMountPoint(const base::FilePath& path) {
220 return !ExtractDrivePath(path).empty();
223 base::FilePath ExtractDrivePath(const base::FilePath& path) {
224 std::vector<base::FilePath::StringType> components;
225 path.GetComponents(&components);
226 if (components.size() < 3)
227 return base::FilePath();
228 if (components[0] != FILE_PATH_LITERAL("/"))
229 return base::FilePath();
230 if (components[1] != FILE_PATH_LITERAL("special"))
231 return base::FilePath();
232 if (!StartsWithASCII(components[2], "drive", true))
233 return base::FilePath();
235 base::FilePath drive_path = GetDriveGrandRootPath();
236 for (size_t i = 3; i < components.size(); ++i)
237 drive_path = drive_path.Append(components[i]);
241 Profile* ExtractProfileFromPath(const base::FilePath& path) {
242 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
244 const std::vector<Profile*>& profiles =
245 g_browser_process->profile_manager()->GetLoadedProfiles();
246 for (size_t i = 0; i < profiles.size(); ++i) {
247 Profile* original_profile = profiles[i]->GetOriginalProfile();
248 if (original_profile == profiles[i] &&
249 !chromeos::ProfileHelper::IsSigninProfile(original_profile)) {
250 const base::FilePath base = GetDriveMountPointPath(original_profile);
251 if (base == path || base.IsParent(path))
252 return original_profile;
258 base::FilePath ExtractDrivePathFromFileSystemUrl(
259 const fileapi::FileSystemURL& url) {
260 if (!url.is_valid() || url.type() != fileapi::kFileSystemTypeDrive)
261 return base::FilePath();
262 return ExtractDrivePath(url.path());
265 base::FilePath GetCacheRootPath(Profile* profile) {
266 base::FilePath cache_base_path;
267 chrome::GetUserCacheDirectory(profile->GetPath(), &cache_base_path);
268 base::FilePath cache_root_path =
269 cache_base_path.Append(chromeos::kDriveCacheDirname);
270 return cache_root_path.Append(kFileCacheVersionDir);
273 std::string EscapeCacheFileName(const std::string& filename) {
274 // This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
276 for (size_t i = 0; i < filename.size(); ++i) {
277 char c = filename[i];
278 if (c == '%' || c == '.' || c == '/') {
279 base::StringAppendF(&escaped, "%%%02X", c);
281 escaped.push_back(c);
287 std::string UnescapeCacheFileName(const std::string& filename) {
288 std::string unescaped;
289 for (size_t i = 0; i < filename.size(); ++i) {
290 char c = filename[i];
291 if (c == '%' && i + 2 < filename.length()) {
292 c = (HexDigitToInt(filename[i + 1]) << 4) +
293 HexDigitToInt(filename[i + 2]);
296 unescaped.push_back(c);
301 std::string NormalizeFileName(const std::string& input) {
302 DCHECK(base::IsStringUTF8(input));
305 if (!base::ConvertToUtf8AndNormalize(input, base::kCodepageUTF8, &output))
307 base::ReplaceChars(output, kSlash, std::string(kEscapedChars), &output);
308 if (!output.empty() && output.find_first_not_of(kDot, 0) == std::string::npos)
309 output = kEscapedChars;
313 void PrepareWritableFileAndRun(Profile* profile,
314 const base::FilePath& path,
315 const PrepareWritableFileCallback& callback) {
316 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
317 DCHECK(!callback.is_null());
319 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
320 if (!file_system || !IsUnderDriveMountPoint(path)) {
321 content::BrowserThread::GetBlockingPool()->PostTask(
322 FROM_HERE, base::Bind(callback, FILE_ERROR_FAILED, base::FilePath()));
326 WriteOnCacheFile(file_system,
327 ExtractDrivePath(path),
328 std::string(), // mime_type
332 void EnsureDirectoryExists(Profile* profile,
333 const base::FilePath& directory,
334 const FileOperationCallback& callback) {
335 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
336 DCHECK(!callback.is_null());
337 if (IsUnderDriveMountPoint(directory)) {
338 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
340 file_system->CreateDirectory(
341 ExtractDrivePath(directory),
342 true /* is_exclusive */,
343 true /* is_recursive */,
346 base::MessageLoopProxy::current()->PostTask(
347 FROM_HERE, base::Bind(callback, FILE_ERROR_OK));
351 void CheckDirectoryExists(Profile* profile,
352 const base::FilePath& directory,
353 const FileOperationCallback& callback) {
354 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
355 DCHECK(!callback.is_null());
357 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
360 file_system->GetResourceEntry(
361 ExtractDrivePath(directory),
362 base::Bind(&CheckDirectoryExistsAfterGetResourceEntry, callback));
365 void EmptyFileOperationCallback(FileError error) {
368 bool CreateGDocFile(const base::FilePath& file_path,
370 const std::string& resource_id) {
371 std::string content = base::StringPrintf(
372 "{\"url\": \"%s\", \"resource_id\": \"%s\"}",
373 url.spec().c_str(), resource_id.c_str());
374 return base::WriteFile(file_path, content.data(), content.size()) ==
375 static_cast<int>(content.size());
378 bool HasGDocFileExtension(const base::FilePath& file_path) {
379 return google_apis::ResourceEntry::ClassifyEntryKindByFileExtension(
381 google_apis::ResourceEntry::KIND_OF_HOSTED_DOCUMENT;
384 GURL ReadUrlFromGDocFile(const base::FilePath& file_path) {
385 return GURL(ReadStringFromGDocFile(file_path, "url"));
388 std::string ReadResourceIdFromGDocFile(const base::FilePath& file_path) {
389 return ReadStringFromGDocFile(file_path, "resource_id");
392 bool IsDriveEnabledForProfile(Profile* profile) {
393 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
395 if (!chromeos::IsProfileAssociatedWithGaiaAccount(profile))
398 // Disable Drive if preference is set. This can happen with commandline flag
399 // --disable-drive or enterprise policy, or with user settings.
400 if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive))
406 ConnectionStatusType GetDriveConnectionStatus(Profile* profile) {
407 drive::DriveServiceInterface* const drive_service =
408 drive::util::GetDriveServiceByProfile(profile);
411 return DRIVE_DISCONNECTED_NOSERVICE;
412 if (net::NetworkChangeNotifier::IsOffline())
413 return DRIVE_DISCONNECTED_NONETWORK;
414 if (!drive_service->CanSendRequest())
415 return DRIVE_DISCONNECTED_NOTREADY;
417 const bool is_connection_cellular =
418 net::NetworkChangeNotifier::IsConnectionCellular(
419 net::NetworkChangeNotifier::GetConnectionType());
420 const bool disable_sync_over_celluar =
421 profile->GetPrefs()->GetBoolean(prefs::kDisableDriveOverCellular);
423 if (is_connection_cellular && disable_sync_over_celluar)
424 return DRIVE_CONNECTED_METERED;
425 return DRIVE_CONNECTED;