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