Updated GhostCluster web sample from upstream
[profile/ivi/sdk/web-sample-build.git] / samples / web / Sample / Tizen / Web App / ModelloAppManager / project / js / packagerepository.js
1 /*global Config, StoreLibrary, _applicationDetail, installedApps */
2
3 /**
4  * Provides Javascript wrapper around AJAX-based requests to package server providing categories, lists of applications,
5  * download (using [tizen.download API](https://developer.tizen.org/dev-guide/2.2.1/org.tizen.web.device.apireference/tizen/download.html))
6  * and allows installation or uninstallation of downloaded packages through
7  * [tizen.package API](https://developer.tizen.org/dev-guide/2.2.1/org.tizen.web.device.apireference/tizen/package.html).
8  *
9  * @class PackageRepository
10  * @module StoreApplication
11  **/
12
13 /**
14  * object holding info about applications available on the server as well as apps installed in the system
15  * @property AppModel
16  * @static
17  **/
18 var AppModel = [];
19
20 var PackageRepository = (function() {
21     "use strict";
22     function PackageRepository() {
23         console.info("Starting up PackageRepository");
24     }
25
26     PackageRepository.prototype = function() {};
27
28     PackageRepository.prototype._storage = "downloads";
29
30     /**
31      * Gets only promoted applications from list of available apps
32      * @method getPromotedApplications
33      * @param callback {Function(results)} Callback function providing array of promoted applications.
34      **/
35         PackageRepository.prototype.getPromotedApplications = function (callback) {
36         if (AppModel.length === 0) {
37             this.availableApplications(function () {
38                 var result = AppModel.filter(function (app) {
39                     return app.isPromoted === true;
40                 });
41                 if (callback) {
42                     callback(result);
43                 } else {
44                     return result;
45                 }
46             });
47         } else {
48             var result = AppModel.filter(function (app) {
49                 return app.isPromoted === true;
50             });
51             if (callback) {
52                 callback(result);
53             } else {
54                 return result;
55             }
56         }
57         };
58
59     /**
60      * Gets only popular applications from list of available apps
61      * @method getPopularApplications
62      * @param callback {Function(results)} Callback function providing array of popular applications.
63      **/
64         PackageRepository.prototype.getPopularApplications = function (callback) {
65                 var result = AppModel.filter(function (app) {
66             return app.isPopular === true;
67         });
68                 if (callback) {
69                         callback(result);
70                 } else {
71                         return result;
72                 }
73         };
74
75     /**
76      * Gets list of available categories from package server.
77      * @method getCategories
78      * @param callback {Function(results)} Callback function providing array of categories.
79      * @param errorCallback {Function(error)} Callback function providing error in case if any issue was detected.
80      **/
81         PackageRepository.prototype.getCategories = function (callback, errorCallback) {
82         $.ajax({
83             type: 'GET',
84             url: Config.httpPrefix + '/packages/categories',
85             dataType: 'json',
86             async: true,
87             username: Config.username,
88             password: Config.pwd,
89             data:'{}'
90             }).done(function(resCategories) {
91                 console.log('categories: ' + JSON.stringify(resCategories));
92                 if (callback) {
93                     callback(resCategories);
94                 } else {
95                     return resCategories;
96                 }
97         }).fail(function (jqXHR, textStatus) {
98             console.log('getCategories fail: ' + textStatus);
99             if (errorCallback) {
100                 errorCallback();
101             }
102         });
103
104         };
105
106     /**
107      * Gets only applications beloging to specified category from list of available apps
108      * @method getCategoryApplications
109      * @param catId {String} Category identifier.
110      * @param callback {Function(results)} Callback function providing array of popular applications.
111      **/
112         PackageRepository.prototype.getCategoryApplications = function (catId, callback) {
113                 var result = AppModel.filter(function (app) {
114             /* jshint camelcase: false */
115             var res = app.category_id === catId;
116             /* jshint camelcase: true */
117             return res;
118         });
119                 if (callback) {
120                         callback(result);
121                 } else {
122                         return result;
123                 }
124         };
125
126     /**
127      * Gets all application data for specified application.
128      * @method getApplicationDetail
129      * @param appId {String} Application identifier.
130      * @param callback {Function(result)} Callback function providing array of popular applications.
131      **/
132         PackageRepository.prototype.getApplicationDetail = function (appId, callback) {
133                 var result = AppModel.filter(function (app) {
134              return app.id === appId;
135         });
136                 if (callback) {
137                         callback(result);
138                 } else {
139                         return result;
140                 }
141         };
142
143     /**
144      * Gets list of available applications from package server.
145      * @method availableApplications
146      * @param callback {Function(results)} Callback function providing array of applications.
147      * @param errorCallback {Function(error)} Callback function providing error in case if any issue was detected.
148      **/
149     PackageRepository.prototype.availableApplications = function (callback, errorCallback) {
150         $.ajax({
151             type: 'GET',
152             url: Config.httpPrefix + '/packages/available',
153             dataType: 'json',
154             async: true,
155             username: Config.username,
156             password: Config.pwd,
157             data:'{}'
158         }).done(function(resp) {
159                 if (callback) {
160                     callback(resp);
161                 }
162         }).fail(function (jqXHR, textStatus) {
163                 console.log('availableApplications fail: ' + textStatus);
164                 if (errorCallback) {
165                     errorCallback();
166                 }
167         });
168     };
169
170
171     /**
172      * Starts package download identified by applidation identifier via [tizen.download API]()
173      * @method downloadApplication
174      * @param appId {String} Application Id
175      * @param callback {Function(error, appId, packageUri)} Callback function providing information about status about download.
176      **/
177     PackageRepository.prototype.downloadApplication = function (appId, callback) {
178         var listener = {
179             onprogress: function(id, receivedSize, totalSize) {
180                 console.log('Received with id: ' + id + ', ' + receivedSize + '/' + totalSize);
181             },
182             onpaused: function(id) {
183                 console.log('Paused with id: ' + id);
184             },
185             oncanceled: function(id) {
186                 console.log('Canceled with id: ' + id);
187             },
188             oncompleted: function(id, fullPath) {
189                 console.log('Completed with id: ' + id + ', full path: ' + fullPath);
190                 tizen.filesystem.resolve(fullPath, function (file) {
191                     callback(null, id, file.toURI());
192                 });
193             },
194             onfailed: function(id, error) {
195                 console.log('Failed with id: ' + id + ', error name: ' + error.name);
196             }
197         };
198
199         // Starts downloading of the file from the Web with the corresponding callbacks.
200         var downloadRequest = new tizen.DownloadRequest("http://"+Config.username+":"+Config.pwd+"@localhost:80" + _applicationDetail.downloadUrl, "downloads", appId.split("/").pop() + ".wgt");
201
202         var downloadId = tizen.download.start(downloadRequest, listener);
203     };
204
205     /**
206      * Provides list of installed application using [tizen application API]().
207      * @method getAppsInfo
208      * @param callback {Function(results)} Callback function providing array of installed applications.
209      **/
210     PackageRepository.prototype.getAppsInfo = function (callback) {
211         try {
212             tizen.application.getAppsInfo(function (installedAppData) {
213                 callback(installedAppData);
214             }, function(err) {
215                 console.log('Failed to get installed apps info.');
216             });
217         } catch (exc) {
218             console.error(exc.message);
219         }
220     };
221
222     /**
223      * Method performs installation of specified application ID using [tizen package API]() by following process:
224      *
225      * * download package
226      * * install package
227      * * cleanup of downloaded package
228      *
229      * @method install
230      * @param appId application Id
231      * @param callback {Function(error)} Callback function invoked after installation is finished or error occurs.
232      **/
233     PackageRepository.prototype.install = function (appId, callback) {
234         var installationFile;
235         var self = this;
236         callback = callback || function() {};
237
238         var cleanup = function(err) {
239             console.log("Removing installation file " + installationFile);
240             tizen.filesystem.resolve(self._storage, function(directory) {
241                 directory.deleteFile(installationFile,
242                     function() {
243                         self.getAppsInfo(function (appsInfo) {
244                             installedApps = appsInfo;
245                             callback(err);
246                         });
247                     },
248                     function(error) { callback(err || error); }
249                 );
250             });
251         };
252
253         var onInstallation = {
254             onprogress: function(packageId, percentage) {
255                 console.log("On installation(" + packageId + ") : progress(" + percentage + ")");
256                 StoreLibrary.displayInstallProgress(true, percentage);
257             },
258             oncomplete: function(packageId) {
259                 console.log("Installation(" + packageId + ") Complete");
260                 cleanup();
261                 this.getAppsInfo(function (appsInfo) {
262                     installedApps = appsInfo;
263                     callback();
264                 });
265             }
266         };
267
268         var onError = function (err) {
269             console.error("Error occurred on installation : " + err.name);
270             callback(err);
271         };
272
273         this.downloadApplication(appId, function(error, fileName, fullPath) {
274             if (error) {
275                 this.cleanup(error);
276             } else {
277                 installationFile = fullPath;
278                 tizen.package.install(fullPath, onInstallation, onError);
279             }
280         });
281     };
282
283     /**
284      * Method performs uninstallation of specified application ID using [tizen package API]()
285      *
286      * @method uninstall
287      * @param appId application Id
288      * @param callback {Function(error)} Callback function invoked after installation is finished or error occurs.
289      **/
290     PackageRepository.prototype.uninstall = function (appId, callback) {
291         var onInstallation = {
292             onprogress: function(packageId, percentage) {
293                 console.log("On uninstallation(" + packageId + ") : progress(" + percentage + ")");
294                 StoreLibrary.displayInstallProgress(false, percentage);
295             },
296             oncomplete: function(packageId) {
297                 console.log("Uninstallation(" + packageId + ") Complete");
298                 if (callback) {
299                     callback(true);
300                 }
301             }
302         };
303
304         var onError = function (err) {
305             console.log("Error occurred on uninstallation : " + err.name);
306             if (callback) {
307                 callback(false);
308             }
309         };
310         var uninstPackageName = this.getPackageId(_applicationDetail.name);
311         console.log("Trying to uninstall "+ _applicationDetail.name);
312         if (uninstPackageName === undefined) {
313             console.log("Package name not available.");
314         } else {
315             tizen.package.uninstall(uninstPackageName, onInstallation, onError);
316         }
317     };
318
319     /**
320      * Function returns package id for specified application name.
321      * @method getPackageId
322      * @param appName {String} Application name
323      **/
324     PackageRepository.prototype.getPackageId = function (appName) {
325         for (var i in installedApps) {
326             if (installedApps[i].name === appName) {
327                 return installedApps[i].packageId;
328             }
329         }
330     };
331
332         return PackageRepository;
333 }());