BlueGit

timfa filemanager

Client-side caching

Server can prune watched video segments earlier because clients retain their own cache now.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
943484ae02059cb5b5f58dbecf6c5788652f8425
Parent
b9425887
6 files changed +234 −2
.github/technical-reference.md +7 −2
@@ -175,7 +175,7 @@
175 175 - Standalone public share page served at /share/:token; no auth required.
176 176 - Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
177 177 - tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
178 - Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, and explicit backend session release on unload.
178 - Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
179 179 - Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
180 180 - Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
181 181
@@ -183,6 +183,11 @@
183 183 - applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184 184 - bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185 185 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186 - enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
187 - clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188
189 ## public/stream-cache-sw.js
190 - fetch handler - Caches successful GET responses for `/api/files/video-stream/*` and `/api/share/video-stream/*`; if the network returns non-OK or fails (for example after server segment pruning), serves the cached response when available.
186 191 - configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
187 192 - ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
188 193
@@ -254,7 +259,7 @@
254 259 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
255 260 - buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
256 261 - bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
257 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
262 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enables service-worker-backed HLS segment caching for the active stream session (and clears that cache on close), enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
258 263 - modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
259 264 - loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
260 265 - modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
@@ -175,7 +175,7 @@
175- Standalone public share page served at /share/:token; no auth required.
175- Standalone public share page served at /share/:token; no auth required.
176- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
176- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
177- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
177- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
178- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, and explicit backend session release on unload.
178- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, service-worker-backed HLS segment cache enablement during playback (with per-session cache cleanup on close), and explicit backend session release on unload.
179- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
179- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
180- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
180- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
181
181
@@ -183,6 +183,11 @@
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186- enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
187- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
188
189## public/stream-cache-sw.js
190- fetch handler - Caches successful GET responses for `/api/files/video-stream/*` and `/api/share/video-stream/*`; if the network returns non-OK or fails (for example after server segment pruning), serves the cached response when available.
186- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
191- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
187- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
192- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
188
193
@@ -254,7 +259,7 @@
254- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
259- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
255- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
260- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
256- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
261- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
257- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
262- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, enables service-worker-backed HLS segment caching for the active stream session (and clears that cache on close), enforces non-live playback UI for file streams, uses container-fill sizing to keep previews within bounds, restores per-user video prefs (volume + subtitle/audio track names when present), wires the image-subtitle overlay controller, forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, warns when subtitle streams exist but none are web-compatible, and releases the backend stream session on close/unload.
258- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
263- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
259- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
264- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
260- modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
265- modelThumbnailDataUrl(item, blob) - Builds a blue SVG thumbnail for STL/OBJ files by parsing their geometry client-side; falls back to a badge when parsing fails.
public/app.js +17 −0
@@ -451,6 +451,20 @@ function ensureVideoPlaybackUi (player, durationSeconds)
451 451 shared.ensureVideoPlaybackUi(player, durationSeconds);
452 452 }
453 453
454 function enableVideoStreamClientCache ()
455 {
456 const shared = sharedVideoPlayer();
457 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
458 return shared.enableVideoStreamClientCache();
459 }
460
461 function clearVideoStreamClientCache (playlistUrl)
462 {
463 const shared = sharedVideoPlayer();
464 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
465 return shared.clearVideoStreamClientCache(playlistUrl);
466 }
467
454 468 async function reportWatchProgress (filePath, progress)
455 469 {
456 470 if (!filePath || !Number.isFinite(progress)) return;
@@ -3907,7 +3921,9 @@ async function preparePreviewDownload (item)
3907 3921 async function renderStreamedVideoPreview (item, targetEl)
3908 3922 {
3909 3923 const videojs = await ensureVideoJsLoaded();
3924 await enableVideoStreamClientCache();
3910 3925 const session = await createVideoStreamSessionForItem(item);
3926 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
3911 3927 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3912 3928 const prefs = loadUserVideoPrefs();
3913 3929 applyUserVideoTextTrackPrefs();
@@ -4035,6 +4051,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4035 4051 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4036 4052 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4037 4053 }
4054 void clearVideoStreamClientCache(sessionPlaylistUrl);
4038 4055 releaseActivePreviewVideoStreamSession();
4039 4056 try { markWatch(); } catch { /* ignore */ }
4040 4057 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
@@ -451,6 +451,20 @@ function ensureVideoPlaybackUi (player, durationSeconds)
451 shared.ensureVideoPlaybackUi(player, durationSeconds);
451 shared.ensureVideoPlaybackUi(player, durationSeconds);
452}
452}
453
453
454function enableVideoStreamClientCache ()
455{
456 const shared = sharedVideoPlayer();
457 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
458 return shared.enableVideoStreamClientCache();
459}
460
461function clearVideoStreamClientCache (playlistUrl)
462{
463 const shared = sharedVideoPlayer();
464 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
465 return shared.clearVideoStreamClientCache(playlistUrl);
466}
467
454async function reportWatchProgress (filePath, progress)
468async function reportWatchProgress (filePath, progress)
455{
469{
456 if (!filePath || !Number.isFinite(progress)) return;
470 if (!filePath || !Number.isFinite(progress)) return;
@@ -3907,7 +3921,9 @@ async function preparePreviewDownload (item)
3907async function renderStreamedVideoPreview (item, targetEl)
3921async function renderStreamedVideoPreview (item, targetEl)
3908{
3922{
3909 const videojs = await ensureVideoJsLoaded();
3923 const videojs = await ensureVideoJsLoaded();
3924 await enableVideoStreamClientCache();
3910 const session = await createVideoStreamSessionForItem(item);
3925 const session = await createVideoStreamSessionForItem(item);
3926 const sessionPlaylistUrl = String(session.playlistUrl || '').trim() || null;
3911 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3927 STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
3912 const prefs = loadUserVideoPrefs();
3928 const prefs = loadUserVideoPrefs();
3913 applyUserVideoTextTrackPrefs();
3929 applyUserVideoTextTrackPrefs();
@@ -4035,6 +4051,7 @@ async function renderStreamedVideoPreview (item, targetEl)
4035 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4051 try { imageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
4036 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4052 try { imageSubtitleController.detach(); } catch { /* ignore */ }
4037 }
4053 }
4054 void clearVideoStreamClientCache(sessionPlaylistUrl);
4038 releaseActivePreviewVideoStreamSession();
4055 releaseActivePreviewVideoStreamSession();
4039 try { markWatch(); } catch { /* ignore */ }
4056 try { markWatch(); } catch { /* ignore */ }
4040 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
4057 try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
public/share.html +19 −0
@@ -327,6 +327,9 @@
327 327 {
328 328 const sessionId = shareVideoSessionId;
329 329 shareVideoSessionId = null;
330 const playlistUrl = shareVideoPlayer && typeof shareVideoPlayer.currentSrc === 'function'
331 ? String(shareVideoPlayer.currentSrc() || '').trim()
332 : null;
330 333
331 334 try { shareImageSubtitleController && shareImageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
332 335 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
@@ -334,6 +337,7 @@
334 337 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
335 338 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
336 339
340 void clearVideoStreamClientCache(playlistUrl);
337 341 if (sessionId) void releaseShareVideoSession(sessionId, { keepalive: true });
338 342
339 343 shareVideoPlayer = null;
@@ -348,6 +352,20 @@
348 352 shared.configureVideoJsBuffering(window.videojs, { seconds: VIDEO_FORWARD_BUFFER_SECONDS });
349 353 }
350 354
355 function enableVideoStreamClientCache ()
356 {
357 const shared = sharedVideoPlayer();
358 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
359 return shared.enableVideoStreamClientCache();
360 }
361
362 function clearVideoStreamClientCache (playlistUrl)
363 {
364 const shared = sharedVideoPlayer();
365 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
366 return shared.clearVideoStreamClientCache(playlistUrl);
367 }
368
351 369 // ── Timer ───────────────────────────────────────────────────────────────
352 370 function startTimer ()
353 371 {
@@ -416,6 +434,7 @@
416 434 el.alt = name;
417 435 } else if (videoExts.includes(ext))
418 436 {
437 enableVideoStreamClientCache().catch(() => false);
419 438 fetch(`/api/share/video-stream/${token}`)
420 439 .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
421 440 .then(({ ok, data }) =>
@@ -327,6 +327,9 @@
327 {
327 {
328 const sessionId = shareVideoSessionId;
328 const sessionId = shareVideoSessionId;
329 shareVideoSessionId = null;
329 shareVideoSessionId = null;
330 const playlistUrl = shareVideoPlayer && typeof shareVideoPlayer.currentSrc === 'function'
331 ? String(shareVideoPlayer.currentSrc() || '').trim()
332 : null;
330
333
331 try { shareImageSubtitleController && shareImageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
334 try { shareImageSubtitleController && shareImageSubtitleController.captureSelectedTracks(); } catch { /* ignore */ }
332 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
335 try { shareImageSubtitleController && shareImageSubtitleController.detach(); } catch { /* ignore */ }
@@ -334,6 +337,7 @@
334 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
337 try { shareTrackPrefs && shareTrackPrefs.detach(); } catch { /* ignore */ }
335 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
338 try { shareVideoPlayer && shareVideoPlayer.dispose(); } catch { /* ignore */ }
336
339
340 void clearVideoStreamClientCache(playlistUrl);
337 if (sessionId) void releaseShareVideoSession(sessionId, { keepalive: true });
341 if (sessionId) void releaseShareVideoSession(sessionId, { keepalive: true });
338
342
339 shareVideoPlayer = null;
343 shareVideoPlayer = null;
@@ -348,6 +352,20 @@
348 shared.configureVideoJsBuffering(window.videojs, { seconds: VIDEO_FORWARD_BUFFER_SECONDS });
352 shared.configureVideoJsBuffering(window.videojs, { seconds: VIDEO_FORWARD_BUFFER_SECONDS });
349 }
353 }
350
354
355 function enableVideoStreamClientCache ()
356 {
357 const shared = sharedVideoPlayer();
358 if (!shared || typeof shared.enableVideoStreamClientCache !== 'function') return Promise.resolve(false);
359 return shared.enableVideoStreamClientCache();
360 }
361
362 function clearVideoStreamClientCache (playlistUrl)
363 {
364 const shared = sharedVideoPlayer();
365 if (!shared || typeof shared.clearVideoStreamClientCache !== 'function') return Promise.resolve();
366 return shared.clearVideoStreamClientCache(playlistUrl);
367 }
368
351 // ── Timer ───────────────────────────────────────────────────────────────
369 // ── Timer ───────────────────────────────────────────────────────────────
352 function startTimer ()
370 function startTimer ()
353 {
371 {
@@ -416,6 +434,7 @@
416 el.alt = name;
434 el.alt = name;
417 } else if (videoExts.includes(ext))
435 } else if (videoExts.includes(ext))
418 {
436 {
437 enableVideoStreamClientCache().catch(() => false);
419 fetch(`/api/share/video-stream/${token}`)
438 fetch(`/api/share/video-stream/${token}`)
420 .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
439 .then(r => r.json().then(d => ({ ok: r.ok, data: d })))
421 .then(({ ok, data }) =>
440 .then(({ ok, data }) =>
public/shared-video-player.js +70 −0
@@ -15,6 +15,8 @@
15 15 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
16 16 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
17 17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
18 20
19 21 function roundLogNumber (value, digits = 3)
20 22 {
@@ -1551,6 +1553,72 @@
1551 1553 }
1552 1554 }
1553 1555
1556 function enableVideoStreamClientCache ()
1557 {
1558 if (typeof navigator === 'undefined' || !navigator.serviceWorker || typeof navigator.serviceWorker.register !== 'function')
1559 {
1560 return Promise.resolve(false);
1561 }
1562
1563 if (window.__filemanagerVideoStreamCacheSwPromise)
1564 {
1565 return window.__filemanagerVideoStreamCacheSwPromise;
1566 }
1567
1568 window.__filemanagerVideoStreamCacheSwPromise = navigator.serviceWorker.register(VIDEO_STREAM_CACHE_SW_URL, {
1569 scope: '/',
1570 updateViaCache: 'none',
1571 }).then(() => true).catch(() => false);
1572
1573 return window.__filemanagerVideoStreamCacheSwPromise;
1574 }
1575
1576 function videoStreamCachePrefixFromPlaylistUrl (playlistUrl)
1577 {
1578 const raw = String(playlistUrl || '').trim();
1579 if (!raw) return null;
1580
1581 let parsed = null;
1582 try
1583 {
1584 parsed = new URL(raw, window.location.origin);
1585 } catch
1586 {
1587 return null;
1588 }
1589
1590 const pathname = String(parsed.pathname || '');
1591 if (!pathname) return null;
1592 const lastSlashIndex = pathname.lastIndexOf('/');
1593 const basePath = lastSlashIndex >= 0 ? pathname.slice(0, lastSlashIndex + 1) : '/';
1594 return `${parsed.origin}${basePath}`;
1595 }
1596
1597 function clearVideoStreamClientCache (playlistUrl)
1598 {
1599 const prefix = videoStreamCachePrefixFromPlaylistUrl(playlistUrl);
1600 if (!prefix || typeof caches === 'undefined' || typeof caches.open !== 'function')
1601 {
1602 return Promise.resolve();
1603 }
1604
1605 return caches.open(VIDEO_STREAM_CACHE_NAME).then(async (cache) =>
1606 {
1607 const requests = await cache.keys();
1608 const deletions = [];
1609 for (const request of requests)
1610 {
1611 const requestUrl = request && request.url ? String(request.url) : '';
1612 if (!requestUrl.startsWith(prefix)) continue;
1613 deletions.push(cache.delete(request));
1614 }
1615 await Promise.all(deletions);
1616 }).catch(() =>
1617 {
1618 // Keep cache cleanup best-effort only.
1619 });
1620 }
1621
1554 1622 function applyDefaultTextTrackPrefs ()
1555 1623 {
1556 1624 try
@@ -1566,7 +1634,9 @@
1566 1634 applyDefaultTextTrackPrefs,
1567 1635 bindImageSubtitleOverlay,
1568 1636 bindTrackPrefs,
1637 clearVideoStreamClientCache,
1569 1638 configureVideoJsBuffering,
1639 enableVideoStreamClientCache,
1570 1640 ensureVideoPlaybackUi,
1571 1641 normaliseVideoDuration,
1572 1642 };
@@ -15,6 +15,8 @@
15 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
15 const IMAGE_SUBTITLE_CURRENT_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
16 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
16 const IMAGE_SUBTITLE_PREFETCH_REQUEST_TIMEOUT_MS_DEFAULT = 4000;
17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
17 const IMAGE_SUBTITLE_PREFETCH_REQUEST_INTERVAL_MS_DEFAULT = 0;
18 const VIDEO_STREAM_CACHE_SW_URL = '/stream-cache-sw.js';
19 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
18
20
19 function roundLogNumber (value, digits = 3)
21 function roundLogNumber (value, digits = 3)
20 {
22 {
@@ -1551,6 +1553,72 @@
1551 }
1553 }
1552 }
1554 }
1553
1555
1556 function enableVideoStreamClientCache ()
1557 {
1558 if (typeof navigator === 'undefined' || !navigator.serviceWorker || typeof navigator.serviceWorker.register !== 'function')
1559 {
1560 return Promise.resolve(false);
1561 }
1562
1563 if (window.__filemanagerVideoStreamCacheSwPromise)
1564 {
1565 return window.__filemanagerVideoStreamCacheSwPromise;
1566 }
1567
1568 window.__filemanagerVideoStreamCacheSwPromise = navigator.serviceWorker.register(VIDEO_STREAM_CACHE_SW_URL, {
1569 scope: '/',
1570 updateViaCache: 'none',
1571 }).then(() => true).catch(() => false);
1572
1573 return window.__filemanagerVideoStreamCacheSwPromise;
1574 }
1575
1576 function videoStreamCachePrefixFromPlaylistUrl (playlistUrl)
1577 {
1578 const raw = String(playlistUrl || '').trim();
1579 if (!raw) return null;
1580
1581 let parsed = null;
1582 try
1583 {
1584 parsed = new URL(raw, window.location.origin);
1585 } catch
1586 {
1587 return null;
1588 }
1589
1590 const pathname = String(parsed.pathname || '');
1591 if (!pathname) return null;
1592 const lastSlashIndex = pathname.lastIndexOf('/');
1593 const basePath = lastSlashIndex >= 0 ? pathname.slice(0, lastSlashIndex + 1) : '/';
1594 return `${parsed.origin}${basePath}`;
1595 }
1596
1597 function clearVideoStreamClientCache (playlistUrl)
1598 {
1599 const prefix = videoStreamCachePrefixFromPlaylistUrl(playlistUrl);
1600 if (!prefix || typeof caches === 'undefined' || typeof caches.open !== 'function')
1601 {
1602 return Promise.resolve();
1603 }
1604
1605 return caches.open(VIDEO_STREAM_CACHE_NAME).then(async (cache) =>
1606 {
1607 const requests = await cache.keys();
1608 const deletions = [];
1609 for (const request of requests)
1610 {
1611 const requestUrl = request && request.url ? String(request.url) : '';
1612 if (!requestUrl.startsWith(prefix)) continue;
1613 deletions.push(cache.delete(request));
1614 }
1615 await Promise.all(deletions);
1616 }).catch(() =>
1617 {
1618 // Keep cache cleanup best-effort only.
1619 });
1620 }
1621
1554 function applyDefaultTextTrackPrefs ()
1622 function applyDefaultTextTrackPrefs ()
1555 {
1623 {
1556 try
1624 try
@@ -1566,7 +1634,9 @@
1566 applyDefaultTextTrackPrefs,
1634 applyDefaultTextTrackPrefs,
1567 bindImageSubtitleOverlay,
1635 bindImageSubtitleOverlay,
1568 bindTrackPrefs,
1636 bindTrackPrefs,
1637 clearVideoStreamClientCache,
1569 configureVideoJsBuffering,
1638 configureVideoJsBuffering,
1639 enableVideoStreamClientCache,
1570 ensureVideoPlaybackUi,
1640 ensureVideoPlaybackUi,
1571 normaliseVideoDuration,
1641 normaliseVideoDuration,
1572 };
1642 };
public/stream-cache-sw.js added +65 −0
@@ -0,0 +1,65 @@
1 'use strict';
2
3 const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
4
5 function isVideoStreamAssetRequest (request)
6 {
7 if (!request || String(request.method || '').toUpperCase() !== 'GET') return false;
8
9 let url = null;
10 try
11 {
12 url = new URL(request.url);
13 } catch
14 {
15 return false;
16 }
17
18 const pathname = String(url.pathname || '');
19 if (!pathname.startsWith('/api/')) return false;
20
21 return pathname.startsWith('/api/files/video-stream/')
22 || pathname.startsWith('/api/share/video-stream/');
23 }
24
25 self.addEventListener('install', (event) =>
26 {
27 event.waitUntil(self.skipWaiting());
28 });
29
30 self.addEventListener('activate', (event) =>
31 {
32 event.waitUntil(self.clients.claim());
33 });
34
35 self.addEventListener('fetch', (event) =>
36 {
37 const request = event.request;
38 if (!isVideoStreamAssetRequest(request)) return;
39
40 event.respondWith((async () =>
41 {
42 const cache = await caches.open(VIDEO_STREAM_CACHE_NAME);
43 const cached = await cache.match(request);
44
45 try
46 {
47 const response = await fetch(request);
48 if (response && response.ok)
49 {
50 void cache.put(request, response.clone()).catch(() =>
51 {
52 // Cache writes are best-effort.
53 });
54 return response;
55 }
56
57 if (cached) return cached;
58 return response;
59 } catch
60 {
61 if (cached) return cached;
62 throw new Error('Video stream request failed and no cached response was available.');
63 }
64 })());
65 });
@@ -0,0 +1,65 @@
1'use strict';
2
3const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
4
5function isVideoStreamAssetRequest (request)
6{
7 if (!request || String(request.method || '').toUpperCase() !== 'GET') return false;
8
9 let url = null;
10 try
11 {
12 url = new URL(request.url);
13 } catch
14 {
15 return false;
16 }
17
18 const pathname = String(url.pathname || '');
19 if (!pathname.startsWith('/api/')) return false;
20
21 return pathname.startsWith('/api/files/video-stream/')
22 || pathname.startsWith('/api/share/video-stream/');
23}
24
25self.addEventListener('install', (event) =>
26{
27 event.waitUntil(self.skipWaiting());
28});
29
30self.addEventListener('activate', (event) =>
31{
32 event.waitUntil(self.clients.claim());
33});
34
35self.addEventListener('fetch', (event) =>
36{
37 const request = event.request;
38 if (!isVideoStreamAssetRequest(request)) return;
39
40 event.respondWith((async () =>
41 {
42 const cache = await caches.open(VIDEO_STREAM_CACHE_NAME);
43 const cached = await cache.match(request);
44
45 try
46 {
47 const response = await fetch(request);
48 if (response && response.ok)
49 {
50 void cache.put(request, response.clone()).catch(() =>
51 {
52 // Cache writes are best-effort.
53 });
54 return response;
55 }
56
57 if (cached) return cached;
58 return response;
59 } catch
60 {
61 if (cached) return cached;
62 throw new Error('Video stream request failed and no cached response was available.');
63 }
64 })());
65});
tests/shared-video-player.test.js +56 −0
@@ -838,4 +838,60 @@ describe('shared image subtitle prefetching', () =>
838 838 await flushAsyncWork(window, 2);
839 839 window.close();
840 840 });
841
842 test('registers stream cache service worker once when supported', async () =>
843 {
844 const window = createWindow();
845 const helper = loadSharedVideoPlayer(window);
846 const register = jest.fn(async () => ({}));
847 window.navigator.serviceWorker = { register };
848
849 const first = await helper.enableVideoStreamClientCache();
850 const second = await helper.enableVideoStreamClientCache();
851
852 expect(first).toBe(true);
853 expect(second).toBe(true);
854 expect(register).toHaveBeenCalledTimes(1);
855 expect(register).toHaveBeenCalledWith('/stream-cache-sw.js', {
856 scope: '/',
857 updateViaCache: 'none',
858 });
859
860 window.close();
861 });
862
863 test('clears cached stream assets for a finished playlist session', async () =>
864 {
865 const window = createWindow();
866 const helper = loadSharedVideoPlayer(window);
867 const requests = [
868 new window.Request('http://localhost/api/files/video-stream/sess-a/master.m3u8'),
869 new window.Request('http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts'),
870 new window.Request('http://localhost/api/files/video-stream/sess-b/master.m3u8'),
871 ];
872 const deleteCalls = [];
873 const cache = {
874 keys: jest.fn(async () => requests),
875 delete: jest.fn(async (request) =>
876 {
877 deleteCalls.push(request.url);
878 return true;
879 }),
880 };
881 window.caches = {
882 open: jest.fn(async () => cache),
883 };
884
885 await helper.clearVideoStreamClientCache('http://localhost/api/files/video-stream/sess-a/master.m3u8');
886
887 expect(window.caches.open).toHaveBeenCalledWith('filemanager-stream-cache-v1');
888 expect(cache.keys).toHaveBeenCalledTimes(1);
889 expect(deleteCalls).toEqual(expect.arrayContaining([
890 'http://localhost/api/files/video-stream/sess-a/master.m3u8',
891 'http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts',
892 ]));
893 expect(deleteCalls).not.toContain('http://localhost/api/files/video-stream/sess-b/master.m3u8');
894
895 window.close();
896 });
841 897 });
@@ -838,4 +838,60 @@ describe('shared image subtitle prefetching', () =>
838 await flushAsyncWork(window, 2);
838 await flushAsyncWork(window, 2);
839 window.close();
839 window.close();
840 });
840 });
841
842 test('registers stream cache service worker once when supported', async () =>
843 {
844 const window = createWindow();
845 const helper = loadSharedVideoPlayer(window);
846 const register = jest.fn(async () => ({}));
847 window.navigator.serviceWorker = { register };
848
849 const first = await helper.enableVideoStreamClientCache();
850 const second = await helper.enableVideoStreamClientCache();
851
852 expect(first).toBe(true);
853 expect(second).toBe(true);
854 expect(register).toHaveBeenCalledTimes(1);
855 expect(register).toHaveBeenCalledWith('/stream-cache-sw.js', {
856 scope: '/',
857 updateViaCache: 'none',
858 });
859
860 window.close();
861 });
862
863 test('clears cached stream assets for a finished playlist session', async () =>
864 {
865 const window = createWindow();
866 const helper = loadSharedVideoPlayer(window);
867 const requests = [
868 new window.Request('http://localhost/api/files/video-stream/sess-a/master.m3u8'),
869 new window.Request('http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts'),
870 new window.Request('http://localhost/api/files/video-stream/sess-b/master.m3u8'),
871 ];
872 const deleteCalls = [];
873 const cache = {
874 keys: jest.fn(async () => requests),
875 delete: jest.fn(async (request) =>
876 {
877 deleteCalls.push(request.url);
878 return true;
879 }),
880 };
881 window.caches = {
882 open: jest.fn(async () => cache),
883 };
884
885 await helper.clearVideoStreamClientCache('http://localhost/api/files/video-stream/sess-a/master.m3u8');
886
887 expect(window.caches.open).toHaveBeenCalledWith('filemanager-stream-cache-v1');
888 expect(cache.keys).toHaveBeenCalledTimes(1);
889 expect(deleteCalls).toEqual(expect.arrayContaining([
890 'http://localhost/api/files/video-stream/sess-a/master.m3u8',
891 'http://localhost/api/files/video-stream/sess-a/stream_0_segment_000001.ts',
892 ]));
893 expect(deleteCalls).not.toContain('http://localhost/api/files/video-stream/sess-b/master.m3u8');
894
895 window.close();
896 });
841});
897});