BlueGit

timfa filemanager

save volume setting

timfa Tim Falken · pushed by timfa

Authored 2026-05-08 · 6 months ago

Hash
0a9d5f29dc7eb4292fd1ad7e48fd22885673ec03
Parent
4edf40bb
7 files changed +424 −22
.github/technical-reference.md +10 −2
@@ -16,7 +16,7 @@
16 16 - setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
17 17
18 18 ## server/db.js
19 - initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
19 - initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
20 20 - getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
21 21 - closeDb() - Closes singleton DB handle to release file locks.
22 22
@@ -59,6 +59,7 @@
59 59 - POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
60 60 - POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
61 61 - POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
62 - POST /api/files/watch-progress - Records per-user watch status (`partway` >=30%, `fully` >=70%) for sidebar "Watched by" display.
62 63
63 64 ## server/routes/share.js
64 65 - POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
@@ -123,7 +124,8 @@
123 124 - disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
124 125 - setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
125 126 - buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
126 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source and initial subtitle track config; warns when subtitle streams exist but none are web-compatible.
127 - renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, restores per-user video prefs (volume + subtitle style), reports watch progress, and warns when subtitle streams exist but none are web-compatible.
128 - closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
127 129
128 130 ## tests/thumbnail-cache.test.js
129 131 - thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
@@ -197,7 +199,13 @@
197 199 - first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
198 200 - expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
199 201 - expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
202 - video preview does not close on backdrop click and closes via X button - Verifies video previews require explicit close via X.
203 - video preview restores per-user saved volume preference - Verifies per-user saved video volume is applied on preview open.
200 204
201 205 ## tests/video-stream.test.js
202 206 - createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
203 207 - createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
208 - createVideoStreamSession keeps playback available when subtitle conversion fails - Verifies subtitle conversion failures are skipped without breaking stream playback.
209
210 ## tests/files.routes.test.js
211 - POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
@@ -16,7 +16,7 @@
16- setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
16- setFolderIconAssignment(folderPath, imagePath) - Saves an explicit folder icon assignment to .folder-icons.json; pass null to clear (auto-detect used instead).
17
17
18## server/db.js
18## server/db.js
19- initDb() - Initializes SQLite schema for users, file metadata, and auth_sessions (idle timeout/revocation support).
19- initDb() - Initializes SQLite schema for users, file metadata (including watched_by), and auth_sessions (idle timeout/revocation support), and migrates watched_by for existing DB files.
20- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
20- getDb() - Returns singleton DB handle with WAL and foreign key pragmas.
21- closeDb() - Closes singleton DB handle to release file locks.
21- closeDb() - Closes singleton DB handle to release file locks.
22
22
@@ -59,6 +59,7 @@
59- POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
59- POST /api/files/upload - Streams multipart uploads into hidden temp files, cleans them up on abort, and only exposes final filenames after completion.
60- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
60- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
61- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
61- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
62- POST /api/files/watch-progress - Records per-user watch status (`partway` >=30%, `fully` >=70%) for sidebar "Watched by" display.
62
63
63## server/routes/share.js
64## server/routes/share.js
64- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
65- POST /api/share/create - Authenticated. Creates a 24-hour share token for a file or directory; returns {token, expiresAt}.
@@ -123,7 +124,8 @@
123- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
124- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
124- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
125- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
125- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
126- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
126- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source and initial subtitle track config; warns when subtitle streams exist but none are web-compatible.
127- renderStreamedVideoPreview(item, targetEl) - Creates the Video.js player with HLS source/track config, restores per-user video prefs (volume + subtitle style), reports watch progress, and warns when subtitle streams exist but none are web-compatible.
128- closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
127
129
128## tests/thumbnail-cache.test.js
130## tests/thumbnail-cache.test.js
129- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
131- thumbnail cache worker / creates cached thumbnail with dimensions smaller than 100px - Verifies cached image generation and manifest write.
@@ -197,7 +199,13 @@
197- first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
199- first-run setup uses new-password autocomplete token - Verifies setup mode switches the password field to the browser-friendly new-password token.
198- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
200- expanded file preview shows a Share button next to Download - Verifies expanded preview UI includes both actions inside a dedicated footer below the preview content.
199- expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
201- expanded video preview uses a stream session and video.js - Verifies streamed video preview uses the server-backed HLS session and registers subtitle tracks with video.js.
202- video preview does not close on backdrop click and closes via X button - Verifies video previews require explicit close via X.
203- video preview restores per-user saved volume preference - Verifies per-user saved video volume is applied on preview open.
200
204
201## tests/video-stream.test.js
205## tests/video-stream.test.js
202- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
206- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
203- createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
207- createVideoStreamSession configures flat segment filenames that match playlist URLs - Verifies ffmpeg segment output paths match the segment URLs emitted in the generated HLS playlists.
208- createVideoStreamSession keeps playback available when subtitle conversion fails - Verifies subtitle conversion failures are skipped without breaking stream playback.
209
210## tests/files.routes.test.js
211- POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
public/app.js +163 −8
@@ -63,6 +63,8 @@ const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
63 63 const MOBILE_LONG_PRESS_MS = 420;
64 64 const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
65 65 const THUMB_OBSERVER_ROOT_MARGIN = '120px';
66 const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
67 const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
66 68 let videoJsLoaderPromise = null;
67 69
68 70 // ───────────────────────────────────────────────────────────────────────────
@@ -200,6 +202,77 @@ function randomIdHex (bytes = 16)
200 202 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
201 203 }
202 204
205 function userVideoPrefsKey ()
206 {
207 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
208 return VIDEO_PREFS_KEY_PREFIX + name;
209 }
210
211 function loadUserVideoPrefs ()
212 {
213 try
214 {
215 const raw = localStorage.getItem(userVideoPrefsKey());
216 const parsed = raw ? JSON.parse(raw) : {};
217 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
218 return parsed;
219 } catch
220 {
221 return {};
222 }
223 }
224
225 function saveUserVideoPrefs (patch)
226 {
227 try
228 {
229 const current = loadUserVideoPrefs();
230 localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) }));
231 } catch
232 {
233 // Ignore localStorage failures.
234 }
235 }
236
237 function applyUserVideoTextTrackPrefs ()
238 {
239 try
240 {
241 const prefs = loadUserVideoPrefs();
242 if (typeof prefs.textTrackSettings === 'string' && prefs.textTrackSettings)
243 {
244 localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, prefs.textTrackSettings);
245 }
246 } catch
247 {
248 // Ignore localStorage failures.
249 }
250 }
251
252 function captureUserVideoTextTrackPrefs ()
253 {
254 try
255 {
256 const raw = localStorage.getItem(VIDEO_TEXT_TRACK_SETTINGS_KEY);
257 if (typeof raw === 'string' && raw)
258 {
259 saveUserVideoPrefs({ textTrackSettings: raw });
260 }
261 } catch
262 {
263 // Ignore localStorage failures.
264 }
265 }
266
267 async function reportWatchProgress (filePath, progress)
268 {
269 if (!filePath || !Number.isFinite(progress)) return;
270 await api('POST', '/files/watch-progress', {
271 filePath,
272 progress,
273 }).catch(() => null);
274 }
275
203 276 function getOrCreateClientBindingId ()
204 277 {
205 278 if (STATE.clientBindingId) return STATE.clientBindingId;
@@ -824,7 +897,7 @@ async function performLogout ()
824 897 STATE.restoreRootPath = null;
825 898 STATE.lastOperationAt = null;
826 899 clearSessionState();
827 closePreview();
900 closePreview({ force: true });
828 901 closeSidebar();
829 902 await initAuth();
830 903 }
@@ -1261,11 +1334,18 @@ async function openSidebar (item)
1261 1334 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
1262 1335 if (meta)
1263 1336 {
1337 const watchedBy = VIDEO_EXTS.has(extOf(item.name))
1338 ? Object.entries(meta.watchedBy || {})
1339 .map(([user, status]) => `${String(user)}: ${String(status)}`)
1340 .sort((a, b) => a.localeCompare(b))
1341 : [];
1342
1264 1343 dl.innerHTML = `
1265 1344 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
1266 1345 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
1267 1346 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
1268 1347 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
1348 ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''}
1269 1349 `;
1270 1350 }
1271 1351
@@ -2187,6 +2267,8 @@ async function renderStreamedVideoPreview (item, targetEl)
2187 2267 {
2188 2268 const videojs = await ensureVideoJsLoaded();
2189 2269 const session = await createVideoStreamSessionForItem(item);
2270 const prefs = loadUserVideoPrefs();
2271 applyUserVideoTextTrackPrefs();
2190 2272
2191 2273 if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2192 2274 {
@@ -2217,8 +2299,67 @@ async function renderStreamedVideoPreview (item, targetEl)
2217 2299 })),
2218 2300 });
2219 2301
2302 let sentPartway = false;
2303 let sentFully = false;
2304 const markWatch = async () =>
2305 {
2306 let ratio = 0;
2307 try
2308 {
2309 const duration = Number(player.duration());
2310 const current = Number(player.currentTime());
2311 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
2312 {
2313 ratio = current / duration;
2314 }
2315 } catch
2316 {
2317 return;
2318 }
2319
2320 if (ratio >= 0.7)
2321 {
2322 if (sentFully) return;
2323 sentPartway = true;
2324 sentFully = true;
2325 void reportWatchProgress(item.path, ratio);
2326 return;
2327 }
2328
2329 if (ratio >= 0.3)
2330 {
2331 if (sentPartway) return;
2332 sentPartway = true;
2333 void reportWatchProgress(item.path, ratio);
2334 }
2335 };
2336
2337 player.ready(() =>
2338 {
2339 const volume = Number(prefs.volume);
2340 if (Number.isFinite(volume))
2341 {
2342 player.volume(Math.max(0, Math.min(1, volume)));
2343 }
2344 });
2345
2346 player.on('timeupdate', markWatch);
2347 player.on('ended', () =>
2348 {
2349 sentPartway = true;
2350 sentFully = true;
2351 void reportWatchProgress(item.path, 1);
2352 });
2353 player.on('volumechange', () =>
2354 {
2355 const v = Number(player.volume());
2356 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
2357 });
2358
2220 2359 STATE.previewCleanup = () =>
2221 2360 {
2361 try { markWatch(); } catch { /* ignore */ }
2362 captureUserVideoTextTrackPrefs();
2222 2363 try { player.dispose(); } catch { /* ignore */ }
2223 2364 };
2224 2365 }
@@ -2392,6 +2533,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2392 2533
2393 2534 STATE.previewExpandState = {
2394 2535 item,
2536 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
2395 2537 tileEl,
2396 2538 sourceSvgEl,
2397 2539 parent,
@@ -2403,6 +2545,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2403 2545 closeBtn,
2404 2546 dlBtn,
2405 2547 shareBtn,
2548 actionsEl,
2406 2549 titleEl,
2407 2550 previewMount,
2408 2551 startRect,
@@ -2412,7 +2555,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2412 2555 {
2413 2556 if (e.target === backdrop) closePreview();
2414 2557 };
2415 const onClose = () => closePreview();
2558 const onClose = () => closePreview({ force: true });
2416 2559 backdrop.addEventListener('click', onBackdrop);
2417 2560 closeBtn.addEventListener('click', onClose);
2418 2561 STATE.previewExpandState.onBackdrop = onBackdrop;
@@ -2467,8 +2610,7 @@ async function closeExpandedTilePreview ()
2467 2610
2468 2611 if (st.titleEl) st.titleEl.remove();
2469 2612 if (st.closeBtn) st.closeBtn.remove();
2470 if (st.dlBtn) st.dlBtn.remove();
2471 if (st.shareBtn) st.shareBtn.remove();
2613 if (st.actionsEl) st.actionsEl.remove();
2472 2614 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
2473 2615 if (st.nameEl) st.nameEl.style.display = '';
2474 2616
@@ -2487,13 +2629,26 @@ async function closeExpandedTilePreview ()
2487 2629 STATE.previewExpandState = null;
2488 2630 }
2489 2631
2490 async function closePreview ()
2632 async function closePreview (opts = {})
2491 2633 {
2634 if (STATE.previewClosing) return;
2492 2635 if (STATE.previewExpandState)
2493 2636 {
2494 await closeExpandedTilePreview();
2637 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
2638 {
2639 return;
2640 }
2641
2642 STATE.previewClosing = true;
2495 2643 clearPreviewObjectUrl();
2496 STATE.previewSourceEl = null;
2644 try
2645 {
2646 await closeExpandedTilePreview();
2647 STATE.previewSourceEl = null;
2648 } finally
2649 {
2650 STATE.previewClosing = false;
2651 }
2497 2652 }
2498 2653 }
2499 2654
@@ -2604,7 +2759,7 @@ async function downloadOrView (item, sourceSvgEl = null)
2604 2759 {
2605 2760 if (STATE.previewExpandState)
2606 2761 {
2607 await closePreview();
2762 await closePreview({ force: true });
2608 2763 }
2609 2764
2610 2765 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
@@ -63,6 +63,8 @@ const MOBILE_BREAKPOINT_QUERY = '(max-width: 600px)';
63const MOBILE_LONG_PRESS_MS = 420;
63const MOBILE_LONG_PRESS_MS = 420;
64const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
64const MOBILE_LONG_PRESS_MOVE_THRESHOLD = 10;
65const THUMB_OBSERVER_ROOT_MARGIN = '120px';
65const THUMB_OBSERVER_ROOT_MARGIN = '120px';
66const VIDEO_PREFS_KEY_PREFIX = 'filemanager.video-prefs.v1.';
67const VIDEO_TEXT_TRACK_SETTINGS_KEY = 'vjs-text-track-settings';
66let videoJsLoaderPromise = null;
68let videoJsLoaderPromise = null;
67
69
68// ───────────────────────────────────────────────────────────────────────────
70// ───────────────────────────────────────────────────────────────────────────
@@ -200,6 +202,77 @@ function randomIdHex (bytes = 16)
200 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
202 return Array.from(arr).map(n => n.toString(16).padStart(2, '0')).join('');
201}
203}
202
204
205function userVideoPrefsKey ()
206{
207 const name = String(STATE.username || 'anonymous').trim().toLowerCase() || 'anonymous';
208 return VIDEO_PREFS_KEY_PREFIX + name;
209}
210
211function loadUserVideoPrefs ()
212{
213 try
214 {
215 const raw = localStorage.getItem(userVideoPrefsKey());
216 const parsed = raw ? JSON.parse(raw) : {};
217 if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
218 return parsed;
219 } catch
220 {
221 return {};
222 }
223}
224
225function saveUserVideoPrefs (patch)
226{
227 try
228 {
229 const current = loadUserVideoPrefs();
230 localStorage.setItem(userVideoPrefsKey(), JSON.stringify({ ...current, ...(patch || {}) }));
231 } catch
232 {
233 // Ignore localStorage failures.
234 }
235}
236
237function applyUserVideoTextTrackPrefs ()
238{
239 try
240 {
241 const prefs = loadUserVideoPrefs();
242 if (typeof prefs.textTrackSettings === 'string' && prefs.textTrackSettings)
243 {
244 localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, prefs.textTrackSettings);
245 }
246 } catch
247 {
248 // Ignore localStorage failures.
249 }
250}
251
252function captureUserVideoTextTrackPrefs ()
253{
254 try
255 {
256 const raw = localStorage.getItem(VIDEO_TEXT_TRACK_SETTINGS_KEY);
257 if (typeof raw === 'string' && raw)
258 {
259 saveUserVideoPrefs({ textTrackSettings: raw });
260 }
261 } catch
262 {
263 // Ignore localStorage failures.
264 }
265}
266
267async function reportWatchProgress (filePath, progress)
268{
269 if (!filePath || !Number.isFinite(progress)) return;
270 await api('POST', '/files/watch-progress', {
271 filePath,
272 progress,
273 }).catch(() => null);
274}
275
203function getOrCreateClientBindingId ()
276function getOrCreateClientBindingId ()
204{
277{
205 if (STATE.clientBindingId) return STATE.clientBindingId;
278 if (STATE.clientBindingId) return STATE.clientBindingId;
@@ -824,7 +897,7 @@ async function performLogout ()
824 STATE.restoreRootPath = null;
897 STATE.restoreRootPath = null;
825 STATE.lastOperationAt = null;
898 STATE.lastOperationAt = null;
826 clearSessionState();
899 clearSessionState();
827 closePreview();
900 closePreview({ force: true });
828 closeSidebar();
901 closeSidebar();
829 await initAuth();
902 await initAuth();
830}
903}
@@ -1261,11 +1334,18 @@ async function openSidebar (item)
1261 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
1334 const meta = await api('GET', `/files/meta?file=${encodeURIComponent(item.path)}`);
1262 if (meta)
1335 if (meta)
1263 {
1336 {
1337 const watchedBy = VIDEO_EXTS.has(extOf(item.name))
1338 ? Object.entries(meta.watchedBy || {})
1339 .map(([user, status]) => `${String(user)}: ${String(status)}`)
1340 .sort((a, b) => a.localeCompare(b))
1341 : [];
1342
1264 dl.innerHTML = `
1343 dl.innerHTML = `
1265 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
1344 <dt>Size</dt> <dd>${formatBytes(meta.size)}</dd>
1266 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
1345 <dt>Modified</dt> <dd>${new Date(meta.mtime).toLocaleString()}</dd>
1267 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
1346 <dt>Uploaded by</dt><dd>${meta.uploader || '—'}</dd>
1268 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
1347 <dt>Downloaded by</dt><dd>${meta.downloaders.join(', ') || '—'}</dd>
1348 ${VIDEO_EXTS.has(extOf(item.name)) ? `<dt>Watched by</dt><dd>${watchedBy.join(', ') || '—'}</dd>` : ''}
1269 `;
1349 `;
1270 }
1350 }
1271
1351
@@ -2187,6 +2267,8 @@ async function renderStreamedVideoPreview (item, targetEl)
2187{
2267{
2188 const videojs = await ensureVideoJsLoaded();
2268 const videojs = await ensureVideoJsLoaded();
2189 const session = await createVideoStreamSessionForItem(item);
2269 const session = await createVideoStreamSessionForItem(item);
2270 const prefs = loadUserVideoPrefs();
2271 applyUserVideoTextTrackPrefs();
2190
2272
2191 if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2273 if ((session.subtitleSummary && session.subtitleSummary.total > 0) && !(session.subtitleTracks || []).length)
2192 {
2274 {
@@ -2217,8 +2299,67 @@ async function renderStreamedVideoPreview (item, targetEl)
2217 })),
2299 })),
2218 });
2300 });
2219
2301
2302 let sentPartway = false;
2303 let sentFully = false;
2304 const markWatch = async () =>
2305 {
2306 let ratio = 0;
2307 try
2308 {
2309 const duration = Number(player.duration());
2310 const current = Number(player.currentTime());
2311 if (Number.isFinite(duration) && duration > 0 && Number.isFinite(current))
2312 {
2313 ratio = current / duration;
2314 }
2315 } catch
2316 {
2317 return;
2318 }
2319
2320 if (ratio >= 0.7)
2321 {
2322 if (sentFully) return;
2323 sentPartway = true;
2324 sentFully = true;
2325 void reportWatchProgress(item.path, ratio);
2326 return;
2327 }
2328
2329 if (ratio >= 0.3)
2330 {
2331 if (sentPartway) return;
2332 sentPartway = true;
2333 void reportWatchProgress(item.path, ratio);
2334 }
2335 };
2336
2337 player.ready(() =>
2338 {
2339 const volume = Number(prefs.volume);
2340 if (Number.isFinite(volume))
2341 {
2342 player.volume(Math.max(0, Math.min(1, volume)));
2343 }
2344 });
2345
2346 player.on('timeupdate', markWatch);
2347 player.on('ended', () =>
2348 {
2349 sentPartway = true;
2350 sentFully = true;
2351 void reportWatchProgress(item.path, 1);
2352 });
2353 player.on('volumechange', () =>
2354 {
2355 const v = Number(player.volume());
2356 if (Number.isFinite(v)) saveUserVideoPrefs({ volume: v });
2357 });
2358
2220 STATE.previewCleanup = () =>
2359 STATE.previewCleanup = () =>
2221 {
2360 {
2361 try { markWatch(); } catch { /* ignore */ }
2362 captureUserVideoTextTrackPrefs();
2222 try { player.dispose(); } catch { /* ignore */ }
2363 try { player.dispose(); } catch { /* ignore */ }
2223 };
2364 };
2224}
2365}
@@ -2392,6 +2533,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2392
2533
2393 STATE.previewExpandState = {
2534 STATE.previewExpandState = {
2394 item,
2535 item,
2536 requireExplicitClose: VIDEO_EXTS.has(extOf(item.name)),
2395 tileEl,
2537 tileEl,
2396 sourceSvgEl,
2538 sourceSvgEl,
2397 parent,
2539 parent,
@@ -2403,6 +2545,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2403 closeBtn,
2545 closeBtn,
2404 dlBtn,
2546 dlBtn,
2405 shareBtn,
2547 shareBtn,
2548 actionsEl,
2406 titleEl,
2549 titleEl,
2407 previewMount,
2550 previewMount,
2408 startRect,
2551 startRect,
@@ -2412,7 +2555,7 @@ async function openExpandedTilePreview (item, tileEl, sourceSvgEl, loadPreviewCo
2412 {
2555 {
2413 if (e.target === backdrop) closePreview();
2556 if (e.target === backdrop) closePreview();
2414 };
2557 };
2415 const onClose = () => closePreview();
2558 const onClose = () => closePreview({ force: true });
2416 backdrop.addEventListener('click', onBackdrop);
2559 backdrop.addEventListener('click', onBackdrop);
2417 closeBtn.addEventListener('click', onClose);
2560 closeBtn.addEventListener('click', onClose);
2418 STATE.previewExpandState.onBackdrop = onBackdrop;
2561 STATE.previewExpandState.onBackdrop = onBackdrop;
@@ -2467,8 +2610,7 @@ async function closeExpandedTilePreview ()
2467
2610
2468 if (st.titleEl) st.titleEl.remove();
2611 if (st.titleEl) st.titleEl.remove();
2469 if (st.closeBtn) st.closeBtn.remove();
2612 if (st.closeBtn) st.closeBtn.remove();
2470 if (st.dlBtn) st.dlBtn.remove();
2613 if (st.actionsEl) st.actionsEl.remove();
2471 if (st.shareBtn) st.shareBtn.remove();
2472 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
2614 if (st.iconEl) st.iconEl.innerHTML = st.iconHtml;
2473 if (st.nameEl) st.nameEl.style.display = '';
2615 if (st.nameEl) st.nameEl.style.display = '';
2474
2616
@@ -2487,13 +2629,26 @@ async function closeExpandedTilePreview ()
2487 STATE.previewExpandState = null;
2629 STATE.previewExpandState = null;
2488}
2630}
2489
2631
2490async function closePreview ()
2632async function closePreview (opts = {})
2491{
2633{
2634 if (STATE.previewClosing) return;
2492 if (STATE.previewExpandState)
2635 if (STATE.previewExpandState)
2493 {
2636 {
2494 await closeExpandedTilePreview();
2637 if (STATE.previewExpandState.requireExplicitClose && !opts.force)
2638 {
2639 return;
2640 }
2641
2642 STATE.previewClosing = true;
2495 clearPreviewObjectUrl();
2643 clearPreviewObjectUrl();
2496 STATE.previewSourceEl = null;
2644 try
2645 {
2646 await closeExpandedTilePreview();
2647 STATE.previewSourceEl = null;
2648 } finally
2649 {
2650 STATE.previewClosing = false;
2651 }
2497 }
2652 }
2498}
2653}
2499
2654
@@ -2604,7 +2759,7 @@ async function downloadOrView (item, sourceSvgEl = null)
2604{
2759{
2605 if (STATE.previewExpandState)
2760 if (STATE.previewExpandState)
2606 {
2761 {
2607 await closePreview();
2762 await closePreview({ force: true });
2608 }
2763 }
2609
2764
2610 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
2765 const sourceTileEl = sourceSvgEl ? sourceSvgEl.closest('.file-item') : null;
public/index.html +1 −1
@@ -173,7 +173,7 @@
173 173 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
174 174 <h2 id="user-modal-title">New User</h2>
175 175 <form id="user-form">
176 <label>Username<input id="user-username" type="text" required /></label>
176 <label>Username<input id="user-username" type="text" autocomplete="username" required /></label>
177 177 <label id="user-password-label">
178 178 Password<input id="user-password" type="password" placeholder="Min 8 characters" autocomplete="new-password" />
179 179 </label>
@@ -173,7 +173,7 @@
173 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
173 <button class="modal-close" id="user-modal-close" aria-label="Close">✕</button>
174 <h2 id="user-modal-title">New User</h2>
174 <h2 id="user-modal-title">New User</h2>
175 <form id="user-form">
175 <form id="user-form">
176 <label>Username<input id="user-username" type="text" required /></label>
176 <label>Username<input id="user-username" type="text" autocomplete="username" required /></label>
177 <label id="user-password-label">
177 <label id="user-password-label">
178 Password<input id="user-password" type="password" placeholder="Min 8 characters" autocomplete="new-password" />
178 Password<input id="user-password" type="password" placeholder="Min 8 characters" autocomplete="new-password" />
179 </label>
179 </label>
server/db.js +9 −1
@@ -33,7 +33,8 @@ function initDb ()
33 33 CREATE TABLE IF NOT EXISTS file_meta (
34 34 file_path TEXT PRIMARY KEY,
35 35 uploader TEXT NOT NULL DEFAULT '',
36 downloaders TEXT NOT NULL DEFAULT '[]'
36 downloaders TEXT NOT NULL DEFAULT '[]',
37 watched_by TEXT NOT NULL DEFAULT '{}'
37 38 );
38 39
39 40 CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -61,6 +62,13 @@ function initDb ()
61 62
62 63 CREATE INDEX IF NOT EXISTS idx_share_tokens_expires ON share_tokens(expires_at);
63 64 `);
65
66 const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all();
67 const hasWatchedBy = fileMetaCols.some((col) => String(col.name || '') === 'watched_by');
68 if (!hasWatchedBy)
69 {
70 d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'");
71 }
64 72 }
65 73
66 74 function closeDb ()
@@ -33,7 +33,8 @@ function initDb ()
33 CREATE TABLE IF NOT EXISTS file_meta (
33 CREATE TABLE IF NOT EXISTS file_meta (
34 file_path TEXT PRIMARY KEY,
34 file_path TEXT PRIMARY KEY,
35 uploader TEXT NOT NULL DEFAULT '',
35 uploader TEXT NOT NULL DEFAULT '',
36 downloaders TEXT NOT NULL DEFAULT '[]'
36 downloaders TEXT NOT NULL DEFAULT '[]',
37 watched_by TEXT NOT NULL DEFAULT '{}'
37 );
38 );
38
39
39 CREATE TABLE IF NOT EXISTS auth_sessions (
40 CREATE TABLE IF NOT EXISTS auth_sessions (
@@ -61,6 +62,13 @@ function initDb ()
61
62
62 CREATE INDEX IF NOT EXISTS idx_share_tokens_expires ON share_tokens(expires_at);
63 CREATE INDEX IF NOT EXISTS idx_share_tokens_expires ON share_tokens(expires_at);
63 `);
64 `);
65
66 const fileMetaCols = d.prepare('PRAGMA table_info(file_meta)').all();
67 const hasWatchedBy = fileMetaCols.some((col) => String(col.name || '') === 'watched_by');
68 if (!hasWatchedBy)
69 {
70 d.exec("ALTER TABLE file_meta ADD COLUMN watched_by TEXT NOT NULL DEFAULT '{}'");
71 }
64}
72}
65
73
66function closeDb ()
74function closeDb ()
server/routes/files.js +97 −9
@@ -252,18 +252,19 @@ function pathInsideResolved (child, root)
252 252 function rewriteMetaPaths (fromPath, toPath)
253 253 {
254 254 const db = getDb();
255 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
255 const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
256 256 .all([fromPath, fromPath + path.sep + '%']);
257 257
258 258 if (!rows.length) return;
259 259
260 260 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
261 261 const upsert = db.prepare(`
262 INSERT INTO file_meta (file_path, uploader, downloaders)
263 VALUES (?, ?, ?)
262 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by)
263 VALUES (?, ?, ?, ?)
264 264 ON CONFLICT(file_path) DO UPDATE SET
265 265 uploader = excluded.uploader,
266 downloaders = excluded.downloaders
266 downloaders = excluded.downloaders,
267 watched_by = excluded.watched_by
267 268 `);
268 269
269 270 for (const row of rows)
@@ -272,10 +273,43 @@ function rewriteMetaPaths (fromPath, toPath)
272 273 ? toPath
273 274 : toPath + row.file_path.slice(fromPath.length);
274 275 del.run([row.file_path]);
275 upsert.run([nextPath, row.uploader, row.downloaders]);
276 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}']);
276 277 }
277 278 }
278 279
280 function parseJsonArray (raw)
281 {
282 try
283 {
284 const value = JSON.parse(raw || '[]');
285 return Array.isArray(value) ? value : [];
286 } catch
287 {
288 return [];
289 }
290 }
291
292 function parseJsonObject (raw)
293 {
294 try
295 {
296 const value = JSON.parse(raw || '{}');
297 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
298 return value;
299 } catch
300 {
301 return {};
302 }
303 }
304
305 function watchStatusForProgress (progress)
306 {
307 if (!Number.isFinite(progress) || progress < 0) return null;
308 if (progress >= 0.7) return 'fully';
309 if (progress >= 0.3) return 'partway';
310 return null;
311 }
312
279 313 function splitNameExt (name)
280 314 {
281 315 const dot = String(name || '').lastIndexOf('.');
@@ -547,7 +581,8 @@ router.get('/meta', requireAuth, (req, res) =>
547 581 size: stat.size,
548 582 mtime: stat.mtime.toISOString(),
549 583 uploader: meta ? meta.uploader : '',
550 downloaders: meta ? JSON.parse(meta.downloaders) : [],
584 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
585 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
551 586 });
552 587 });
553 588
@@ -608,7 +643,7 @@ router.get('/download', requireAuth, (req, res) =>
608 643 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
609 644 if (meta)
610 645 {
611 const downloaders = JSON.parse(meta.downloaders);
646 const downloaders = parseJsonArray(meta.downloaders);
612 647 if (!downloaders.includes(req.user.username))
613 648 {
614 649 downloaders.push(req.user.username);
@@ -617,13 +652,66 @@ router.get('/download', requireAuth, (req, res) =>
617 652 }
618 653 } else
619 654 {
620 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
621 .run([file, '', JSON.stringify([req.user.username])]);
655 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
656 .run([file, '', JSON.stringify([req.user.username]), '{}']);
622 657 }
623 658
624 659 res.download(file, path.basename(file));
625 660 });
626 661
662 // ---------------------------------------------------------------------------
663 // POST /api/files/watch-progress
664 // Body: { filePath: <absolute-path>, progress: <0..1> }
665 // Records per-user video watch state for sidebar display.
666 // ---------------------------------------------------------------------------
667 router.post('/watch-progress', requireAuth, (req, res) =>
668 {
669 const filePath = String(req.body && req.body.filePath || '').trim();
670 const progress = Number(req.body && req.body.progress);
671 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
672
673 const status = watchStatusForProgress(progress);
674 if (!status)
675 {
676 return res.json({ ok: true, updated: false });
677 }
678
679 const roots = effectivePaths();
680 const info = resolveRoot(filePath, roots);
681 if (!info || !canRead(req.user, info.label))
682 {
683 return res.status(403).json({ error: 'Access denied.' });
684 }
685
686 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
687 {
688 return res.status(404).json({ error: 'File not found.' });
689 }
690
691 const db = getDb();
692 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
693 const watchedBy = parseJsonObject(row && row.watched_by);
694 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
695 const next = prev === 'fully' ? 'fully' : status;
696 if (prev === next)
697 {
698 return res.json({ ok: true, updated: false, status: next });
699 }
700
701 watchedBy[req.user.username] = next;
702 if (row)
703 {
704 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
705 .run([JSON.stringify(watchedBy), filePath]);
706 } else
707 {
708 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
709 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
710 }
711
712 res.json({ ok: true, updated: true, status: next });
713 });
714
627 715 // ---------------------------------------------------------------------------
628 716 // POST /api/files/video-stream
629 717 // Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
@@ -252,18 +252,19 @@ function pathInsideResolved (child, root)
252function rewriteMetaPaths (fromPath, toPath)
252function rewriteMetaPaths (fromPath, toPath)
253{
253{
254 const db = getDb();
254 const db = getDb();
255 const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
255 const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
256 .all([fromPath, fromPath + path.sep + '%']);
256 .all([fromPath, fromPath + path.sep + '%']);
257
257
258 if (!rows.length) return;
258 if (!rows.length) return;
259
259
260 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
260 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
261 const upsert = db.prepare(`
261 const upsert = db.prepare(`
262 INSERT INTO file_meta (file_path, uploader, downloaders)
262 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by)
263 VALUES (?, ?, ?)
263 VALUES (?, ?, ?, ?)
264 ON CONFLICT(file_path) DO UPDATE SET
264 ON CONFLICT(file_path) DO UPDATE SET
265 uploader = excluded.uploader,
265 uploader = excluded.uploader,
266 downloaders = excluded.downloaders
266 downloaders = excluded.downloaders,
267 watched_by = excluded.watched_by
267 `);
268 `);
268
269
269 for (const row of rows)
270 for (const row of rows)
@@ -272,10 +273,43 @@ function rewriteMetaPaths (fromPath, toPath)
272 ? toPath
273 ? toPath
273 : toPath + row.file_path.slice(fromPath.length);
274 : toPath + row.file_path.slice(fromPath.length);
274 del.run([row.file_path]);
275 del.run([row.file_path]);
275 upsert.run([nextPath, row.uploader, row.downloaders]);
276 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}']);
276 }
277 }
277}
278}
278
279
280function parseJsonArray (raw)
281{
282 try
283 {
284 const value = JSON.parse(raw || '[]');
285 return Array.isArray(value) ? value : [];
286 } catch
287 {
288 return [];
289 }
290}
291
292function parseJsonObject (raw)
293{
294 try
295 {
296 const value = JSON.parse(raw || '{}');
297 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
298 return value;
299 } catch
300 {
301 return {};
302 }
303}
304
305function watchStatusForProgress (progress)
306{
307 if (!Number.isFinite(progress) || progress < 0) return null;
308 if (progress >= 0.7) return 'fully';
309 if (progress >= 0.3) return 'partway';
310 return null;
311}
312
279function splitNameExt (name)
313function splitNameExt (name)
280{
314{
281 const dot = String(name || '').lastIndexOf('.');
315 const dot = String(name || '').lastIndexOf('.');
@@ -547,7 +581,8 @@ router.get('/meta', requireAuth, (req, res) =>
547 size: stat.size,
581 size: stat.size,
548 mtime: stat.mtime.toISOString(),
582 mtime: stat.mtime.toISOString(),
549 uploader: meta ? meta.uploader : '',
583 uploader: meta ? meta.uploader : '',
550 downloaders: meta ? JSON.parse(meta.downloaders) : [],
584 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
585 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
551 });
586 });
552});
587});
553
588
@@ -608,7 +643,7 @@ router.get('/download', requireAuth, (req, res) =>
608 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
643 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
609 if (meta)
644 if (meta)
610 {
645 {
611 const downloaders = JSON.parse(meta.downloaders);
646 const downloaders = parseJsonArray(meta.downloaders);
612 if (!downloaders.includes(req.user.username))
647 if (!downloaders.includes(req.user.username))
613 {
648 {
614 downloaders.push(req.user.username);
649 downloaders.push(req.user.username);
@@ -617,13 +652,66 @@ router.get('/download', requireAuth, (req, res) =>
617 }
652 }
618 } else
653 } else
619 {
654 {
620 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
655 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
621 .run([file, '', JSON.stringify([req.user.username])]);
656 .run([file, '', JSON.stringify([req.user.username]), '{}']);
622 }
657 }
623
658
624 res.download(file, path.basename(file));
659 res.download(file, path.basename(file));
625});
660});
626
661
662// ---------------------------------------------------------------------------
663// POST /api/files/watch-progress
664// Body: { filePath: <absolute-path>, progress: <0..1> }
665// Records per-user video watch state for sidebar display.
666// ---------------------------------------------------------------------------
667router.post('/watch-progress', requireAuth, (req, res) =>
668{
669 const filePath = String(req.body && req.body.filePath || '').trim();
670 const progress = Number(req.body && req.body.progress);
671 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
672
673 const status = watchStatusForProgress(progress);
674 if (!status)
675 {
676 return res.json({ ok: true, updated: false });
677 }
678
679 const roots = effectivePaths();
680 const info = resolveRoot(filePath, roots);
681 if (!info || !canRead(req.user, info.label))
682 {
683 return res.status(403).json({ error: 'Access denied.' });
684 }
685
686 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
687 {
688 return res.status(404).json({ error: 'File not found.' });
689 }
690
691 const db = getDb();
692 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
693 const watchedBy = parseJsonObject(row && row.watched_by);
694 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
695 const next = prev === 'fully' ? 'fully' : status;
696 if (prev === next)
697 {
698 return res.json({ ok: true, updated: false, status: next });
699 }
700
701 watchedBy[req.user.username] = next;
702 if (row)
703 {
704 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
705 .run([JSON.stringify(watchedBy), filePath]);
706 } else
707 {
708 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
709 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
710 }
711
712 res.json({ ok: true, updated: true, status: next });
713});
714
627// ---------------------------------------------------------------------------
715// ---------------------------------------------------------------------------
628// POST /api/files/video-stream
716// POST /api/files/video-stream
629// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
717// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
tests/files.routes.test.js +30 −1
@@ -37,7 +37,8 @@ jest.mock('../server/db', () =>
37 37 CREATE TABLE IF NOT EXISTS file_meta (
38 38 file_path TEXT PRIMARY KEY,
39 39 uploader TEXT NOT NULL DEFAULT '',
40 downloaders TEXT NOT NULL DEFAULT '[]'
40 downloaders TEXT NOT NULL DEFAULT '[]',
41 watched_by TEXT NOT NULL DEFAULT '{}'
41 42 );
42 43 `);
43 44 }
@@ -702,6 +703,7 @@ describe('video streaming routes', () =>
702 703
703 704 expect(status).toBe(200);
704 705 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
706 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
705 707 expect(body.subtitleTracks).toEqual([
706 708 {
707 709 label: 'English',
@@ -725,4 +727,31 @@ describe('video streaming routes', () =>
725 727 expect(headers['content-type']).toMatch(/text\/vtt/);
726 728 expect(body.toString()).toBe('WEBVTT\n');
727 729 });
730
731 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
732 {
733 const filePath = path.join(rootDir, 'clip.mkv');
734 fs.writeFileSync(filePath, 'video');
735
736 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.35 });
737 expect(result.status).toBe(200);
738 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
739
740 // A lower progress update should not downgrade the status.
741 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.4 });
742 expect(result.status).toBe(200);
743 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
744
745 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
746 expect(result.status).toBe(200);
747 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
748
749 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
750 expect(result.status).toBe(200);
751 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
752
753 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
754 expect(result.status).toBe(200);
755 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
756 });
728 757 });
@@ -37,7 +37,8 @@ jest.mock('../server/db', () =>
37 CREATE TABLE IF NOT EXISTS file_meta (
37 CREATE TABLE IF NOT EXISTS file_meta (
38 file_path TEXT PRIMARY KEY,
38 file_path TEXT PRIMARY KEY,
39 uploader TEXT NOT NULL DEFAULT '',
39 uploader TEXT NOT NULL DEFAULT '',
40 downloaders TEXT NOT NULL DEFAULT '[]'
40 downloaders TEXT NOT NULL DEFAULT '[]',
41 watched_by TEXT NOT NULL DEFAULT '{}'
41 );
42 );
42 `);
43 `);
43 }
44 }
@@ -702,6 +703,7 @@ describe('video streaming routes', () =>
702
703
703 expect(status).toBe(200);
704 expect(status).toBe(200);
704 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
705 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
706 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
705 expect(body.subtitleTracks).toEqual([
707 expect(body.subtitleTracks).toEqual([
706 {
708 {
707 label: 'English',
709 label: 'English',
@@ -725,4 +727,31 @@ describe('video streaming routes', () =>
725 expect(headers['content-type']).toMatch(/text\/vtt/);
727 expect(headers['content-type']).toMatch(/text\/vtt/);
726 expect(body.toString()).toBe('WEBVTT\n');
728 expect(body.toString()).toBe('WEBVTT\n');
727 });
729 });
730
731 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
732 {
733 const filePath = path.join(rootDir, 'clip.mkv');
734 fs.writeFileSync(filePath, 'video');
735
736 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.35 });
737 expect(result.status).toBe(200);
738 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
739
740 // A lower progress update should not downgrade the status.
741 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.4 });
742 expect(result.status).toBe(200);
743 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
744
745 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
746 expect(result.status).toBe(200);
747 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
748
749 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
750 expect(result.status).toBe(200);
751 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
752
753 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
754 expect(result.status).toBe(200);
755 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
756 });
728});
757});
tests/page.load.test.js +114 −0
@@ -99,6 +99,24 @@ describe('page load smoke test', () =>
99 99 }
100 100 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
101 101 });
102 app.get('/api/files/meta', (req, res) =>
103 {
104 const file = String(req.query.file || '');
105 const allItems = Object.values(listFixture).flat();
106 const item = allItems.find((it) => it.path === file);
107 if (!item)
108 {
109 return res.status(404).json({ error: 'File not found.' });
110 }
111 res.json({
112 name: item.name,
113 size: item.size || 0,
114 mtime: new Date(item.mtime || Date.now()).toISOString(),
115 uploader: '',
116 downloaders: [],
117 watchedBy: {},
118 });
119 });
102 120 app.post('/api/files/video-stream', (req, res) =>
103 121 {
104 122 const filePath = String(req.body?.filePath || '');
@@ -109,6 +127,10 @@ describe('page load smoke test', () =>
109 127 }
110 128 res.json(payload);
111 129 });
130 app.post('/api/files/watch-progress', (req, res) =>
131 {
132 res.json({ ok: true, updated: true });
133 });
112 134 app.get('/api/files/root-access', (req, res) =>
113 135 {
114 136 const rootPath = String(req.query.rootPath || '');
@@ -177,10 +199,26 @@ describe('page load smoke test', () =>
177 199 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
178 200 window.URL.revokeObjectURL = () => { };
179 201 window.__lastVideoJsOptions = null;
202 window.__lastVideoJsVolumeSet = null;
180 203 window.videojs = (element, options) =>
181 204 {
182 205 window.__lastVideoJsOptions = options;
206 let volumeValue = 1;
183 207 return {
208 ready (cb)
209 {
210 if (typeof cb === 'function') cb();
211 },
212 on () { },
213 duration () { return 100; },
214 currentTime () { return 0; },
215 volume (next)
216 {
217 if (next === undefined) return volumeValue;
218 volumeValue = Number(next);
219 window.__lastVideoJsVolumeSet = volumeValue;
220 return volumeValue;
221 },
184 222 dispose () { },
185 223 };
186 224 };
@@ -646,4 +684,80 @@ describe('page load smoke test', () =>
646 684
647 685 dom.window.close();
648 686 });
687
688 test('video preview does not close on backdrop click and closes via X button', async () =>
689 {
690 listFixture['/data'] = [
691 {
692 name: 'clip.mkv',
693 path: '/data/clip.mkv',
694 isDir: false,
695 size: 64,
696 mtime: Date.now(),
697 },
698 ];
699 videoStreamFixture['/data/clip.mkv'] = {
700 sessionId: 'video-session',
701 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
702 subtitleTracks: [],
703 subtitleSummary: { total: 0, converted: 0, skipped: 0 },
704 };
705
706 const { dom, runtimeErrors } = await bootClient();
707 expect(runtimeErrors).toEqual([]);
708
709 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
710
711 const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
712 tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
713 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-backdrop'));
714
715 const backdrop = dom.window.document.querySelector('.preview-backdrop');
716 backdrop.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
717 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
718
719 expect(dom.window.document.querySelector('.preview-backdrop')).toBeTruthy();
720
721 const closeBtn = dom.window.document.querySelector('.preview-expand-close');
722 closeBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
723 await new Promise(resolve => dom.window.setTimeout(resolve, 280));
724
725 expect(dom.window.document.querySelector('.preview-backdrop')).toBeNull();
726
727 dom.window.close();
728 });
729
730 test('video preview restores per-user saved volume preference', async () =>
731 {
732 listFixture['/data'] = [
733 {
734 name: 'clip.mkv',
735 path: '/data/clip.mkv',
736 isDir: false,
737 size: 64,
738 mtime: Date.now(),
739 },
740 ];
741 videoStreamFixture['/data/clip.mkv'] = {
742 sessionId: 'video-session',
743 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
744 subtitleTracks: [],
745 subtitleSummary: { total: 0, converted: 0, skipped: 0 },
746 };
747
748 const { dom, runtimeErrors } = await bootClient();
749 expect(runtimeErrors).toEqual([]);
750
751 dom.window.localStorage.setItem('filemanager.video-prefs.v1.tester', JSON.stringify({ volume: 0.3 }));
752
753 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
754
755 const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
756 tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
757 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
758
759 expect(dom.window.__lastVideoJsVolumeSet).toBe(0.3);
760
761 dom.window.close();
762 });
649 763 });
@@ -99,6 +99,24 @@ describe('page load smoke test', () =>
99 }
99 }
100 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
100 res.type(payload.type || 'application/octet-stream').send(payload.body || 'x');
101 });
101 });
102 app.get('/api/files/meta', (req, res) =>
103 {
104 const file = String(req.query.file || '');
105 const allItems = Object.values(listFixture).flat();
106 const item = allItems.find((it) => it.path === file);
107 if (!item)
108 {
109 return res.status(404).json({ error: 'File not found.' });
110 }
111 res.json({
112 name: item.name,
113 size: item.size || 0,
114 mtime: new Date(item.mtime || Date.now()).toISOString(),
115 uploader: '',
116 downloaders: [],
117 watchedBy: {},
118 });
119 });
102 app.post('/api/files/video-stream', (req, res) =>
120 app.post('/api/files/video-stream', (req, res) =>
103 {
121 {
104 const filePath = String(req.body?.filePath || '');
122 const filePath = String(req.body?.filePath || '');
@@ -109,6 +127,10 @@ describe('page load smoke test', () =>
109 }
127 }
110 res.json(payload);
128 res.json(payload);
111 });
129 });
130 app.post('/api/files/watch-progress', (req, res) =>
131 {
132 res.json({ ok: true, updated: true });
133 });
112 app.get('/api/files/root-access', (req, res) =>
134 app.get('/api/files/root-access', (req, res) =>
113 {
135 {
114 const rootPath = String(req.query.rootPath || '');
136 const rootPath = String(req.query.rootPath || '');
@@ -177,10 +199,26 @@ describe('page load smoke test', () =>
177 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
199 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
178 window.URL.revokeObjectURL = () => { };
200 window.URL.revokeObjectURL = () => { };
179 window.__lastVideoJsOptions = null;
201 window.__lastVideoJsOptions = null;
202 window.__lastVideoJsVolumeSet = null;
180 window.videojs = (element, options) =>
203 window.videojs = (element, options) =>
181 {
204 {
182 window.__lastVideoJsOptions = options;
205 window.__lastVideoJsOptions = options;
206 let volumeValue = 1;
183 return {
207 return {
208 ready (cb)
209 {
210 if (typeof cb === 'function') cb();
211 },
212 on () { },
213 duration () { return 100; },
214 currentTime () { return 0; },
215 volume (next)
216 {
217 if (next === undefined) return volumeValue;
218 volumeValue = Number(next);
219 window.__lastVideoJsVolumeSet = volumeValue;
220 return volumeValue;
221 },
184 dispose () { },
222 dispose () { },
185 };
223 };
186 };
224 };
@@ -646,4 +684,80 @@ describe('page load smoke test', () =>
646
684
647 dom.window.close();
685 dom.window.close();
648 });
686 });
687
688 test('video preview does not close on backdrop click and closes via X button', async () =>
689 {
690 listFixture['/data'] = [
691 {
692 name: 'clip.mkv',
693 path: '/data/clip.mkv',
694 isDir: false,
695 size: 64,
696 mtime: Date.now(),
697 },
698 ];
699 videoStreamFixture['/data/clip.mkv'] = {
700 sessionId: 'video-session',
701 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
702 subtitleTracks: [],
703 subtitleSummary: { total: 0, converted: 0, skipped: 0 },
704 };
705
706 const { dom, runtimeErrors } = await bootClient();
707 expect(runtimeErrors).toEqual([]);
708
709 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
710
711 const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
712 tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
713 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-backdrop'));
714
715 const backdrop = dom.window.document.querySelector('.preview-backdrop');
716 backdrop.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
717 await new Promise(resolve => dom.window.setTimeout(resolve, 40));
718
719 expect(dom.window.document.querySelector('.preview-backdrop')).toBeTruthy();
720
721 const closeBtn = dom.window.document.querySelector('.preview-expand-close');
722 closeBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
723 await new Promise(resolve => dom.window.setTimeout(resolve, 280));
724
725 expect(dom.window.document.querySelector('.preview-backdrop')).toBeNull();
726
727 dom.window.close();
728 });
729
730 test('video preview restores per-user saved volume preference', async () =>
731 {
732 listFixture['/data'] = [
733 {
734 name: 'clip.mkv',
735 path: '/data/clip.mkv',
736 isDir: false,
737 size: 64,
738 mtime: Date.now(),
739 },
740 ];
741 videoStreamFixture['/data/clip.mkv'] = {
742 sessionId: 'video-session',
743 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
744 subtitleTracks: [],
745 subtitleSummary: { total: 0, converted: 0, skipped: 0 },
746 };
747
748 const { dom, runtimeErrors } = await bootClient();
749 expect(runtimeErrors).toEqual([]);
750
751 dom.window.localStorage.setItem('filemanager.video-prefs.v1.tester', JSON.stringify({ volume: 0.3 }));
752
753 await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
754
755 const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
756 tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
757 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
758
759 expect(dom.window.__lastVideoJsVolumeSet).toBe(0.3);
760
761 dom.window.close();
762 });
649});
763});