Upstream version 7.36.149.0
[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/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"
43
44 using content::BrowserThread;
45
46 namespace drive {
47 namespace util {
48
49 namespace {
50
51 const base::FilePath::CharType kSpecialMountPointRoot[] =
52     FILE_PATH_LITERAL("/special");
53
54 const char kDriveMountPointNameBase[] = "drive";
55
56 const base::FilePath::CharType kDriveMyDriveRootPath[] =
57     FILE_PATH_LITERAL("drive/root");
58
59 const base::FilePath::CharType kFileCacheVersionDir[] =
60     FILE_PATH_LITERAL("v1");
61
62 const char kSlash[] = "/";
63 const char kDot = '.';
64 const char kEscapedChars[] = "_";
65
66 std::string ReadStringFromGDocFile(const base::FilePath& file_path,
67                                    const std::string& key) {
68   const int64 kMaxGDocSize = 4096;
69   int64 file_size = 0;
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();
73     return std::string();
74   }
75
76   JSONFileValueSerializer reader(file_path);
77   std::string error_message;
78   scoped_ptr<base::Value> root_value(reader.Deserialize(NULL, &error_message));
79   if (!root_value) {
80     LOG(WARNING) << "Failed to parse " << file_path.value() << " as JSON."
81                  << " error = " << error_message;
82     return std::string();
83   }
84
85   base::DictionaryValue* dictionary_value = NULL;
86   std::string result;
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;
91     return std::string();
92   }
93
94   return result;
95 }
96
97 // Returns DriveIntegrationService instance, if Drive is enabled.
98 // Otherwise, NULL.
99 DriveIntegrationService* GetIntegrationServiceByProfile(Profile* profile) {
100   DriveIntegrationService* service =
101       DriveIntegrationServiceFactory::FindForProfile(profile);
102   if (!service || !service->IsMounted())
103     return NULL;
104   return service;
105 }
106
107 void CheckDirectoryExistsAfterGetResourceEntry(
108     const FileOperationCallback& callback,
109     FileError error,
110     scoped_ptr<ResourceEntry> entry) {
111   if (error == FILE_ERROR_OK && !entry->file_info().is_directory())
112     error = FILE_ERROR_NOT_A_DIRECTORY;
113   callback.Run(error);
114 }
115
116 }  // namespace
117
118 const base::FilePath& GetDriveGrandRootPath() {
119   CR_DEFINE_STATIC_LOCAL(base::FilePath, grand_root_path,
120       (kDriveGrandRootDirName));
121   return grand_root_path;
122 }
123
124 const base::FilePath& GetDriveMyDriveRootPath() {
125   CR_DEFINE_STATIC_LOCAL(base::FilePath, drive_root_path,
126       (kDriveMyDriveRootPath));
127   return drive_root_path;
128 }
129
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)));
135 }
136
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;
148     if (user)
149       id = user->username_hash();
150   }
151   return GetDriveMountPointPathForUserIdHash(id);
152 }
153
154 FileSystemInterface* GetFileSystemByProfile(Profile* profile) {
155   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
156
157   DriveIntegrationService* integration_service =
158       GetIntegrationServiceByProfile(profile);
159   return integration_service ? integration_service->file_system() : NULL;
160 }
161
162 FileSystemInterface* GetFileSystemByProfileId(void* profile_id) {
163   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
164
165   // |profile_id| needs to be checked with ProfileManager::IsValidProfile
166   // before using it.
167   Profile* profile = reinterpret_cast<Profile*>(profile_id);
168   if (!g_browser_process->profile_manager()->IsValidProfile(profile))
169     return NULL;
170   return GetFileSystemByProfile(profile);
171 }
172
173 DriveAppRegistry* GetDriveAppRegistryByProfile(Profile* profile) {
174   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
175
176   DriveIntegrationService* integration_service =
177       GetIntegrationServiceByProfile(profile);
178   return integration_service ?
179       integration_service->drive_app_registry() :
180       NULL;
181 }
182
183 DriveServiceInterface* GetDriveServiceByProfile(Profile* profile) {
184   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
185
186   DriveIntegrationService* integration_service =
187       GetIntegrationServiceByProfile(profile);
188   return integration_service ? integration_service->drive_service() : NULL;
189 }
190
191 GURL FilePathToDriveURL(const base::FilePath& path) {
192   std::string url(base::StringPrintf("%s:%s",
193                                      chrome::kDriveScheme,
194                                      path.AsUTF8Unsafe().c_str()));
195   return GURL(url);
196 }
197
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);
204 }
205
206 void MaybeSetDriveURL(Profile* profile, const base::FilePath& path, GURL* url) {
207   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
208
209   if (!IsUnderDriveMountPoint(path))
210     return;
211
212   FileSystemInterface* file_system = GetFileSystemByProfile(profile);
213   if (!file_system)
214     return;
215
216   *url = FilePathToDriveURL(util::ExtractDrivePath(path));
217 }
218
219 bool IsUnderDriveMountPoint(const base::FilePath& path) {
220   return !ExtractDrivePath(path).empty();
221 }
222
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();
234
235   base::FilePath drive_path = GetDriveGrandRootPath();
236   for (size_t i = 3; i < components.size(); ++i)
237     drive_path = drive_path.Append(components[i]);
238   return drive_path;
239 }
240
241 Profile* ExtractProfileFromPath(const base::FilePath& path) {
242   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
243
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;
253     }
254   }
255   return NULL;
256 }
257
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());
263 }
264
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);
271 }
272
273 std::string EscapeCacheFileName(const std::string& filename) {
274   // This is based on net/base/escape.cc: net::(anonymous namespace)::Escape
275   std::string escaped;
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);
280     } else {
281       escaped.push_back(c);
282     }
283   }
284   return escaped;
285 }
286
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]);
294       i += 2;
295     }
296     unescaped.push_back(c);
297   }
298   return unescaped;
299 }
300
301 std::string NormalizeFileName(const std::string& input) {
302   DCHECK(base::IsStringUTF8(input));
303
304   std::string output;
305   if (!base::ConvertToUtf8AndNormalize(input, base::kCodepageUTF8, &output))
306     output = input;
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;
310   return output;
311 }
312
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());
318
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()));
323     return;
324   }
325
326   WriteOnCacheFile(file_system,
327                    ExtractDrivePath(path),
328                    std::string(), // mime_type
329                    callback);
330 }
331
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);
339     DCHECK(file_system);
340     file_system->CreateDirectory(
341         ExtractDrivePath(directory),
342         true /* is_exclusive */,
343         true /* is_recursive */,
344         callback);
345   } else {
346     base::MessageLoopProxy::current()->PostTask(
347         FROM_HERE, base::Bind(callback, FILE_ERROR_OK));
348   }
349 }
350
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());
356
357   FileSystemInterface* file_system = GetFileSystemByProfile(profile);
358   DCHECK(file_system);
359
360   file_system->GetResourceEntry(
361       ExtractDrivePath(directory),
362       base::Bind(&CheckDirectoryExistsAfterGetResourceEntry, callback));
363 }
364
365 void EmptyFileOperationCallback(FileError error) {
366 }
367
368 bool CreateGDocFile(const base::FilePath& file_path,
369                     const GURL& url,
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());
376 }
377
378 bool HasGDocFileExtension(const base::FilePath& file_path) {
379   return google_apis::ResourceEntry::ClassifyEntryKindByFileExtension(
380       file_path) &
381       google_apis::ResourceEntry::KIND_OF_HOSTED_DOCUMENT;
382 }
383
384 GURL ReadUrlFromGDocFile(const base::FilePath& file_path) {
385   return GURL(ReadStringFromGDocFile(file_path, "url"));
386 }
387
388 std::string ReadResourceIdFromGDocFile(const base::FilePath& file_path) {
389   return ReadStringFromGDocFile(file_path, "resource_id");
390 }
391
392 bool IsDriveEnabledForProfile(Profile* profile) {
393   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
394
395   if (!chromeos::IsProfileAssociatedWithGaiaAccount(profile))
396     return false;
397
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))
401     return false;
402
403   return true;
404 }
405
406 ConnectionStatusType GetDriveConnectionStatus(Profile* profile) {
407   drive::DriveServiceInterface* const drive_service =
408       drive::util::GetDriveServiceByProfile(profile);
409
410   if (!drive_service)
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;
416
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);
422
423   if (is_connection_cellular && disable_sync_over_celluar)
424     return DRIVE_CONNECTED_METERED;
425   return DRIVE_CONNECTED;
426 }
427
428 }  // namespace util
429 }  // namespace drive