about summary refs log tree commit diff stats
path: root/src
diff options
context:
space:
mode:
authorAndrew Dolgov <fox@fakecake.org>2026-05-28 18:19:58 +0300
committerAndrew Dolgov <fox@fakecake.org>2026-05-28 18:19:58 +0300
commitd4f72e3aeaae49501e46ac4fbe825c6d747b4150 (patch)
treea1fa38e1f376c1f7fdc119b613c2fb3ab186ae80 /src
parentf67299765ab2d276b07b2354b1e42e698cdf3e8a (diff)
downloadthe-epube-d4f72e3aeaae49501e46ac4fbe825c6d747b4150.tar.gz
the-epube-d4f72e3aeaae49501e46ac4fbe825c6d747b4150.tar.xz
embed cache version & build timestamp into generated JS files, drop previous sync mechanism, rewrite serviceworker to be less fragile
Diffstat (limited to 'src')
-rw-r--r--src/app.js135
-rw-r--r--src/index.d.ts3
-rw-r--r--src/reader.js92
-rw-r--r--src/worker.js145
4 files changed, 267 insertions, 108 deletions
diff --git a/src/app.js b/src/app.js
index e340727..dca9d76 100644
--- a/src/app.js
+++ b/src/app.js
@@ -47,6 +47,44 @@ class AppCommon {
 			return navigator.onLine;
 	}
 
