48812fc75b3002043db16b857657c3bd26a3b99d
[platform/framework/web/crosswalk.git] / src / third_party / WebKit / Source / modules / filesystem / DOMFileSystemBase.cpp
1 /*
2  * Copyright (C) 2010 Google Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions are
6  * met:
7  *
8  *     * Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *     * Redistributions in binary form must reproduce the above
11  * copyright notice, this list of conditions and the following disclaimer
12  * in the documentation and/or other materials provided with the
13  * distribution.
14  *     * Neither the name of Google Inc. nor the names of its
15  * contributors may be used to endorse or promote products derived from
16  * this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29  */
30
31 #include "config.h"
32 #include "modules/filesystem/DOMFileSystemBase.h"
33
34 #include "core/dom/ExecutionContext.h"
35 #include "core/fileapi/File.h"
36 #include "core/fileapi/FileError.h"
37 #include "core/html/VoidCallback.h"
38 #include "modules/filesystem/DOMFilePath.h"
39 #include "modules/filesystem/DirectoryEntry.h"
40 #include "modules/filesystem/DirectoryReaderBase.h"
41 #include "modules/filesystem/EntriesCallback.h"
42 #include "modules/filesystem/Entry.h"
43 #include "modules/filesystem/EntryBase.h"
44 #include "modules/filesystem/EntryCallback.h"
45 #include "modules/filesystem/ErrorCallback.h"
46 #include "modules/filesystem/FileSystemCallbacks.h"
47 #include "modules/filesystem/MetadataCallback.h"
48 #include "platform/weborigin/SecurityOrigin.h"
49 #include "public/platform/Platform.h"
50 #include "public/platform/WebFileSystem.h"
51 #include "public/platform/WebFileSystemCallbacks.h"
52 #include "wtf/OwnPtr.h"
53 #include "wtf/text/StringBuilder.h"
54
55 namespace blink {
56
57 const char DOMFileSystemBase::persistentPathPrefix[] = "persistent";
58 const char DOMFileSystemBase::temporaryPathPrefix[] = "temporary";
59 const char DOMFileSystemBase::isolatedPathPrefix[] = "isolated";
60 const char DOMFileSystemBase::externalPathPrefix[] = "external";
61
62 DOMFileSystemBase::DOMFileSystemBase(ExecutionContext* context, const String& name, FileSystemType type, const KURL& rootURL)
63     : m_context(context)
64     , m_name(name)
65     , m_type(type)
66     , m_filesystemRootURL(rootURL)
67     , m_clonable(false)
68 {
69 }
70
71 DOMFileSystemBase::~DOMFileSystemBase()
72 {
73 }
74
75 WebFileSystem* DOMFileSystemBase::fileSystem() const
76 {
77     Platform* platform = Platform::current();
78     if (!platform)
79         return nullptr;
80     return platform->fileSystem();
81 }
82
83 SecurityOrigin* DOMFileSystemBase::securityOrigin() const
84 {
85     return m_context->securityOrigin();
86 }
87
88 bool DOMFileSystemBase::isValidType(FileSystemType type)
89 {
90     return type == FileSystemTypeTemporary || type == FileSystemTypePersistent || type == FileSystemTypeIsolated || type == FileSystemTypeExternal;
91 }
92
93 bool DOMFileSystemBase::crackFileSystemURL(const KURL& url, FileSystemType& type, String& filePath)
94 {
95     if (!url.protocolIs("filesystem"))
96         return false;
97
98     if (!url.innerURL())
99         return false;
100
101     String typeString = url.innerURL()->path().substring(1);
102     if (!pathPrefixToFileSystemType(typeString, type))
103         return false;
104
105     filePath = decodeURLEscapeSequences(url.path());
106     return true;
107 }
108
109 KURL DOMFileSystemBase::createFileSystemRootURL(const String& origin, FileSystemType type)
110 {
111     String typeString;
112     if (type == FileSystemTypeTemporary)
113         typeString = temporaryPathPrefix;
114     else if (type == FileSystemTypePersistent)
115         typeString = persistentPathPrefix;
116     else if (type == FileSystemTypeExternal)
117         typeString = externalPathPrefix;
118     else
119         return KURL();
120
121     String result = "filesystem:" + origin + "/" + typeString + "/";
122     return KURL(ParsedURLString, result);
123 }
124
125 bool DOMFileSystemBase::supportsToURL() const
126 {
127     ASSERT(isValidType(m_type));
128     return m_type != FileSystemTypeIsolated;
129 }
130
131 KURL DOMFileSystemBase::createFileSystemURL(const EntryBase* entry) const
132 {
133     return createFileSystemURL(entry->fullPath());
134 }
135
136 KURL DOMFileSystemBase::createFileSystemURL(const String& fullPath) const
137 {
138     ASSERT(DOMFilePath::isAbsolute(fullPath));
139
140     if (type() == FileSystemTypeExternal) {
141         // For external filesystem originString could be different from what we have in m_filesystemRootURL.
142         StringBuilder result;
143         result.appendLiteral("filesystem:");
144         result.append(securityOrigin()->toString());
145         result.append('/');
146         result.append(externalPathPrefix);
147         result.append(m_filesystemRootURL.path());
148         // Remove the extra leading slash.
149         result.append(encodeWithURLEscapeSequences(fullPath.substring(1)));
150         return KURL(ParsedURLString, result.toString());
151     }
152
153     // For regular types we can just append the entry's fullPath to the m_filesystemRootURL that should look like 'filesystem:<origin>/<typePrefix>'.
154     ASSERT(!m_filesystemRootURL.isEmpty());
155     KURL url = m_filesystemRootURL;
156     // Remove the extra leading slash.
157     url.setPath(url.path() + encodeWithURLEscapeSequences(fullPath.substring(1)));
158     return url;
159 }
160
161 bool DOMFileSystemBase::pathToAbsolutePath(FileSystemType type, const EntryBase* base, String path, String& absolutePath)
162 {
163     ASSERT(base);
164
165     if (!DOMFilePath::isAbsolute(path))
166         path = DOMFilePath::append(base->fullPath(), path);
167     absolutePath = DOMFilePath::removeExtraParentReferences(path);
168
169     return (type != FileSystemTypeTemporary && type != FileSystemTypePersistent) || DOMFilePath::isValidPath(absolutePath);
170 }
171
172 bool DOMFileSystemBase::pathPrefixToFileSystemType(const String& pathPrefix, FileSystemType& type)
173 {
174     if (pathPrefix == temporaryPathPrefix) {
175         type = FileSystemTypeTemporary;
176         return true;
177     }
178
179     if (pathPrefix == persistentPathPrefix) {
180         type = FileSystemTypePersistent;
181         return true;
182     }
183
184     if (pathPrefix == externalPathPrefix) {
185         type = FileSystemTypeExternal;
186         return true;
187     }
188
189     return false;
190 }
191
192 File* DOMFileSystemBase::createFile(const FileMetadata& metadata, const KURL& fileSystemURL, FileSystemType type, const String name)
193 {
194     // For regular filesystem types (temporary or persistent), we should not cache file metadata as it could change File semantics.
195     // For other filesystem types (which could be platform-specific ones), there's a chance that the files are on remote filesystem.
196     // If the port has returned metadata just pass it to File constructor (so we may cache the metadata).
197     // FIXME: We should use the snapshot metadata for all files.
198     // https://www.w3.org/Bugs/Public/show_bug.cgi?id=17746
199     if (type == FileSystemTypeTemporary || type == FileSystemTypePersistent)
200         return File::createForFileSystemFile(metadata.platformPath, name);
201
202     const File::UserVisibility userVisibility = (type == FileSystemTypeExternal) ? File::IsUserVisible : File::IsNotUserVisible;
203
204     if (!metadata.platformPath.isEmpty()) {
205         // If the platformPath in the returned metadata is given, we create a File object for the snapshot path.
206         return File::createForFileSystemFile(name, metadata, userVisibility);
207     } else {
208         // Otherwise we create a File object for the fileSystemURL.
209         return File::createForFileSystemFile(fileSystemURL, metadata, userVisibility);
210     }
211 }
212
213 void DOMFileSystemBase::getMetadata(const EntryBase* entry, MetadataCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
214 {
215     if (!fileSystem()) {
216         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
217         return;
218     }
219
220     OwnPtr<AsyncFileSystemCallbacks> callbacks(MetadataCallbacks::create(successCallback, errorCallback, m_context, this));
221     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
222     fileSystem()->readMetadata(createFileSystemURL(entry), callbacks.release());
223 }
224
225 static bool verifyAndGetDestinationPathForCopyOrMove(const EntryBase* source, EntryBase* parent, const String& newName, String& destinationPath)
226 {
227     ASSERT(source);
228
229     if (!parent || !parent->isDirectory())
230         return false;
231
232     if (!newName.isEmpty() && !DOMFilePath::isValidName(newName))
233         return false;
234
235     const bool isSameFileSystem = (*source->filesystem() == *parent->filesystem());
236
237     // It is an error to try to copy or move an entry inside itself at any depth if it is a directory.
238     if (source->isDirectory() && isSameFileSystem && DOMFilePath::isParentOf(source->fullPath(), parent->fullPath()))
239         return false;
240
241     // It is an error to copy or move an entry into its parent if a name different from its current one isn't provided.
242     if (isSameFileSystem && (newName.isEmpty() || source->name() == newName) && DOMFilePath::getDirectory(source->fullPath()) == parent->fullPath())
243         return false;
244
245     destinationPath = parent->fullPath();
246     if (!newName.isEmpty())
247         destinationPath = DOMFilePath::append(destinationPath, newName);
248     else
249         destinationPath = DOMFilePath::append(destinationPath, source->name());
250
251     return true;
252 }
253
254 void DOMFileSystemBase::move(const EntryBase* source, EntryBase* parent, const String& newName, EntryCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
255 {
256     if (!fileSystem()) {
257         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
258         return;
259     }
260
261     String destinationPath;
262     if (!verifyAndGetDestinationPathForCopyOrMove(source, parent, newName, destinationPath)) {
263         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
264         return;
265     }
266
267     OwnPtr<AsyncFileSystemCallbacks> callbacks(EntryCallbacks::create(successCallback, errorCallback, m_context, parent->filesystem(), destinationPath, source->isDirectory()));
268     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
269
270     fileSystem()->move(createFileSystemURL(source), parent->filesystem()->createFileSystemURL(destinationPath), callbacks.release());
271 }
272
273 void DOMFileSystemBase::copy(const EntryBase* source, EntryBase* parent, const String& newName, EntryCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
274 {
275     if (!fileSystem()) {
276         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
277         return;
278     }
279
280     String destinationPath;
281     if (!verifyAndGetDestinationPathForCopyOrMove(source, parent, newName, destinationPath)) {
282         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
283         return;
284     }
285
286     OwnPtr<AsyncFileSystemCallbacks> callbacks(EntryCallbacks::create(successCallback, errorCallback, m_context, parent->filesystem(), destinationPath, source->isDirectory()));
287     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
288
289     fileSystem()->copy(createFileSystemURL(source), parent->filesystem()->createFileSystemURL(destinationPath), callbacks.release());
290 }
291
292 void DOMFileSystemBase::remove(const EntryBase* entry, VoidCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
293 {
294     if (!fileSystem()) {
295         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
296         return;
297     }
298
299     ASSERT(entry);
300     // We don't allow calling remove() on the root directory.
301     if (entry->fullPath() == String(DOMFilePath::root)) {
302         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
303         return;
304     }
305
306     OwnPtr<AsyncFileSystemCallbacks> callbacks(VoidCallbacks::create(successCallback, errorCallback, m_context, this));
307     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
308
309     fileSystem()->remove(createFileSystemURL(entry), callbacks.release());
310 }
311
312 void DOMFileSystemBase::removeRecursively(const EntryBase* entry, VoidCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
313 {
314     if (!fileSystem()) {
315         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
316         return;
317     }
318
319     ASSERT(entry && entry->isDirectory());
320     // We don't allow calling remove() on the root directory.
321     if (entry->fullPath() == String(DOMFilePath::root)) {
322         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
323         return;
324     }
325
326     OwnPtr<AsyncFileSystemCallbacks> callbacks(VoidCallbacks::create(successCallback, errorCallback, m_context, this));
327     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
328
329     fileSystem()->removeRecursively(createFileSystemURL(entry), callbacks.release());
330 }
331
332 void DOMFileSystemBase::getParent(const EntryBase* entry, EntryCallback* successCallback, ErrorCallback* errorCallback)
333 {
334     if (!fileSystem()) {
335         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
336         return;
337     }
338
339     ASSERT(entry);
340     String path = DOMFilePath::getDirectory(entry->fullPath());
341
342     fileSystem()->directoryExists(createFileSystemURL(path), EntryCallbacks::create(successCallback, errorCallback, m_context, this, path, true));
343 }
344
345 void DOMFileSystemBase::getFile(const EntryBase* entry, const String& path, const FileSystemFlags& flags, EntryCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
346 {
347     if (!fileSystem()) {
348         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
349         return;
350     }
351
352     String absolutePath;
353     if (!pathToAbsolutePath(m_type, entry, path, absolutePath)) {
354         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
355         return;
356     }
357
358     OwnPtr<AsyncFileSystemCallbacks> callbacks(EntryCallbacks::create(successCallback, errorCallback, m_context, this, absolutePath, false));
359     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
360
361     if (flags.createFlag())
362         fileSystem()->createFile(createFileSystemURL(absolutePath), flags.exclusive(), callbacks.release());
363     else
364         fileSystem()->fileExists(createFileSystemURL(absolutePath), callbacks.release());
365 }
366
367 void DOMFileSystemBase::getDirectory(const EntryBase* entry, const String& path, const FileSystemFlags& flags, EntryCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
368 {
369     if (!fileSystem()) {
370         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
371         return;
372     }
373
374     String absolutePath;
375     if (!pathToAbsolutePath(m_type, entry, path, absolutePath)) {
376         reportError(errorCallback, FileError::create(FileError::INVALID_MODIFICATION_ERR));
377         return;
378     }
379
380     OwnPtr<AsyncFileSystemCallbacks> callbacks(EntryCallbacks::create(successCallback, errorCallback, m_context, this, absolutePath, true));
381     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
382
383     if (flags.createFlag())
384         fileSystem()->createDirectory(createFileSystemURL(absolutePath), flags.exclusive(), callbacks.release());
385     else
386         fileSystem()->directoryExists(createFileSystemURL(absolutePath), callbacks.release());
387 }
388
389 int DOMFileSystemBase::readDirectory(DirectoryReaderBase* reader, const String& path, EntriesCallback* successCallback, ErrorCallback* errorCallback, SynchronousType synchronousType)
390 {
391     if (!fileSystem()) {
392         reportError(errorCallback, FileError::create(FileError::ABORT_ERR));
393         return 0;
394     }
395
396     ASSERT(DOMFilePath::isAbsolute(path));
397
398     OwnPtr<AsyncFileSystemCallbacks> callbacks(EntriesCallbacks::create(successCallback, errorCallback, m_context, reader, path));
399     callbacks->setShouldBlockUntilCompletion(synchronousType == Synchronous);
400
401     return fileSystem()->readDirectory(createFileSystemURL(path), callbacks.release());
402 }
403
404 bool DOMFileSystemBase::waitForAdditionalResult(int callbacksId)
405 {
406     if (!fileSystem())
407         return false;
408     return fileSystem()->waitForAdditionalResult(callbacksId);
409 }
410
411 } // namespace blink