summaryrefslogtreecommitdiff
path: root/worker.js
blob: e40d731daf62358ebbf16b100a06d471180db2f2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const CACHE_PREFIX = 'epube';
const CACHE_NAME = CACHE_PREFIX + '-v3';

self.addEventListener('activate', function(event) {
	event.waitUntil(
		caches.keys().then(function(keyList) {
			return Promise.all(keyList.map((key) => {
				if (key.indexOf(CACHE_PREFIX) != -1 && key != CACHE_NAME) {
					return caches.delete(key);
				}
				return false;
			}));
		})
    );
});

function send_message(client, msg) {
	return client.postMessage(msg);
}

function send_broadcast(msg) {
	return self.clients.matchAll().then((clients) => {
		clients.forEach((client) => {
			send_message(client, msg);
		})
	})
}

self.addEventListener('message', async (event) => {
	console.log('[worker] got message', event.data);

	if (event.data.msg == 'refresh-cache') {
		console.log("[worker] refreshing cache...");

		await send_broadcast('refresh-started');

		const cache = await caches.open(CACHE_NAME);

		await Promise.all(event.data.urls.map(async (url) => {
			const resp = await fetch(url + "?ts=" + Date.now());
			send_broadcast('refreshed:' + resp.url);
			if (resp.ok) {
				console.log('[worker] refresh complete for', resp.url);
				return cache.put(url, resp);
			} else if (resp.status == 404) {
				console.log('[worker] removing obsolete file', resp.url);
				return cache.delete(url);
			}
		}));

		console.log('[worker] refresh finished');

		await send_broadcast('refresh-finished');
	}
});

this.addEventListener('fetch', (event) => {
	if (event.request.url.match('/assets/'))
		return;

	event.respondWith(caches.match(event.request).then((resp) => {
			if (resp) {
				console.log('[worker] cache hit for', event.request.url);
				return resp;
			} else {
				console.log('[worker] cache miss for', event.request.url);
				return fetch(event.request.clone())
					.then((resp) => {
						if (resp.ok && resp.url.match("backend.php\\?op=(cover|getinfo)")) {
							return caches.open(CACHE_NAME).then((cache) => {
								console.log('[worker] caching response', resp.url);
								cache.put(resp.url, resp.clone());
								return resp;
							});
						} else {
							return resp;
						}
					})
					.catch((err) => {
						console.warn('[worker] fetch request failed', event.request.url, err);

						if (event.request.url[event.request.url.length-1] == "/" || event.request.url.match("index.php|offline.html")) {
							return caches.match("offline.html");
						} else if (event.request.url.match("read.html")) {
							return caches.match("read.html");
						} else {
							console.error('[worker] no fetch fallback for ', event.request.url);
						}
					}
				);
			}
		})
	);
});