| 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 | }); |