Merge "[Calendar] Fix for reccurrence rule." into tizen_2.4
[platform/core/api/webapi-plugins.git] / src / download / download_api.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 validator_ = xwalk.utils.validator;
18 var types_ = validator_.Types;
19 var check_ = xwalk.utils.type;
20
21
22 var callbackId = 0;
23 var callbacks = {};
24 var requests = {};
25
26
27 extension.setMessageListener(function(json) {
28
29   var result = JSON.parse(json);
30   var callback = callbacks[result.callbackId];
31   //console.log("PostMessage received: " + result.status);
32
33   if (!callback) {
34     console.logd('Ignoring unknown callback: ' + result.callbackId);
35     return;
36   }
37   setTimeout(function() {
38     if (result.status == 'progress') {
39       if (callback.onprogress) {
40         var receivedSize = result.receivedSize;
41         var totalSize = result.totalSize;
42         callback.onprogress(result.callbackId, receivedSize, totalSize);
43       }
44     } else if (result.status == 'paused') {
45       if (callback.onpaused) {
46         callback.onpaused(result.callbackId);
47       }
48     } else if (result.status == 'canceled') {
49       if (callback.oncanceled) {
50         callback.oncanceled(result.callbackId);
51       }
52     } else if (result.status == 'completed') {
53       if (callback.oncompleted) {
54         var fullPath = result.fullPath;
55         callback.oncompleted(result.callbackId, fullPath);
56       }
57     } else if (result.status == 'error') {
58       if (callback.onfailed) {
59         callback.onfailed(result.callbackId,
60             new WebAPIException(result.error));
61       }
62     }
63   }, 0);
64 });
65
66 function nextCallbackId() {
67   return ++callbackId;
68 }
69
70 function callNative(cmd, args) {
71   var json = {'cmd': cmd, 'args': args};
72   var argjson = JSON.stringify(json);
73   var resultString = extension.internal.sendSyncMessage(argjson);
74   var result = JSON.parse(resultString);
75
76   if (typeof result !== 'object') {
77     throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
78   }
79
80   if (result.status == 'success') {
81     if (result.result) {
82       return result.result;
83     }
84     return true;
85   } else if (result.status == 'error') {
86     var err = result.error;
87     if (err) {
88       throw new WebAPIException(err);
89     }
90     return false;
91   }
92 }
93
94
95 function callNativeWithCallback(cmd, args, callback) {
96   if (callback) {
97     var id = nextCallbackId();
98     args.callbackId = id;
99     callbacks[id] = callback;
100   }
101
102   return callNative(cmd, args);
103 }
104
105 function SetReadOnlyProperty(obj, n, v) {
106   Object.defineProperty(obj, n, {value: v, writable: false});
107 }
108
109 var DownloadState = {
110   'QUEUED': 'QUEUED',
111   'DOWNLOADING': 'DOWNLOADING',
112   'PAUSED': 'PAUSED',
113   'CANCELED': 'CANCELED',
114   'COMPLETED': 'COMPLETED',
115   'FAILED': 'FAILED'
116 };
117
118 var DownloadNetworkType = {
119   'CELLULAR': 'CELLULAR',
120   'WIFI': 'WIFI',
121   'ALL': 'ALL'
122 };
123
124 tizen.DownloadRequest = function(url, destination, fileName, networkType, httpHeader) {
125   validator_.isConstructorCall(this, tizen.DownloadRequest);
126
127   var url_ = url;
128   var networkType_;
129
130   if (networkType === undefined || !(networkType in DownloadNetworkType)) {
131     networkType_ = 'ALL';
132   } else {
133     networkType_ = networkType;
134   }
135
136   Object.defineProperties(this, {
137     'url': {
138       enumerable: true,
139       get: function() {
140         return url_;
141       },
142       set: function(value) {
143         if (value !== null) {
144           url_ = value;
145         }
146       },
147     },
148     'destination': {
149       writable: true,
150       enumerable: true,
151       value: destination === undefined ? '' : destination,
152     },
153     'fileName': {
154       writable: true,
155       enumerable: true,
156       value: fileName === undefined ? '' : fileName,
157     },
158     'networkType': {
159       enumerable: true,
160       get: function() {
161         return networkType_;
162       },
163       set: function(value) {
164         if (value === null || value in DownloadNetworkType) {
165           networkType_ = value;
166         }
167       },
168     },
169     'httpHeader': {
170       writable: true,
171       enumerable: true,
172       value: httpHeader === undefined ? {} : httpHeader,
173     }
174   });
175 };
176
177
178 function DownloadManager() {
179   // constructor of DownloadManager
180 }
181
182 DownloadManager.prototype.start = function() {
183   xwalk.utils.checkPrivilegeAccess(xwalk.utils.privilege.DOWNLOAD);
184
185   var args = validator_.validateArgs(arguments, [
186     {'name' : 'downloadRequest', 'type': types_.PLATFORM_OBJECT, 'values': tizen.DownloadRequest},
187     {'name' : 'downloadCallback', 'type': types_.LISTENER,
188       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
189       optional: true, nullable: true}
190   ]);
191
192   var nativeParam = {
193     'url': args.downloadRequest.url,
194     'destination': args.downloadRequest.destination,
195     'fileName': args.downloadRequest.fileName,
196     'networkType': args.downloadRequest.networkType,
197     'httpHeader': args.downloadRequest.httpHeader,
198     'callbackId': nextCallbackId()
199   };
200
201   if (args.downloadCallback) {
202     this.setListener(nativeParam.callbackId, args.downloadCallback);
203   }
204
205   try {
206     callNative('DownloadManager_start', nativeParam);
207   } catch (e) {
208     if ('NetworkError' === e.name) {
209       return -1;
210     }
211     throw e;
212   }
213
214   requests[nativeParam.callbackId] = args.downloadRequest;
215
216   return nativeParam.callbackId;
217 };
218
219 DownloadManager.prototype.cancel = function() {
220   var args = validator_.validateArgs(arguments, [
221     {name: 'downloadId', type: types_.LONG, 'nullable': false, 'optional': false}
222   ]);
223
224   var nativeParam = {
225     'downloadId': args.downloadId
226   };
227
228   if (typeof requests[args.downloadId] === 'undefined')
229     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
230         'the identifier does not match any download operation in progress');
231
232   try {
233     callNative('DownloadManager_cancel', nativeParam);
234   } catch (e) {
235     throw e;
236   }
237 };
238
239 DownloadManager.prototype.pause = function() {
240   var args = validator_.validateArgs(arguments, [
241     {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
242   ]);
243
244   var nativeParam = {
245     'downloadId': args.downloadId
246   };
247
248   if (typeof requests[args.downloadId] === 'undefined')
249     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
250         'the identifier does not match any download operation in progress');
251
252   try {
253     callNative('DownloadManager_pause', nativeParam);
254   } catch (e) {
255     throw e;
256   }
257 };
258
259 DownloadManager.prototype.resume = function() {
260   var args = validator_.validateArgs(arguments, [
261     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
262   ]);
263
264   var nativeParam = {
265     'downloadId': args.downloadId
266   };
267
268   if (typeof requests[args.downloadId] === 'undefined')
269     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
270         'the identifier does not match any download operation in progress');
271
272   try {
273     callNative('DownloadManager_resume', nativeParam);
274   } catch (e) {
275     throw e;
276   }
277 };
278
279 DownloadManager.prototype.getState = function() {
280   var args = validator_.validateArgs(arguments, [
281     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
282   ]);
283
284   var nativeParam = {
285     'downloadId': args.downloadId
286   };
287
288   if (typeof requests[args.downloadId] === 'undefined')
289     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
290         'the identifier does not match any download operation in progress');
291
292   try {
293     return callNative('DownloadManager_getState', nativeParam);
294   } catch (e) {
295     throw e;
296   }
297 };
298
299 DownloadManager.prototype.getDownloadRequest = function() {
300   var args = validator_.validateArgs(arguments, [
301     {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
302   ]);
303
304   if (typeof requests[args.downloadId] === 'undefined')
305     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
306         'the identifier does not match any download operation in progress');
307
308   return requests[args.downloadId];
309 };
310
311 DownloadManager.prototype.getMIMEType = function() {
312   var args = validator_.validateArgs(arguments, [
313     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
314   ]);
315
316   var nativeParam = {
317     'downloadId': args.downloadId
318   };
319
320   if (typeof requests[args.downloadId] === 'undefined')
321     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
322         'the identifier does not match any download operation in progress');
323
324   try {
325     return callNative('DownloadManager_getMIMEType', nativeParam);
326   } catch (e) {
327     throw e;
328   }
329 };
330
331 DownloadManager.prototype.setListener = function() {
332   var args = validator_.validateArgs(arguments, [
333     {'name' : 'downloadId', 'type': types_.LONG},
334     {'name' : 'downloadCallback', 'type': types_.LISTENER,
335       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']}
336   ]);
337
338   callbacks[args.downloadId] = args.downloadCallback;
339 };
340
341
342
343 exports = new DownloadManager();
344