forked from espruino/BangleApps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.js
360 lines (332 loc) · 13.8 KB
/
loader.js
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
if (window.location.host=="banglejs.com") {
document.getElementById("apploaderlinks").innerHTML =
'This is the official Bangle.js App Loader - you can also try the <a href="https://espruino.github.io/BangleApps/">Development Version</a> for the most recent apps.';
} else if (window.location.host=="espruino.github.io") {
document.title = " [Development]";
document.getElementById("apploaderlinks").innerHTML =
'This is the development Bangle.js App Loader - you can also try the <a href="https://banglejs.com/apps/">Official Version</a> for stable apps.';
} else if (window.location.hostname==='localhost') {
document.title = " [Local]";
Const.APPS_JSON_FILE = "apps.local.json";
document.getElementById("apploaderlinks").innerHTML =
'This is your local Bangle.js App Loader - you can try the <a href="https://banglejs.com/apps/">Official Version</a> here.';
} else {
document.title = " [Unofficial]";
document.getElementById("apploaderlinks").innerHTML =
'This is not the official Bangle.js App Loader - you can try the <a href="https://banglejs.com/apps/">Official Version</a> here.';
}
var RECOMMENDED_VERSION = "2v21";
// could check http://www.espruino.com/json/BANGLEJS.json for this
// We're only interested in Bangles
DEVICEINFO = DEVICEINFO.filter(x=>x.id.startsWith("BANGLEJS"));
// Where we get our usage data from
Const.APP_USAGE_JSON = "https://banglejs.com/apps/appusage.json";
Const.APP_DATES_CSV = "appdates.csv";
// Set up source code URL
(function() {
let username = "espruino";
let githubMatch = window.location.href.match(/\/([\w-] )\.github\.io/);
if (githubMatch) username = githubMatch[1];
Const.APP_SOURCECODE_URL = `https://github.com/${username}/BangleApps/tree/master/apps`;
})();
// When a device is found, filter the apps accordingly
function onFoundDeviceInfo(deviceId, deviceVersion) {
var fwURL = "#", fwExtraText = "";
if (deviceId == "BANGLEJS") {
fwURL = "https://www.espruino.com/Bangle.js#firmware-updates";
Const.MESSAGE_RELOAD = 'Hold BTN3\nto reload';
}
if (deviceId == "BANGLEJS2") {
fwExtraText = "with the <b>Firmware Update</b> app in this App Loader, or "
fwURL = "https://www.espruino.com/Bangle.js2#firmware-updates";
Const.MESSAGE_RELOAD = 'Hold button\nto reload';
}
if (deviceId != "BANGLEJS" && deviceId != "BANGLEJS2") {
showToast(`You're using ${deviceId}, not a Bangle.js. Did you want <a href="https://espruino.com/apps">espruino.com/apps</a> instead?` ,"warning", 20000);
} else if (versionLess(deviceVersion, RECOMMENDED_VERSION)) {
showToast(`You're using an old Bangle.js firmware (${deviceVersion}) and ${RECOMMENDED_VERSION} is available (<a href="https://www.espruino.com/ChangeLog" target="_blank">see changes</a>). You can update ${fwExtraText}<a href="${fwURL}" target="_blank">with the instructions here</a>` ,"warning", 20000);
}
// check against features shown?
filterAppsForDevice(deviceId);
/* if we'd saved a device ID but this device is different, ensure
we ask again next time */
var savedDeviceId = getSavedDeviceId();
if (savedDeviceId!==undefined && savedDeviceId!=deviceId)
setSavedDeviceId(undefined);
}
// Called when we refresh the list of installed apps
function onRefreshMyApps() {
/* if we're allowed to, send usage stats. We'll only
actually send if the data has changed */
sendUsageStats();
}
var submittedUsageInfo = "";
/* Send usage stats to servers if it has changed */
function sendUsageStats() {
if (!SETTINGS.sendUsageStats) return; // not allowed!
if (device.uid === undefined) return; // no data yet!
if (!device.appsInstalled.length) return; // no installed apps or disconnected
/* Work out what we'll send:
* A suitably garbled UID so we can avoid too many duplicates
* firmware version
* apps installed
* apps favourited
*/
var usageInfo = `uid=${encodeURIComponent(device.uid)}&fw=${encodeURIComponent(device.version)}&apps=${encodeURIComponent(device.appsInstalled.map(a=>a.id).join(","))}&favs=${encodeURIComponent(SETTINGS.favourites.join(","))}`;
// Do a quick check for unchanged data to reduce server load
if (usageInfo != submittedUsageInfo) {
console.log("sendUsageStats: Submitting usage stats...");
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "https://banglejs.com/submit_app_stats.php", true /*async*/);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onload = (e) => {
if (xmlhttp.readyState === 4)
console.log(`sendUsageStats (${xmlhttp.status}): ${xmlhttp.responseText}`);
};
xmlhttp.onerror = (e) => {
console.error("sendUsageStats ERROR: " xmlhttp.statusText);
};
xmlhttp.send(usageInfo);
submittedUsageInfo = usageInfo;
}
}
var originalAppJSON = undefined;
function filterAppsForDevice(deviceId) {
if (originalAppJSON===undefined && appJSON.length)
originalAppJSON = appJSON;
var device = DEVICEINFO.find(d=>d.id==deviceId);
// set the device dropdown
document.querySelector(".devicetype-nav span").innerText = device ? device.name : "All apps";
if (originalAppJSON) { // JSON might not have loaded yet
if (!device) {
if (deviceId!==undefined)
showToast(`Device ID ${deviceId} not recognised. Some apps may not work`, "warning");
appJSON = originalAppJSON;
} else {
// Now filter apps
appJSON = originalAppJSON.filter(app => {
var supported = ["BANGLEJS"];
if (!app.supports) {
console.log(`App ${app.id} doesn't include a 'supports' field - ignoring`);
return false;
}
if (app.supports.includes(deviceId)) return true;
//console.log(`Dropping ${app.id} because ${deviceId} is not in supported list ${app.supports.join(",")}`);
return false;
});
}
}
refreshLibrary();
}
// If 'remember' was checked in the window below, this is the device
function getSavedDeviceId() {
let deviceId = localStorage.getItem("deviceId");
if (("string"==typeof deviceId) && DEVICEINFO.find(d=>d.id == deviceId))
return deviceId;
return undefined;
}
function setSavedDeviceId(deviceId) {
localStorage.setItem("deviceId", deviceId);
}
// At boot, show a window to choose which type of device you have...
window.addEventListener('load', (event) => {
let deviceId = getSavedDeviceId()
if (deviceId !== undefined) return; // already chosen
var html = `<div class="columns">
${DEVICEINFO.map(d=>`
<div class="column col-6 col-xs-6">
<div class="card devicechooser" deviceid="${d.id}" style="cursor:pointer">
<div class="card-header">
<div class="card-title h5">${d.name}</div>
<!--<div class="card-subtitle text-gray">...</div>-->
</div>
<div class="card-image">
<img src="${d.img}" alt="${d.name}" width="256" height="256" class="img-responsive">
</div>
</div>
</div>`).join("\n")}
</div><div class="columns">
<div class="column col-12">
<div class="form-group">
<label class="form-switch">
<input type="checkbox" id="usage_stats" ${SETTINGS.sendUsageStats?"checked":""}>
<i class="form-icon"></i> Send favourite and installed apps to banglejs.com<br/>
<small>For 'Sort by Installed/Favourited' functionality (see <a href="http://www.espruino.com/Privacy">privacy policy</a>)</small>
</label>
<label class="form-switch">
<input type="checkbox" id="remember_device">
<i class="form-icon"></i> Don't ask again
</label>
</div>
</div>
</div>`;
showPrompt("Which Bangle.js?",html,{},false);
var usageStats = document.getElementById("usage_stats");
usageStats.addEventListener("change",event=>{
console.log("Send Usage Stats " (event.target.checked?"on":"off"));
SETTINGS.sendUsageStats = event.target.checked;
saveSettings();
});
htmlToArray(document.querySelectorAll(".devicechooser")).forEach(button => {
button.addEventListener("click",event => {
let rememberDevice = !!document.getElementById("remember_device").checked;
let button = event.currentTarget;
let deviceId = button.getAttribute("deviceid");
hidePrompt();
console.log("Chosen device", deviceId);
setSavedDeviceId(rememberDevice ? deviceId : undefined);
filterAppsForDevice(deviceId);
});
});
});
window.addEventListener('load', (event) => {
// Hook onto device chooser dropdown
htmlToArray(document.querySelectorAll(".devicetype-nav .menu-item")).forEach(button => {
button.addEventListener("click", event => {
var a = event.target;
var deviceId = a.getAttribute("dt")||undefined;
filterAppsForDevice(deviceId); // also sets the device dropdown
setSavedDeviceId(undefined); // ask at startup next time
document.querySelector(".devicetype-nav span").innerText = a.innerText;
});
});
var el;
// Button to install all default apps in one go
el = document.getElementById("reinstallall");
if (el) el.addEventListener("click",event=>{
var promise = showPrompt("Reinstall","Really re-install all apps?").then(() => {
Comms.reset().then(_ =>
getInstalledApps()
).then(installedapps => {
console.log(installedapps);
var promise = Promise.resolve();
installedapps.forEach(app => {
if (app.custom)
return console.log(`Ignoring ${app.id} as customised`);
var oldApp = app;
app = appJSON.find(a => a.id==oldApp.id);
if (!app)
return console.log(`Ignoring ${oldApp.id} as not found`);
promise = promise.then(() => updateApp(app, {noReset:true, noFinish:true}));
});
return promise;
}).then( _ =>
Comms.showUploadFinished()
).catch(err=>{
Progress.hide({sticky:true});
showToast("App re-install failed, " err,"error");
});
});
});
// Button to install all default apps in one go
el = document.getElementById("installdefault");
if (el) el.addEventListener("click", event=>{
getInstalledApps().then(() => {
if (device.id == "BANGLEJS")
return httpGet("defaultapps_banglejs1.json");
if (device.id == "BANGLEJS2")
return httpGet("defaultapps_banglejs2.json");
throw new Error("Unknown device " device.id);
}).then(json=>{
return installMultipleApps(JSON.parse(json), "default");
}).catch(err=>{
Progress.hide({sticky:true});
showToast("App Install failed, " err,"error");
});
});
// Button to reset the Bangle's settings
el = document.getElementById("defaultbanglesettings");
if (el) el.addEventListener("click", event=>{
showPrompt("Reset Settings","Really reset Bangle.js settings?").then(() => {
Comms.write("\x10require('Storage').erase('setting.json');load()\n");
showToast("Settings reset!", "success");
}, function() { /* cancelled */ });
});
// BLE Compatibility
var selectBLECompat = document.getElementById("settings-ble-compat");
if (selectBLECompat) {
Puck.increaseMTU = !SETTINGS.bleCompat;
selectBLECompat.checked = !!SETTINGS.bleCompat;
selectBLECompat.addEventListener("change",event=>{
console.log("BLE compatibility mode " (event.target.checked?"on":"off"));
SETTINGS.bleCompat = event.target.checked;
Puck.increaseMTU = !SETTINGS.bleCompat;
saveSettings();
});
}
// Sending usage stats
var selectUsageStats = document.getElementById("settings-usage-stats");
if (selectUsageStats) {
selectUsageStats.checked = !!SETTINGS.sendUsageStats;
selectUsageStats.addEventListener("change",event=>{
console.log("Send Usage Stats " (event.target.checked?"on":"off"));
SETTINGS.sendUsageStats = event.target.checked;
saveSettings();
});
}
// Load language list
httpGet("lang/index.json").then(languagesJSON=>{
var languages;
try {
languages = JSON.parse(languagesJSON);
} catch(e) {
console.error("lang/index.json Corrupted", e);
}
languages = languages.filter( l=> l.disabled===undefined );
function reloadLanguage() {
LANGUAGE = undefined;
if (SETTINGS.language) {
var language = languages.find(l=>l.code==SETTINGS.language);
if (language) {
var langURL = "lang/" language.url;
httpGet(langURL).then(languageJSON=>{
try {
LANGUAGE = JSON.parse(languageJSON);
console.log(`${langURL} loaded successfully`);
} catch(e) {
console.error(`${langURL} Corrupted`, e);
}
});
} else {
console.error(`Language code ${JSON.stringify(SETTINGS.language)} not found in lang/index.json`);
}
}
}
var selectLang = document.getElementById("settings-lang");
languages.forEach(lang => {
selectLang.innerHTML = `<option value="${lang.code}" ${SETTINGS.language==lang.code?"selected":""}>${lang.name} (${lang.code})</option>`;
});
selectLang.addEventListener("change",event=>{
SETTINGS.language = event.target.value;
reloadLanguage();
saveSettings();
});
reloadLanguage();
});
});
function onAppJSONLoaded() {
let deviceId = getSavedDeviceId()
if (deviceId !== undefined)
filterAppsForDevice(deviceId);
/* Disable external screenshot loading - seems we probably have enough
screenshots added manually in apps.json */
/*return new Promise(resolve => {
httpGet("screenshots.json").then(screenshotJSON=>{
var screenshots = [];
try {
screenshots = JSON.parse(screenshotJSON);
} catch(e) {
console.error("Screenshot JSON Corrupted", e);
}
screenshots.forEach(s => {
var app = appJSON.find(a=>a.id==s.id);
if (!app) return;
if (!app.screenshots) app.screenshots = [];
app.screenshots.push({url:s.url});
})
}).catch(err=>{
console.log("No screenshots.json found");
resolve();
});
});*/
}