Merge "Revert "[Bookmark] Moved checking privileges to JS layer."" into tizen_3.0
[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   var args = validator_.validateArgs(arguments, [
184     {'name' : 'downloadRequest', 'type': types_.PLATFORM_OBJECT, 'values': tizen.DownloadRequest},
185     {'name' : 'downloadCallback', 'type': types_.LISTENER,
186       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
187       optional: true, nullable: true}
188   ]);
189
190   var nativeParam = {
191     'url': args.downloadRequest.url,
192     'destination': args.downloadRequest.destination,
193     'fileName': args.downloadRequest.fileName,
194     'networkType': args.downloadRequest.networkType,
195     'httpHeader': args.downloadRequest.httpHeader,
196     'callbackId': nextCallbackId()
197   };
198
199   if (args.downloadCallback) {
200     this.setListener(nativeParam.callbackId, args.downloadCallback);
201   }
202
203   try {
204     callNative('DownloadManager_start', nativeParam);
205   } catch (e) {
206     if ('NetworkError' === e.name) {
207       return -1;
208     }
209     throw e;
210   }
211
212   requests[nativeParam.callbackId] = args.downloadRequest;
213
214   return nativeParam.callbackId;
215 };
216
217 DownloadManager.prototype.cancel = function() {
218   var args = validator_.validateArgs(arguments, [
219     {name: 'downloadId', type: types_.LONG, 'nullable': false, 'optional': false}
220   ]);
221
222   var nativeParam = {
223     'downloadId': args.downloadId
224   };
225
226   if (typeof requests[args.downloadId] === 'undefined')
227     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
228         'the identifier does not match any download operation in progress');
229
230   try {
231     callNative('DownloadManager_cancel', nativeParam);
232   } catch (e) {
233     throw e;
234   }
235 };
236
237 DownloadManager.prototype.pause = function() {
238   var args = validator_.validateArgs(arguments, [
239     {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
240   ]);
241
242   var nativeParam = {
243     'downloadId': args.downloadId
244   };
245
246   if (typeof requests[args.downloadId] === 'undefined')
247     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
248         'the identifier does not match any download operation in progress');
249
250   try {
251     callNative('DownloadManager_pause', nativeParam);
252   } catch (e) {
253     throw e;
254   }
255 };
256
257 DownloadManager.prototype.resume = function() {
258   var args = validator_.validateArgs(arguments, [
259     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
260   ]);
261
262   var nativeParam = {
263     'downloadId': args.downloadId
264   };
265
266   if (typeof requests[args.downloadId] === 'undefined')
267     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
268         'the identifier does not match any download operation in progress');
269
270   try {
271     callNative('DownloadManager_resume', nativeParam);
272   } catch (e) {
273     throw e;
274   }
275 };
276
277 DownloadManager.prototype.getState = function() {
278   var args = validator_.validateArgs(arguments, [
279     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
280   ]);
281
282   var nativeParam = {
283     'downloadId': args.downloadId
284   };
285
286   if (typeof requests[args.downloadId] === 'undefined')
287     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
288         'the identifier does not match any download operation in progress');
289
290   try {
291     return callNative('DownloadManager_getState', nativeParam);
292   } catch (e) {
293     throw e;
294   }
295 };
296
297 DownloadManager.prototype.getDownloadRequest = function() {
298   var args = validator_.validateArgs(arguments, [
299     {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
300   ]);
301
302   if (typeof requests[args.downloadId] === 'undefined')
303     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
304         'the identifier does not match any download operation in progress');
305
306   return requests[args.downloadId];
307 };
308
309 DownloadManager.prototype.getMIMEType = function() {
310   var args = validator_.validateArgs(arguments, [
311     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
312   ]);
313
314   var nativeParam = {
315     'downloadId': args.downloadId
316   };
317
318   if (typeof requests[args.downloadId] === 'undefined')
319     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
320         'the identifier does not match any download operation in progress');
321
322   try {
323     return callNative('DownloadManager_getMIMEType', nativeParam);
324   } catch (e) {
325     throw e;
326   }
327 };
328
329 DownloadManager.prototype.setListener = function() {
330   var args = validator_.validateArgs(arguments, [
331     {'name' : 'downloadId', 'type': types_.LONG},
332     {'name' : 'downloadCallback', 'type': types_.LISTENER,
333       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']}
334   ]);
335
336   callbacks[args.downloadId] = args.downloadCallback;
337 };
338
339
340
341 exports = new DownloadManager();
342