Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / xwalk / experimental / native_file_system / native_file_system_api.js
1 // Copyright (c) 2014 Intel Corporation. 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 var _promises = {};
6 var _next_promise_id = 0;
7
8 var Promise = requireNative('sysapps_promise').Promise;
9 var IsolatedFileSystem = requireNative('isolated_file_system');
10
11 var postMessage = function(msg, success, error) {
12   var p = new Promise();
13   p.then(success, error);
14
15   _promises[_next_promise_id] = p;
16   msg._promise_id = _next_promise_id.toString();
17   _next_promise_id += 1;
18
19   extension.postMessage(msg);
20 };
21
22 function _isFunction(fn) {
23   return !!fn && !fn.nodeName &&
24       fn.constructor != String && fn.constructor != RegExp &&
25       fn.constructor != Array && /function/i.test(fn + "");
26 }
27
28 var NativeFileSystem = function() {
29 };
30
31 var requestNativeFileSystem = function(path, success, error) {
32   var msg = new Object();
33   msg.data = new Object();
34   msg.data.virtual_root = path;
35   msg.cmd = "requestNativeFileSystem";
36   function get_file_system_id_success(data) {
37     var fs = IsolatedFileSystem.getIsolatedFileSystem(data.file_system_id);
38     success(fs);
39   }
40   postMessage(msg, get_file_system_id_success, error);
41 }
42
43 var getDirectoryList = function() {
44   extension.internal.sendSyncMessage("get");
45 }
46
47 NativeFileSystem.prototype = new Object();
48 NativeFileSystem.prototype.constructor = NativeFileSystem;
49 NativeFileSystem.prototype.requestNativeFileSystem = requestNativeFileSystem;
50 NativeFileSystem.prototype.getDirectoryList = getDirectoryList;
51
52 exports = new NativeFileSystem();
53
54 function handlePromise(msgObj) {
55   if (msgObj.data.error) {
56     if (_isFunction(_promises[msgObj._promise_id].reject)) {
57       _promises[msgObj._promise_id].reject(msgObj.data);
58     }
59   } else {
60     if (_isFunction(_promises[msgObj._promise_id].fulfill)) {
61       _promises[msgObj._promise_id].fulfill(msgObj.data);
62     }
63   }
64   delete _promises[msgObj._promise_id];
65 }
66
67 extension.setMessageListener(function(msgStr) {
68   // TODO(shawngao5): This part of code should be refactored.
69   // Follow DeviceCapability extension way to implement.
70   var msgObj = JSON.parse(msgStr);
71   switch (msgObj.cmd) {
72     case "requestNativeFileSystem_ret":
73       handlePromise(msgObj);
74     default:
75       break;
76   }
77 });