-
Notifications
You must be signed in to change notification settings - Fork 6
/
app-update-service.ts
84 lines (77 loc) · 2.76 KB
/
app-update-service.ts
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
import 'rxjs/add/operator/map';
import { Injectable } from '@angular/core';
import { CodePush, InstallMode, SyncStatus, DownloadProgress } from '@ionic-native/code-push';
import { LocalNotifications } from '@ionic-native/local-notifications';
@Injectable()
export class AppUpdateService {
constructor(private codePush: CodePush,
private localNotifications: LocalNotifications) {
}
checkForUpdate() {
const notificationObject = {
id: 1,
title: "Baruch",
text: "",
vibrate: false,
sound: null,
icon: "/assets/icon/favicon.ico"
};
const downloadProgress = (progress: DownloadProgress) => {
const received = AppUpdateService.humanFileSize(progress.receivedBytes, false);
const total = AppUpdateService.humanFileSize(progress.totalBytes, false);
notificationObject.text = `Downloaded ${received} of ${total}`;
notificationObject["progressBar"] = { value: Math.ceil((progress.receivedBytes / progress.totalBytes) * 100) };
this.localNotifications.update(notificationObject);
};
this.codePush
.sync({
updateDialog: {
updateTitle: "An update is available",
optionalUpdateMessage: "Change log:\n\n",
optionalIgnoreButtonLabel: "Not now",
optionalInstallButtonLabel: "Install",
appendReleaseDescription: true,
descriptionPrefix: ""
},
installMode: InstallMode.IMMEDIATE
}, downloadProgress)
.catch((err) => {
return [];
})
.subscribe((syncStatus) => {
switch (syncStatus) {
case SyncStatus.CHECKING_FOR_UPDATE:
notificationObject.text = "Checking for updates..."
this.localNotifications.schedule(notificationObject);
break;
case SyncStatus.INSTALLING_UPDATE:
notificationObject.text = "Installing update...";
notificationObject["progressBar"] = { value: 100 };
this.localNotifications.update(notificationObject);
break;
case SyncStatus.UP_TO_DATE:
case SyncStatus.ERROR:
case SyncStatus.UPDATE_IGNORED:
case SyncStatus.UPDATE_INSTALLED:
this.localNotifications.cancel(notificationObject.id);
break;
}
});
}
// From https://stackoverflow.com/a/14919494/5866781
static humanFileSize(bytes, si) {
var thresh = si ? 1000 : 1024;
if (Math.abs(bytes) < thresh) {
return bytes + ' B';
}
var units = si
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
var u = -1;
do {
bytes /= thresh;
++u;
} while (Math.abs(bytes) >= thresh && u < units.length - 1);
return bytes.toFixed(1) + ' ' + units[u];
}
}