2020-08-05 18:38:55 +02:00
|
|
|
/*
|
|
|
|
Copyright 2020 Bruno Windels <bruno@windels.cloud>
|
2020-10-05 15:10:06 +02:00
|
|
|
Copyright 2020 The Matrix.org Foundation C.I.C.
|
2020-08-05 18:38:55 +02:00
|
|
|
|
|
|
|
Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
you may not use this file except in compliance with the License.
|
|
|
|
You may obtain a copy of the License at
|
|
|
|
|
|
|
|
http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
|
|
|
Unless required by applicable law or agreed to in writing, software
|
|
|
|
distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
See the License for the specific language governing permissions and
|
|
|
|
limitations under the License.
|
|
|
|
*/
|
|
|
|
|
2021-12-09 15:13:05 +01:00
|
|
|
import NOTIFICATION_BADGE_ICON from "./assets/icon.png?url";
|
|
|
|
// replaced by the service worker build plugin
|
2021-12-09 16:37:31 +01:00
|
|
|
const UNHASHED_PRECACHED_ASSETS = DEFINE_UNHASHED_PRECACHED_ASSETS;
|
|
|
|
const HASHED_PRECACHED_ASSETS = DEFINE_HASHED_PRECACHED_ASSETS;
|
|
|
|
const HASHED_CACHED_ON_REQUEST_ASSETS = DEFINE_HASHED_CACHED_ON_REQUEST_ASSETS;
|
2021-12-09 15:13:05 +01:00
|
|
|
|
2021-12-09 16:37:31 +01:00
|
|
|
const unhashedCacheName = `hydrogen-assets-${DEFINE_GLOBAL_HASH}`;
|
2020-10-02 19:54:24 +02:00
|
|
|
const hashedCacheName = `hydrogen-assets`;
|
2020-10-20 17:28:42 +02:00
|
|
|
const mediaThumbnailCacheName = `hydrogen-media-thumbnails-v2`;
|
2019-09-15 14:32:12 +02:00
|
|
|
|
|
|
|
self.addEventListener('install', function(e) {
|
2020-10-02 19:54:24 +02:00
|
|
|
e.waitUntil((async () => {
|
|
|
|
const unhashedCache = await caches.open(unhashedCacheName);
|
|
|
|
await unhashedCache.addAll(UNHASHED_PRECACHED_ASSETS);
|
|
|
|
const hashedCache = await caches.open(hashedCacheName);
|
|
|
|
await Promise.all(HASHED_PRECACHED_ASSETS.map(async asset => {
|
|
|
|
if (!await hashedCache.match(asset)) {
|
|
|
|
await hashedCache.add(asset);
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
})());
|
2019-09-15 14:32:12 +02:00
|
|
|
});
|
|
|
|
|
2021-03-18 19:34:41 +01:00
|
|
|
self.addEventListener('activate', (event) => {
|
|
|
|
// on a first page load/sw install,
|
|
|
|
// start using the service worker on all pages straight away
|
|
|
|
self.clients.claim();
|
|
|
|
event.waitUntil(purgeOldCaches());
|
|
|
|
});
|
|
|
|
|
2020-10-02 19:54:24 +02:00
|
|
|
async function purgeOldCaches() {
|
|
|
|
// remove any caches we don't know about
|
|
|
|
const keyList = await caches.keys();
|
|
|
|
for (const key of keyList) {
|
2020-10-05 15:58:29 +02:00
|
|
|
if (key !== unhashedCacheName && key !== hashedCacheName && key !== mediaThumbnailCacheName) {
|
2020-10-02 19:54:24 +02:00
|
|
|
await caches.delete(key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
// remove the cache for any old hashed resource
|
|
|
|
const hashedCache = await caches.open(hashedCacheName);
|
|
|
|
const keys = await hashedCache.keys();
|
|
|
|
const hashedAssetURLs =
|
|
|
|
HASHED_PRECACHED_ASSETS
|
|
|
|
.concat(HASHED_CACHED_ON_REQUEST_ASSETS)
|
|
|
|
.map(a => new URL(a, self.registration.scope).href);
|
|
|
|
|
|
|
|
for (const request of keys) {
|
|
|
|
if (!hashedAssetURLs.some(url => url === request.url)) {
|
|
|
|
hashedCache.delete(request);
|
2019-09-15 14:32:12 +02:00
|
|
|
}
|
2020-10-02 19:54:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-11-08 17:50:56 +01:00
|
|
|
self.addEventListener('fetch', (event) => {
|
2021-11-09 11:09:24 +01:00
|
|
|
/*
|
|
|
|
service worker shouldn't handle xhr uploads because otherwise
|
|
|
|
the progress events won't fire.
|
|
|
|
This has to do with xhr not being supported in service workers.
|
|
|
|
*/
|
2021-11-08 13:33:20 +01:00
|
|
|
if (event.request.method === "GET") {
|
|
|
|
event.respondWith(handleRequest(event.request));
|
2021-11-08 10:07:32 +01:00
|
|
|
}
|
2019-09-15 14:32:12 +02:00
|
|
|
});
|
2020-10-02 19:54:24 +02:00
|
|
|
|
2020-10-20 17:28:42 +02:00
|
|
|
function isCacheableThumbnail(url) {
|
|
|
|
if (url.pathname.startsWith("/_matrix/media/r0/thumbnail/")) {
|
|
|
|
const width = parseInt(url.searchParams.get("width"), 10);
|
|
|
|
const height = parseInt(url.searchParams.get("height"), 10);
|
|
|
|
if (width <= 50 && height <= 50) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2020-10-23 12:58:45 +02:00
|
|
|
const baseURL = new URL(self.registration.scope);
|
2021-03-18 19:34:41 +01:00
|
|
|
let pendingFetchAbortController = new AbortController();
|
2020-10-02 19:54:24 +02:00
|
|
|
async function handleRequest(request) {
|
2020-11-05 22:51:21 +01:00
|
|
|
try {
|
|
|
|
const url = new URL(request.url);
|
2021-03-18 19:34:41 +01:00
|
|
|
// rewrite / to /index.html so it hits the cache
|
2020-11-05 22:51:21 +01:00
|
|
|
if (url.origin === baseURL.origin && url.pathname === baseURL.pathname) {
|
|
|
|
request = new Request(new URL("index.html", baseURL.href));
|
|
|
|
}
|
|
|
|
let response = await readCache(request);
|
|
|
|
if (!response) {
|
|
|
|
// use cors so the resource in the cache isn't opaque and uses up to 7mb
|
|
|
|
// https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps?utm_source=devtools#opaque-responses
|
|
|
|
if (isCacheableThumbnail(url)) {
|
2021-03-18 19:34:41 +01:00
|
|
|
response = await fetch(request, {signal: pendingFetchAbortController.signal, mode: "cors", credentials: "omit"});
|
2020-11-05 22:51:21 +01:00
|
|
|
} else {
|
2021-03-18 19:34:41 +01:00
|
|
|
response = await fetch(request, {signal: pendingFetchAbortController.signal});
|
2020-11-05 22:51:21 +01:00
|
|
|
}
|
|
|
|
await updateCache(request, response);
|
|
|
|
}
|
|
|
|
return response;
|
|
|
|
} catch (err) {
|
2021-03-18 19:34:41 +01:00
|
|
|
if (err.name !== "TypeError" && err.name !== "AbortError") {
|
2020-11-05 22:51:21 +01:00
|
|
|
console.error("error in service worker", err);
|
2020-10-20 17:28:42 +02:00
|
|
|
}
|
2020-11-05 22:51:21 +01:00
|
|
|
throw err;
|
2020-10-02 19:54:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function updateCache(request, response) {
|
2020-11-05 22:31:00 +01:00
|
|
|
// don't write error responses to the cache
|
|
|
|
if (response.status >= 400) {
|
|
|
|
return;
|
|
|
|
}
|
2020-10-05 15:58:29 +02:00
|
|
|
const url = new URL(request.url);
|
2020-10-02 19:54:24 +02:00
|
|
|
const baseURL = self.registration.scope;
|
2020-10-20 17:28:42 +02:00
|
|
|
if (isCacheableThumbnail(url)) {
|
|
|
|
const cache = await caches.open(mediaThumbnailCacheName);
|
|
|
|
cache.put(request, response.clone());
|
2020-10-05 15:58:29 +02:00
|
|
|
} else if (request.url.startsWith(baseURL)) {
|
|
|
|
let assetName = request.url.substr(baseURL.length);
|
|
|
|
if (HASHED_CACHED_ON_REQUEST_ASSETS.includes(assetName)) {
|
|
|
|
const cache = await caches.open(hashedCacheName);
|
|
|
|
await cache.put(request, response.clone());
|
|
|
|
}
|
2020-10-02 19:54:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
async function readCache(request) {
|
|
|
|
const unhashedCache = await caches.open(unhashedCacheName);
|
|
|
|
let response = await unhashedCache.match(request);
|
|
|
|
if (response) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
const hashedCache = await caches.open(hashedCacheName);
|
|
|
|
response = await hashedCache.match(request);
|
2020-10-05 15:58:29 +02:00
|
|
|
if (response) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
const url = new URL(request.url);
|
2020-10-20 17:28:42 +02:00
|
|
|
if (isCacheableThumbnail(url)) {
|
2020-10-05 15:58:29 +02:00
|
|
|
const mediaThumbnailCache = await caches.open(mediaThumbnailCacheName);
|
|
|
|
response = await mediaThumbnailCache.match(request);
|
2020-11-05 22:31:00 +01:00
|
|
|
// added in 0.1.26, remove previously cached error responses, remove this in some time
|
2020-11-05 22:45:20 +01:00
|
|
|
if (response?.status >= 400) {
|
2020-11-05 22:31:00 +01:00
|
|
|
await mediaThumbnailCache.delete(request);
|
|
|
|
response = null;
|
|
|
|
}
|
2020-10-05 15:58:29 +02:00
|
|
|
}
|
2020-10-02 19:54:24 +02:00
|
|
|
return response;
|
|
|
|
}
|
2020-10-16 12:50:19 +02:00
|
|
|
|
|
|
|
self.addEventListener('message', (event) => {
|
|
|
|
const reply = payload => event.source.postMessage({replyTo: event.data.id, payload});
|
|
|
|
const {replyTo} = event.data;
|
|
|
|
if (replyTo) {
|
|
|
|
const resolve = pendingReplies.get(replyTo);
|
|
|
|
if (resolve) {
|
|
|
|
pendingReplies.delete(replyTo);
|
|
|
|
resolve(event.data.payload);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
switch (event.data?.type) {
|
|
|
|
case "version":
|
2021-12-09 16:37:31 +01:00
|
|
|
reply({version: DEFINE_VERSION, buildHash: DEFINE_GLOBAL_HASH});
|
2020-10-16 12:50:19 +02:00
|
|
|
break;
|
|
|
|
case "skipWaiting":
|
|
|
|
self.skipWaiting();
|
|
|
|
break;
|
2021-03-18 19:34:41 +01:00
|
|
|
case "haltRequests":
|
2021-03-18 19:49:06 +01:00
|
|
|
event.waitUntil(haltRequests().finally(() => reply()));
|
2021-03-18 19:34:41 +01:00
|
|
|
break;
|
2020-10-16 12:50:19 +02:00
|
|
|
case "closeSession":
|
|
|
|
event.waitUntil(
|
|
|
|
closeSession(event.data.payload.sessionId, event.source.id)
|
2021-03-18 19:49:06 +01:00
|
|
|
.finally(() => reply())
|
2020-10-16 12:50:19 +02:00
|
|
|
);
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2021-03-24 15:23:01 +01:00
|
|
|
const NOTIF_TAG_NEW_MESSAGE = "new_message";
|
|
|
|
|
2021-03-18 20:46:11 +01:00
|
|
|
async function openClientFromNotif(event) {
|
2021-03-24 15:25:59 +01:00
|
|
|
if (event.notification.tag !== NOTIF_TAG_NEW_MESSAGE) {
|
2021-03-25 10:11:05 +01:00
|
|
|
console.log("clicked notif with tag", event.notification.tag);
|
2021-03-24 15:25:59 +01:00
|
|
|
return;
|
|
|
|
}
|
2021-03-18 20:46:11 +01:00
|
|
|
const {sessionId, roomId} = event.notification.data;
|
|
|
|
const sessionHash = `#/session/${sessionId}`;
|
|
|
|
const roomHash = `${sessionHash}/room/${roomId}`;
|
2021-03-24 15:25:59 +01:00
|
|
|
const clientWithSession = await findClient(async client => {
|
|
|
|
return await sendAndWaitForReply(client, "hasSessionOpen", {sessionId});
|
|
|
|
});
|
|
|
|
if (clientWithSession) {
|
|
|
|
console.log("notificationclick: client has session open, showing room there");
|
2021-03-31 16:51:25 +02:00
|
|
|
// use a message rather than clientWithSession.navigate here as this refreshes the page on chrome
|
|
|
|
clientWithSession.postMessage({type: "openRoom", payload: {roomId}});
|
2021-03-24 15:25:59 +01:00
|
|
|
if ('focus' in clientWithSession) {
|
2021-03-25 10:03:44 +01:00
|
|
|
try {
|
|
|
|
await clientWithSession.focus();
|
|
|
|
} catch (err) { console.error(err); } // I've had this throw on me on Android
|
2021-03-18 20:46:11 +01:00
|
|
|
}
|
2021-03-25 10:01:25 +01:00
|
|
|
} else if (self.clients.openWindow) {
|
2021-03-24 15:25:59 +01:00
|
|
|
console.log("notificationclick: no client found with session open, opening new window");
|
2021-03-31 16:34:37 +02:00
|
|
|
const roomURL = new URL(`./${roomHash}`, baseURL).href;
|
2021-03-18 20:46:11 +01:00
|
|
|
await self.clients.openWindow(roomURL);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
self.addEventListener('notificationclick', event => {
|
|
|
|
event.notification.close();
|
|
|
|
event.waitUntil(openClientFromNotif(event));
|
|
|
|
});
|
|
|
|
|
2021-03-24 15:23:01 +01:00
|
|
|
async function handlePushNotification(n) {
|
2021-03-18 20:45:46 +01:00
|
|
|
console.log("got a push message", n);
|
2021-03-24 15:23:01 +01:00
|
|
|
const sessionId = n.session_id;
|
2021-03-18 20:45:46 +01:00
|
|
|
let sender = n.sender_display_name || n.sender;
|
|
|
|
if (sender && n.event_id) {
|
2021-03-24 15:23:01 +01:00
|
|
|
const roomId = n.room_id;
|
|
|
|
const hasFocusedClientOnRoom = !!await findClient(async client => {
|
|
|
|
if (client.visibilityState === "visible" && client.focused) {
|
|
|
|
return await sendAndWaitForReply(client, "hasRoomOpen", {sessionId, roomId});
|
|
|
|
}
|
|
|
|
});
|
|
|
|
if (hasFocusedClientOnRoom) {
|
|
|
|
console.log("client is focused, room is open, don't show notif");
|
|
|
|
return;
|
|
|
|
}
|
2021-03-25 10:08:38 +01:00
|
|
|
const newMessageNotifs = Array.from(await self.registration.getNotifications({tag: NOTIF_TAG_NEW_MESSAGE}));
|
|
|
|
const notifsForRoom = newMessageNotifs.filter(n => n.data.roomId === roomId);
|
|
|
|
const hasMultiNotification = notifsForRoom.some(n => n.data.multi);
|
2021-03-25 11:13:54 +01:00
|
|
|
const hasSingleNotifsForRoom = newMessageNotifs.some(n => !n.data.multi);
|
|
|
|
const roomName = n.room_name || n.room_alias;
|
2021-03-25 10:08:38 +01:00
|
|
|
let multi = false;
|
2021-03-18 20:45:46 +01:00
|
|
|
let label;
|
2021-03-25 10:08:38 +01:00
|
|
|
let body;
|
|
|
|
if (hasMultiNotification) {
|
|
|
|
console.log("already have a multi message, don't do anything");
|
|
|
|
return;
|
2021-03-25 11:13:54 +01:00
|
|
|
} else if (hasSingleNotifsForRoom) {
|
2021-03-25 10:08:38 +01:00
|
|
|
console.log("showing multi message notification");
|
|
|
|
multi = true;
|
|
|
|
label = roomName || sender;
|
|
|
|
body = "New messages";
|
2021-03-18 20:45:46 +01:00
|
|
|
} else {
|
2021-03-25 10:08:38 +01:00
|
|
|
console.log("showing new message notification");
|
|
|
|
if (roomName && roomName !== sender) {
|
|
|
|
label = `${sender} in ${roomName}`;
|
|
|
|
} else {
|
|
|
|
label = sender;
|
|
|
|
}
|
|
|
|
body = n.content?.body || "New message";
|
2021-03-18 20:45:46 +01:00
|
|
|
}
|
2021-03-24 15:23:01 +01:00
|
|
|
await self.registration.showNotification(label, {
|
2021-03-18 20:45:46 +01:00
|
|
|
body,
|
2021-03-25 10:08:38 +01:00
|
|
|
data: {sessionId, roomId, multi},
|
|
|
|
tag: NOTIF_TAG_NEW_MESSAGE,
|
2021-03-25 00:12:57 +01:00
|
|
|
badge: NOTIFICATION_BADGE_ICON
|
2021-03-18 20:45:46 +01:00
|
|
|
});
|
|
|
|
}
|
2021-03-25 10:08:38 +01:00
|
|
|
// we could consider hiding previous notifications here based on the unread count
|
|
|
|
// (although we can't really figure out which notifications to hide) and also hiding
|
|
|
|
// notifications makes it hard to ensure we always show a notification after a push message
|
|
|
|
// when no client is visible, see https://goo.gl/yqv4Q4
|
2021-03-24 15:23:01 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
self.addEventListener('push', event => {
|
|
|
|
event.waitUntil(handlePushNotification(event.data.json()));
|
2021-03-18 20:45:46 +01:00
|
|
|
});
|
2020-10-16 12:50:19 +02:00
|
|
|
|
|
|
|
async function closeSession(sessionId, requestingClientId) {
|
|
|
|
const clients = await self.clients.matchAll();
|
|
|
|
await Promise.all(clients.map(async client => {
|
|
|
|
if (client.id !== requestingClientId) {
|
|
|
|
await sendAndWaitForReply(client, "closeSession", {sessionId});
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2021-03-18 19:34:41 +01:00
|
|
|
async function haltRequests() {
|
|
|
|
// first ask all clients to block sending any more requests
|
|
|
|
const clients = await self.clients.matchAll({type: "window"});
|
|
|
|
await Promise.all(clients.map(client => {
|
|
|
|
return sendAndWaitForReply(client, "haltRequests");
|
|
|
|
}));
|
|
|
|
// and only then abort the current requests
|
|
|
|
pendingFetchAbortController.abort();
|
|
|
|
}
|
|
|
|
|
2020-10-16 12:50:19 +02:00
|
|
|
const pendingReplies = new Map();
|
|
|
|
let messageIdCounter = 0;
|
|
|
|
function sendAndWaitForReply(client, type, payload) {
|
|
|
|
messageIdCounter += 1;
|
|
|
|
const id = messageIdCounter;
|
|
|
|
const promise = new Promise(resolve => {
|
|
|
|
pendingReplies.set(id, resolve);
|
|
|
|
});
|
|
|
|
client.postMessage({type, id, payload});
|
|
|
|
return promise;
|
|
|
|
}
|
2021-03-24 15:23:01 +01:00
|
|
|
|
|
|
|
async function findClient(predicate) {
|
|
|
|
const clientList = await self.clients.matchAll({type: "window"});
|
|
|
|
for (const client of clientList) {
|
|
|
|
if (await predicate(client)) {
|
|
|
|
return client;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|