BlueGit

timfa filemanager

formatting

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

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