Merge branch 'fix/video-stream-disconnect-cleanup'
@@ -59,6 +59,7 @@
59
59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, unpipes stream writes on abort/failure, cleans temp files, 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, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
62
- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
62
63
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
63
64
64
65
## server/routes/share.js
@@ -73,9 +74,11 @@
73
74
74
75
## server/video-stream.js
75
76
- createVideoStreamSession(sourcePath) - Probes the input duration, attempts WebVTT conversion for all subtitle streams (skipping only failed conversions), starts ffmpeg HLS transcoding, and resolves only when HLS assets are present (not subtitle files alone); returns durationSeconds, subtitleTracks, and subtitleSummary {total, converted, skipped}.
76
- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
77
- sendVideoStreamAsset(sessionId, assetPath, req, res) - Serves HLS playlists, segments, and extracted subtitle files, tracks request lifecycle, and stops session processing when clients go idle/disconnect.
78
- releaseVideoStreamSession(sessionId) - Explicitly stops an active stream session, terminates ffmpeg, and removes temporary assets.
77
79
- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
78
80
- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
81
- STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated.
79
82
80
83
## server/db.js
81
84
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
@@ -125,7 +128,7 @@
125
128
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
126
129
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
127
130
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
128
- 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), forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, and warns when subtitle streams exist but none are web-compatible.
131
- 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), 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.
129
132
- closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
130
133
131
134
## tests/thumbnail-cache.test.js
@@ -207,6 +210,7 @@
207
210
- video preview saves subtitle/audio track names per user when selection changes - Verifies subtitle/audio selections are persisted into per-user video preferences.
208
211
- video preview applies caption overrides per open - Verifies requested caption overrides are always loaded into Video.js settings.
209
212
- video preview does not save caption style settings per user on close - Verifies caption style changes are not persisted to per-user video preferences.
213
- video preview releases the backend stream session when closed - Verifies closing a streamed video preview sends an explicit backend release call.
210
214
211
215
## tests/video-stream.test.js
212
216
- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
@@ -220,3 +224,4 @@
220
224
221
225
## tests/files.routes.test.js
222
226
- POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
227
- DELETE /api/files/video-stream/:sessionId releases an active stream session - Verifies explicit stream session release route wiring.
@@ -59,6 +59,7 @@59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, unpipes stream writes on abort/failure, cleans temp files, and only exposes final filenames after completion.
59
- POST /api/files/upload - Streams multipart uploads into hidden temp files, unpipes stream writes on abort/failure, cleans temp files, 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, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
61
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
62
- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
62
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
63
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
63
64
64
## server/routes/share.js
65
## server/routes/share.js
@@ -73,9 +74,11 @@73
74
74
## server/video-stream.js
75
## server/video-stream.js
75
- createVideoStreamSession(sourcePath) - Probes the input duration, attempts WebVTT conversion for all subtitle streams (skipping only failed conversions), starts ffmpeg HLS transcoding, and resolves only when HLS assets are present (not subtitle files alone); returns durationSeconds, subtitleTracks, and subtitleSummary {total, converted, skipped}.
76
- createVideoStreamSession(sourcePath) - Probes the input duration, attempts WebVTT conversion for all subtitle streams (skipping only failed conversions), starts ffmpeg HLS transcoding, and resolves only when HLS assets are present (not subtitle files alone); returns durationSeconds, subtitleTracks, and subtitleSummary {total, converted, skipped}.
76
- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
77
- sendVideoStreamAsset(sessionId, assetPath, req, res) - Serves HLS playlists, segments, and extracted subtitle files, tracks request lifecycle, and stops session processing when clients go idle/disconnect.
78
- releaseVideoStreamSession(sessionId) - Explicitly stops an active stream session, terminates ffmpeg, and removes temporary assets.
77
- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
79
- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
78
- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
80
- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
81
- STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated.
79
82
80
## server/db.js
83
## server/db.js
81
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
84
- initDb() - Initializes SQLite schema for users, file metadata, auth_sessions, and share_tokens (expires_at index).
@@ -125,7 +128,7 @@125
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
128
- disconnectThumbnailObserver() - Clears active IntersectionObserver when the grid is rebuilt.
126
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
129
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
127
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
130
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
128
- 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), forces caption overrides on each open (text background opacity transparent + text edge style uniform), reports watch progress, and warns when subtitle streams exist but none are web-compatible.
131
- 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), 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.
129
- closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
132
- closePreview(opts) - Closes expanded previews; video previews ignore backdrop close and require explicit close action.
130
133
131
## tests/thumbnail-cache.test.js
134
## tests/thumbnail-cache.test.js
@@ -207,6 +210,7 @@207
- video preview saves subtitle/audio track names per user when selection changes - Verifies subtitle/audio selections are persisted into per-user video preferences.
210
- video preview saves subtitle/audio track names per user when selection changes - Verifies subtitle/audio selections are persisted into per-user video preferences.
208
- video preview applies caption overrides per open - Verifies requested caption overrides are always loaded into Video.js settings.
211
- video preview applies caption overrides per open - Verifies requested caption overrides are always loaded into Video.js settings.
209
- video preview does not save caption style settings per user on close - Verifies caption style changes are not persisted to per-user video preferences.
212
- video preview does not save caption style settings per user on close - Verifies caption style changes are not persisted to per-user video preferences.
213
- video preview releases the backend stream session when closed - Verifies closing a streamed video preview sends an explicit backend release call.
210
214
211
## tests/video-stream.test.js
215
## tests/video-stream.test.js
212
- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
216
- createVideoStreamSession resolves once ffmpeg starts writing stream assets - Verifies session creation no longer waits for the final master playlist before preview can begin.
@@ -220,3 +224,4 @@220
224
221
## tests/files.routes.test.js
225
## tests/files.routes.test.js
222
- POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
226
- POST /api/files/watch-progress stores per-user watched status by thresholds - Verifies watch-status persistence and no downgrade from fully to partway.
227
- DELETE /api/files/video-stream/:sessionId releases an active stream session - Verifies explicit stream session release route wiring.
@@ -50,6 +50,7 @@ const STATE = {
50
50
previewObjectUrl: null,
51
51
previewCleanup: null,
52
52
previewDownloadAction: null,
53
previewVideoStreamSessionId: null,
53
54
previewSourceEl: null, // SVG element that triggered the preview
54
55
previewClosing: false, // guard to prevent double-close during animation
55
56
previewExpandState: null, // in-place expanded tile preview state
@@ -2538,6 +2539,25 @@ async function createVideoStreamSessionForItem (item)
2538
2539
return api('POST', '/files/video-stream', { filePath: item.path });
2539
2540
}
2540
2541
2542
async function releaseVideoStreamSession (sessionId, opts = {})
2543
{
2544
const id = String(sessionId || '').trim();
2545
if (!id) return;
2546
2547
await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {
2548
keepalive: !!opts.keepalive,
2549
noAutoLogout: true,
2550
}).catch(() => null);
2551
}
2552
2553
function releaseActivePreviewVideoStreamSession (opts = {})
2554
{
2555
const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();
2556
if (!sessionId) return;
2557
STATE.previewVideoStreamSessionId = null;
2558
void releaseVideoStreamSession(sessionId, opts);
2559
}
2560
2541
2561
async function preparePreviewDownload (item)
2542
2562
{
2543
2563
const blob = await fetchFileBlob(item);
@@ -2556,6 +2576,7 @@ async function renderStreamedVideoPreview (item, targetEl)
2556
2576
{
2557
2577
const videojs = await ensureVideoJsLoaded();
2558
2578
const session = await createVideoStreamSessionForItem(item);
2579
STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;
2559
2580
const prefs = loadUserVideoPrefs();
2560
2581
applyUserVideoTextTrackPrefs();
2561
2582
@@ -2663,6 +2684,7 @@ async function renderStreamedVideoPreview (item, targetEl)
2663
2684
2664
2685
STATE.previewCleanup = () =>
2665
2686
{
2687
releaseActivePreviewVideoStreamSession();
2666
2688
try { markWatch(); } catch { /* ignore */ }
2667
2689
try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }
2668
2690
try { trackPrefs.detach(); } catch { /* ignore */ }
@@ -4386,6 +4408,14 @@ function wireEvents ()
4386
4408
{
4387
4409
wireEvents();
4388
4410
initDragDrop();
4389
window.addEventListener('beforeunload', saveSessionState);
4411
window.addEventListener('beforeunload', () =>
4412
{
4413
saveSessionState();
4414
releaseActivePreviewVideoStreamSession({ keepalive: true });
4415
});
4416
window.addEventListener('pagehide', () =>
4417
{
4418
releaseActivePreviewVideoStreamSession({ keepalive: true });
4419
});
4390
4420
await initAuth();
4391
4421
})();
@@ -50,6 +50,7 @@ const STATE = {50
previewObjectUrl: null,50
previewObjectUrl: null,51
previewCleanup: null,51
previewCleanup: null,52
previewDownloadAction: null,52
previewDownloadAction: null,53
previewVideoStreamSessionId: null,53
previewSourceEl: null, // SVG element that triggered the preview54
previewSourceEl: null, // SVG element that triggered the preview54
previewClosing: false, // guard to prevent double-close during animation55
previewClosing: false, // guard to prevent double-close during animation55
previewExpandState: null, // in-place expanded tile preview state56
previewExpandState: null, // in-place expanded tile preview state@@ -2538,6 +2539,25 @@ async function createVideoStreamSessionForItem (item)2538
return api('POST', '/files/video-stream', { filePath: item.path });2539
return api('POST', '/files/video-stream', { filePath: item.path });2539
}2540
}2540
2541
2542
async function releaseVideoStreamSession (sessionId, opts = {})2543
{2544
const id = String(sessionId || '').trim();2545
if (!id) return;2546
2547
await api('DELETE', `/files/video-stream/${encodeURIComponent(id)}`, null, {2548
keepalive: !!opts.keepalive,2549
noAutoLogout: true,2550
}).catch(() => null);2551
}2552
2553
function releaseActivePreviewVideoStreamSession (opts = {})2554
{2555
const sessionId = String(STATE.previewVideoStreamSessionId || '').trim();2556
if (!sessionId) return;2557
STATE.previewVideoStreamSessionId = null;2558
void releaseVideoStreamSession(sessionId, opts);2559
}2560
2541
async function preparePreviewDownload (item)2561
async function preparePreviewDownload (item)2542
{2562
{2543
const blob = await fetchFileBlob(item);2563
const blob = await fetchFileBlob(item);@@ -2556,6 +2576,7 @@ async function renderStreamedVideoPreview (item, targetEl)2556
{2576
{2557
const videojs = await ensureVideoJsLoaded();2577
const videojs = await ensureVideoJsLoaded();2558
const session = await createVideoStreamSessionForItem(item);2578
const session = await createVideoStreamSessionForItem(item);2579
STATE.previewVideoStreamSessionId = String(session.sessionId || '').trim() || null;2559
const prefs = loadUserVideoPrefs();2580
const prefs = loadUserVideoPrefs();2560
applyUserVideoTextTrackPrefs();2581
applyUserVideoTextTrackPrefs();2561
2582
@@ -2663,6 +2684,7 @@ async function renderStreamedVideoPreview (item, targetEl)2663
2684
2664
STATE.previewCleanup = () =>2685
STATE.previewCleanup = () =>2665
{2686
{2687
releaseActivePreviewVideoStreamSession();2666
try { markWatch(); } catch { /* ignore */ }2688
try { markWatch(); } catch { /* ignore */ }2667
try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }2689
try { trackPrefs.captureSelectedTracks(); } catch { /* ignore */ }2668
try { trackPrefs.detach(); } catch { /* ignore */ }2690
try { trackPrefs.detach(); } catch { /* ignore */ }@@ -4386,6 +4408,14 @@ function wireEvents ()4386
{4408
{4387
wireEvents();4409
wireEvents();4388
initDragDrop();4410
initDragDrop();4389
window.addEventListener('beforeunload', saveSessionState);4411
window.addEventListener('beforeunload', () =>4412
{4413
saveSessionState();4414
releaseActivePreviewVideoStreamSession({ keepalive: true });4415
});4416
window.addEventListener('pagehide', () =>4417
{4418
releaseActivePreviewVideoStreamSession({ keepalive: true });4419
});4390
await initAuth();4420
await initAuth();4391
})();4421
})();@@ -12,7 +12,7 @@ const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('.
12
12
const { requireAuth } = require('../auth');
13
13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14
14
const { buildZip } = require('./share');
15
const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream');
15
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
16
16
17
17
// ---------------------------------------------------------------------------
18
18
// Multer storage — files are staged into temporary files and only promoted
@@ -781,13 +781,26 @@ router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
781
781
{
782
782
try
783
783
{
784
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);
784
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
785
785
} catch (err)
786
786
{
787
787
next(err);
788
788
}
789
789
});
790
790
791
// ---------------------------------------------------------------------------
792
// DELETE /api/files/video-stream/:sessionId
793
// Authenticated. Explicitly releases an active short-lived video session.
794
// ---------------------------------------------------------------------------
795
router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
796
{
797
const sessionId = String(req.params.sessionId || '').trim();
798
if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
799
800
releaseVideoStreamSession(sessionId);
801
res.json({ ok: true });
802
});
803
791
804
// ---------------------------------------------------------------------------
792
805
// GET /api/files/download-zip?dir=<absolute-path>
793
806
// Authenticated. Streams a zip of the given directory.
@@ -12,7 +12,7 @@ const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('.12
const { requireAuth } = require('../auth');12
const { requireAuth } = require('../auth');13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');13
const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');14
const { buildZip } = require('./share');14
const { buildZip } = require('./share');15
const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream');15
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');16
16
17
// ---------------------------------------------------------------------------17
// ---------------------------------------------------------------------------18
// Multer storage — files are staged into temporary files and only promoted18
// Multer storage — files are staged into temporary files and only promoted@@ -781,13 +781,26 @@ router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>781
{781
{782
try782
try783
{783
{784
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res);784
await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);785
} catch (err)785
} catch (err)786
{786
{787
next(err);787
next(err);788
}788
}789
});789
});790
790
791
// ---------------------------------------------------------------------------792
// DELETE /api/files/video-stream/:sessionId793
// Authenticated. Explicitly releases an active short-lived video session.794
// ---------------------------------------------------------------------------795
router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>796
{797
const sessionId = String(req.params.sessionId || '').trim();798
if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });799
800
releaseVideoStreamSession(sessionId);801
res.json({ ok: true });802
});803
791
// ---------------------------------------------------------------------------804
// ---------------------------------------------------------------------------792
// GET /api/files/download-zip?dir=<absolute-path>805
// GET /api/files/download-zip?dir=<absolute-path>793
// Authenticated. Streams a zip of the given directory.806
// Authenticated. Streams a zip of the given directory.@@ -9,6 +9,7 @@ const path = require('path');
9
9
const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');
10
10
const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;
11
11
const STREAM_READY_TIMEOUT_MS = 20 * 1000;
12
const STREAM_IDLE_STOP_MS = 20 * 1000;
12
13
const sessions = new Map();
13
14
14
15
function hasInitialHlsAssets (outputDir)
@@ -58,15 +59,7 @@ function pruneExpiredSessions ()
58
59
for (const [sessionId, session] of sessions)
59
60
{
60
61
if (session.expiresAt > now) continue;
61
try
62
{
63
if (session.process) session.process.kill('SIGTERM');
64
} catch
65
{
66
// Ignore process cleanup failures.
67
}
68
sessions.delete(sessionId);
69
fs.rmSync(session.outputDir, { recursive: true, force: true });
62
destroySession(sessionId);
70
63
}
71
64
}
72
65
@@ -75,6 +68,77 @@ function refreshSession (session)
75
68
session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;
76
69
}
77
70
71
function destroySession (sessionId)
72
{
73
const session = sessions.get(sessionId);
74
if (!session) return false;
75
76
sessions.delete(sessionId);
77
78
if (session.idleTimer)
79
{
80
clearTimeout(session.idleTimer);
81
session.idleTimer = null;
82
}
83
84
try
85
{
86
if (session.process) session.process.kill('SIGTERM');
87
} catch
88
{
89
// Ignore process cleanup failures.
90
}
91
92
fs.rmSync(session.outputDir, { recursive: true, force: true });
93
return true;
94
}
95
96
function touchSessionActivity (session)
97
{
98
refreshSession(session);
99
session.lastActivityAt = Date.now();
100
}
101
102
function clearIdleStopTimer (session)
103
{
104
if (!session.idleTimer) return;
105
clearTimeout(session.idleTimer);
106
session.idleTimer = null;
107
}
108
109
function scheduleIdleStop (session)
110
{
111
clearIdleStopTimer(session);
112
if (session.activeRequests > 0) return;
113
114
session.idleTimer = setTimeout(() =>
115
{
116
const activeSession = sessions.get(session.id);
117
if (!activeSession) return;
118
if (activeSession.activeRequests > 0) return;
119
if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS)
120
{
121
scheduleIdleStop(activeSession);
122
return;
123
}
124
destroySession(activeSession.id);
125
}, STREAM_IDLE_STOP_MS);
126
}
127
128
function startAssetRequest (session)
129
{
130
session.activeRequests += 1;
131
touchSessionActivity(session);
132
clearIdleStopTimer(session);
133
}
134
135
function finishAssetRequest (session)
136
{
137
if (session.activeRequests > 0) session.activeRequests -= 1;
138
touchSessionActivity(session);
139
if (session.activeRequests === 0) scheduleIdleStop(session);
140
}
141
78
142
function runCommand (command, args)
79
143
{
80
144
return new Promise((resolve, reject) =>
@@ -476,6 +540,9 @@ async function createVideoStreamSession (sourcePath)
476
540
subtitleTracks: [],
477
541
subtitleSummary: { total: 0, converted: 0, skipped: 0 },
478
542
readyPromise: null,
543
activeRequests: 0,
544
lastActivityAt: Date.now(),
545
idleTimer: null,
479
546
};
480
547
481
548
session.readyPromise = initialiseSession(session).catch((err) =>
@@ -510,13 +577,13 @@ function contentTypeForAsset (assetPath)
510
577
return 'application/octet-stream';
511
578
}
512
579
513
async function sendVideoStreamAsset (sessionId, assetPath, res)
580
async function sendVideoStreamAsset (sessionId, assetPath, req, res)
514
581
{
515
582
pruneExpiredSessions();
516
583
const session = sessions.get(sessionId);
517
584
if (!session) throw makeHttpError(404, 'Video stream session not found.');
518
585
519
refreshSession(session);
586
touchSessionActivity(session);
520
587
await session.readyPromise;
521
588
522
589
const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');
@@ -530,12 +597,55 @@ async function sendVideoStreamAsset (sessionId, assetPath, res)
530
597
await waitForFile(resolvedPath, session);
531
598
res.set('Cache-Control', 'private, no-store');
532
599
res.type(contentTypeForAsset(resolvedPath));
533
res.sendFile(resolvedPath);
600
601
startAssetRequest(session);
602
603
let settled = false;
604
const finish = () =>
605
{
606
if (settled) return;
607
settled = true;
608
finishAssetRequest(session);
609
};
610
611
req.on('aborted', finish);
612
res.on('close', finish);
613
res.on('finish', finish);
614
res.on('error', finish);
615
616
await new Promise((resolve, reject) =>
617
{
618
res.sendFile(resolvedPath, (err) =>
619
{
620
finish();
621
if (!err)
622
{
623
resolve();
624
return;
625
}
626
627
if (err.code === 'ECONNABORTED' || err.message === 'Request aborted')
628
{
629
resolve();
630
return;
631
}
632
633
reject(err);
634
});
635
});
636
}
637
638
function releaseVideoStreamSession (sessionId)
639
{
640
pruneExpiredSessions();
641
return destroySession(String(sessionId || ''));
534
642
}
535
643
536
644
module.exports = {
537
645
STREAM_ROOT_DIR,
538
646
STREAM_SESSION_TTL_MS,
647
STREAM_IDLE_STOP_MS,
539
648
createVideoStreamSession,
540
649
sendVideoStreamAsset,
650
releaseVideoStreamSession,
541
651
};
@@ -9,6 +9,7 @@ const path = require('path');9
const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');9
const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');10
const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;10
const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;11
const STREAM_READY_TIMEOUT_MS = 20 * 1000;11
const STREAM_READY_TIMEOUT_MS = 20 * 1000;12
const STREAM_IDLE_STOP_MS = 20 * 1000;12
const sessions = new Map();13
const sessions = new Map();13
14
14
function hasInitialHlsAssets (outputDir)15
function hasInitialHlsAssets (outputDir)@@ -58,15 +59,7 @@ function pruneExpiredSessions ()58
for (const [sessionId, session] of sessions)59
for (const [sessionId, session] of sessions)59
{60
{60
if (session.expiresAt > now) continue;61
if (session.expiresAt > now) continue;61
try62
destroySession(sessionId);62
{63
if (session.process) session.process.kill('SIGTERM');64
} catch65
{66
// Ignore process cleanup failures.67
}68
sessions.delete(sessionId);69
fs.rmSync(session.outputDir, { recursive: true, force: true });70
}63
}71
}64
}72
65
@@ -75,6 +68,77 @@ function refreshSession (session)75
session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;68
session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;76
}69
}77
70
71
function destroySession (sessionId)72
{73
const session = sessions.get(sessionId);74
if (!session) return false;75
76
sessions.delete(sessionId);77
78
if (session.idleTimer)79
{80
clearTimeout(session.idleTimer);81
session.idleTimer = null;82
}83
84
try85
{86
if (session.process) session.process.kill('SIGTERM');87
} catch88
{89
// Ignore process cleanup failures.90
}91
92
fs.rmSync(session.outputDir, { recursive: true, force: true });93
return true;94
}95
96
function touchSessionActivity (session)97
{98
refreshSession(session);99
session.lastActivityAt = Date.now();100
}101
102
function clearIdleStopTimer (session)103
{104
if (!session.idleTimer) return;105
clearTimeout(session.idleTimer);106
session.idleTimer = null;107
}108
109
function scheduleIdleStop (session)110
{111
clearIdleStopTimer(session);112
if (session.activeRequests > 0) return;113
114
session.idleTimer = setTimeout(() =>115
{116
const activeSession = sessions.get(session.id);117
if (!activeSession) return;118
if (activeSession.activeRequests > 0) return;119
if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS)120
{121
scheduleIdleStop(activeSession);122
return;123
}124
destroySession(activeSession.id);125
}, STREAM_IDLE_STOP_MS);126
}127
128
function startAssetRequest (session)129
{130
session.activeRequests += 1;131
touchSessionActivity(session);132
clearIdleStopTimer(session);133
}134
135
function finishAssetRequest (session)136
{137
if (session.activeRequests > 0) session.activeRequests -= 1;138
touchSessionActivity(session);139
if (session.activeRequests === 0) scheduleIdleStop(session);140
}141
78
function runCommand (command, args)142
function runCommand (command, args)79
{143
{80
return new Promise((resolve, reject) =>144
return new Promise((resolve, reject) =>@@ -476,6 +540,9 @@ async function createVideoStreamSession (sourcePath)476
subtitleTracks: [],540
subtitleTracks: [],477
subtitleSummary: { total: 0, converted: 0, skipped: 0 },541
subtitleSummary: { total: 0, converted: 0, skipped: 0 },478
readyPromise: null,542
readyPromise: null,543
activeRequests: 0,544
lastActivityAt: Date.now(),545
idleTimer: null,479
};546
};480
547
481
session.readyPromise = initialiseSession(session).catch((err) =>548
session.readyPromise = initialiseSession(session).catch((err) =>@@ -510,13 +577,13 @@ function contentTypeForAsset (assetPath)510
return 'application/octet-stream';577
return 'application/octet-stream';511
}578
}512
579
513
async function sendVideoStreamAsset (sessionId, assetPath, res)580
async function sendVideoStreamAsset (sessionId, assetPath, req, res)514
{581
{515
pruneExpiredSessions();582
pruneExpiredSessions();516
const session = sessions.get(sessionId);583
const session = sessions.get(sessionId);517
if (!session) throw makeHttpError(404, 'Video stream session not found.');584
if (!session) throw makeHttpError(404, 'Video stream session not found.');518
585
519
refreshSession(session);586
touchSessionActivity(session);520
await session.readyPromise;587
await session.readyPromise;521
588
522
const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');589
const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');@@ -530,12 +597,55 @@ async function sendVideoStreamAsset (sessionId, assetPath, res)530
await waitForFile(resolvedPath, session);597
await waitForFile(resolvedPath, session);531
res.set('Cache-Control', 'private, no-store');598
res.set('Cache-Control', 'private, no-store');532
res.type(contentTypeForAsset(resolvedPath));599
res.type(contentTypeForAsset(resolvedPath));533
res.sendFile(resolvedPath);600
601
startAssetRequest(session);602
603
let settled = false;604
const finish = () =>605
{606
if (settled) return;607
settled = true;608
finishAssetRequest(session);609
};610
611
req.on('aborted', finish);612
res.on('close', finish);613
res.on('finish', finish);614
res.on('error', finish);615
616
await new Promise((resolve, reject) =>617
{618
res.sendFile(resolvedPath, (err) =>619
{620
finish();621
if (!err)622
{623
resolve();624
return;625
}626
627
if (err.code === 'ECONNABORTED' || err.message === 'Request aborted')628
{629
resolve();630
return;631
}632
633
reject(err);634
});635
});636
}637
638
function releaseVideoStreamSession (sessionId)639
{640
pruneExpiredSessions();641
return destroySession(String(sessionId || ''));534
}642
}535
643
536
module.exports = {644
module.exports = {537
STREAM_ROOT_DIR,645
STREAM_ROOT_DIR,538
STREAM_SESSION_TTL_MS,646
STREAM_SESSION_TTL_MS,647
STREAM_IDLE_STOP_MS,539
createVideoStreamSession,648
createVideoStreamSession,540
sendVideoStreamAsset,649
sendVideoStreamAsset,650
releaseVideoStreamSession,541
};651
};@@ -16,6 +16,7 @@ let mockFolderIconFile = null;
16
16
let lastFolderIconAssignment = undefined;
17
17
let mockVideoStreamSession = null;
18
18
let mockVideoStreamAsset = null;
19
let releasedVideoStreamSessionId = null;
19
20
20
21
jest.mock('../server/db', () =>
21
22
{
@@ -91,15 +92,20 @@ jest.mock('../server/video-stream', () => ({
91
92
if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
92
93
return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
93
94
}),
94
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, res) =>
95
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
95
96
{
96
97
if (typeof mockVideoStreamAsset === 'function')
97
98
{
98
await mockVideoStreamAsset(sessionId, assetPath, res);
99
await mockVideoStreamAsset(sessionId, assetPath, req, res);
99
100
return;
100
101
}
101
102
res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
102
103
}),
104
releaseVideoStreamSession: jest.fn((sessionId) =>
105
{
106
releasedVideoStreamSessionId = String(sessionId || '');
107
return true;
108
}),
103
109
}));
104
110
105
111
const filesRoutes = require('../server/routes/files');
@@ -146,6 +152,7 @@ beforeEach(() =>
146
152
lastFolderIconAssignment = undefined;
147
153
mockVideoStreamSession = null;
148
154
mockVideoStreamAsset = null;
155
releasedVideoStreamSessionId = null;
149
156
const db = getDb();
150
157
db.prepare('DELETE FROM file_meta').run([]);
151
158
db.prepare('DELETE FROM users').run([]);
@@ -718,7 +725,7 @@ describe('video streaming routes', () =>
718
725
719
726
test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
720
727
{
721
mockVideoStreamAsset = async (_sessionId, _assetPath, res) =>
728
mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
722
729
{
723
730
res.type('text/vtt').send('WEBVTT\n');
724
731
};
@@ -730,6 +737,15 @@ describe('video streaming routes', () =>
730
737
expect(body.toString()).toBe('WEBVTT\n');
731
738
});
732
739
740
test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
741
{
742
const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
743
744
expect(status).toBe(200);
745
expect(body).toEqual({ ok: true });
746
expect(releasedVideoStreamSessionId).toBe('sess-123');
747
});
748
733
749
test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
734
750
{
735
751
const filePath = path.join(rootDir, 'clip.mkv');
@@ -16,6 +16,7 @@ let mockFolderIconFile = null;16
let lastFolderIconAssignment = undefined;16
let lastFolderIconAssignment = undefined;17
let mockVideoStreamSession = null;17
let mockVideoStreamSession = null;18
let mockVideoStreamAsset = null;18
let mockVideoStreamAsset = null;19
let releasedVideoStreamSessionId = null;19
20
20
jest.mock('../server/db', () =>21
jest.mock('../server/db', () =>21
{22
{@@ -91,15 +92,20 @@ jest.mock('../server/video-stream', () => ({91
if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;92
if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;92
return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };93
return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };93
}),94
}),94
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, res) =>95
sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>95
{96
{96
if (typeof mockVideoStreamAsset === 'function')97
if (typeof mockVideoStreamAsset === 'function')97
{98
{98
await mockVideoStreamAsset(sessionId, assetPath, res);99
await mockVideoStreamAsset(sessionId, assetPath, req, res);99
return;100
return;100
}101
}101
res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');102
res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');102
}),103
}),104
releaseVideoStreamSession: jest.fn((sessionId) =>105
{106
releasedVideoStreamSessionId = String(sessionId || '');107
return true;108
}),103
}));109
}));104
110
105
const filesRoutes = require('../server/routes/files');111
const filesRoutes = require('../server/routes/files');@@ -146,6 +152,7 @@ beforeEach(() =>146
lastFolderIconAssignment = undefined;152
lastFolderIconAssignment = undefined;147
mockVideoStreamSession = null;153
mockVideoStreamSession = null;148
mockVideoStreamAsset = null;154
mockVideoStreamAsset = null;155
releasedVideoStreamSessionId = null;149
const db = getDb();156
const db = getDb();150
db.prepare('DELETE FROM file_meta').run([]);157
db.prepare('DELETE FROM file_meta').run([]);151
db.prepare('DELETE FROM users').run([]);158
db.prepare('DELETE FROM users').run([]);@@ -718,7 +725,7 @@ describe('video streaming routes', () =>718
725
719
test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>726
test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>720
{727
{721
mockVideoStreamAsset = async (_sessionId, _assetPath, res) =>728
mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>722
{729
{723
res.type('text/vtt').send('WEBVTT\n');730
res.type('text/vtt').send('WEBVTT\n');724
};731
};@@ -730,6 +737,15 @@ describe('video streaming routes', () =>730
expect(body.toString()).toBe('WEBVTT\n');737
expect(body.toString()).toBe('WEBVTT\n');731
});738
});732
739
740
test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>741
{742
const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');743
744
expect(status).toBe(200);745
expect(body).toEqual({ ok: true });746
expect(releasedVideoStreamSessionId).toBe('sess-123');747
});748
733
test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>749
test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>734
{750
{735
const filePath = path.join(rootDir, 'clip.mkv');751
const filePath = path.join(rootDir, 'clip.mkv');@@ -28,6 +28,7 @@ describe('page load smoke test', () =>
28
28
let adminConfigFixture;
29
29
let downloadFixture;
30
30
let videoStreamFixture;
31
let releasedVideoStreamSessions;
31
32
let setupNeededFixture;
32
33
const openDoms = [];
33
34
@@ -56,6 +57,7 @@ describe('page load smoke test', () =>
56
57
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
57
58
downloadFixture = {};
58
59
videoStreamFixture = {};
60
releasedVideoStreamSessions = [];
59
61
setupNeededFixture = false;
60
62
});
61
63
@@ -132,6 +134,11 @@ describe('page load smoke test', () =>
132
134
}
133
135
res.json(payload);
134
136
});
137
app.delete('/api/files/video-stream/:sessionId', (req, res) =>
138
{
139
releasedVideoStreamSessions.push(String(req.params.sessionId || ''));
140
res.json({ ok: true });
141
});
135
142
app.post('/api/files/watch-progress', (req, res) =>
136
143
{
137
144
res.json({ ok: true, updated: true });
@@ -831,6 +838,40 @@ describe('page load smoke test', () =>
831
838
dom.window.close();
832
839
});
833
840
841
test('video preview releases the backend stream session when closed', async () =>
842
{
843
listFixture['/data'] = [
844
{
845
name: 'clip.mkv',
846
path: '/data/clip.mkv',
847
isDir: false,
848
size: 64,
849
mtime: Date.now(),
850
},
851
];
852
videoStreamFixture['/data/clip.mkv'] = {
853
sessionId: 'video-session',
854
playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
855
subtitleTracks: [],
856
subtitleSummary: { total: 0, converted: 0, skipped: 0 },
857
};
858
859
const { dom, runtimeErrors } = await bootClient();
860
expect(runtimeErrors).toEqual([]);
861
862
await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
863
864
const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
865
tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
866
await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
867
868
const closeBtn = dom.window.document.querySelector('.preview-expand-close');
869
closeBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
870
await waitFor(dom, () => releasedVideoStreamSessions.includes('video-session'));
871
872
dom.window.close();
873
});
874
834
875
test('video preview restores per-user saved volume preference', async () =>
835
876
{
836
877
listFixture['/data'] = [
@@ -28,6 +28,7 @@ describe('page load smoke test', () =>28
let adminConfigFixture;
28
let adminConfigFixture;
29
let downloadFixture;
29
let downloadFixture;
30
let videoStreamFixture;
30
let videoStreamFixture;
31
let releasedVideoStreamSessions;
31
let setupNeededFixture;
32
let setupNeededFixture;
32
const openDoms = [];
33
const openDoms = [];
33
34
@@ -56,6 +57,7 @@ describe('page load smoke test', () =>56
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
57
adminConfigFixture = { port: 3000, paths: ['/data'], effectivePaths: ['/data'] };
57
downloadFixture = {};
58
downloadFixture = {};
58
videoStreamFixture = {};
59
videoStreamFixture = {};
60
releasedVideoStreamSessions = [];
59
setupNeededFixture = false;
61
setupNeededFixture = false;
60
});
62
});
61
63
@@ -132,6 +134,11 @@ describe('page load smoke test', () =>132
}
134
}
133
res.json(payload);
135
res.json(payload);
134
});
136
});
137
app.delete('/api/files/video-stream/:sessionId', (req, res) =>
138
{
139
releasedVideoStreamSessions.push(String(req.params.sessionId || ''));
140
res.json({ ok: true });
141
});
135
app.post('/api/files/watch-progress', (req, res) =>
142
app.post('/api/files/watch-progress', (req, res) =>
136
{
143
{
137
res.json({ ok: true, updated: true });
144
res.json({ ok: true, updated: true });
@@ -831,6 +838,40 @@ describe('page load smoke test', () =>831
dom.window.close();
838
dom.window.close();
832
});
839
});
833
840
841
test('video preview releases the backend stream session when closed', async () =>
842
{
843
listFixture['/data'] = [
844
{
845
name: 'clip.mkv',
846
path: '/data/clip.mkv',
847
isDir: false,
848
size: 64,
849
mtime: Date.now(),
850
},
851
];
852
videoStreamFixture['/data/clip.mkv'] = {
853
sessionId: 'video-session',
854
playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
855
subtitleTracks: [],
856
subtitleSummary: { total: 0, converted: 0, skipped: 0 },
857
};
858
859
const { dom, runtimeErrors } = await bootClient();
860
expect(runtimeErrors).toEqual([]);
861
862
await waitFor(dom, () => !!dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]'));
863
864
const tile = dom.window.document.querySelector('.file-item[data-path="/data/clip.mkv"]');
865
tile.dispatchEvent(new dom.window.MouseEvent('dblclick', { bubbles: true }));
866
await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
867
868
const closeBtn = dom.window.document.querySelector('.preview-expand-close');
869
closeBtn.dispatchEvent(new dom.window.MouseEvent('click', { bubbles: true }));
870
await waitFor(dom, () => releasedVideoStreamSessions.includes('video-session'));
871
872
dom.window.close();
873
});
874
834
test('video preview restores per-user saved volume preference', async () =>
875
test('video preview restores per-user saved volume preference', async () =>
835
{
876
{
836
listFixture['/data'] = [
877
listFixture['/data'] = [