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