1bc8ed305d4181c0906e5b850dbfcb77f4605c31
[platform/core/api/webapi-plugins.git] / src / filesystem / js / common.js
1 /*
2  * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
3  *
4  *    Licensed under the Apache License, Version 2.0 (the "License");
5  *    you may not use this file except in compliance with the License.
6  *    You may obtain a copy of the License at
7  *
8  *        http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *    Unless required by applicable law or agreed to in writing, software
11  *    distributed under the License is distributed on an "AS IS" BASIS,
12  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *    See the License for the specific language governing permissions and
14  *    limitations under the License.
15  */
16
17 var utils_ = xwalk.utils;
18 var type_ = utils_.type;
19 var converter_ = utils_.converter;
20 var validator_ = utils_.validator;
21 var types_ = validator_.Types;
22 var native_ = new xwalk.utils.NativeManager(extension);
23
24 function SetReadOnlyProperty(obj, n, v) {
25   Object.defineProperty(obj, n, {value: v, writable: false});
26 }
27
28 var FileSystemStorageType = {
29   INTERNAL: 'INTERNAL',
30   EXTERNAL: 'EXTERNAL'
31 };
32
33 var FileSystemStorageState = {
34   MOUNTED: 'MOUNTED',
35   REMOVED: 'REMOVED',
36   UNMOUNTABLE: 'UNMOUNTABLE'
37 };
38
39 var FileMode = {
40   r: 'r',
41   rw: 'rw',
42   w: 'w',
43   a: 'a'
44 };
45
46 var commonFS_ = (function() {
47   var cacheReady = false;
48   var listenerRegistered = false;
49   var cacheVirtualToReal = {};
50   var cacheStorages = [];
51   var uriPrefix = 'file://';
52
53   function clearCache() {
54     cacheVirtualToReal = {};
55     cacheStorages = [];
56     cacheReady = false;
57   }
58
59   function initCache() {
60     if (cacheReady) {
61       return;
62     }
63
64     var result = native_.callSync('Filesystem_fetchVirtualRoots', {});
65     if (native_.isFailure(result)) {
66       throw native_.getErrorObject(result);
67     }
68     var virtualRoots = native_.getResultObject(result);
69
70     for (var i = 0; i < virtualRoots.length; ++i) {
71       cacheVirtualToReal[virtualRoots[i].name] = {
72         path: virtualRoots[i].path,
73         type: FileSystemStorageType.INTERNAL,
74         state: FileSystemStorageState.MOUNTED
75       };
76     }
77
78     var result = native_.callSync('FileSystemManager_fetchStorages', {});
79     if (native_.isFailure(result)) {
80       throw native_.getErrorObject(result);
81     }
82
83     var storages = native_.getResultObject(result);
84     for (var i = 0; i < storages.length; ++i) {
85       cacheStorages.push({
86         path: storages[i].path,
87         label: storages[i].name,
88         type: storages[i].type,
89         state: storages[i].state,
90         storage_id: storages[i].storage_id
91       });
92     }
93
94     if (!listenerRegistered) {
95       try {
96         tizen.filesystem.addStorageStateChangeListener(function() {
97           clearCache();
98         });
99         listenerRegistered = true;
100       } catch (e) {
101         console.log('Failed to register storage change listener, ' +
102                     'storage information may be corrupted: ' + e.message);
103       }
104     }
105
106     cacheReady = true;
107   }
108
109   function toRealPath(aPath) {
110     var _fileRealPath = '';
111
112     if (aPath.indexOf(uriPrefix) === 0) {
113       _fileRealPath = aPath.substr(uriPrefix.length);
114     } else if (aPath[0] !== '/') {
115       //virtual path
116       initCache();
117
118       var _pathTokens = aPath.split('/');
119
120       if (cacheVirtualToReal[_pathTokens[0]]) {
121         _fileRealPath = cacheVirtualToReal[_pathTokens[0]].path;
122         for (var i = 1; i < _pathTokens.length; ++i) {
123           _fileRealPath += '/' + _pathTokens[i];
124         }
125       } else {
126         //If path token is not present in cache then it is invalid
127         _fileRealPath = undefined;
128         // check storages
129         for (var j = 0; j < cacheStorages.length; ++j) {
130           if (cacheStorages[j].label === _pathTokens[0]) {
131             _fileRealPath = cacheStorages[j].path;
132             for (var i = 1; i < _pathTokens.length; ++i) {
133               _fileRealPath += '/' + _pathTokens[i];
134             }
135             break;
136           }
137         }
138       }
139     } else {
140       _fileRealPath = aPath;
141     }
142
143     return _fileRealPath;
144   }
145
146   function toVirtualPath(aPath) {
147     var _virtualPath = aPath;
148     if (_virtualPath.indexOf(uriPrefix) === 0) {
149       _virtualPath = _virtualPath.substr(uriPrefix.length);
150     }
151
152     initCache();
153
154     for (var virtual_root in cacheVirtualToReal) {
155       var real_root_path = cacheVirtualToReal[virtual_root].path;
156       if (aPath.indexOf(real_root_path, 0) === 0) {
157         return aPath.replace(real_root_path, virtual_root);
158       }
159     }
160
161     return aPath;
162   }
163
164   function getFileInfo(aStatObj, secondIter, aMode) {
165     var _result = {},
166         _pathTokens,
167         _fileParentPath = '',
168         i;
169     var aPath = toVirtualPath(aStatObj.path);
170
171     _result.readOnly = aStatObj.readOnly;
172     _result.isFile = aStatObj.isFile;
173     _result.isDirectory = aStatObj.isDirectory;
174     _result.created = new Date(aStatObj.ctime * 1000);
175     _result.modified = new Date(aStatObj.mtime * 1000);
176     _result.fullPath = aPath;
177     _result.fileSize = aStatObj.size;
178     _result.mode = aMode;
179     if (_result.isDirectory) {
180       try {
181         _result.length = aStatObj.nlink;
182       } catch (err) {
183         _result.length = 0;
184       }
185     } else {
186       _result.length = undefined;
187     }
188
189     _pathTokens = aPath.split('/');
190     if (_pathTokens.length > 1) {
191       for (i = 0; i < _pathTokens.length - 1; ++i) {
192         _fileParentPath += _pathTokens[i] + '/';
193       }
194       _result.path = _fileParentPath;
195       _result.name = _pathTokens[_pathTokens.length - 1];
196       _result.parent = (secondIter) ? null : _fileParentPath;
197     } else {
198       _result.parent = null;
199       _result.path = aPath;
200       _result.name = '';
201     }
202     return _result;
203   }
204
205   function isLocationAllowed(aPath) {
206     if (!aPath) {
207       return false;
208     }
209     initCache();
210     if (aPath.indexOf(cacheVirtualToReal.ringtones.path) === 0) {
211       return false;
212     }
213     if (aPath.indexOf(cacheVirtualToReal['wgt-package'].path) === 0) {
214       return false;
215     }
216
217     return true;
218   }
219
220   function f_isSubDir(fullPathToCheck, fullPath) {
221     var realFullPath = toRealPath(fullPath);
222     return ((-1 !== fullPathToCheck.indexOf(realFullPath)) && (fullPathToCheck !== realFullPath));
223   };
224
225   function f_isCorrectRelativePath(relativePath) {
226     return ((0 !== relativePath.indexOf('/')) &&
227         (0 !== relativePath.indexOf('\\')) &&
228         (-1 === relativePath.indexOf('?')) &&
229         (-1 === relativePath.indexOf('*')) &&
230         (-1 === relativePath.indexOf(':')) &&
231         (-1 === relativePath.indexOf('"')) &&
232         (-1 === relativePath.indexOf('<')) &&
233         (-1 === relativePath.indexOf('>')));
234   };
235
236   function cloneStorage(storage) {
237     return {
238       label: storage.label,
239       type: storage.type,
240       state: storage.state
241     };
242   }
243
244   function getStorage(label) {
245     initCache();
246     for (var i = 0; i < cacheStorages.length; ++i) {
247       if (cacheStorages[i].label === label) {
248         return cloneStorage(cacheStorages[i]);
249       }
250     }
251     return null;
252   }
253
254   function getAllStorages() {
255     var ret = [];
256     initCache();
257     for (var i = 0; i < cacheStorages.length; ++i) {
258       ret.push(cloneStorage(cacheStorages[i]));
259     }
260     return ret;
261   }
262
263   return {
264     clearCache: clearCache,
265     toRealPath: toRealPath,
266     toVirtualPath: toVirtualPath,
267     getFileInfo: getFileInfo,
268     isLocationAllowed: isLocationAllowed,
269     f_isSubDir: f_isSubDir,
270     f_isCorrectRelativePath: f_isCorrectRelativePath,
271     getStorage: getStorage,
272     getAllStorages: getAllStorages
273   };
274 })();