Merge branch 'tizen_4.0' into tizen
[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 privUtils_ = xwalk.utils;
18 var validator_ = xwalk.utils.validator;
19 var types_ = validator_.Types;
20 var converter_ = xwalk.utils.converter;
21 var native_ = new xwalk.utils.NativeManager(extension);
22
23 var DOWNLOAD_MANAGER_LISTENER_ID = 'DownloadManagerListener';
24
25 var downloadId = 0;
26 var callbacks = {};
27 var requests = {};
28
29 function DownloadManagerChangeCallback(result) {
30   var callback = callbacks[result.downloadId];
31
32   if (!callback) {
33     privUtils_.log('Ignoring unknown callback: ' + result.downloadId);
34     return;
35   }
36   setTimeout(function() {
37     if (result.status == 'progress') {
38       if (callback.onprogress) {
39         var receivedSize = result.receivedSize;
40         var totalSize = result.totalSize;
41         callback.onprogress(result.downloadId, receivedSize, totalSize);
42       }
43     } else if (result.status == 'paused') {
44       if (callback.onpaused) {
45         callback.onpaused(result.downloadId);
46       }
47     } else if (result.status == 'canceled') {
48       if (callback.oncanceled) {
49         callback.oncanceled(result.downloadId);
50         delete callbacks[result.downloadId];
51       }
52     } else if (result.status == 'completed') {
53       if (callback.oncompleted) {
54         var fullPath = result.fullPath;
55         callback.oncompleted(result.downloadId, fullPath);
56         delete callbacks[result.downloadId];
57       }
58     } else if (result.status == 'error') {
59       if (callback.onfailed) {
60         callback.onfailed(result.downloadId,
61             new WebAPIException(result.error));
62         delete callbacks[result.downloadId];
63       }
64     }
65   }, 0);
66 }
67
68 function nextDownloadId() {
69   return ++downloadId;
70 }
71
72 function SetReadOnlyProperty(obj, n, v) {
73   Object.defineProperty(obj, n, {value: v, writable: false});
74 }
75
76 var DownloadState = {
77   'QUEUED': 'QUEUED',
78   'DOWNLOADING': 'DOWNLOADING',
79   'PAUSED': 'PAUSED',
80   'CANCELED': 'CANCELED',
81   'COMPLETED': 'COMPLETED',
82   'FAILED': 'FAILED'
83 };
84
85 var DownloadNetworkType = {
86   'CELLULAR': 'CELLULAR',
87   'WIFI': 'WIFI',
88   'ALL': 'ALL'
89 };
90
91 tizen.DownloadRequest = function(url, destination, fileName, networkType, httpHeader) {
92   validator_.isConstructorCall(this, tizen.DownloadRequest);
93
94   var url_ = converter_.toString(url);
95   var destination_ = destination === undefined ? '' : converter_.toString(destination);
96   var fileName_ = fileName === undefined ? '' : converter_.toString(fileName);
97
98   var networkType_;
99
100   if (networkType === undefined || !(networkType in DownloadNetworkType)) {
101     networkType_ = 'ALL';
102   } else {
103     networkType_ = networkType;
104   }
105
106   Object.defineProperties(this, {
107     'url': {
108       enumerable: true,
109       get: function() {
110         return url_;
111       },
112       set: function(value) {
113         if (value !== null) {
114           url_ = converter_.toString(value);
115         }
116       },
117     },
118     'destination': {
119       enumerable: true,
120       get: function() {
121         return destination_;
122       },
123       set: function(value) {
124         if (value !== null) {
125           destination_ = converter_.toString(value);
126         }
127       },
128     },
129     'fileName': {
130       enumerable: true,
131       get: function() {
132         return fileName_;
133       },
134       set: function(value) {
135         if (value !== null) {
136           fileName_ = converter_.toString(value);
137         }
138       },
139     },
140     'networkType': {
141       enumerable: true,
142       get: function() {
143         return networkType_;
144       },
145       set: function(value) {
146         if (value === null || value in DownloadNetworkType) {
147           networkType_ = value;
148         }
149       },
150     },
151     'httpHeader': {
152       writable: true,
153       enumerable: true,
154       value: httpHeader === undefined ? {} : httpHeader,
155     }
156   });
157 };
158
159
160 function DownloadManager() {
161   // constructor of DownloadManager
162 }
163
164 DownloadManager.prototype.start = function() {
165   var args = validator_.validateArgs(arguments, [
166     {'name' : 'downloadRequest', 'type': types_.PLATFORM_OBJECT, 'values': tizen.DownloadRequest},
167     {'name' : 'downloadCallback', 'type': types_.LISTENER,
168       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
169       optional: true, nullable: true}
170   ]);
171
172   var nativeParam = {
173     'url': args.downloadRequest.url,
174     'destination': args.downloadRequest.destination,
175     'fileName': args.downloadRequest.fileName,
176     'networkType': args.downloadRequest.networkType,
177     'httpHeader': args.downloadRequest.httpHeader,
178     'downloadId': nextDownloadId()
179   };
180
181   if (args.downloadCallback) {
182     this.setListener(nativeParam.downloadId, args.downloadCallback);
183   }
184
185   var result = native_.callSync('DownloadManager_start', nativeParam);
186
187   if (native_.isFailure(result)) {
188     if ('NetworkError' === result.error.name) {
189       return -1;
190     }
191     throw native_.getErrorObject(result);
192   }
193
194   requests[nativeParam.downloadId] = args.downloadRequest;
195
196   return nativeParam.downloadId;
197 };
198
199 DownloadManager.prototype.cancel = function() {
200   var args = validator_.validateArgs(arguments, [
201     {name: 'downloadId', type: types_.LONG, 'nullable': false, 'optional': false}
202   ]);
203
204   var nativeParam = {
205     'downloadId': args.downloadId
206   };
207
208   if (typeof requests[args.downloadId] === 'undefined')
209     throw new WebAPIException(WebAPIException.INVALID_VALUES_ERR,
210         'the identifier does not match any download operation in progress');
211
212   var result = native_.callSync('DownloadManager_cancel', nativeParam);
213
214   if (native_.isFailure(result)) {
215     throw native_.getErrorObject(result);
216   }
217 };
218
219 DownloadManager.prototype.pause = 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   var result = native_.callSync('DownloadManager_pause', nativeParam);
233
234   if (native_.isFailure(result)) {
235     throw native_.getErrorObject(result);
236   }
237 };
238
239 DownloadManager.prototype.resume = 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   var result = native_.callSync('DownloadManager_resume', nativeParam);
253
254   if (native_.isFailure(result)) {
255     throw native_.getErrorObject(result);
256   }
257 };
258
259 DownloadManager.prototype.getState = 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   var result = native_.callSync('DownloadManager_getState', nativeParam);
273
274   if (native_.isSuccess(result)) {
275     return native_.getResultObject(result);
276   } else {
277     throw native_.getErrorObject(result);
278   }
279 };
280
281 DownloadManager.prototype.getDownloadRequest = function() {
282   var args = validator_.validateArgs(arguments, [
283     {'name': 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
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   return requests[args.downloadId];
291 };
292
293 DownloadManager.prototype.getMIMEType = function() {
294   var args = validator_.validateArgs(arguments, [
295     {'name' : 'downloadId', 'type': types_.LONG, 'nullable': false, 'optional': false}
296   ]);
297
298   var nativeParam = {
299     'downloadId': args.downloadId
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   var result = native_.callSync('DownloadManager_getMIMEType', nativeParam);
307
308   if (native_.isSuccess(result)) {
309     return native_.getResultObject(result);
310   } else {
311     throw native_.getErrorObject(result);
312   }
313 };
314
315 DownloadManager.prototype.setListener = function() {
316   var args = validator_.validateArgs(arguments, [
317     {'name' : 'downloadId', 'type': types_.LONG},
318     {'name' : 'downloadCallback', 'type': types_.LISTENER,
319       'values' : ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']}
320   ]);
321
322   if (!native_.isListenerSet(DOWNLOAD_MANAGER_LISTENER_ID)) {
323     native_.addListener(DOWNLOAD_MANAGER_LISTENER_ID, DownloadManagerChangeCallback);
324   }
325   callbacks[args.downloadId] = args.downloadCallback;
326 };
327
328 exports = new DownloadManager();