AnyBot/mobile/sw.js

120 lines
6.7 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// AnyBot 手機 App 的 Service Worker(帳號伺服器和直接連線都送):頁面存在手機上、推播通知、點通知打開那個 Bot、App 圖示上的數字。
// 通知的圖示是 AnyBot 的貓(黃色底);Android 狀態列的小圖示只能是單色,用那隻貓的剪影(badge-96.png)。
// 打開得快:頁面、圖示、App 資訊存在這支手機上(只有這幾個每個人都一樣的檔,沒有聊天或帳號資料),
// 打開時直接用。頁面每次打開都在背景問一次換版沒(帶著存的那份的版本標記,沒換只回「沒有變」);
// 換了就存新的、先告訴頁面(還在連線畫面就重新載入;已經進去的話,App 退到背景、手上沒東西時才換),
// 再重抓圖示。重新整理(reload)一定先問伺服器,連不上才用存的。
const SHELL = "anybot-shell-v1";
// (Not novnc.js: the screen page, always asked from the server, must get the one it was built with.)
const KEPT = ["", "index.html", "manifest.webmanifest", "icon.svg", "icon-180.png", "icon-192.png", "icon-512.png", "icon-maskable-192.png", "icon-maskable-512.png", "badge-96.png"];
// What the page shows while it connects: kept at install, so even the first reopen needs nothing.
const FIRST = ["", "manifest.webmanifest", "icon.svg", "icon-180.png", "icon-192.png"];
const scope = () => self.registration.scope;
// The one key a kept file is under (the page under the folder's own address), or null: not one of
// them (the API, a published site, a download, the screen — never touched here).
function keyOf(url) {
const u = new URL(url), root = new URL(scope());
if (u.origin !== root.origin || !u.pathname.startsWith(root.pathname)) return null;
const rest = u.pathname.slice(root.pathname.length);
return KEPT.includes(rest) ? new URL(rest === "index.html" ? "" : rest, root).href : null;
}
// Kept as the plain bytes that arrived: the body is unpacked by then, so how it was packed for the
// trip (and its length on the wire) is not said again.
async function keepable(r) {
const h = new Headers(r.headers);
h.delete("Content-Encoding"); h.delete("Content-Length");
return new Response(await r.blob(), {status: r.status, statusText: r.statusText, headers: h});
}
async function store(c, key) {
const r = await fetch(key, {cache: "no-cache"});
if (r.status !== 200 || r.redirected) throw new Error("not kept");
const k = await keepable(r);
await c.put(key, k.clone());
return k;
}
// The page from the server, asked against the build kept ("not modified": {}): another build is
// kept at once (`changed`).
async function renew(c, held) {
const key = scope(), was = held.headers.get("ETag");
const r = await fetch(key, {cache: "no-store", headers: was ? {"If-None-Match": was} : {}});
if (r.status !== 200 || r.redirected) return {};
const page = await keepable(r);
// (No tag from the server: never taken for a new build, or every opening would be one.)
const now = page.headers.get("ETag"), changed = !!now && now !== was;
if (changed) await c.put(key, page.clone());
return {page, changed};
}
async function iconsAgain(c) {
const key = scope();
await Promise.all((await c.keys()).map((q) => q.url).filter((k) => k !== key).map((k) => store(c, k).catch(() => {})));
}
async function tell() {
for (const w of await self.clients.matchAll({type: "window"})) w.postMessage({fresh: true});
}
self.addEventListener("install", (e) => {
self.skipWaiting();
e.waitUntil(caches.open(SHELL).then((c) => Promise.all(FIRST.map((k) => store(c, new URL(k, scope()).href).catch(() => {})))));
});
self.addEventListener("activate", (e) => e.waitUntil((async () => {
for (const k of await caches.keys()) if (k.startsWith("anybot-shell-") && k !== SHELL) await caches.delete(k);
await self.clients.claim();
})()));
self.addEventListener("fetch", (e) => {
if (e.request.method !== "GET") return;
const key = keyOf(e.request.url);
if (!key) return;
e.respondWith((async () => {
const c = await caches.open(SHELL);
const held = await c.match(key);
if (!held) return store(c, key).catch(() => fetch(e.request));
if (key !== scope()) return held;
// 重新整理: the server's first (this build if nothing changed); the kept one only when it can't be reached.
if (e.request.mode === "navigate" && (e.request.cache === "reload" || e.request.cache === "no-cache")) {
const {page, changed} = await renew(c, held).catch(() => ({}));
if (changed) e.waitUntil(iconsAgain(c).catch(() => {}));
return page || held;
}
e.waitUntil(renew(c, held).then(async ({changed}) => { if (changed) { await tell(); await iconsAgain(c); } }).catch(() => {}));
return held;
})());
});
// kind: need(需要你允許、問你、需要你處理)、done(做完了)、routine(例行任務暫停)、file(收到傳來的檔案)、test。
self.addEventListener("push", (e) => {
let d = {};
try { d = e.data ? e.data.json() : {}; } catch (_) { d = {body: e.data ? e.data.text() : ""}; }
const need = d.kind === "need";
const shown = self.registration.showNotification(d.title || "AnyBot", {
body: d.body || "",
// One notification per bot: the newest word about it replaces the last one, and still rings.
tag: d.kind === "test" ? "test" : "bot-" + (d.bot || 0),
renotify: true,
data: d,
icon: "icon-192.png",
badge: "badge-96.png",
timestamp: Date.now(),
// 需要你: stays until you look (Android, desktop), and buzzes twice.
requireInteraction: need,
vibrate: need ? [90, 70, 90] : [70],
// 允許/拒絕 right on the banner (Android; iOS opens the chat): only for a request to allow,
// and it answers only that request (d.ask is its id — the brain checks it is still the one waiting).
actions: d.ask ? [{action: "allow", title: "允許"}, {action: "deny", title: "拒絕"}] : [],
});
// The number on the app's icon: bots waiting for you.
const n = typeof d.badge === "number" ? d.badge : null;
const badge = n === null || !self.navigator.setAppBadge ? null : n > 0 ? self.navigator.setAppBadge(n) : self.navigator.clearAppBadge();
e.waitUntil(Promise.all([shown, badge].filter(Boolean)).catch(() => {}));
});
self.addEventListener("notificationclick", (e) => {
e.notification.close();
const d = e.notification.data || {};
const answer = d.ask && e.action === "allow" ? "once" : d.ask && e.action === "deny" ? "reject" : "";
const url = "./#host=" + encodeURIComponent(d.host || "") + "&bot=" + (d.bot || "") + (answer ? "&answer=" + answer + "&call=" + encodeURIComponent(d.ask) : "");
e.waitUntil(self.clients.matchAll({type: "window", includeUncontrolled: true}).then((cs) => {
for (const c of cs) { c.postMessage({open: Object.assign({}, d, {answer})}); return c.focus(); }
return self.clients.openWindow(url);
}));
});