53 lines
2.0 KiB
JavaScript
53 lines
2.0 KiB
JavaScript
// The car's server updating itself (GET/POST /api/update, SELF_UPDATE=1 in
|
|
// its .env): a topbar button shows up when main has a newer version that
|
|
// passed CI; a click installs it (bin/update-maptool.sh on the host) and the
|
|
// page reloads once the server answers with the new revision.
|
|
const CHECK_MS = 10 * 60 * 1000;
|
|
const RESTART_POLL_MS = 5000;
|
|
|
|
export function setupUpdate(button) {
|
|
let latest = null;
|
|
|
|
async function check() {
|
|
try {
|
|
const state = await (await fetch("/api/update", { cache: "no-store" })).json();
|
|
if (!state.enabled) return;
|
|
latest = state.latest;
|
|
button.hidden = !state.available;
|
|
button.textContent = `⟳ ${state.latest}`;
|
|
button.title = `A new version (${state.latest}, now ${state.current}) — click to update; the app restarts for about a minute`;
|
|
if (state.status?.state === "failed") button.title += `\nThe last update failed: ${state.status.message}`;
|
|
setTimeout(check, CHECK_MS);
|
|
} catch {
|
|
setTimeout(check, CHECK_MS);
|
|
}
|
|
}
|
|
|
|
async function waitForRestart(revision) {
|
|
try {
|
|
const health = await (await fetch("/api/health", { cache: "no-store" })).json();
|
|
if (health.revision !== revision) return window.location.reload();
|
|
} catch {
|
|
// restarting: not answering for a while
|
|
}
|
|
setTimeout(() => waitForRestart(revision), RESTART_POLL_MS);
|
|
}
|
|
|
|
button.addEventListener("click", async () => {
|
|
if (!window.confirm(`Update to ${latest}? The app restarts — about a minute without it.`)) return;
|
|
button.disabled = true;
|
|
button.textContent = "Updating…";
|
|
const response = await fetch("/api/update", { method: "POST" });
|
|
const data = await response.json().catch(() => ({}));
|
|
if (!response.ok) {
|
|
window.alert(data.error || `Update failed (${response.status})`);
|
|
button.disabled = false;
|
|
return check();
|
|
}
|
|
const revision = (await (await fetch("/api/health")).json()).revision;
|
|
waitForRestart(revision);
|
|
});
|
|
|
|
check();
|
|
}
|