cache small media repo thumbnails in service worker

This commit is contained in:
Bruno Windels 2020-10-05 15:58:29 +02:00
parent c8fd9d423d
commit 8f5d678698

View File

@ -21,6 +21,7 @@ const HASHED_PRECACHED_ASSETS = "%%HASHED_PRECACHED_ASSETS%%";
const HASHED_CACHED_ON_REQUEST_ASSETS = "%%HASHED_CACHED_ON_REQUEST_ASSETS%%"; const HASHED_CACHED_ON_REQUEST_ASSETS = "%%HASHED_CACHED_ON_REQUEST_ASSETS%%";
const unhashedCacheName = `hydrogen-assets-${GLOBAL_HASH}`; const unhashedCacheName = `hydrogen-assets-${GLOBAL_HASH}`;
const hashedCacheName = `hydrogen-assets`; const hashedCacheName = `hydrogen-assets`;
const mediaThumbnailCacheName = `hydrogen-media-thumbnails`;
self.addEventListener('install', function(e) { self.addEventListener('install', function(e) {
e.waitUntil((async () => { e.waitUntil((async () => {
@ -39,7 +40,7 @@ async function purgeOldCaches() {
// remove any caches we don't know about // remove any caches we don't know about
const keyList = await caches.keys(); const keyList = await caches.keys();
for (const key of keyList) { for (const key of keyList) {
if (key !== unhashedCacheName && key !== hashedCacheName) { if (key !== unhashedCacheName && key !== hashedCacheName && key !== mediaThumbnailCacheName) {
await caches.delete(key); await caches.delete(key);
} }
} }
@ -80,14 +81,21 @@ async function handleRequest(request) {
} }
async function updateCache(request, response) { async function updateCache(request, response) {
const url = new URL(request.url);
const baseURL = self.registration.scope; const baseURL = self.registration.scope;
if(!request.url.startsWith(baseURL)) { if (url.pathname.startsWith("/_matrix/media/r0/thumbnail/")) {
return; const width = parseInt(url.searchParams.get("width"), 10);
} const height = parseInt(url.searchParams.get("height"), 10);
let assetName = request.url.substr(baseURL.length); if (width <= 50 && height <= 50) {
if (HASHED_CACHED_ON_REQUEST_ASSETS.includes(assetName)) { const cache = await caches.open(mediaThumbnailCacheName);
const cache = await caches.open(hashedCacheName); cache.put(request, response.clone());
await cache.put(request, response.clone()); }
} 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());
}
} }
} }
@ -99,6 +107,15 @@ async function readCache(request) {
} }
const hashedCache = await caches.open(hashedCacheName); const hashedCache = await caches.open(hashedCacheName);
response = await hashedCache.match(request); response = await hashedCache.match(request);
if (response) {
return response;
}
const url = new URL(request.url);
if (url.pathname.startsWith("/_matrix/media/r0/thumbnail/")) {
const mediaThumbnailCache = await caches.open(mediaThumbnailCacheName);
response = await mediaThumbnailCache.match(request);
}
return response; return response;
} }