Episodes can be kept on the device to listen offline (#412)

Offline mode (#389) kept lists, text and pictures, but the worker let
every /media/ request pass, so no episode played without a connection.

A downloaded episode's files pane has a keep button beside Play. It
fetches the copy that person plays, the file or, when DeadAir cuts
something for them, the version without its dead air (/media/{id}/deadair,
the save button's), whole into a cache of its own, ipx-episodes, and
asks once for persistent storage. A kept episode plays as
/media/...?offline, online or not, and the worker answers that from the
cache with the byte ranges an audio element asks for (206, 416, 200);
not kept there, it goes to the server as before. Pressing it again takes
it off; signing out clears it with everything else. Only someone's
choice is kept, so there is no budget: a full device is the quota's
refusal, said in words. The button is data-a="offline", not "keep",
which the Directory's show page already uses for subscribing.

Places saved from DeadAir's version were read in its clock only if ipx
had handed out that file's playlist since it started (state.playing). A
kept copy plays without one, so the player now names the file in the
position it saves (deadair: <enclosure>) whenever it plays DeadAir's
clock, and ipx loads that file's plan when it has none, for that item's
file only. Checked the beacon is queued by the worker offline: it is.

Tests: playing a kept episode offline, its place queued and sent once
back, and taking it off (the offline show plays quiet.mp3, the only real
MP3 among the fixtures); the worker's ranges; which copy is kept and
played, in page-unit; the server reading a flagged place in DeadAir's
clock without a playlist, and ignoring another item's file. The files
pane's one-row test counts five buttons and checks a phone's width too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RqkrVDqdiQEMWAkNGQ2tYA
This commit is contained in:
2026-11-07 15:31:04 +00:00
parent 07923d665b
commit 2c4d03668f
15 changed files with 284 additions and 7 deletions

View File

@@ -15,7 +15,7 @@ const sw = self as unknown as ServiceWorkerGlobalScope;
/// A write kept for later, as the outbox holds it.
type Saved = {url: string, body: string, type: string};
const PAGE = 'ipx-page', API = 'ipx-api', PICS = 'ipx-pics', OUTBOX = 'ipx-outbox';
const PAGE = 'ipx-page', API = 'ipx-api', PICS = 'ipx-pics', OUTBOX = 'ipx-outbox', KEPT = 'ipx-episodes';
// shortcut: a byte budget over pictures counted when kept, oldest out first; nothing tracks
// which were looked at since. Raise it, or prune by use, if 200 MB proves too little or too much.
const PICS_BUDGET = 200 << 20;
@@ -34,7 +34,13 @@ sw.addEventListener('fetch', e => {
if (req.method === 'GET' && req.destination === 'image') e.respondWith(picture(req));
return;
}
// The live stream, audio and video pass by: a stream cannot be kept, a file is too big to.
// An episode kept on this device (#412), which the page asks for as such.
if (req.method === 'GET' && url.pathname.startsWith('/media/') && url.searchParams.has('offline')) {
e.respondWith(keptEpisode(req, url.pathname));
return;
}
// The live stream, audio and video pass by: a stream cannot be kept, a file is too big to
// unless someone keeps it, above.
if (url.pathname === '/api/events' || url.pathname.startsWith('/media/') || url.pathname === '/sw.js') return;
if (req.method !== 'GET') {
if (req.method === 'POST' && QUEUED.test(url.pathname)) e.respondWith(write(req));
@@ -154,6 +160,38 @@ function flush(): Promise<void> {
return flushing;
}
// ---- episodes kept on the device (#412) ------------------------------------------------------
/// The kept copy, or the byte range of it a player asks for: an audio element asks for ranges and
/// Safari plays nothing it cannot have them for. Not kept (cleared, or another device's page), the
/// server's own, as without `?offline`.
async function keptEpisode(req: Request, path: string): Promise<Response> {
const kept = await caches.match(path, { cacheName: KEPT });
const range = req.headers.get('Range');
if (!kept) return fetch(path, { headers: range ? { Range: range } : {}, credentials: 'same-origin' });
const blob = await kept.blob();
return ranged(blob, range, kept.headers.get('Content-Type') || 'audio/mpeg');
}
/// `blob` answered as a server answers a Range request: 206 with the part asked for, 416 for a
/// part past its end, 200 with all of it when no range is asked for or the one asked is not
/// understood.
function ranged(blob: Blob, range: string | null, type: string): Response {
const size = blob.size;
const m = range?.match(/^bytes=(\d*)-(\d*)$/);
const head = { 'Content-Type': type, 'Accept-Ranges': 'bytes' };
if (!m || (m[1] === '' && m[2] === '')) return new Response(blob, { headers: { ...head, 'Content-Length': String(size) } });
// `bytes=-N` is the last N bytes.
const start = m[1] === '' ? Math.max(0, size - Number(m[2])) : Number(m[1]);
const end = m[1] === '' || m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
if (start >= size || start > end) {
return new Response(null, { status: 416, headers: { ...head, 'Content-Range': `bytes */${size}` } });
}
return new Response(blob.slice(start, end + 1), { status: 206, headers: {
...head, 'Content-Length': String(end - start + 1), 'Content-Range': `bytes ${start}-${end}/${size}`,
} });
}
// ---- pictures ----------------------------------------------------------------------------------
const artFor = (src: string) => `/api/art?u=${encodeURIComponent(src)}`;