43 lines
2.5 KiB
JavaScript
43 lines
2.5 KiB
JavaScript
// AnyBot 手機 App 的 Service Worker(帳號伺服器送出):推播通知、點通知打開那個 Bot、App 圖示上的數字。
|
||
// 通知的圖示是 AnyBot 的貓(黃色底);Android 狀態列的小圖示只能是單色,用那隻貓的剪影(badge-96.png)。
|
||
self.addEventListener("install", () => self.skipWaiting());
|
||
self.addEventListener("activate", (e) => e.waitUntil(self.clients.claim()));
|
||
|
||
// 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);
|
||
}));
|
||
});
|