BlueGit

timfa filemanager

Files

filemanager / public / stream-cache-sw.js

stream-cache-sw.js

formatting
timfa Tim Falken · pushed by timfa · 5 months ago
feb493fc History
stream-cache-sw.js 5.9 KiB Download Raw
1'use strict';
2
3const VIDEO_STREAM_CACHE_NAME = 'filemanager-stream-cache-v1';
4
5function isVideoStreamSegmentRequest (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 const isStreamAsset = pathname.startsWith('/api/files/video-stream/')
21 || pathname.startsWith('/api/share/video-stream/');
22 if (!isStreamAsset) return false;
23
24 // Cache only immutable segment/init assets. Avoid caching playlists because
25 // stale manifests can break seek behaviour after the server prunes older entries.
26 if (/\.m3u8(?:$|\?)/i.test(pathname)) return false;
27 return /(?:\.ts|\.m4s|\.mp4|\.aac|\.vtt)(?:$|\?)/i.test(pathname);
28}
29
30function requestWithoutRange (request)
31{
32 return new Request(request.url, {
33 method: 'GET',
34 credentials: request.credentials,
35 mode: request.mode,
36 redirect: request.redirect,
37 referrer: request.referrer,
38 referrerPolicy: request.referrerPolicy,
39 integrity: request.integrity,
40 cache: 'no-store',
41 });
42}
43
44function parseRangeHeader (rawHeader, size)
45{
46 const header = String(rawHeader || '').trim().toLowerCase();
47 if (!header || !header.startsWith('bytes=')) return null;
48
49 const [startRaw, endRaw] = header.slice('bytes='.length).split('-', 2);
50 if (startRaw.includes(',') || (endRaw && endRaw.includes(','))) return null;
51
52 let start = startRaw === '' ? null : Number.parseInt(startRaw, 10);
53 let end = endRaw === '' ? null : Number.parseInt(endRaw, 10);
54
55 if (start === null && end === null) return null;
56 if (start !== null && (!Number.isInteger(start) || start < 0)) return null;
57 if (end !== null && (!Number.isInteger(end) || end < 0)) return null;
58
59 if (start === null)
60 {
61 const suffixLength = end;
62 if (!Number.isInteger(suffixLength) || suffixLength <= 0) return null;
63 start = Math.max(0, size - suffixLength);
64 end = size - 1;
65 } else if (end === null)
66 {
67 end = size - 1;
68 }
69
70 if (start >= size) return null;
71 if (end >= size) end = size - 1;
72 if (end < start) return null;
73
74 return { start, end };
75}
76
77async function buildRangeResponseFromCached (cachedResponse, rangeHeader)
78{
79 if (!cachedResponse || !rangeHeader) return null;
80
81 const clone = cachedResponse.clone();
82 const bodyBuffer = await clone.arrayBuffer();
83 const totalBytes = bodyBuffer.byteLength;
84 const range = parseRangeHeader(rangeHeader, totalBytes);
85 if (!range) return null;
86
87 const slicedBody = bodyBuffer.slice(range.start, range.end + 1);
88 const headers = new Headers(cachedResponse.headers || {});
89 headers.set('content-range', `bytes ${range.start}-${range.end}/${totalBytes}`);
90 headers.set('content-length', String(range.end - range.start + 1));
91 headers.set('accept-ranges', 'bytes');
92
93 return new Response(slicedBody, {
94 status: 206,
95 statusText: 'Partial Content',
96 headers,
97 });
98}
99
100self.addEventListener('install', (event) =>
101{
102 event.waitUntil(self.skipWaiting());
103});
104
105self.addEventListener('activate', (event) =>
106{
107 event.waitUntil(self.clients.claim());
108});
109
110self.addEventListener('fetch', (event) =>
111{
112 const request = event.request;
113 if (!isVideoStreamSegmentRequest(request)) return;
114
115 event.respondWith((async () =>
116 {
117 const cache = await caches.open(VIDEO_STREAM_CACHE_NAME);
118 const rangeHeader = request.headers && typeof request.headers.get === 'function'
119 ? String(request.headers.get('range') || '').trim()
120 : '';
121 const isRangeRequest = !!rangeHeader;
122 const normalizedRequest = isRangeRequest ? requestWithoutRange(request) : request;
123 const cached = await cache.match(normalizedRequest);
124
125 try
126 {
127 const response = await fetch(request);
128 const hasContentRange = response && response.headers && typeof response.headers.get === 'function'
129 ? String(response.headers.get('content-range') || '').trim()
130 : '';
131
132 if (response && response.ok && !hasContentRange)
133 {
134 void cache.put(normalizedRequest, response.clone()).catch(() =>
135 {
136 // Cache writes are best-effort.
137 });
138 return response;
139 }
140
141 if (response && (response.status === 206 || hasContentRange) && isRangeRequest)
142 {
143 // Warm a full-body cache entry in the background so rewinds can still
144 // use cached segments if the server later prunes old files.
145 void fetch(normalizedRequest).then((fullResponse) =>
146 {
147 if (!fullResponse || !fullResponse.ok) return;
148 return cache.put(normalizedRequest, fullResponse.clone());
149 }).catch(() =>
150 {
151 // Full-body warmup is best-effort only.
152 });
153 }
154
155 if (cached)
156 {
157 if (isRangeRequest)
158 {
159 const rangeResponse = await buildRangeResponseFromCached(cached, rangeHeader);
160 if (rangeResponse) return rangeResponse;
161 }
162 return cached;
163 }
164 return response;
165 } catch
166 {
167 if (cached)
168 {
169 if (isRangeRequest)
170 {
171 const rangeResponse = await buildRangeResponseFromCached(cached, rangeHeader);
172 if (rangeResponse) return rangeResponse;
173 }
174 return cached;
175 }
176 return new Response(null, {
177 status: 504,
178 statusText: 'Gateway Timeout',
179 });
180 }
181 })());
182});