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/files/scoped_platform_file_closer.h"
15 #include "base/i18n/icu_string_conversions.h"
16 #include "base/json/json_file_value_serializer.h"
17 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/message_loop/message_loop_proxy.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/threading/sequenced_worker_pool.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chromeos/drive/drive.pb.h"
28 #include "chrome/browser/chromeos/drive/drive_integration_service.h"
29 #include "chrome/browser/chromeos/drive/file_system_interface.h"
30 #include "chrome/browser/chromeos/drive/job_list.h"
31 #include "chrome/browser/chromeos/drive/write_on_cache_file.h"
32 #include "chrome/browser/chromeos/profiles/profile_util.h"
33 #include "chrome/browser/google_apis/gdata_wapi_parser.h"
34 #include "chrome/browser/profiles/profile.h"
35 #include "chrome/browser/profiles/profile_manager.h"
36 #include "chrome/common/chrome_constants.h"
37 #include "chrome/common/chrome_paths_internal.h"
38 #include "chrome/common/pref_names.h"
39 #include "chrome/common/url_constants.h"
40 #include "chromeos/chromeos_constants.h"
41 #include "content/public/browser/browser_thread.h"
42 #include "net/base/escape.h"
43 #include "webkit/browser/fileapi/file_system_url.h"
45 using content::BrowserThread;
52 const char kDriveMountPointPath[] = "/special/drive";
54 const base::FilePath::CharType kDriveMyDriveMountPointPath[] =
55 FILE_PATH_LITERAL("/special/drive/root");
57 const base::FilePath::CharType kDriveMyDriveRootPath[] =
58 FILE_PATH_LITERAL("drive/root");
60 const base::FilePath::CharType kFileCacheVersionDir[] =
61 FILE_PATH_LITERAL("v1");
63 const char kSlash[] = "/";
64 const char kEscapedSlash[] = "\xE2\x88\x95";
66 const base::FilePath& GetDriveMyDriveMountPointPath() {
67 CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_mydrive_mount_path,
68 (kDriveMyDriveMountPointPath));
69 return drive_mydrive_mount_path;
72 std::string ReadStringFromGDocFile(const base::FilePath& file_path,
73 const std::string& key) {
74 const int64 kMaxGDocSize = 4096;
76 if (!file_util::GetFileSize(file_path, &file_size) ||
77 file_size > kMaxGDocSize) {
78 DLOG(INFO) << "File too large to be a GDoc file " << file_path.value();
82 JSONFileValueSerializer reader(file_path);
83 std::string error_message;
84 scoped_ptr<base::Value> root_value(reader.Deserialize(NULL, &error_message));
86 DLOG(INFO) << "Failed to parse " << file_path.value() << " as JSON."
87 << " error = " << error_message;
91 base::DictionaryValue* dictionary_value = NULL;
93 if (!root_value->GetAsDictionary(&dictionary_value) ||
94 !dictionary_value->GetString(key, &result)) {
95 DLOG(INFO) << "No value for the given key is stored in "
96 << file_path.value() << ". key = " << key;
103 // Returns DriveIntegrationService instance, if Drive is enabled.
105 DriveIntegrationService* GetIntegrationServiceByProfile(Profile* profile) {
106 DriveIntegrationService* service =
107 DriveIntegrationServiceFactory::FindForProfile(profile);
108 if (!service || !service->IsMounted())
115 const base::FilePath& GetDriveGrandRootPath() {
116 CR_DEFINE_STATIC_LOCAL(base::FilePath, grand_root_path,
117 (util::kDriveGrandRootDirName));
118 return grand_root_path;
121 const base::FilePath& GetDriveMyDriveRootPath() {
122 CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_root_path,
123 (util::kDriveMyDriveRootPath));
124 return drive_root_path;
127 const base::FilePath& GetDriveMountPointPath() {
128 CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_mount_path,
129 (base::FilePath::FromUTF8Unsafe(kDriveMountPointPath)));
130 return drive_mount_path;
133 FileSystemInterface* GetFileSystemByProfile(Profile* profile) {
134 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
136 DriveIntegrationService* integration_service =
137 GetIntegrationServiceByProfile(profile);
138 return integration_service ? integration_service->file_system() : NULL;
141 FileSystemInterface* GetFileSystemByProfileId(void* profile_id) {
142 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
144 // |profile_id| needs to be checked with ProfileManager::IsValidProfile
146 Profile* profile = reinterpret_cast<Profile*>(profile_id);
147 if (!g_browser_process->profile_manager()->IsValidProfile(profile))
149 return GetFileSystemByProfile(profile);
152 DriveAppRegistry* GetDriveAppRegistryByProfile(Profile* profile) {
153 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
155 DriveIntegrationService* integration_service =
156 GetIntegrationServiceByProfile(profile);
157 return integration_service ?
158 integration_service->drive_app_registry() :
162 DriveServiceInterface* GetDriveServiceByProfile(Profile* profile) {
163 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
165 DriveIntegrationService* integration_service =
166 GetIntegrationServiceByProfile(profile);
167 return integration_service ? integration_service->drive_service() : NULL;
170 bool IsSpecialResourceId(const std::string& resource_id) {
171 return resource_id == kDriveGrandRootSpecialResourceId ||
172 resource_id == kDriveOtherDirSpecialResourceId;
175 ResourceEntry CreateMyDriveRootEntry(const std::string& root_resource_id) {
176 ResourceEntry mydrive_root;
177 mydrive_root.mutable_file_info()->set_is_directory(true);
178 mydrive_root.set_resource_id(root_resource_id);
179 mydrive_root.set_parent_local_id(util::kDriveGrandRootSpecialResourceId);
180 mydrive_root.set_title(util::kDriveMyDriveRootDirName);
184 const std::string& GetDriveMountPointPathAsString() {
185 CR_DEFINE_STATIC_LOCAL(std::string, drive_mount_path_string,
186 (kDriveMountPointPath));
187 return drive_mount_path_string;
190 GURL FilePathToDriveURL(const base::FilePath& path) {
191 std::string url(base::StringPrintf("%s:%s",
192 chrome::kDriveScheme,
193 path.AsUTF8Unsafe().c_str()));
197 base::FilePath DriveURLToFilePath(const GURL& url) {
198 if (!url.is_valid() || url.scheme() != chrome::kDriveScheme)
199 return base::FilePath();
200 std::string path_string = net::UnescapeURLComponent(
201 url.GetContent(), net::UnescapeRule::NORMAL);
202 return base::FilePath::FromUTF8Unsafe(path_string);
205 void MaybeSetDriveURL(Profile* profile, const base::FilePath& path, GURL* url) {
206 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
208 if (!IsUnderDriveMountPoint(path))
211 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
215 *url = FilePathToDriveURL(util::ExtractDrivePath(path));
218 bool IsUnderDriveMountPoint(const base::FilePath& path) {
219 return GetDriveMountPointPath() == path ||
220 GetDriveMountPointPath().IsParent(path);
223 bool NeedsNamespaceMigration(const base::FilePath& path) {
224 // Before migration, "My Drive" which was represented as "drive.
225 // The user might use some path pointing a directory in "My Drive".
226 // e.g. "drive/downloads_dir"
227 // We changed the path for the "My Drive" to "drive/root", hence the user pref
228 // pointing to the old path needs update to the new path.
229 // e.g. "drive/root/downloads_dir"
230 // If |path| already points to some directory in "drive/root", there's no need
232 return IsUnderDriveMountPoint(path) &&
233 !(GetDriveMyDriveMountPointPath() == path ||
234 GetDriveMyDriveMountPointPath().IsParent(path));
237 base::FilePath ConvertToMyDriveNamespace(const base::FilePath& path) {
238 DCHECK(NeedsNamespaceMigration(path));
240 // Need to migrate "/special/drive(.*)" to "/special/drive/root(.*)".
241 // Append the relative path from "/special/drive".
242 base::FilePath new_path(GetDriveMyDriveMountPointPath());
243 GetDriveMountPointPath().AppendRelativePath(path, &new_path);
244 DVLOG(1) << "Migrate download.default_directory setting from "
245 << path.AsUTF8Unsafe() << " to " << new_path.AsUTF8Unsafe();
246 DCHECK(!NeedsNamespaceMigration(new_path));
250 base::FilePath ExtractDrivePath(const base::FilePath& path) {
251 if (!IsUnderDriveMountPoint(path))
252 return base::FilePath();
254 base::FilePath drive_path = GetDriveGrandRootPath();
255 GetDriveMountPointPath().AppendRelativePath(path, &drive_path);
259 base::FilePath ExtractDrivePathFromFileSystemUrl(
260 const fileapi::FileSystemURL& url) {
261 if (!url.is_valid() || url.type() != fileapi::kFileSystemTypeDrive)
262 return base::FilePath();
263 return ExtractDrivePath(url.path());
266 base::FilePath GetCacheRootPath(Profile* profile) {
267 base::FilePath cache_base_path;
268 chrome::GetUserCacheDirectory(profile->GetPath(), &cache_base_path);
269 base::FilePath cache_root_path =
270 cache_base_path.Append(chromeos::kDriveCacheDirname);
271 return cache_root_path.Append(kFileCacheVersionDir);
274 std::string EscapeCacheFileName(const std::string& filename) {
275 // This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
277 for (size_t i = 0; i < filename.size(); ++i) {
278 char c = filename[i];
279 if (c == '%' || c == '.' || c == '/') {
280 base::StringAppendF(&escaped, "%%%02X", c);
282 escaped.push_back(c);
288 std::string UnescapeCacheFileName(const std::string& filename) {
289 std::string unescaped;
290 for (size_t i = 0; i < filename.size(); ++i) {
291 char c = filename[i];
292 if (c == '%' && i + 2 < filename.length()) {
293 c = (HexDigitToInt(filename[i + 1]) << 4) +
294 HexDigitToInt(filename[i + 2]);
297 unescaped.push_back(c);
302 std::string NormalizeFileName(const std::string& input) {
303 DCHECK(IsStringUTF8(input));
306 if (!base::ConvertToUtf8AndNormalize(input, base::kCodepageUTF8, &output))
308 ReplaceChars(output, kSlash, std::string(kEscapedSlash), &output);
312 void PrepareWritableFileAndRun(Profile* profile,
313 const base::FilePath& path,
314 const PrepareWritableFileCallback& callback) {
315 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
316 DCHECK(!callback.is_null());
318 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
319 if (!file_system || !IsUnderDriveMountPoint(path)) {
320 content::BrowserThread::GetBlockingPool()->PostTask(
321 FROM_HERE, base::Bind(callback, FILE_ERROR_FAILED, base::FilePath()));
325 WriteOnCacheFile(file_system,
326 ExtractDrivePath(path),
327 std::string(), // mime_type
331 void EnsureDirectoryExists(Profile* profile,
332 const base::FilePath& directory,
333 const FileOperationCallback& callback) {
334 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
335 DCHECK(!callback.is_null());
336 if (IsUnderDriveMountPoint(directory)) {
337 FileSystemInterface* file_system = GetFileSystemByProfile(profile);
339 file_system->CreateDirectory(
340 ExtractDrivePath(directory),
341 true /* is_exclusive */,
342 true /* is_recursive */,
345 base::MessageLoopProxy::current()->PostTask(
346 FROM_HERE, base::Bind(callback, FILE_ERROR_OK));
350 void EmptyFileOperationCallback(FileError error) {
353 bool CreateGDocFile(const base::FilePath& file_path,
355 const std::string& resource_id) {
356 std::string content = base::StringPrintf(
357 "{\"url\": \"%s\", \"resource_id\": \"%s\"}",
358 url.spec().c_str(), resource_id.c_str());
359 return file_util::WriteFile(file_path, content.data(), content.size()) ==
360 static_cast<int>(content.size());
363 bool HasGDocFileExtension(const base::FilePath& file_path) {
364 return google_apis::ResourceEntry::ClassifyEntryKindByFileExtension(
366 google_apis::ResourceEntry::KIND_OF_HOSTED_DOCUMENT;
369 GURL ReadUrlFromGDocFile(const base::FilePath& file_path) {
370 return GURL(ReadStringFromGDocFile(file_path, "url"));
373 std::string ReadResourceIdFromGDocFile(const base::FilePath& file_path) {
374 return ReadStringFromGDocFile(file_path, "resource_id");
377 std::string GetMd5Digest(const base::FilePath& file_path) {
378 const int kBufferSize = 512 * 1024; // 512kB.
380 base::PlatformFile file = base::CreatePlatformFile(
381 file_path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
383 if (file == base::kInvalidPlatformFileValue)
384 return std::string();
385 base::ScopedPlatformFileCloser file_closer(&file);
387 base::MD5Context context;
388 base::MD5Init(&context);
390 scoped_ptr<char[]> buffer(new char[kBufferSize]);
392 int result = base::ReadPlatformFileCurPosNoBestEffort(
393 file, buffer.get(), kBufferSize);
397 return std::string();
405 base::MD5Update(&context, base::StringPiece(buffer.get(), result));
408 base::MD5Digest digest;
409 base::MD5Final(&digest, &context);
410 return MD5DigestToBase16(digest);
413 bool IsDriveEnabledForProfile(Profile* profile) {
414 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
416 if (!chromeos::IsProfileAssociatedWithGaiaAccount(profile))
419 // Disable Drive if preference is set. This can happen with commandline flag
420 // --disable-drive or enterprise policy, or with user settings.
421 if (profile->GetPrefs()->GetBoolean(prefs::kDisableDrive))