[Project] JS code formatting
[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 JSON_ = xwalk.JSON;
18 var privUtils_ = xwalk.utils;
19 var validator_ = xwalk.utils.validator;
20 var types_ = validator_.Types;
21 var check_ = xwalk.utils.type;
22 var converter_ = xwalk.utils.converter;
23
24 var callbackId = 0;
25 var callbacks = {};
26 var requests = {};
27
28 extension.setMessageListener(function(json) {
29     var result = JSON_.parse(json);
30     var callback = callbacks[result.callbackId];
31     //privUtils_.log("PostMessage received: " + result.status);
32
33     if (!callback) {
34         privUtils_.log('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, new WebAPIException(result.error));
60             }
61         }
62     }, 0);
63 });
64
65 function nextCallbackId() {
66     return ++callbackId;
67 }
68
69 function callNative(cmd, args) {
70     var json = { cmd: cmd, args: args };
71     var argjson = JSON_.stringify(json);
72     var resultString = extension.internal.sendSyncMessage(argjson);
73     var result = JSON_.parse(resultString);
74
75     if (typeof result !== 'object') {
76         throw new WebAPIException(WebAPIException.UNKNOWN_ERR);
77     }
78
79     if (result.status == 'success') {
80         if (result.result) {
81             return result.result;
82         }
83         return true;
84     } else if (result.status == 'error') {
85         var err = result.error;
86         if (err) {
87             throw new WebAPIException(err);
88         }
89         return false;
90     }
91 }
92
93 function callNativeWithCallback(cmd, args, callback) {
94     if (callback) {
95         var id = nextCallbackId();
96         args.callbackId = id;
97         callbacks[id] = callback;
98     }
99
100     return callNative(cmd, args);
101 }
102
103 function SetReadOnlyProperty(obj, n, v) {
104     Object.defineProperty(obj, n, { value: v, writable: false });
105 }
106
107 var DownloadState = {
108     QUEUED: 'QUEUED',
109     DOWNLOADING: 'DOWNLOADING',
110     PAUSED: 'PAUSED',
111     CANCELED: 'CANCELED',
112     COMPLETED: 'COMPLETED',
113     FAILED: 'FAILED'
114 };
115
116 var DownloadNetworkType = {
117     CELLULAR: 'CELLULAR',
118     WIFI: 'WIFI',
119     ALL: 'ALL'
120 };
121
122 tizen.DownloadRequest = function(url, destination, fileName, networkType, httpHeader) {
123     validator_.isConstructorCall(this, tizen.DownloadRequest);
124
125     var url_ = converter_.toString(url);
126     var destination_ = destination === undefined ? '' : converter_.toString(destination);
127     var fileName_ = fileName === undefined ? '' : converter_.toString(fileName);
128
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_ = converter_.toString(value);
146                 }
147             }
148         },
149         destination: {
150             enumerable: true,
151             get: function() {
152                 return destination_;
153             },
154             set: function(value) {
155                 if (value !== null) {
156                     destination_ = converter_.toString(value);
157                 }
158             }
159         },
160         fileName: {
161             enumerable: true,
162             get: function() {
163                 return fileName_;
164             },
165             set: function(value) {
166                 if (value !== null) {
167                     fileName_ = converter_.toString(value);
168                 }
169             }
170         },
171         networkType: {
172             enumerable: true,
173             get: function() {
174                 return networkType_;
175             },
176             set: function(value) {
177                 if (value === null || value in DownloadNetworkType) {
178                     networkType_ = value;
179                 }
180             }
181         },
182         httpHeader: {
183             writable: true,
184             enumerable: true,
185             value: httpHeader === undefined ? {} : httpHeader
186         }
187     });
188 };
189
190 function DownloadManager() {
191     // constructor of DownloadManager
192 }
193
194 DownloadManager.prototype.start = function() {
195     var args = validator_.validateArgs(arguments, [
196         {
197             name: 'downloadRequest',
198             type: types_.PLATFORM_OBJECT,
199             values: tizen.DownloadRequest
200         },
201         {
202             name: 'downloadCallback',
203             type: types_.LISTENER,
204             values: ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed'],
205             optional: true,
206             nullable: true
207         }
208     ]);
209
210     var nativeParam = {
211         url: args.downloadRequest.url,
212         destination: args.downloadRequest.destination,
213         fileName: args.downloadRequest.fileName,
214         networkType: args.downloadRequest.networkType,
215         httpHeader: args.downloadRequest.httpHeader,
216         callbackId: nextCallbackId()
217     };
218
219     if (args.downloadCallback) {
220         this.setListener(nativeParam.callbackId, args.downloadCallback);
221     }
222
223     try {
224         callNative('DownloadManager_start', nativeParam);
225     } catch (e) {
226         if ('NetworkError' === e.name) {
227             return -1;
228         }
229         throw e;
230     }
231
232     requests[nativeParam.callbackId] = args.downloadRequest;
233
234     return nativeParam.callbackId;
235 };
236
237 DownloadManager.prototype.cancel = 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(
248             WebAPIException.INVALID_VALUES_ERR,
249             'the identifier does not match any download operation in progress'
250         );
251
252     try {
253         callNative('DownloadManager_cancel', nativeParam);
254     } catch (e) {
255         throw e;
256     }
257 };
258
259 DownloadManager.prototype.pause = 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(
270             WebAPIException.INVALID_VALUES_ERR,
271             'the identifier does not match any download operation in progress'
272         );
273
274     try {
275         callNative('DownloadManager_pause', nativeParam);
276     } catch (e) {
277         throw e;
278     }
279 };
280
281 DownloadManager.prototype.resume = function() {
282     var args = validator_.validateArgs(arguments, [
283         { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
284     ]);
285
286     var nativeParam = {
287         downloadId: args.downloadId
288     };
289
290     if (typeof requests[args.downloadId] === 'undefined')
291         throw new WebAPIException(
292             WebAPIException.INVALID_VALUES_ERR,
293             'the identifier does not match any download operation in progress'
294         );
295
296     try {
297         callNative('DownloadManager_resume', nativeParam);
298     } catch (e) {
299         throw e;
300     }
301 };
302
303 DownloadManager.prototype.getState = function() {
304     var args = validator_.validateArgs(arguments, [
305         { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
306     ]);
307
308     var nativeParam = {
309         downloadId: args.downloadId
310     };
311
312     if (typeof requests[args.downloadId] === 'undefined')
313         throw new WebAPIException(
314             WebAPIException.INVALID_VALUES_ERR,
315             'the identifier does not match any download operation in progress'
316         );
317
318     try {
319         return callNative('DownloadManager_getState', nativeParam);
320     } catch (e) {
321         throw e;
322     }
323 };
324
325 DownloadManager.prototype.getDownloadRequest = function() {
326     var args = validator_.validateArgs(arguments, [
327         { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
328     ]);
329
330     if (typeof requests[args.downloadId] === 'undefined')
331         throw new WebAPIException(
332             WebAPIException.INVALID_VALUES_ERR,
333             'the identifier does not match any download operation in progress'
334         );
335
336     return requests[args.downloadId];
337 };
338
339 DownloadManager.prototype.getMIMEType = function() {
340     var args = validator_.validateArgs(arguments, [
341         { name: 'downloadId', type: types_.LONG, nullable: false, optional: false }
342     ]);
343
344     var nativeParam = {
345         downloadId: args.downloadId
346     };
347
348     if (typeof requests[args.downloadId] === 'undefined')
349         throw new WebAPIException(
350             WebAPIException.INVALID_VALUES_ERR,
351             'the identifier does not match any download operation in progress'
352         );
353
354     try {
355         return callNative('DownloadManager_getMIMEType', nativeParam);
356     } catch (e) {
357         throw e;
358     }
359 };
360
361 DownloadManager.prototype.setListener = function() {
362     var args = validator_.validateArgs(arguments, [
363         { name: 'downloadId', type: types_.LONG },
364         {
365             name: 'downloadCallback',
366             type: types_.LISTENER,
367             values: ['onprogress', 'onpaused', 'oncanceled', 'oncompleted', 'onfailed']
368         }
369     ]);
370
371     callbacks[args.downloadId] = args.downloadCallback;
372 };
373
374 exports = new DownloadManager();