- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / drive / file_system_util.cc
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.
4
5 #include "chrome/browser/chromeos/drive/file_system_util.h"
6
7 #include <string>
8
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"
18 #include "base/md5.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"
44
45 using content::BrowserThread;
46
47 namespace drive {
48 namespace util {
49
50 namespace {
51
52 const char kDriveMountPointPath[] = "/special/drive";
53
54 const base::FilePath::CharType kDriveMyDriveMountPointPath[] =
55     FILE_PATH_LITERAL("/special/drive/root");
56
57 const base::FilePath::CharType kDriveMyDriveRootPath[] =
58     FILE_PATH_LITERAL("drive/root");
59
60 const base::FilePath::CharType kFileCacheVersionDir[] =
61     FILE_PATH_LITERAL("v1");
62
63 const char kSlash[] = "/";
64 const char kEscapedSlash[] = "\xE2\x88\x95";
65
66 const base::FilePath& GetDriveMyDriveMountPointPath() {
67   CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_mydrive_mount_path,
68       (kDriveMyDriveMountPointPath));
69   return drive_mydrive_mount_path;
70 }
71
72 std::string ReadStringFromGDocFile(const base::FilePath& file_path,
73                                    const std::string& key) {
74   const int64 kMaxGDocSize = 4096;
75   int64 file_size = 0;
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();
79     return std::string();
80   }
81
82   JSONFileValueSerializer reader(file_path);
83   std::string error_message;
84   scoped_ptr<base::Value> root_value(reader.Deserialize(NULL, &error_message));
85   if (!root_value) {
86     DLOG(INFO) << "Failed to parse " << file_path.value() << " as JSON."
87                << " error = " << error_message;
88     return std::string();
89   }
90
91   base::DictionaryValue* dictionary_value = NULL;
92   std::string result;
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;
97     return std::string();
98   }
99
100   return result;
101 }
102
103 // Returns DriveIntegrationService instance, if Drive is enabled.
104 // Otherwise, NULL.
105 DriveIntegrationService* GetIntegrationServiceByProfile(Profile* profile) {
106   DriveIntegrationService* service =
107       DriveIntegrationServiceFactory::FindForProfile(profile);
108   if (!service || !service->IsMounted())
109     return NULL;
110   return service;
111 }
112
113 }  // namespace
114
115 const base::FilePath& GetDriveGrandRootPath() {
116   CR_DEFINE_STATIC_LOCAL(base::FilePath, grand_root_path,
117       (util::kDriveGrandRootDirName));
118   return grand_root_path;
119 }
120
121 const base::FilePath& GetDriveMyDriveRootPath() {
122   CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_root_path,
123       (util::kDriveMyDriveRootPath));
124   return drive_root_path;
125 }
126
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;
131 }
132
133 FileSystemInterface* GetFileSystemByProfile(Profile* profile) {
134   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
135
136   DriveIntegrationService* integration_service =
137       GetIntegrationServiceByProfile(profile);
138   return integration_service ? integration_service->file_system() : NULL;
139 }
140
141 FileSystemInterface* GetFileSystemByProfileId(void* profile_id) {
142   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
143
144   // |profile_id| needs to be checked with ProfileManager::IsValidProfile
145   // before using it.
146   Profile* profile = reinterpret_cast<Profile*>(profile_id);
147   if (!g_browser_process->profile_manager()->IsValidProfile(profile))
148     return NULL;
149   return GetFileSystemByProfile(profile);
150 }
151
152 DriveAppRegistry* GetDriveAppRegistryByProfile(Profile* profile) {
153   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
154
155   DriveIntegrationService* integration_service =
156       GetIntegrationServiceByProfile(profile);
157   return integration_service ?
158       integration_service->drive_app_registry() :
159       NULL;
160 }
161
162 DriveServiceInterface* GetDriveServiceByProfile(Profile* profile) {
163   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
164
165   DriveIntegrationService* integration_service =
166       GetIntegrationServiceByProfile(profile);
167   return integration_service ? integration_service->drive_service() : NULL;
168 }
169
170 bool IsSpecialResourceId(const std::string& resource_id) {
171   return resource_id == kDriveGrandRootSpecialResourceId ||
172       resource_id == kDriveOtherDirSpecialResourceId;
173 }
174
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);
181   return mydrive_root;
182 }
183
184 const std::string& GetDriveMountPointPathAsString() {
185   CR_DEFINE_STATIC_LOCAL(std::string, drive_mount_path_string,
186       (kDriveMountPointPath));
187   return drive_mount_path_string;
188 }
189
190 GURL FilePathToDriveURL(const base::FilePath& path) {
191   std::string url(base::StringPrintf("%s:%s",
192                                      chrome::kDriveScheme,
193                                      path.AsUTF8Unsafe().c_str()));
194   return GURL(url);
195 }
196
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);
203 }
204
205 void MaybeSetDriveURL(Profile* profile, const base::FilePath& path, GURL* url) {
206   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
207
208   if (!IsUnderDriveMountPoint(path))
209     return;
210
211   FileSystemInterface* file_system = GetFileSystemByProfile(profile);
212   if (!file_system)
213     return;
214
215   *url = FilePathToDriveURL(util::ExtractDrivePath(path));
216 }
217
218 bool IsUnderDriveMountPoint(const base::FilePath& path) {
219   return GetDriveMountPointPath() == path ||
220          GetDriveMountPointPath().IsParent(path);
221 }
222
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
231   // to update it.
232   return IsUnderDriveMountPoint(path) &&
233          !(GetDriveMyDriveMountPointPath() == path ||
234            GetDriveMyDriveMountPointPath().IsParent(path));
235 }
236
237 base::FilePath ConvertToMyDriveNamespace(const base::FilePath& path) {
238   DCHECK(NeedsNamespaceMigration(path));
239
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));
247   return new_path;
248 }
249
250 base::FilePath ExtractDrivePath(const base::FilePath& path) {
251   if (!IsUnderDriveMountPoint(path))
252     return base::FilePath();
253
254   base::FilePath drive_path = GetDriveGrandRootPath();
255   GetDriveMountPointPath().AppendRelativePath(path, &drive_path);
256   return drive_path;
257 }
258
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());
264 }
265
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);
272 }
273
274 std::string EscapeCacheFileName(const std::string& filename) {
275   // This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
276   std::string escaped;
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);
281     } else {
282       escaped.push_back(c);
283     }
284   }
285   return escaped;
286 }
287
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]);
295       i += 2;
296     }
297     unescaped.push_back(c);
298   }
299   return unescaped;
300 }
301
302 std::string NormalizeFileName(const std::string& input) {
303   DCHECK(IsStringUTF8(input));
304
305   std::string output;
306   if (!base::ConvertToUtf8AndNormalize(input, base::kCodepageUTF8, &output))
307     output = input;
308   ReplaceChars(output, kSlash, std::string(kEscapedSlash), &output);
309   return output;
310 }
311
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());
317
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()));
322     return;
323   }
324
325   WriteOnCacheFile(file_system,
326                    ExtractDrivePath(path),
327                    std::string(), // mime_type
328                    callback);
329 }
330
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);
338     DCHECK(file_system);
339     file_system->CreateDirectory(
340         ExtractDrivePath(directory),
341         true /* is_exclusive */,
342         true /* is_recursive */,
343         callback);
344   } else {
345     base::MessageLoopProxy::current()->PostTask(
346         FROM_HERE, base::Bind(callback, FILE_ERROR_OK));
347   }
348 }
349
350 void EmptyFileOperationCallback(FileError error) {
351 }
352
353 bool CreateGDocFile(const base::FilePath& file_path,
354                     const GURL& url,
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());
361 }
362
363 bool HasGDocFileExtension(const base::FilePath& file_path) {
364   return google_apis::ResourceEntry::ClassifyEntryKindByFileExtension(
365       file_path) &
366       google_apis::ResourceEntry::KIND_OF_HOSTED_DOCUMENT;
367 }
368
369 GURL ReadUrlFromGDocFile(const base::FilePath& file_path) {
370   return GURL(ReadStringFromGDocFile(file_path, "url"));
371 }
372
373 std::string ReadResourceIdFromGDocFile(const base::FilePath& file_path) {
374   return ReadStringFromGDocFile(file_path, "resource_id");
375 }
376
377 std::string GetMd5Digest(const base::FilePath& file_path) {
378   const int kBufferSize = 512 * 1024;  // 512kB.
379
380   base::PlatformFile file = base::CreatePlatformFile(
381       file_path, base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ,
382       NULL, NULL);
383   if (file == base::kInvalidPlatformFileValue)
384     return std::string();
385   base::ScopedPlatformFileCloser file_closer(&file);
386
387   base::MD5Context context;
388   base::MD5Init(&context);
389
390   scoped_ptr<char[]> buffer(new char[kBufferSize]);
391   while (true) {
392     int result = base::ReadPlatformFileCurPosNoBestEffort(
393         file, buffer.get(), kBufferSize);
394
395     if (result < 0) {
396       // Found an error.
397       return std::string();
398     }
399
400     if (result == 0) {
401       // End of file.
402       break;
403     }
404
405     base::MD5Update(&context, base::StringPiece(buffer.get(), result));
406   }
407
408   base::MD5Digest digest;
409   base::MD5Final(&digest, &context);
410   return MD5DigestToBase16(digest);
411 }
412
413 bool IsDriveEnabledForProfile(Profile* profile) {
414   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
415
416   if (!chromeos::IsProfileAssociatedWithGaiaAccount(profile))
417     return false;
418
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))
422     return false;
423
424   return true;
425 }
426
427 }  // namespace util
428 }  // namespace drive