Stop video stream sessions after disconnect or explicit release
@@ -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');