-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin.js
More file actions
564 lines (507 loc) · 17.3 KB
/
Copy pathadmin.js
File metadata and controls
564 lines (507 loc) · 17.3 KB
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
new Vue({
el: '#app',
data() {
return {
innerWidth,
leftOpen: innerWidth >= 1100,
rightOpen: innerWidth >= 1100,
masterKey: "",
showMasterKeyModal: false,
masterKeyInput: "",
versions: {},
orbID: localStorage.getItem("orbID") || "demo",
alias: null,
serverOrbID: "demo",
serverUrl: location.origin,
orbInfo: [],
idToConfig: {},
idToPrefs: {},
idToTimingPrefs: {},
idToLog: {},
idToIP: {},
idToCommit: {},
config: "",
prefs: "",
timingprefs: "",
log: "",
logDaysAgo: 0,
viewingErrorLog: false,
viewing: "config",
infoInterval: null,
backupList: [],
selectedBackup: null,
deleteSelected: false,
manualBackupName: "",
commandResponses: " ",
command: "",
commandHistory: [],
historyIndex: -1,
prefsBackup: null,
calibratingPower: false,
powerValue: 1,
powerStep: 2,
stepIncreasing: true,
MAX_POWER_DRAW: false,
MAX_AVG_PIXEL_BRIGHTNESS: false,
}
},
computed: {
selectedResetReason() {
return this.orbInfo.find(orb => orb.id == this.orbID)?.resetReason
},
width() {
return Math.min(700, this.innerWidth)
},
navTextX() {
const fontScale = Math.min(1, this.width / 500)
return this.width / 2 - 224 * fontScale
},
navFontSize() {
return (Math.min(6, this.width / 500 * 6)).toFixed(2) + 'em'
},
isLocal() {
const h = location.hostname
return h === 'localhost' || h === '127.0.0.1' ||
h.startsWith('10.') || h.startsWith('192.168.') || h.startsWith('172.')
},
isArduino() {
return (this.config || '').trim().startsWith('{')
},
isNarrow() {
return this.innerWidth < 1100
},
drawerOverlay() {
return this.isNarrow && (this.leftOpen || this.rightOpen)
},
},
async created() {
let self = this
addEventListener('resize', () => {
self.innerWidth = innerWidth
if (innerWidth < 1100) {
self.leftOpen = false
self.rightOpen = false
} else {
self.leftOpen = true
self.rightOpen = true
}
})
addEventListener('keydown', event => {
if (event.key == 's' && (event.metaKey || event.ctrlKey)) {
if (self.viewing == 'config') self.saveConfig()
if (self.viewing == 'prefs') self.savePrefs()
if (self.viewing == 'timing') self.saveTimingPrefs()
event.preventDefault()
}
})
if (location.protocol === 'http:') {
try {
this.masterKey = await (await fetch("http://localhost:8000/admin/masterkey")).text()
} catch(_) {}
}
if (!this.masterKey) {
this.masterKey = localStorage.getItem("masterKey") || ""
}
if (!this.masterKey) {
this.masterKey = await this.promptMasterKey()
}
this.versions = await (await fetch("/admin/versions")).json()
await this.getOrbInfo()
for (let orb of this.orbInfo) this.fetchOrbVersionAndIP(orb)
let pollCount = 0
this.infoInterval = setInterval(async function() {
if (document.hasFocus()) {
self.versions = await (await fetch("/admin/versions")).json()
await self.getOrbInfo()
// Refresh version/IP for all known orbs every 30s (every 6th poll)
if (pollCount++ % 6 === 0) {
for (let orb of self.orbInfo) self.fetchOrbVersionAndIP(orb)
}
await self.updateViewing()
}
}, 5000)
await this.updateConfig()
this.setOrb(this.orbID)
this.viewing = localStorage.getItem("adminviewing") || this.viewing
},
beforeDestroy() {
clearInterval(this.infoInterval)
},
watch: {
orbID(val) { localStorage.setItem("orbID", val) },
viewing(val) { localStorage.setItem("adminviewing", val) },
},
methods: {
formatTime(iso) {
if (!iso) return ""
return new Date(iso).toLocaleString()
},
async genOrbID() {
let orbID = createRandomID()
this.config = upsertKeyValueInConfig(this.config, 'ORB_ID', orbID, "exports")
await this.setOrbKey()
},
async getOrbKey(orbID) {
return await sha256(orbID.toLowerCase() + this.masterKey)
},
focusCommandPrompt() {
this.$nextTick(() => {
let el = document.querySelector(".command-prompt")
if (el) el.focus()
})
},
async setViewing(type) {
this.viewing = type
this.updateViewing()
if (type == "command") this.focusCommandPrompt()
},
async setOrb(orbID) {
this.orbID = orbID
for (let orb of this.orbInfo) {
if (orb.id == orbID) {
this.alias = orb.alias
break
}
}
if (this.viewing == "command") this.focusCommandPrompt()
this.commandResponses = " "
this.log = ""
this.prefs = ""
this.timingprefs = ""
this.config = this.idToConfig[this.orbID]
this.logDaysAgo = 0
this.viewingErrorLog = false
this.calibratingPower = false
if (this.prefsBackup) {
this.prefs = this.prefsBackup
await this.savePrefs()
}
this.prefsBackup = null
this.updateViewing()
},
async setOrbKey() {
if (this.config.trim().startsWith('{')) {
// Arduino: JSON config
let cfg = JSON.parse(this.config)
cfg.ORB_KEY = await this.getOrbKey(cfg.ORB_ID)
this.config = JSON.stringify(cfg, null, 2)
} else {
// Pi: JS module config
let orbID = readFromConfig(this.config, 'ORB_ID')
let orbKey = await this.getOrbKey(orbID)
this.config = upsertKeyValueInConfig(this.config, 'ORB_KEY', orbKey, 'ORB_ID')
}
},
async unlockOrb() {
if (!confirm("Unlock orb? This resets the Pi password, removes ORB_KEY, and clears WiFi credentials.")) return
let command = 'sudo bash -c "echo pi:lumatron | chpasswd"'
let response = await this.sendCommand({ type: "run", command })
this.commandResponses += "% " + command + "\n" + (response.trim() || "(success)") + "\n"
this.commandResponses += "Removing ORB_KEY from config.js\n"
this.config = removeLineInConfig(this.config, "ORB_KEY")
await this.saveConfig(true)
this.commandResponses += "Successfully removed ORB_KEY\n"
await this.sendCommand({ type: "clearwifi" })
this.commandResponses += "WiFi credentials cleared\n"
},
async saveConfig(dontRestart) {
let isArduino = this.config.trim().startsWith('{')
let orbID, existingOrbKey
if (isArduino) {
let cfg = JSON.parse(this.config)
orbID = cfg.ORB_ID
existingOrbKey = cfg.ORB_KEY
} else {
try { orbID = readFromConfig(this.config, 'ORB_ID') } catch(_) {}
try { existingOrbKey = readFromConfig(this.config, 'ORB_KEY') } catch(_) {}
}
if (orbID && existingOrbKey) {
let expectedOrbKey = await this.getOrbKey(orbID)
if (existingOrbKey !== expectedOrbKey) {
console.log("ORB_KEY not compatible with master key. Not saving.")
return
}
}
await this.sendCommand({ type: "setconfig", data: this.config, dontRestart })
this.idToConfig[this.orbID] = this.config
},
async savePrefs(dontRestart) {
await this.sendCommand({ type: "setprefs", data: this.prefs, dontRestart })
this.idToPrefs[this.orbID] = this.prefs
},
async saveTimingPrefs() {
await this.sendCommand({ type: "settimingprefs", data: this.timingprefs })
this.idToTimingPrefs[this.orbID] = this.timingprefs
},
async restartOrb() {
await this.sendCommand({ type: "restart" })
},
async updateFirmware() {
await this.sendCommand({ type: "updateFirmware" })
},
async clearWifi() {
await this.sendCommand({ type: "clearwifi" })
},
fetchOrbVersionAndIP(orb) {
this.sendCommand({ type: "ip" }, orb.id).then(ip => {
Vue.set(this.idToIP, orb.id, ip)
}).catch(() => {})
this.sendCommand({ type: "version" }, orb.id).then(orbVersion => {
orbVersion = parseInt(orbVersion)
if (!orbVersion) {
Vue.set(this.idToCommit, orb.id, null)
return
}
let serverVersion = orb.isArduino ? (this.versions.arduinoVersions?.esp32c3 ?? 0) : this.versions.gitCount
Vue.set(this.idToCommit, orb.id, serverVersion - orbVersion)
}).catch(() => {})
},
async getOrbInfo() {
try {
const prevIDs = new Set(this.orbInfo.map(o => o.id))
this.orbInfo = JSON.parse(await this.sendServerCommand({ type: "orblist" }))
this.orbInfo = this.orbInfo.sort((a, b) => {
let aName = a.alias != null ? a.alias : a.id
let bName = b.alias != null ? b.alias : b.id
return aName < bName ? -1 : 1
})
for (let orb of this.orbInfo) {
if (!prevIDs.has(orb.id)) {
this.fetchOrbVersionAndIP(orb)
}
}
} catch(e) {}
},
async updateViewing() {
if (this.viewing == 'config' || this.viewing == 'calibration') {
await this.updateConfig()
} else if (this.viewing == 'log') {
await this.updateLog()
} else if (this.viewing == 'prefs') {
await this.updatePrefs()
} else if (this.viewing == 'timing') {
await this.updateTimingPrefs()
}
},
async updateConfig() {
let previousValue = this.idToConfig[this.orbID]
let newConfig = await this.sendCommand({ type: "getconfig" })
if (previousValue != newConfig) {
this.idToConfig[this.orbID] = newConfig
this.config = newConfig
}
this.MAX_POWER_DRAW = this.config.includes("MAX_POWER_DRAW")
this.MAX_AVG_PIXEL_BRIGHTNESS = this.config.includes("MAX_AVG_PIXEL_BRIGHTNESS")
},
async updatePrefs() {
let previousValue = this.idToPrefs[this.orbID]
this.idToPrefs[this.orbID] = await this.sendCommand({ type: "getprefs" })
if (previousValue != this.idToPrefs[this.orbID]) {
this.prefs = this.idToPrefs[this.orbID]
}
},
async updateTimingPrefs() {
let previousValue = this.idToTimingPrefs[this.orbID]
this.idToTimingPrefs[this.orbID] = await this.sendCommand({ type: "gettimingprefs" })
if (previousValue != this.idToTimingPrefs[this.orbID]) {
this.timingprefs = this.idToTimingPrefs[this.orbID]
}
},
async updateLog() {
const stream = this.viewingErrorLog ? "error" : "out"
this.idToLog[this.orbID] = await this.sendCommand(
{ type: "getlog", daysAgo: this.logDaysAgo, stream }, this.orbID)
this.log = this.idToLog[this.orbID]
},
async toggleErrorLog() {
this.viewingErrorLog = !this.viewingErrorLog
await this.updateLog()
},
async viewBackups() {
this.viewing = "backups"
this.selectedBackup = null
this.backupList = JSON.parse(await this.sendServerCommand({ type: "backuplist" }))
},
async restoreBackup() {
await this.sendServerCommand({
type: "restoreBackup",
fileName: this.selectedBackup,
orbID: this.orbID,
})
this.viewing = 'config'
},
async deleteBackup() {
await this.sendServerCommand({ type: "deleteBackup", fileName: this.selectedBackup })
let idx = this.backupList.indexOf(this.selectedBackup)
if (idx >= 0) this.backupList.splice(idx, 1)
this.selectedBackup = null
this.deleteSelected = false
},
async manualBackup() {
if (!this.manualBackupName) return
if (this.backupList.includes(this.manualBackupName)) return
await this.sendCommand({ type: "manualBackup", nameOverride: this.manualBackupName })
this.backupList.push(this.manualBackupName + ".bak")
},
async onCommandKeydown(event) {
if (event.key == "Enter") {
event.preventDefault()
let cmd = this.command.replace(/\n/g, "")
this.commandHistory.unshift(cmd)
let response = await this.sendCommand({ type: "run", command: cmd })
this.commandResponses += "% " + cmd + "\n" + (response.trim() || "(success)") + "\n"
this.command = ""
this.historyIndex = -1
}
if (event.key == "ArrowUp" && this.historyIndex < this.commandHistory.length) {
this.historyIndex += 1
this.command = this.commandHistory[this.historyIndex]
}
if (event.key == "ArrowDown" && this.historyIndex >= 0) {
this.historyIndex -= 1
this.command = this.historyIndex >= 0 ? this.commandHistory[this.historyIndex] : ""
}
},
promptMasterKey() {
this.masterKeyInput = ""
this.showMasterKeyModal = true
return new Promise(resolve => {
this._masterKeyResolve = resolve
})
},
submitMasterKey() {
let key = this.masterKeyInput.trim()
if (!key) return
localStorage.setItem("masterKey", key)
this.masterKey = key
this.showMasterKeyModal = false
this._masterKeyResolve(key)
},
sendServerCommand(command) {
return this.sendCommand(command, this.serverOrbID, true)
},
async sendCommand(command, orbID, isServerCommand) {
if (!orbID) orbID = this.orbID
command.timestamp = Date.now()
command = JSON.stringify(command)
let hash = await sha256(command + await this.getOrbKey(orbID))
let message = encodeURIComponent(command)
let pathPrefix = isServerCommand ? "" : orbID + "/"
let url = `${this.serverUrl}/${pathPrefix}admin?message=${message}&hash=${hash}`
try {
const controller = new AbortController()
setTimeout(() => controller.abort(), 6000)
return await (await fetch(url, { signal: controller.signal })).text()
} catch(_) {
return ""
}
},
showCalibration() {
this.viewing = "calibration"
this.updateConfig()
},
clearMaxes() {
if (this.isArduino) {
let cfg = JSON.parse(this.config)
delete cfg.MAX_POWER_DRAW
delete cfg.MAX_AVG_PIXEL_BRIGHTNESS
this.config = JSON.stringify(cfg, null, 2)
} else {
this.config = removeLineInConfig(this.config, "MAX_POWER_DRAW")
this.config = removeLineInConfig(this.config, "MAX_AVG_PIXEL_BRIGHTNESS")
}
this.saveConfig()
},
sendPrefsUpdate(update) {
if (this.isArduino) {
this.sendCommand({ type: "updatePrefs", update })
} else {
this.sendCommand({ type: "python", content: { type: "prefs", update } })
}
},
async startPowerCalibration() {
await this.updatePrefs()
this.prefsBackup = this.prefs
this.calibratingPower = true
this.powerValue = 1
this.powerStep = 1
this.stepIncreasing = true
this.sendPowerValue()
this.sendPrefsUpdate({ brightness: 234, idlePattern: "static", idleColor: "gradient", dimmer: 1 })
},
sendPowerValue() {
let powerHex = this.powerValue.toString(16).padStart(2, '0')
let color = `#${powerHex}${powerHex}${powerHex}`
this.sendPrefsUpdate({ gradientStartColor: color, gradientEndColor: color, idlePattern: "static" })
},
async nextPowerValue(wasGood) {
if ((this.powerStep == 1 && !this.stepIncreasing) || (wasGood && this.powerValue == 255)) {
this.calibratingPower = false
if (!wasGood) this.powerValue -= 1
this.prefs = this.prefsBackup
await this.savePrefs(true)
if (this.isArduino) {
let cfg = JSON.parse(this.config)
cfg.MAX_AVG_PIXEL_BRIGHTNESS = this.powerValue
this.config = JSON.stringify(cfg, null, 2)
} else {
this.config = upsertKeyValueInConfig(this.config, "MAX_AVG_PIXEL_BRIGHTNESS", this.powerValue)
}
this.saveConfig()
return
}
if (!wasGood) this.stepIncreasing = false
if (this.stepIncreasing) {
this.powerStep *= 2
} else {
this.powerStep /= 2
}
this.powerValue += this.powerStep * (wasGood ? 1 : -1)
this.sendPowerValue()
},
},
})
async function sha256(message) {
const msgBuffer = new TextEncoder().encode(message)
const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer)
const hashArray = Array.from(new Uint8Array(hashBuffer))
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('')
}
function base64(n) {
let result = ''
do {
result = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.charAt(n % 64) + result
n = Math.floor(n / 64) - 1
} while (n > -1)
return result
}
function createRandomID() {
return base64(Math.floor(Math.random() * 0xffffffffffff)).slice(-7)
}
function readFromConfig(config, key) {
let regex = new RegExp(`\\'?\\"?${key}\\'?\\"?\\s*:\\s*[\\'\\"](.*)[\\'\\"],`)
let match = config.match(regex)
return match[1]
}
function upsertKeyValueInConfig(config, key, value, after, tabs) {
if (tabs == undefined) tabs = 2
if (typeof value == "string") value = `"${value}"`
let newLine = `${" ".repeat(tabs)}${key}: ${value},`
let match = config.match(new RegExp(`.*${key}.*`))
if (match) {
config = config.replace(match[0], newLine)
return config
}
return insertLineInConfig(config, newLine, after)
}
function insertLineInConfig(config, newLine, after) {
if (after) {
config = config.replace(new RegExp(`.*${after}.*`), "$&\n" + newLine)
} else {
config = config.replace(/^\}/m, newLine + "\n$&")
}
return config
}
function removeLineInConfig(config, key) {
return config.replace(new RegExp(`.*${key}.*\n`), "")
}