| 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867 |
1×
| /* ---------------------------------------------------------- *\
* PACKAGE FACTORY
* PackageService
*
* Provide all the function and the metadata for the routes and
* packages
* Every function does not return directly a value but emit an
* event to notify the update of the specified data
* Make sure to listen to the specific event to update your data
* The data will be emitted twice, one for the instant data (not
* yet updated) and one for the final updated data (that are
* emitted after some time)
*
* @example
* getRoutes() update the packages object and notify everyone
* the updated values
\* ---------------------------------------------------------- */
angular.module('webmapp')
.factory('PackageService', function PackageService(
$http,
$rootScope,
$ionicLoading,
$ionicModal,
$ionicPopup,
$translate,
CONFIG,
Auth,
Communication,
GeolocationService,
MapService,
Offline,
Utils
) {
var packageService = {};
var communicationConf = CONFIG.COMMUNICATION,
// currentLang = $translate.preferredLanguage() ? $translate.preferredLanguage() : 'it',
defaultLang = CONFIG.MAIN ? (CONFIG.MAIN.LANGUAGES && CONFIG.MAIN.LANGUAGES.actual ? CONFIG.MAIN.LANGUAGES.actual.substring(0, 2) : "it") :
((CONFIG.LANGUAGES && CONFIG.LANGUAGES.actual) ? CONFIG.LANGUAGES.actual.substring(0, 2) : 'it');
var packages = localStorage.$wm_packages ? JSON.parse(localStorage.$wm_packages) : null,
userPackagesId = localStorage.$wm_userPackagesId ? JSON.parse(localStorage.$wm_userPackagesId) : null,
userDownloadedPackages = {},
packagesToActivate = localStorage.$wm_packagesToActivate ? JSON.parse(localStorage.$wm_packagesToActivate) : [],
taxonomy = localStorage.$wm_taxonomy ? JSON.parse(localStorage.$wm_taxonomy) : {
activity: null,
theme: null,
when: null,
where: null,
who: null
};
var updated = {
packages: false,
taxonomy: {
activity: false,
theme: false,
when: false,
where: false,
who: false
}
};
// To let update from old version
if (localStorage.$wm_userDownloadedPackages) {
userDownloadedPackages = JSON.parse(localStorage.$wm_userDownloadedPackages);
if (userDownloadedPackages) {
MapService.setItemInLocalStorage("$wm_userDownloadedPackages", JSON.stringify(userDownloadedPackages));
}
delete localStorage.$wm_userDownloadedPackages;
}
MapService.getItemFromLocalStorage("$wm_userDownloadedPackages")
.then(function (item) {
userDownloadedPackages = JSON.parse(item.data);
$rootScope.$emit("userDownloadedPackages-updated", userDownloadedPackages);
})
.catch(function (err) {
console.warn("$wm_userDownloadedPackages: " + err.message);
userDownloadedPackages = {};
});
var userData = Auth.isLoggedIn() ? Auth.getUserData() : null,
asyncTranslations = 0,
asyncRoutes = 0,
asyncRouteTranslations = 0;
var modalDownloadScope = $rootScope.$new(),
modalDownload = {};
modalDownloadScope.vm = {};
modalDownloadScope.vm.hide = function () {
modalDownload && modalDownload.hide();
};
$ionicModal.fromTemplateUrl(templateBasePath + 'js/modals/downloadModal.html', {
scope: modalDownloadScope,
animation: 'slide-in-up'
}).then(function (modalObj) {
modalDownload = modalObj;
});
//Keep userData updated
$rootScope.$on('logged-in', function () {
if (Auth.isLoggedIn()) {
userData = Auth.getUserData();
} else {
userData = null;
}
});
var activatePack = function (data) {
$http({
method: 'POST',
url: communicationConf.baseUrl + communicationConf.endpoint + 'purchase',
dataType: 'json',
crossDomain: true,
data: data,
headers: {
'Content-Type': 'application/json'
}
}).success(function (response) {
for (var i in packagesToActivate) {
if (+packagesToActivate[i] === +data.route_id) {
packagesToActivate.splice(i, 1);
break;
}
}
localStorage.$wm_packagesToActivate = JSON.stringify(packagesToActivate);
}).error(function (err) {
});
};
var activatePackages = function () {
if (!Auth.isLoggedIn()) {
return;
}
userData = Auth.getUserData();
for (var i in packagesToActivate) {
var data = {
user_id: userData.ID,
route_id: packagesToActivate[i]
};
activatePack(data);
userPackagesId[packagesToActivate[i]] = true;
}
$rootScope.$emit('userPackagesId-updated', userPackagesId);
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
};
var mergePackages = function (newPackages) {
var result = {};
var packId = 0;
for (var i in newPackages) {
if (i !== 'length') {
var packId = newPackages[i].id;
result[packId] = newPackages[i];
if (packages[packId]) {
result[packId].imgUrl = packages[packId].imgUrl ? packages[packId].imgUrl : "core/images/image-loading.gif";
if (packages[packId].localImageUrl) {
result[packId].localImageUrl = packages[packId].localImageUrl;
}
}
if (!result[packId].packageTitle) {
result[packId].packageTitle = {};
}
if (result[packId].wpml_current_locale && result[packId].title && result[packId].title.rendered) {
result[packId].packageTitle[result[packId].wpml_current_locale.substring(0, 2)] = result[packId].title.rendered;
}
else {
if (result[packId].title && result[packId].title.rendered) {
result[packId].packageTitle[defaultLang] = result[packId].title.rendered;
}
}
if (result[packId].wpml_translations) {
for (var p in result[packId].wpml_translations) {
if (result[packId].wpml_translations[p].locale) {
var lang = result[packId].wpml_translations[p].locale.substring(0, 2);
result[packId].packageTitle[lang] = result[packId].wpml_translations[p].post_title;
}
}
}
if (!result[packId].packageDescription) {
result[packId].packageDescription = {};
}
if (packages[packId] && packages[packId].packageDescription) {
result[packId].packageDescription = packages[packId].packageDescription;
}
if (result[packId].wpml_current_locale) {
result[packId].packageDescription[result[packId].wpml_current_locale.substring(0, 2)] = result[packId].content.rendered;
}
else if (result[packId].content && result[packId].content.rendered) {
result[packId].packageDescription[defaultLang] = result[packId].content.rendered;
}
}
}
packages = result;
};
var getImage = function (packId) {
if (!packages[packId].imgUrl) {
packages[packId].imgUrl = "core/images/image-loading.gif";
}
Communication.getJSON(communicationConf.baseUrl + communicationConf.wordPressEndpoint + 'media/' + packages[packId].featured_media)
.then(function (data) {
if (packages[packId].imgUrl !== data.media_details.sizes.thumbnail.source_url) {
packages[packId].imgUrl = data.media_details.sizes.thumbnail.source_url;
}
Communication.get(packages[packId].imgUrl)
.then(function (response) {
var imageDownloaded = response;
var urlCreator = window.URL || window.webkitURL;
packages[packId].localImageUrl = urlCreator.createObjectURL(imageDownloaded);
var reader = new FileReader();
reader.readAsDataURL(imageDownloaded);
reader.onloadend = function () {
base64data = reader.result;
packages[packId].localImageUrl = base64data;
asyncRoutes--;
if (asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
localStorage.$wm_packages = JSON.stringify(packages);
}
},
function (err) {
asyncRoutes--;
if (asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
console.warn("Error downloading image for " + packId)
});
localStorage.$wm_packages = JSON.stringify(packages);
},
function (err) {
asyncRoutes--;
if (asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
console.error('Unable to download images');
});
};
var getTranslatedRoute = function (id, apiId, lang) {
$.getJSON(CONFIG.COMMUNICATION.baseUrl + CONFIG.COMMUNICATION.wordPressEndpoint + 'route/' + apiId, function (data) {
packages[id].packageTitle[lang] = data.title.rendered;
packages[id].packageDescription[lang] = data.content.rendered;
asyncRouteTranslations--;
if (asyncRouteTranslations === 0 && asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
localStorage.$wm_packages = JSON.stringify(packages);
}).fail(function () {
asyncRouteTranslations--;
if (asyncRouteTranslations === 0 && asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
console.error('Route translation retrive error');
});
};
/**
* @description
* Update the packages start point to order the routes
* Emit the updated lists
*
* @event packages-updated
*/
var getRoutePoint = function () {
var baseUrl = communicationConf.baseUrl.replace(/http(s)?:\/\//, "");
var url = "https://api.webmapp.it/a/" + baseUrl + "geojson/route_index.geojson";
Communication.getJSON(url).then(function (data) {
for (var i in data.features) {
if (data.features[i].properties && data.features[i].properties.id) {
var id = data.features[i].properties.id;
if (packages[id] && data.features[i].geometry && data.features[i].geometry.coordinates && data.features[i].geometry.coordinates.length === 2) {
packages[id].startPoi = {
lat: data.features[i].geometry.coordinates[1],
long: data.features[i].geometry.coordinates[0]
}
}
}
}
$rootScope.$emit('packages-updated', {
packages: packages,
loading: asyncRoutes > 0
});
localStorage.$wm_packages = JSON.stringify(packages);
}, function (err) {
console.warn(err);
});
};
var getTaxonomyTranslated = function (taxonomyType, id, lang) {
Communication.getJSON(communicationConf.baseUrl + communicationConf.wordPressEndpoint + taxonomyType + '/' + id + '?lang=' + lang)
.then(function (data) {
taxonomy[taxonomyType][id].name[lang] = data.name;
taxonomy[taxonomyType][id].description[lang] = data.description;
asyncTranslations--;
if (asyncTranslations === 0) {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: false });
}
else {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: true });
}
localStorage.$wm_taxonomy = JSON.stringify(taxonomy);
})
.catch(function (err) {
asyncTranslations--;
if (asyncTranslations === 0) {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: false });
}
console.warn("Unable to update taxonomy. Using local data")
});
};
/**
* @description
* Update the packages and the categories list and
* Emit the updated lists
*
* @event packages-updated
*/
packageService.getRoutes = function (forceUpdate) {
//Prevent multiple requests
if (forceUpdate) {
updated.packages = false;
}
if (updated.packages) {
$rootScope.$emit('packages-updated', { packages: packages, loading: asyncRoutes > 0 || asyncTranslations > 0 });
return;
}
updated.packages = true;
if (packages) {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
Communication.getJSON(communicationConf.baseUrl + communicationConf.wordPressEndpoint + 'route/?per_page=100')
.then(function (data) {
if (!packages) {
packages = {};
}
mergePackages(data);
getRoutePoint();
asyncRoutes = 0;
asyncRouteTranslations = 0;
for (var i in packages) {
asyncRoutes++;
getImage(i);
for (var j in packages[i].wpml_translations) {
if (packages[i].wpml_translations[j].locale) {
asyncRouteTranslations++;
getTranslatedRoute(i, packages[i].wpml_translations[j].id, packages[i].wpml_translations[j].locale.substring(0, 2));
}
}
}
if (asyncRoutes === 0) {
$rootScope.$emit('packages-updated', { packages: packages, loading: false });
}
else {
$rootScope.$emit('packages-updated', { packages: packages, loading: true });
}
localStorage.$wm_packages = JSON.stringify(packages);
}, function (err) {
getRoutePoint();
if (!packages) {
console.warn("No routes available. Restart the app with an open connection");
}
});
};
/**
* @description
* Emit taxonomy of type [taxonomyType] updated
*
* @event taxonomy-[taxonomyType]-updated
*
* @param {string} taxonomyType
* the type of taxonomy to update
*/
packageService.getTaxonomy = function (taxonomyType, forceUpdate) {
if (forceUpdate) {
updated.taxonomy[taxonomyType] = false;
}
if (updated.taxonomy[taxonomyType]) {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: asyncTranslations !== 0 });
return;
}
updated.taxonomy[taxonomyType] = true;
if (taxonomy[taxonomyType]) {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: true });
}
Communication.getJSON(communicationConf.baseUrl + communicationConf.wordPressEndpoint + taxonomyType + '?per_page=100')
.then(function (data) {
asyncTranslations = 0;
taxonomy[taxonomyType] = {};
for (var i in data) {
if (data[i].count > 0) {
taxonomy[taxonomyType][data[i].id] = data[i];
if (CONFIG.LANGUAGES) {
var tmpName = taxonomy[taxonomyType][data[i].id].name;
taxonomy[taxonomyType][data[i].id].name = {};
taxonomy[taxonomyType][data[i].id].name[defaultLang] = tmpName;
delete tmpName;
var tmpDescription = taxonomy[taxonomyType][data[i].id].description;
taxonomy[taxonomyType][data[i].id].description = {};
taxonomy[taxonomyType][data[i].id].description[defaultLang] = tmpDescription;
delete tmpDescription;
if (CONFIG.LANGUAGES.available) {
for (var langId in CONFIG.LANGUAGES.available) {
asyncTranslations++;
getTaxonomyTranslated(taxonomyType, data[i].id, CONFIG.LANGUAGES.available[langId]);
}
}
}
}
}
if (asyncTranslations === 0) {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: false });
}
else {
$rootScope.$emit('taxonomy-' + taxonomyType + '-updated', { taxonomy: taxonomy[taxonomyType], loading: true });
}
localStorage.$wm_taxonomy = JSON.stringify(taxonomy);
})
.catch(function (err) {
if (!taxonomy[taxonomyType]) {
console.warn("No taxonomy " + taxonomyType);
return;
}
});
};
/**
* @description
* Get the list of packages allowed to a specific user and
* Emit the updated list of available packages
*
* @event userPackagesId-updated
*
*/
packageService.getPackagesIdByUserId = function () {
userData = Auth.getUserData();
if (!userData || !userData.ID) {
userPackagesId = {};
$rootScope.$emit('userPackagesId-updated', {});
return;
}
if (userPackagesId) {
$rootScope.$emit('userPackagesId-updated', userPackagesId);
}
Communication.getJSON(communicationConf.baseUrl + communicationConf.endpoint + 'route_id/' + userData.ID)
.then(function (data) {
userPackagesId = {};
for (var key in data) {
userPackagesId[key] = true;
}
$rootScope.$emit('userPackagesId-updated', userPackagesId);
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
},
function (err) {
if (!userPackagesId) {
console.warn("No userPackagesId available. Shutting down...");
}
});
};
/**
* @description
* Use a voucher to get permission to download a route and
* Emit the new list of available packages
*
* @event userPackagesId-updated
*
* @param {number} packId
* the id of the pack to request
*
*/
packageService.useVoucher = function (packId) {
userData = Auth.getUserData();
if (!userData || !userData.ID) {
return;
}
$ionicPopup.prompt({
title: $translate.instant('Codice Viaggio'),
subTitle: $translate.instant('Inserisci il codice del tuo pacchetto di viaggio'),
inputType: 'text',
inputPlaceholder: $translate.instant('Codice Viaggio')
}).then(function (res) {
if (res) {
var data = $.param({
route_id: packId,
user_id: userData.ID,
code: res
});
var config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'
}
}
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
$http.post(
CONFIG.COMMUNICATION.baseUrl + CONFIG.COMMUNICATION.endpoint + 'voucher',
data,
config
)
.success(function (data, status, headers, config) {
$ionicLoading.hide();
///Update offline data
userPackagesId[packId] = true;
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
})
.error(function (data, status, header, config) {
$ionicLoading.hide();
if (data.error === "Voucher Expired") {
$ionicPopup.alert({
template: $translate.instant("Il codice di viaggio che hai utilizzato è scaduto")
});
} else {
$ionicPopup.alert({
template: $translate.instant("Il codice di viaggio che hai inserito non è valido. Controlla di averlo inserito correttamente e inseriscilo nuovamente.")
});
}
});
}
});
};
/**
* @description
* Buy the package via in-app purchase and
* Emit the new list of available packages
*
* @event userPackagesId-updated
*
* @param {number} packId
* the id of the pack to buy
*/
packageService.buyPack = function (packId) {
$ionicLoading.show();
userData = Auth.getUserData();
if (!userData || !userData.ID) {
return;
}
var productId = CONFIG.appId + '.' + packId;
inAppPurchase.getProducts([productId])
.then(function (product) {
$ionicLoading.hide();
if (product[0]) {
product = product[0];
}
if (product && product.productId) {
inAppPurchase.buy(product.productId)
.then(function () {
var data = {
user_id: userData.ID,
route_id: packId
};
userPackagesId[packId] = true;
$rootScope.$emit('userPackagesId-updated', userPackagesId);
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
activatePack(data);
})
.catch(function (err) {
console.warn(err)
var code = err.code ? err.code : (err.errorCode ? err.errorCode : -1);
switch (code) {
case -5:
//User cancelled
break;
case -8:
//item unavailable
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Questo prodotto non è al momento disponibile")
});
break;
case -9:
//item already owned
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Hai già acquistato questo prodotto in precedenza: per te sarà disponibile da subito senza ulteriori spese")
});
var data = {
user_id: userData.ID,
route_id: packId
};
userPackagesId[packId] = true;
$rootScope.$emit('userPackagesId-updated', userPackagesId);
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
activatePack(data);
break;
default:
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Si è verificato un errore. Riprova")
});
break;
}
});
}
else {
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Questo prodotto non è al momento disponibile")
});
}
})
.catch(function (err) {
$ionicLoading.hide();
console.error(err);
var code = err.code ? err.code : (err.errorCode ? err.errorCode : -1);
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Si è verificato un errore. Riprova") + "<br>Error " + code
});
});
};
/**
* @description
* Restore the purchases and
* Emit the new list of purchased packages
*
* @event userPackagesId-updated
*
*/
packageService.restorePurchases = function () {
$ionicLoading.show();
inAppPurchase.restorePurchases()
.then(function (purchases) {
for (var i in purchases) {
var id = purchases[i].productId.split('.');
id = id.pop();
if (!userPackagesId[id]) {
userPackagesId[id] = true;
packagesToActivate.push(id);
}
}
$ionicLoading.hide();
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Tutti gli acquisti sono stati ripristinati correttamente")
});
$rootScope.$emit('userPackagesId-updated', userPackagesId);
localStorage.$wm_userPackagesId = JSON.stringify(userPackagesId);
localStorage.$wm_packagesToActivate = JSON.stringify(packagesToActivate);
activatePackages();
})
.catch(function (err) {
$ionicLoading.hide();
$ionicPopup.alert({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Si è verificato un errore. Controlla di essere connesso e riprova")
});
console.log("Error restoring purchases", err);
});
};
/**
* @description
* Download the requested package and
* emit the new list of downloaded packages
*
* @event userDownloadedPackages-updated
*
* @param {number} packId
* the id of the pack to download
*/
packageService.downloadPackage = function (packId) {
$ionicPopup.confirm({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Stai per scaricare l'itinerario sul dispositivo, vuoi procedere?")
}).then(function (res) {
if (res) {
$.ajaxSetup({
cache: false
});
modalDownload.show();
Communication.getJSON(communicationConf.downloadJSONUrl + packId + '/app.json').then(function (data) {
var arrayLink = [];
var downloadSuccess = function () {
modalDownload.hide();
userDownloadedPackages[packId] = true;
$rootScope.$emit('userDownloadedPackages-updated', userDownloadedPackages);
MapService.setItemInLocalStorage("$wm_userDownloadedPackages", JSON.stringify(userDownloadedPackages));
};
var downloadFail = function () {
// TODO: add ionic alert
// TODO: rimuovere cartella, verificare interuzzione altri dowload
alert($translate.instant("Si è verificato un errore nello scaricamento del pacchetto, riprova"));
modalDownload.hide();
// updateDownloadedPackagesInStorage();
};
for (var i in data) {
if (typeof data[i] === 'string' && data[i].substring(0, 4) === "http") {
arrayLink.push(data[i]);
} else if (typeof data[i] === 'object') {
for (var j in data[i]) {
if (data[i][j] && data[i][j].substring && data[i][j].substring(0, 4) === "http") {
arrayLink.push(data[i][j]);
}
}
}
}
Offline
.downloadUserMap(packId, arrayLink, modalDownloadScope.vm)
.then(downloadSuccess, downloadFail);
$.ajaxSetup();
},
function () {
// TODO: add ionic alert
modalDownload.hide();
alert($translate.instant("Si è verificato un errore nello scaricamento del pacchetto, assicurati di essere online e riprova"));
});
}
});
};
/**
* @description
* Method to open a package already downloaded
*
* @param {number} packId
* the id of the pack to open
*/
packageService.openPackage = function (packId) {
if (GeolocationService.isActive()) {
GeolocationService.disable();
}
var basePackUrl = Offline.getOfflineMhildBasePathById(packId);
Communication.getLocalFile(basePackUrl + 'config.json')
.then(function (data) {
localStorage.$wm_mhildConf = data;
localStorage.$wm_mhildBaseUrl = Offline.getOfflineMhildBasePathById(packId);
localStorage.$wm_mhildId = packId;
sessionStorage.$wm_doBack = 'allowed';
$ionicLoading.show({
template: '<ion-spinner></ion-spinner>'
});
location.reload();
Utils.forceDigest();
});
};
/**
* @description
* Delete a package already downloaded and
* Emit the updated list of downloaded packages
*
* @event userDownloadedPackages-updated
*
* @param {number} packId
* the id of the pack to remove from storage
*/
packageService.removePack = function (packId) {
$ionicPopup.confirm({
title: $translate.instant("ATTENZIONE"),
template: $translate.instant("Stai per rimuovere l'itinerario dal dispositivo, vuoi procedere?<br />") + $translate.instant("Questo itinerario è riservato ai clienti Verde Natura che hanno acquistato questo viaggio. Terminata la fase di sperimentazione, gli itinerari saranno disponibili a tutti")
})
.then(function (res) {
if (res) {
Offline.removePackById(packId);
delete userDownloadedPackages[packId];
$rootScope.$emit('userDownloadedPackages-updated', userDownloadedPackages);
MapService.setItemInLocalStorage("$wm_userDownloadedPackages", JSON.stringify(userDownloadedPackages));
}
});
};
/**
* @description
* Emit the updated list of downloaded packages
* and return it
*
* @event userDownloadedPackages-updated
*
*/
packageService.getDownloadedPackages = function () {
$rootScope.$emit('userDownloadedPackages-updated', userDownloadedPackages);
return userDownloadedPackages;
};
activatePackages();
return packageService;
});
|