+	async getActiveCacheName() {
+		const registration = await navigator.serviceWorker.ready;
+		const worker = registration.active;
+
+		if (!worker) return null;
+
+		return new Promise((resolve) => {
+			const channel = new MessageChannel();
+
+			// Listen for the service worker's response
+			channel.port1.onmessage = (event) => {
+				resolve(event.data.cacheName);
+			};
+
+			// Dispatch message to the service worker along with the response port
+			worker.postMessage({ type: 'GET_CACHE_NAME' }, [channel.port2]);
+		});
+	}
+
+	async getActiveCacheVersion() {
+		const registration = await navigator.serviceWorker.ready;
+		const worker = registration.active;
+
+		if (!worker) return null;
+
+		return new Promise((resolve) => {
+			const channel = new MessageChannel();
+
+			// Listen for the service worker's response
+			channel.port1.onmessage = (event) => {
+				resolve(event.data.cacheName);
+			};
+
+			// Dispatch message to the service worker along with the response port
+			worker.postMessage({ type: 'GET_CACHE_VERSION' }, [channel.port2]);
+		});
+	}
+
 	initNightMode() {
 		if (typeof EpubeApp != "undefined") {
 			this.applyNightMode(EpubeApp.isNightMode());
@@ -84,14 +122,14 @@ class AppClass extends AppCommon {
 
 	cached_urls = [];
 
-	version = "UNKNOWN";
+	version = BUILD_CACHE_VERSION;
 
-	buildTimestamp = 0;
+	// cacheManifest = [];
 
 	csrf_token = "";
 
-	init() {
-		let refreshed_files = 0;
+	async init() {
+		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
 
 		this.csrf_token = Cookie.get('epube_csrf_token');
 
@@ -115,36 +153,13 @@ class AppClass extends AppCommon {
 		this.populateList();
 
 		if ('serviceWorker' in navigator) {
-			navigator.serviceWorker.addEventListener('message', (event) => {
-
-				if (event.data == 'refresh-started') {
-					console.log('cache refresh started');
-					refreshed_files = 0;
-
-					$(".dl-progress")
-						.fadeIn()
-						.text("Loading, please wait...");
-				}
-
-				if (event.data && event.data.indexOf("refreshed:") == 0) {
-					++refreshed_files;
-
-					$(".dl-progress")
-						.fadeIn()
-						.text("Updated " + refreshed_files + " files...");
-				}
-
-				if (event.data == 'refresh-finished') {
-					localforage.setItem("epube.cache-version", this.version);
-					localforage.setItem("epube.cache-timestamp", this.buildTimestamp);
-					window.location.reload()
-				}
-
+			navigator.serviceWorker.addEventListener('message', () => {
+				// Future: handle SW messages (e.g., update available notifications)
 			});
 
 			this.showCovers();
 			this.updateOfflinePrompts();
-			this.refreshCache();
+			//this.refreshCache();
 
 		} else {
 			$(".container-main")
@@ -154,9 +169,9 @@ class AppClass extends AppCommon {
 	}
 
 	initCommonEventHandlers() {
-		$(".refresh_cache_link").on('click', () => {
+		/* $(".refresh_cache_link").on('click', () => {
 			this.refreshCache(true);
-		});
+		}); */
 
 		$(".remove_all_downloads").on('click', () => {
 			this.removeAll();
@@ -249,48 +264,34 @@ class AppClass extends AppCommon {
 		return false;
 	}
 
-	async refreshCache(force) {
+	/* async refreshCache(force) {
 		if ('serviceWorker' in navigator) {
-			const version = await localforage.getItem("epube.cache-version");
+			const cachedVersion = await localforage.getItem("epube.cache-version");
 
-			console.log('local version', version, 'remote version', this.version);
+			console.log('cached version', cachedVersion, 'current version', this.version);
 
-			if (force || version != this.version) {
-				console.log('asking worker to refresh cache');
+			if (force || cachedVersion != this.version) {
+				console.log('cache needs update, reloading...');
 
+				// Show progress if SW is already controlling the page
 				if (navigator.serviceWorker.controller) {
-					navigator.serviceWorker.controller.postMessage({msg: "refresh-cache", urls: this.cached_urls});
-				} else {
-					const done = await localforage.getItem("epube.initial-load-done");
-
-					console.log("initial load done?", done);
-
-					if (done) {
-						$(".dl-progress")
-							.show()
-							.addClass("alert-danger")
-							.html("Could not communicate with service worker. Try reloading the page.");
-					} else {
-						await localforage.setItem("epube.initial-load-done", true);
+					$(".dl-progress")
+						.show()
+						.addClass("alert-info")
+						.html("Updating cache...");
+				}
 
-						$(".dl-progress")
-							.show()
-							.addClass("alert-info")
-							.html("Page will reload to activate service worker...");
+				await localforage.setItem("epube.cache-version", this.version);
 
-						window.setTimeout(function() {
-							window.location.reload();
-						}, 3*1000);
-					}
-				}
+				// Reload — the SW will precache new assets on install
+				// and serve from cache on the next load
+				window.location.reload();
+			} else {
+				// Version matches — save it so we don't keep reloading
+				await localforage.setItem("epube.cache-version", this.version);
 			}
-		} else {
-			$(".dl-progress")
-				.show()
-				.addClass("alert-danger")
-				.html("Could not communicate with service worker. Try reloading the page.");
 		}
-	}
+	} */
 
 	updateOfflinePrompts() {
 		const elems = $(".offline_dropitem");
@@ -329,7 +330,9 @@ class AppClass extends AppCommon {
 		}
 	}
 
-	offlineInit() {
+	async offlineInit() {
+		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+
 		if (typeof EpubeApp != "undefined") {
 			$(".navbar").hide();
 			$(".epube-app-filler").show();
diff --git a/src/index.d.ts b/src/index.d.ts
index 6f25e34..9a01600 100644
--- a/src/index.d.ts
+++ b/src/index.d.ts
@@ -13,3 +13,6 @@ declare interface EpubeApp {
 declare var EpubeApp: EpubeApp;
 
 declare var localforage: LocalForage;
+
+declare const BUILD_CACHE_VERSION: string;
+declare const BUILD_MANIFEST_ASSETS: string;
diff --git a/src/reader.js b/src/reader.js
index b3a470a..1ffb06e 100644
--- a/src/reader.js
+++ b/src/reader.js
@@ -28,6 +28,8 @@ class ReaderClass extends AppCommon {
 
 	_prevent_lastread;
 
+	version = BUILD_CACHE_VERSION;
+
 	/**
 	 * @type {ePub.Book}
 	 */
@@ -108,6 +110,8 @@ class ReaderClass extends AppCommon {
 	}
 
 	async init() {
+		console.log('version', this.version, 'current, worker', await this.getActiveCacheVersion());
+
 		this.csrf_token = Cookie.get('epube_csrf_token');
 
 		/** global setupCsrfPrefilter */
@@ -149,7 +153,7 @@ class ReaderClass extends AppCommon {
 			this.onTouchEnd(evt);
 		});
 
-		const load_failed = await this.loader.init();
+		const load_failed = await this.loader.init(this);
 
 		console.log('[init] load failed', load_failed);
 
@@ -692,11 +696,7 @@ class ReaderClass extends AppCommon {
 				});
 			}
 
-			const stamp = await localforage.getItem("epube.cache-timestamp");
-			const version = await localforage.getItem("epube.cache-version");
-
-			$(".last-mod-timestamp").html(`${version}
-				&mdash; ${parseInt(stamp) ? new Date(stamp*1000).toLocaleString("en-GB") : "Unknown"}
+			$(".last-mod-timestamp").html(`${this.version}
 				(${this.isOnline() ? `<span class='text-success'>Online</span>` : `<span class='text-danger'>Offline</span>`})
 				`);
 
@@ -1719,59 +1719,67 @@ class ReaderClass extends AppCommon {
 }
 
 class ReaderLoader {
-	_res_data = [];
+	_res_data = {};
 
-	CACHE_NAME = 'epube-v3';
+	/**
+	 * @param {ReaderClass} app
+	 */
+	async init(app) {
+		const cacheName = await app.getActiveCacheName();
+
+		console.log('loader init for cache:', cacheName);
 
-	async init() {
 		if (typeof EpubeApp != "undefined") {
 			$("body").addClass("epube-app");
 		}
 
-		// we need to manually provide resources for reader iframe because service worker fetch() handler doesn't work inside iframes (chrome bug?)
-
-		const promises = [];
-		let load_failed = false;
+		// Reader runs inside an iframe where the service worker can't intercept requests.
+		// We read resources directly from the cache (no network) and inject them into the iframe.
 
-		const cache = await caches.open(this.CACHE_NAME);
-		const cache_keys = await cache.keys();
+		const cache = await caches.open(cacheName);
+		const cacheKeys = await cache.keys();
 
-		cache_keys.forEach((req) => {
-			if (!req.url.match('backend\.php')) {
-				console.log('[loader] loading resource', req.url);
-				const promise = fetch(req.url).then(async (resp) => {
-					if (resp.ok) {
-						const url = new URL(resp.url);
-						url.searchParams.delete("ts");
-
-						if (resp.url.match('\\.ttf|\\.otf')) {
-							const blob = await resp.blob();
-							console.log('[loader] storing blob', url.href);
+		const promises = [];
+		let loadFailed = false;
 
-							this._res_data[url.toString()] = URL.createObjectURL(blob);
-						} else {
-							const text = await resp.text();
-							console.log('[loader] storing text', url.href);
+		for (const req of cacheKeys) {
+			// Skip API responses — we only need static assets for the iframe
+			if (req.url.match(/backend\.php/)) continue;
 
-							this._res_data[url.toString()] = text;
-						}
-					} else {
-						console.warn('[loader] failed for resource', req.url, resp);
+			const response = await cache.match(req.url);
+			if (!response) {
+				console.warn('[loader] cache miss for', req.url);
+				loadFailed = true;
+				continue;
+			}
 
-						$(".loading-message").html(`Unable to load resource.<br/><small>${req.url}</small>`);
+			const url = new URL(req.url);
+			url.searchParams.delete("ts");
+			const key = url.toString();
 
-						load_failed = true;
-					}
+			let promise;
+			if (req.url.match(/\.(ttf|otf)$/)) {
+				promise = response.blob().then((blob) => {
+					this._res_data[key] = URL.createObjectURL(blob);
+				});
+			} else {
+				promise = response.text().then((text) => {
+					this._res_data[key] = text;
 				});
-
-				promises.push(promise);
 			}
-		});
+
+			promises.push(promise.catch((err) => {
+				console.warn('[loader] failed to read', req.url, err);
+				loadFailed = true;
+			}));
+		}
 
 		await Promise.allSettled(promises);
 
-		console.log('[loader] resource load complete, failed: ', load_failed);
+		if (Object.keys(this._res_data).length === 0) loadFailed = true;
+
+		console.log('[loader] loaded', Object.keys(this._res_data).length, 'resources, failed:', loadFailed);
 
-		return load_failed;
+		return loadFailed;
 	}
 }
diff --git a/src/worker.js b/src/worker.js
new file mode 100644
index 0000000..cf863ef
--- /dev/null
+++ b/src/worker.js
@@ -0,0 +1,145 @@
+const CACHE_PREFIX = 'epube';
+
+const CACHE_VERSION = BUILD_CACHE_VERSION;
+const CACHE_NAME = CACHE_PREFIX + "-" + CACHE_VERSION;
+const MANIFEST_ASSETS = BUILD_MANIFEST_ASSETS;
+
+/* async function loadConfig() {
+	if (CACHE_NAME) return;
+
+	try {
+		const resp = await fetch('/cache-manifest.json');
+		const config = await resp.json();
+		CACHE_VERSION = config.version;
+		CACHE_NAME = CACHE_PREFIX + '-' + config.version;
+		MANIFEST_ASSETS = config.assets;
+		console.log('[worker] CACHE_NAME:', CACHE_NAME);
+	} catch (err) {
+		console.error('[worker] failed to load cache manifest:', err);
+		CACHE_NAME = CACHE_PREFIX + '-v0';
+		MANIFEST_ASSETS = [];
+	}
+} */
+
+// Install: precache all assets from manifest
+self.addEventListener('install', (event) => {
+	event.waitUntil(
+		(async () => {
+			console.log('[worker] install started');
+
+			// await loadConfig();
+
+			const cache = await caches.open(CACHE_NAME);
+
+			// 1. Map assets to Request objects that bypass old service worker caches
+			const requests = MANIFEST_ASSETS.map((url) => new Request(url, { cache: 'reload' }));
+
+			try {
+				// 2. Atomic install: fills cache entirely, or fails completely if one file is missing
+				await cache.addAll(requests);
+				console.log('[worker] all assets cached successfully');
+
+				// Only skip waiting if the entire cache was successfully built
+				self.skipWaiting();
+			} catch (err) {
+				console.error('[worker] Critical precache failed! Critical asset missing:', err);
+				// Do NOT call skipWaiting(). Let this installation fail so the old worker stays safe.
+			}
+		})()
+	);
+});
+
+self.addEventListener('message', (event) => {
+	if (event.data && event.data.type === 'GET_CACHE_NAME') {
+		// Respond directly to the specific frontend window/tab that asked
+		event.ports[0].postMessage({ cacheName: CACHE_NAME });
+	} else if (event.data && event.data.type === 'GET_CACHE_VERSION') {
+		// Respond directly to the specific frontend window/tab that asked
+		event.ports[0].postMessage({ cacheName: CACHE_VERSION });
+	}
+
+});
+
+// Activate: clean up old caches and take control of all pages
+self.addEventListener('activate', (event) => {
+	console.log('[worker] activate');
+
+	// Create the async task block
+	const activationTask = async () => {
+		// await loadConfig();
+
+		const keyList = await caches.keys();
+		for (const key of keyList) {
+			if (key.includes(CACHE_PREFIX) && key !== CACHE_NAME) {
+				/* eslint-disable no-await-in-loop */
+				await caches.delete(key);
+			}
+		}
+
+		await self.clients.claim();
+	};
+
+	// Hand the executed promise directly to the event
+	event.waitUntil(activationTask());
+});
+
+// Fetch: cache-first for static assets, network-first for API
+self.addEventListener('fetch', (event) => {
+	const url = new URL(event.request.url);
+
+	// Skip /assets/ — handled separately (e.g., book content)
+	if (url.pathname.startsWith('/assets/')) return;
+
+	// API endpoints: network-first with cache fallback
+	if (url.pathname.includes('backend.php')) {
+		event.respondWith(
+			(async () => {
+				try {
+					const networkResp = await fetch(event.request);
+
+					if (networkResp.ok) {
+						const cache = await caches.open(CACHE_NAME);
+						await cache.put(networkResp.url, networkResp.clone());
+					}
+
+					return networkResp;
+				} catch (err) {
+					// Network failed, try to get the cached API response
+					const cachedResp = await caches.match(event.request);
+					if (cachedResp) return cachedResp;
+
+					// Both failed, return the offline fallback page (Removed redundant await here)
+					return caches.match('/offline.html');
+				}
+			})()
+		);
+		return;
+	}
+
+	// Static assets: cache-first with background update (Stale-While-Revalidate)
+	event.respondWith(
+		(async () => {
+			const cache = await caches.open(CACHE_NAME);
+			const cached = await cache.match(event.request);
+
+			if (cached) {
+				// Fire background network check without waiting for it (no await)
+				fetch(event.request)
+					.then((networkResp) => {
+						if (networkResp.ok) cache.put(event.request, networkResp.clone());
+					})
+					.catch((e) => console.warn('[worker] Background sync failed:', e));
+
+				// Return cached asset immediately
+				return cached;
+			}
+
+			// Cache miss: fetch from network and cache it
+			const networkResp = await fetch(event.request);
+			if (networkResp.ok) {
+				await cache.put(event.request, networkResp.clone());
+			}
+			return networkResp;
+		})()
+	);
+});