Files
maptool/public/sw.js
T
randy 25b87b94fe
CI / check (push) Successful in 18s
CI / deploy (push) Successful in 13s
Installable PWA with a share target; design for an item-based library
Android's share sheet (OsmAnd, Locus, mapy.com, ...) can now send
GPX/FIT/GeoJSON/ZIP files to the installed app: the service worker parks
them and the page offers to import them into a Tracks & Points folder,
waiting through a login if needed. Manifest, app icon, a server-side
fallback for /share-target.

docs/library-design.adoc proposes replacing the file-based GpxStore with
folders and items (stable ids, timestamps, tombstones, a change feed) as
the base for syncing with OsmAnd and Locus.
2026-11-12 13:42:04 +01:00

102 lines
3.7 KiB
JavaScript

// Caches RainViewer radar tile images so the last-seen frames stay visible
// once the network is actually gone, and receives files shared to the
// installed app (manifest.webmanifest's share_target, below). No app-shell
// precaching: the app itself is served by the same local server that's
// already the offline resource in the van, so there's no "app unreachable
// but should still work" scenario to solve, unlike the radar tiles (a
// third-party CDN).
const CACHE_VERSION = "v1";
const RADAR_CACHE = `radar-tiles-${CACHE_VERSION}`;
// Files shared to the app wait here until the page imports them (see
// public/js/share_import.js) — not versioned, so a SW update can't drop a
// file someone shared but hasn't imported yet.
const SHARED_CACHE = "shared-files";
// ponytail: a rough cap, not real LRU/expiry — trims oldest-by-insertion via
// Cache API iteration order (stable in practice, not spec-guaranteed).
// Revisit with timestamp-based expiry if storage actually becomes a
// problem; 400 tiles is at most a few MB either way.
const MAX_RADAR_TILES = 400;
function isRadarTile(url) {
return url.hostname.endsWith("rainviewer.com") && url.pathname.includes("/v2/radar/");
}
self.addEventListener("install", (event) => {
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) => Promise.all(keys.filter((key) => key !== RADAR_CACHE && key !== SHARED_CACHE).map((key) => caches.delete(key))))
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
if (event.request.method === "POST" && url.origin === self.location.origin && url.pathname === "/share-target") {
event.respondWith(receiveSharedFiles(event.request));
return;
}
if (!isRadarTile(url)) return;
event.respondWith(networkFallingBackToCache(event.request));
});
// Network first (frame ids rotate as new radar sweeps come in, so a cached
// tile can go stale) — cache is only the answer once the network actually
// fails, not a shortcut when it's merely slow.
async function networkFallingBackToCache(request) {
const cache = await caches.open(RADAR_CACHE);
try {
const response = await fetch(request);
if (response.ok) {
cache.put(request, response.clone());
trimRadarCache(cache);
}
return response;
} catch (err) {
const cached = await cache.match(request);
if (cached) return cached;
throw err;
}
}
async function trimRadarCache(cache) {
const keys = await cache.keys();
if (keys.length <= MAX_RADAR_TILES) return;
await Promise.all(keys.slice(0, keys.length - MAX_RADAR_TILES).map((key) => cache.delete(key)));
}
// Android's share sheet (OsmAnd, Locus, mapy.com, a file manager, ...)
// POSTs the files here. They're parked in SHARED_CACHE rather than
// uploaded straight away: the page does that with a normal same-origin
// request (session cookie, login redirect, folder choice) — see
// share_import.js.
async function receiveSharedFiles(request) {
try {
const form = await request.formData();
const cache = await caches.open(SHARED_CACHE);
const stamp = Date.now();
await Promise.all(
form
.getAll("file")
.filter((file) => file instanceof File)
.map((file, i) =>
cache.put(
`/shared-files/${stamp}-${i}`,
new Response(file, {
headers: { "content-type": file.type || "application/octet-stream", "x-filename": encodeURIComponent(file.name || "shared") },
}),
),
),
);
} catch {
// fall through to the app anyway — nothing parked just means nothing to offer
}
return Response.redirect("/?shared=1", 303);
}