BlueGit

timfa filemanager

fix jumping partially

timfa Tim Falken · pushed by timfa

Authored 2026-05-08 · 6 months ago

Hash
ec1bfab73a76a56ffcca3f74dcab41ad1f0f7451
Parent
1a987d8b
10 files changed +360 −37
.github/technical-reference.md +3 −3
@@ -58,7 +58,7 @@
58 58 - removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
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 - 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, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
62 62 - POST /api/files/watch-progress - Records per-user watch status (`partway` >=30%, `fully` >=70%) for sidebar "Watched by" display.
63 63
64 64 ## server/routes/share.js
@@ -66,13 +66,13 @@
66 66 - GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
67 67 - GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
68 68 - GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
69 - GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
69 - GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
70 70 - buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
71 71 - pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
72 72 - ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
73 73
74 74 ## server/video-stream.js
75 - createVideoStreamSession(sourcePath) - Probes the input, 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 subtitleTracks plus subtitleSummary {total, converted, skipped}.
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 76 - sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
77 77 - STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
78 78 - STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
@@ -58,7 +58,7 @@
58- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
58- removePathRecursive(targetPath) - Deletes existing file or directory destination to support overwrite moves.
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, durationSeconds, 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- POST /api/files/watch-progress - Records per-user watch status (`partway` >=30%, `fully` >=70%) for sidebar "Watched by" display.
63
63
64## server/routes/share.js
64## server/routes/share.js
@@ -66,13 +66,13 @@
66- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
66- GET /api/share/info/:token - Public. Returns {name, isDir, expiresAt} for a valid non-expired token; 410 when expired, 404 when unknown.
67- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
67- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
68- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
68- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
69- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
69- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, and subtitleSummary ({total, converted, skipped}).
70- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
70- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
71- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
71- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
72- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
72- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
73
73
74## server/video-stream.js
74## server/video-stream.js
75- createVideoStreamSession(sourcePath) - Probes the input, 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 subtitleTracks plus subtitleSummary {total, converted, skipped}.
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- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
76- sendVideoStreamAsset(sessionId, assetPath, res) - Serves HLS playlists, segments, and extracted subtitle files from an active short-lived stream session.
77- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
77- 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.
78- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
public/app.js +86 −2
@@ -264,12 +264,89 @@ function captureUserVideoTextTrackPrefs ()
264 264 }
265 265 }
266 266
267 function ensureVideoPlaybackUi (player)
267 function normaliseVideoDuration (player, durationSeconds)
268 {
269 const duration = Number(durationSeconds);
270 if (!player || !Number.isFinite(duration) || duration <= 0) return;
271
272 let originalDuration = null;
273 let durationWasChanged = false;
274 try
275 {
276 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
277 installDurationFallback(player, originalDuration, duration);
278 if (player.__filemanagerDurationApplied) return;
279
280 const current = originalDuration ? Number(originalDuration()) : NaN;
281 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
282 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
283 if (withinTolerance)
284 {
285 player.__filemanagerDurationApplied = true;
286 return;
287 }
288
289 if (originalDuration)
290 {
291 durationWasChanged = true;
292 originalDuration(duration);
293 }
294 } catch
295 {
296 // Ignore players that do not support setting duration.
297 }
298
299 try
300 {
301 const updated = originalDuration ? Number(originalDuration()) : NaN;
302 if (Number.isFinite(updated) && updated >= duration * 0.95)
303 {
304 player.__filemanagerDurationApplied = true;
305 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
306 return;
307 }
308
309 player.__filemanagerDurationApplied = true;
310 if (typeof player.trigger === 'function') player.trigger('durationchange');
311 } catch
312 {
313 // Ignore duration fallback failures.
314 }
315 }
316
317 function installDurationFallback (player, originalDuration, duration)
318 {
319 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
320
321 player.__filemanagerDurationFallback = true;
322 player.duration = function durationWithFallback (...args)
323 {
324 if (args.length) return originalDuration(...args);
325 const current = Number(originalDuration());
326 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
327 };
328 }
329
330 function formatDurationForDebug (seconds)
331 {
332 const value = Number(seconds);
333 if (!Number.isFinite(value) || value < 0) return 'unknown';
334
335 const totalSeconds = Math.floor(value);
336 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
337 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
338 const ss = String(totalSeconds % 60).padStart(2, '0');
339 return `${hh}:${mm}:${ss}`;
340 }
341
342 function ensureVideoPlaybackUi (player, durationSeconds)
268 343 {
269 344 if (!player || typeof player.on !== 'function') return;
270 345
271 346 const forceVodUi = () =>
272 347 {
348 normaliseVideoDuration(player, durationSeconds);
349
273 350 try
274 351 {
275 352 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
@@ -305,6 +382,7 @@ function ensureVideoPlaybackUi (player)
305 382 player.ready(forceVodUi);
306 383 player.on('loadedmetadata', forceVodUi);
307 384 player.on('durationchange', forceVodUi);
385 player.on('loadedplaylist', forceVodUi);
308 386 }
309 387
310 388 async function reportWatchProgress (filePath, progress)
@@ -2334,6 +2412,12 @@ async function renderStreamedVideoPreview (item, targetEl)
2334 2412 fill: true,
2335 2413 responsive: false,
2336 2414 preload: 'auto',
2415 controlBar: {
2416 currentTimeDisplay: true,
2417 timeDivider: true,
2418 durationDisplay: true,
2419 remainingTimeDisplay: false,
2420 },
2337 2421 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2338 2422 tracks: (session.subtitleTracks || []).map((track) => ({
2339 2423 kind: 'subtitles',
@@ -2344,7 +2428,7 @@ async function renderStreamedVideoPreview (item, targetEl)
2344 2428 })),
2345 2429 });
2346 2430
2347 ensureVideoPlaybackUi(player);
2431 ensureVideoPlaybackUi(player, session.durationSeconds);
2348 2432
2349 2433 let sentPartway = false;
2350 2434 let sentFully = false;
@@ -264,12 +264,89 @@ function captureUserVideoTextTrackPrefs ()
264 }
264 }
265}
265}
266
266
267function ensureVideoPlaybackUi (player)
267function normaliseVideoDuration (player, durationSeconds)
268{
269 const duration = Number(durationSeconds);
270 if (!player || !Number.isFinite(duration) || duration <= 0) return;
271
272 let originalDuration = null;
273 let durationWasChanged = false;
274 try
275 {
276 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
277 installDurationFallback(player, originalDuration, duration);
278 if (player.__filemanagerDurationApplied) return;
279
280 const current = originalDuration ? Number(originalDuration()) : NaN;
281 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
282 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
283 if (withinTolerance)
284 {
285 player.__filemanagerDurationApplied = true;
286 return;
287 }
288
289 if (originalDuration)
290 {
291 durationWasChanged = true;
292 originalDuration(duration);
293 }
294 } catch
295 {
296 // Ignore players that do not support setting duration.
297 }
298
299 try
300 {
301 const updated = originalDuration ? Number(originalDuration()) : NaN;
302 if (Number.isFinite(updated) && updated >= duration * 0.95)
303 {
304 player.__filemanagerDurationApplied = true;
305 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
306 return;
307 }
308
309 player.__filemanagerDurationApplied = true;
310 if (typeof player.trigger === 'function') player.trigger('durationchange');
311 } catch
312 {
313 // Ignore duration fallback failures.
314 }
315}
316
317function installDurationFallback (player, originalDuration, duration)
318{
319 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
320
321 player.__filemanagerDurationFallback = true;
322 player.duration = function durationWithFallback (...args)
323 {
324 if (args.length) return originalDuration(...args);
325 const current = Number(originalDuration());
326 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
327 };
328}
329
330function formatDurationForDebug (seconds)
331{
332 const value = Number(seconds);
333 if (!Number.isFinite(value) || value < 0) return 'unknown';
334
335 const totalSeconds = Math.floor(value);
336 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
337 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
338 const ss = String(totalSeconds % 60).padStart(2, '0');
339 return `${hh}:${mm}:${ss}`;
340}
341
342function ensureVideoPlaybackUi (player, durationSeconds)
268{
343{
269 if (!player || typeof player.on !== 'function') return;
344 if (!player || typeof player.on !== 'function') return;
270
345
271 const forceVodUi = () =>
346 const forceVodUi = () =>
272 {
347 {
348 normaliseVideoDuration(player, durationSeconds);
349
273 try
350 try
274 {
351 {
275 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
352 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
@@ -305,6 +382,7 @@ function ensureVideoPlaybackUi (player)
305 player.ready(forceVodUi);
382 player.ready(forceVodUi);
306 player.on('loadedmetadata', forceVodUi);
383 player.on('loadedmetadata', forceVodUi);
307 player.on('durationchange', forceVodUi);
384 player.on('durationchange', forceVodUi);
385 player.on('loadedplaylist', forceVodUi);
308}
386}
309
387
310async function reportWatchProgress (filePath, progress)
388async function reportWatchProgress (filePath, progress)
@@ -2334,6 +2412,12 @@ async function renderStreamedVideoPreview (item, targetEl)
2334 fill: true,
2412 fill: true,
2335 responsive: false,
2413 responsive: false,
2336 preload: 'auto',
2414 preload: 'auto',
2415 controlBar: {
2416 currentTimeDisplay: true,
2417 timeDivider: true,
2418 durationDisplay: true,
2419 remainingTimeDisplay: false,
2420 },
2337 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2421 sources: [{ src: session.playlistUrl, type: 'application/x-mpegURL' }],
2338 tracks: (session.subtitleTracks || []).map((track) => ({
2422 tracks: (session.subtitleTracks || []).map((track) => ({
2339 kind: 'subtitles',
2423 kind: 'subtitles',
@@ -2344,7 +2428,7 @@ async function renderStreamedVideoPreview (item, targetEl)
2344 })),
2428 })),
2345 });
2429 });
2346
2430
2347 ensureVideoPlaybackUi(player);
2431 ensureVideoPlaybackUi(player, session.durationSeconds);
2348
2432
2349 let sentPartway = false;
2433 let sentPartway = false;
2350 let sentFully = false;
2434 let sentFully = false;
public/share.html +120 −1
@@ -283,6 +283,118 @@
283 283 }
284 284
285 285 // ── Preview ──────────────────────────────────────────────────────────────
286 function normaliseVideoDuration (player, durationSeconds)
287 {
288 const duration = Number(durationSeconds);
289 if (!player || !Number.isFinite(duration) || duration <= 0) return;
290
291 let originalDuration = null;
292 let durationWasChanged = false;
293 try
294 {
295 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
296 installDurationFallback(player, originalDuration, duration);
297 if (player.__filemanagerDurationApplied) return;
298
299 const current = originalDuration ? Number(originalDuration()) : NaN;
300 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
301 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
302 if (withinTolerance)
303 {
304 player.__filemanagerDurationApplied = true;
305 return;
306 }
307
308 if (originalDuration)
309 {
310 durationWasChanged = true;
311 originalDuration(duration);
312 }
313 } catch
314 {
315 // Ignore players that do not support setting duration.
316 }
317
318 try
319 {
320 const updated = originalDuration ? Number(originalDuration()) : NaN;
321 if (Number.isFinite(updated) && updated >= duration * 0.95)
322 {
323 player.__filemanagerDurationApplied = true;
324 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
325 return;
326 }
327
328 player.__filemanagerDurationApplied = true;
329 if (typeof player.trigger === 'function') player.trigger('durationchange');
330 } catch
331 {
332 // Ignore duration fallback failures.
333 }
334 }
335
336 function installDurationFallback (player, originalDuration, duration)
337 {
338 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
339
340 player.__filemanagerDurationFallback = true;
341 player.duration = function durationWithFallback (...args)
342 {
343 if (args.length) return originalDuration(...args);
344 const current = Number(originalDuration());
345 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
346 };
347 }
348
349 function formatDurationForDebug (seconds)
350 {
351 const value = Number(seconds);
352 if (!Number.isFinite(value) || value < 0) return 'unknown';
353
354 const totalSeconds = Math.floor(value);
355 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
356 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
357 const ss = String(totalSeconds % 60).padStart(2, '0');
358 return `${hh}:${mm}:${ss}`;
359 }
360
361 function ensureVideoPlaybackUi (player, durationSeconds)
362 {
363 if (!player || typeof player.on !== 'function') return;
364
365 const forceVodUi = () =>
366 {
367 normaliseVideoDuration(player, durationSeconds);
368
369 try
370 {
371 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
372 {
373 player.liveTracker.stopTracking();
374 }
375 } catch
376 {
377 // Ignore live tracker availability issues.
378 }
379
380 try
381 {
382 if (typeof player.removeClass === 'function')
383 {
384 player.removeClass('vjs-live');
385 }
386 } catch
387 {
388 // Ignore class update failures.
389 }
390 };
391
392 player.ready(forceVodUi);
393 player.on('loadedmetadata', forceVodUi);
394 player.on('durationchange', forceVodUi);
395 player.on('loadedplaylist', forceVodUi);
396 }
397
286 398 function tryPreview (name, isDir)
287 399 {
288 400 if (isDir) return; // no preview for folders
@@ -330,6 +442,12 @@
330 442 fluid: true,
331 443 responsive: true,
332 444 preload: 'auto',
445 controlBar: {
446 currentTimeDisplay: true,
447 timeDivider: true,
448 durationDisplay: true,
449 remainingTimeDisplay: false,
450 },
333 451 sources: [{ src: data.playlistUrl, type: 'application/x-mpegURL' }],
334 452 tracks: (data.subtitleTracks || []).map(track => ({
335 453 kind: 'subtitles',
@@ -339,6 +457,7 @@
339 457 default: !!track.default,
340 458 })),
341 459 });
460 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
342 461
343 462 wrap.style.display = '';
344 463 })
@@ -450,4 +569,4 @@
450 569 <script src="/vendor/video.js/video.min.js"></script>
451 570 </body>
452 571
453 </html>
572 </html>
@@ -283,6 +283,118 @@
283 }
283 }
284
284
285 // ── Preview ──────────────────────────────────────────────────────────────
285 // ── Preview ──────────────────────────────────────────────────────────────
286 function normaliseVideoDuration (player, durationSeconds)
287 {
288 const duration = Number(durationSeconds);
289 if (!player || !Number.isFinite(duration) || duration <= 0) return;
290
291 let originalDuration = null;
292 let durationWasChanged = false;
293 try
294 {
295 originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
296 installDurationFallback(player, originalDuration, duration);
297 if (player.__filemanagerDurationApplied) return;
298
299 const current = originalDuration ? Number(originalDuration()) : NaN;
300 const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
301 console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
302 if (withinTolerance)
303 {
304 player.__filemanagerDurationApplied = true;
305 return;
306 }
307
308 if (originalDuration)
309 {
310 durationWasChanged = true;
311 originalDuration(duration);
312 }
313 } catch
314 {
315 // Ignore players that do not support setting duration.
316 }
317
318 try
319 {
320 const updated = originalDuration ? Number(originalDuration()) : NaN;
321 if (Number.isFinite(updated) && updated >= duration * 0.95)
322 {
323 player.__filemanagerDurationApplied = true;
324 if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
325 return;
326 }
327
328 player.__filemanagerDurationApplied = true;
329 if (typeof player.trigger === 'function') player.trigger('durationchange');
330 } catch
331 {
332 // Ignore duration fallback failures.
333 }
334 }
335
336 function installDurationFallback (player, originalDuration, duration)
337 {
338 if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
339
340 player.__filemanagerDurationFallback = true;
341 player.duration = function durationWithFallback (...args)
342 {
343 if (args.length) return originalDuration(...args);
344 const current = Number(originalDuration());
345 return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
346 };
347 }
348
349 function formatDurationForDebug (seconds)
350 {
351 const value = Number(seconds);
352 if (!Number.isFinite(value) || value < 0) return 'unknown';
353
354 const totalSeconds = Math.floor(value);
355 const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
356 const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
357 const ss = String(totalSeconds % 60).padStart(2, '0');
358 return `${hh}:${mm}:${ss}`;
359 }
360
361 function ensureVideoPlaybackUi (player, durationSeconds)
362 {
363 if (!player || typeof player.on !== 'function') return;
364
365 const forceVodUi = () =>
366 {
367 normaliseVideoDuration(player, durationSeconds);
368
369 try
370 {
371 if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
372 {
373 player.liveTracker.stopTracking();
374 }
375 } catch
376 {
377 // Ignore live tracker availability issues.
378 }
379
380 try
381 {
382 if (typeof player.removeClass === 'function')
383 {
384 player.removeClass('vjs-live');
385 }
386 } catch
387 {
388 // Ignore class update failures.
389 }
390 };
391
392 player.ready(forceVodUi);
393 player.on('loadedmetadata', forceVodUi);
394 player.on('durationchange', forceVodUi);
395 player.on('loadedplaylist', forceVodUi);
396 }
397
286 function tryPreview (name, isDir)
398 function tryPreview (name, isDir)
287 {
399 {
288 if (isDir) return; // no preview for folders
400 if (isDir) return; // no preview for folders
@@ -330,6 +442,12 @@
330 fluid: true,
442 fluid: true,
331 responsive: true,
443 responsive: true,
332 preload: 'auto',
444 preload: 'auto',
445 controlBar: {
446 currentTimeDisplay: true,
447 timeDivider: true,
448 durationDisplay: true,
449 remainingTimeDisplay: false,
450 },
333 sources: [{ src: data.playlistUrl, type: 'application/x-mpegURL' }],
451 sources: [{ src: data.playlistUrl, type: 'application/x-mpegURL' }],
334 tracks: (data.subtitleTracks || []).map(track => ({
452 tracks: (data.subtitleTracks || []).map(track => ({
335 kind: 'subtitles',
453 kind: 'subtitles',
@@ -339,6 +457,7 @@
339 default: !!track.default,
457 default: !!track.default,
340 })),
458 })),
341 });
459 });
460 ensureVideoPlaybackUi(shareVideoPlayer, data.durationSeconds);
342
461
343 wrap.style.display = '';
462 wrap.style.display = '';
344 })
463 })
@@ -450,4 +569,4 @@
450 <script src="/vendor/video.js/video.min.js"></script>
569 <script src="/vendor/video.js/video.min.js"></script>
451</body>
570</body>
452
571
453</html>
572</html>
server/routes/files.js +1 −0
@@ -739,6 +739,7 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>
739 739 res.json({
740 740 sessionId: session.sessionId,
741 741 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
742 durationSeconds: session.durationSeconds || null,
742 743 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
743 744 subtitleTracks: session.subtitleTracks.map((track) => ({
744 745 label: track.label,
@@ -739,6 +739,7 @@ router.post('/video-stream', requireAuth, async (req, res, next) =>
739 res.json({
739 res.json({
740 sessionId: session.sessionId,
740 sessionId: session.sessionId,
741 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
741 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
742 durationSeconds: session.durationSeconds || null,
742 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
743 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
743 subtitleTracks: session.subtitleTracks.map((track) => ({
744 subtitleTracks: session.subtitleTracks.map((track) => ({
744 label: track.label,
745 label: track.label,
server/routes/share.js +1 −0
@@ -278,6 +278,7 @@ router.get('/video-stream/:token', async (req, res, next) =>
278 278 res.json({
279 279 sessionId: session.sessionId,
280 280 playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`,
281 durationSeconds: session.durationSeconds || null,
281 282 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
282 283 subtitleTracks: session.subtitleTracks.map((track) => ({
283 284 label: track.label,
@@ -278,6 +278,7 @@ router.get('/video-stream/:token', async (req, res, next) =>
278 res.json({
278 res.json({
279 sessionId: session.sessionId,
279 sessionId: session.sessionId,
280 playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`,
280 playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`,
281 durationSeconds: session.durationSeconds || null,
281 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
282 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
282 subtitleTracks: session.subtitleTracks.map((track) => ({
283 subtitleTracks: session.subtitleTracks.map((track) => ({
283 label: track.label,
284 label: track.label,
server/video-stream.js +52 −1
@@ -152,12 +152,61 @@ async function probeInput (sourcePath)
152 152
153 153 return {
154 154 raw: payload,
155 durationSeconds: inputDurationSeconds(payload, streams),
155 156 video: streams.filter((stream) => stream.codecType === 'video'),
156 157 audio: streams.filter((stream) => stream.codecType === 'audio'),
157 158 subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
158 159 };
159 160 }
160 161
162 function parsePositiveNumber (value)
163 {
164 const number = Number(value);
165 return Number.isFinite(number) && number > 0 ? number : null;
166 }
167
168 function parseDurationTagSeconds (value)
169 {
170 const raw = String(value || '').trim();
171 if (!raw) return null;
172
173 const numeric = parsePositiveNumber(raw);
174 if (numeric) return numeric;
175
176 const match = raw.match(/^(\d+):([0-5]?\d):([0-5]?\d(?:\.\d+)?)$/);
177 if (!match) return null;
178
179 const hours = Number(match[1]);
180 const minutes = Number(match[2]);
181 const seconds = Number(match[3]);
182 if (!Number.isFinite(hours) || !Number.isFinite(minutes) || !Number.isFinite(seconds)) return null;
183 return hours * 3600 + minutes * 60 + seconds;
184 }
185
186 function inputDurationSeconds (payload, streams)
187 {
188 const formatDuration = parsePositiveNumber(payload && payload.format && payload.format.duration);
189 if (formatDuration) return formatDuration;
190
191 for (const stream of streams)
192 {
193 const duration = parsePositiveNumber(stream.duration);
194 if (duration) return duration;
195 }
196
197 const formatTags = payload && payload.format && payload.format.tags;
198 const formatTagDuration = formatTags && parseDurationTagSeconds(formatTags.duration || formatTags.DURATION);
199 if (formatTagDuration) return formatTagDuration;
200
201 for (const stream of streams)
202 {
203 const tagDuration = parseDurationTagSeconds(stream.tags.duration || stream.tags.DURATION);
204 if (tagDuration) return tagDuration;
205 }
206
207 return null;
208 }
209
161 210 function sanitiseTrackValue (value, fallback)
162 211 {
163 212 const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
@@ -404,6 +453,7 @@ async function initialiseSession (session)
404 453 skipped: subtitleResult.skippedCount,
405 454 };
406 455 startHlsTranscode(session, streamInfo);
456 session.durationSeconds = streamInfo.durationSeconds;
407 457 await waitForStreamStart(session);
408 458 }
409 459
@@ -439,6 +489,7 @@ async function createVideoStreamSession (sourcePath)
439 489
440 490 return {
441 491 sessionId,
492 durationSeconds: session.durationSeconds,
442 493 subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
443 494 subtitleSummary: {
444 495 total: Number(session.subtitleSummary.total || 0),
@@ -487,4 +538,4 @@ module.exports = {
487 538 STREAM_SESSION_TTL_MS,
488 539 createVideoStreamSession,
489 540 sendVideoStreamAsset,
490 };
541 };
@@ -152,12 +152,61 @@ async function probeInput (sourcePath)
152
152
153 return {
153 return {
154 raw: payload,
154 raw: payload,
155 durationSeconds: inputDurationSeconds(payload, streams),
155 video: streams.filter((stream) => stream.codecType === 'video'),
156 video: streams.filter((stream) => stream.codecType === 'video'),
156 audio: streams.filter((stream) => stream.codecType === 'audio'),
157 audio: streams.filter((stream) => stream.codecType === 'audio'),
157 subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
158 subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
158 };
159 };
159}
160}
160
161
162function parsePositiveNumber (value)
163{
164 const number = Number(value);
165 return Number.isFinite(number) && number > 0 ? number : null;
166}
167
168function parseDurationTagSeconds (value)
169{
170 const raw = String(value || '').trim();
171 if (!raw) return null;
172
173 const numeric = parsePositiveNumber(raw);
174 if (numeric) return numeric;
175
176 const match = raw.match(/^(\d+):([0-5]?\d):([0-5]?\d(?:\.\d+)?)$/);
177 if (!match) return null;
178
179 const hours = Number(match[1]);
180 const minutes = Number(match[2]);
181 const seconds = Number(match[3]);
182 if (!Number.isFinite(hours) || !Number.isFinite(minutes) || !Number.isFinite(seconds)) return null;
183 return hours * 3600 + minutes * 60 + seconds;
184}
185
186function inputDurationSeconds (payload, streams)
187{
188 const formatDuration = parsePositiveNumber(payload && payload.format && payload.format.duration);
189 if (formatDuration) return formatDuration;
190
191 for (const stream of streams)
192 {
193 const duration = parsePositiveNumber(stream.duration);
194 if (duration) return duration;
195 }
196
197 const formatTags = payload && payload.format && payload.format.tags;
198 const formatTagDuration = formatTags && parseDurationTagSeconds(formatTags.duration || formatTags.DURATION);
199 if (formatTagDuration) return formatTagDuration;
200
201 for (const stream of streams)
202 {
203 const tagDuration = parseDurationTagSeconds(stream.tags.duration || stream.tags.DURATION);
204 if (tagDuration) return tagDuration;
205 }
206
207 return null;
208}
209
161function sanitiseTrackValue (value, fallback)
210function sanitiseTrackValue (value, fallback)
162{
211{
163 const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
212 const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
@@ -404,6 +453,7 @@ async function initialiseSession (session)
404 skipped: subtitleResult.skippedCount,
453 skipped: subtitleResult.skippedCount,
405 };
454 };
406 startHlsTranscode(session, streamInfo);
455 startHlsTranscode(session, streamInfo);
456 session.durationSeconds = streamInfo.durationSeconds;
407 await waitForStreamStart(session);
457 await waitForStreamStart(session);
408}
458}
409
459
@@ -439,6 +489,7 @@ async function createVideoStreamSession (sourcePath)
439
489
440 return {
490 return {
441 sessionId,
491 sessionId,
492 durationSeconds: session.durationSeconds,
442 subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
493 subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
443 subtitleSummary: {
494 subtitleSummary: {
444 total: Number(session.subtitleSummary.total || 0),
495 total: Number(session.subtitleSummary.total || 0),
@@ -487,4 +538,4 @@ module.exports = {
487 STREAM_SESSION_TTL_MS,
538 STREAM_SESSION_TTL_MS,
488 createVideoStreamSession,
539 createVideoStreamSession,
489 sendVideoStreamAsset,
540 sendVideoStreamAsset,
490};
541};
tests/files.routes.test.js +2 −0
@@ -696,6 +696,7 @@ describe('video streaming routes', () =>
696 696 fs.writeFileSync(filePath, 'video');
697 697 mockVideoStreamSession = {
698 698 sessionId: 'sess-123',
699 durationSeconds: 42.25,
699 700 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
700 701 };
701 702
@@ -703,6 +704,7 @@ describe('video streaming routes', () =>
703 704
704 705 expect(status).toBe(200);
705 706 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
707 expect(body.durationSeconds).toBe(42.25);
706 708 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
707 709 expect(body.subtitleTracks).toEqual([
708 710 {
@@ -696,6 +696,7 @@ describe('video streaming routes', () =>
696 fs.writeFileSync(filePath, 'video');
696 fs.writeFileSync(filePath, 'video');
697 mockVideoStreamSession = {
697 mockVideoStreamSession = {
698 sessionId: 'sess-123',
698 sessionId: 'sess-123',
699 durationSeconds: 42.25,
699 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
700 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
700 };
701 };
701
702
@@ -703,6 +704,7 @@ describe('video streaming routes', () =>
703
704
704 expect(status).toBe(200);
705 expect(status).toBe(200);
705 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
706 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
707 expect(body.durationSeconds).toBe(42.25);
706 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
708 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
707 expect(body.subtitleTracks).toEqual([
709 expect(body.subtitleTracks).toEqual([
708 {
710 {
tests/page.load.test.js +47 −29
@@ -198,30 +198,40 @@ describe('page load smoke test', () =>
198 198 let blobCounter = 0;
199 199 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
200 200 window.URL.revokeObjectURL = () => { };
201 window.__lastVideoJsOptions = null;
202 window.__lastVideoJsVolumeSet = null;
203 window.videojs = (element, options) =>
204 {
205 window.__lastVideoJsOptions = options;
206 let volumeValue = 1;
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 {
201 window.__lastVideoJsOptions = null;
202 window.__lastVideoJsVolumeSet = null;
203 window.__lastVideoJsPlayer = null;
204 window.videojs = (element, options) =>
205 {
206 window.__lastVideoJsOptions = options;
207 let volumeValue = 1;
208 let durationValue = 20;
209 const player = {
210 ready (cb)
211 {
212 if (typeof cb === 'function') cb();
213 },
214 on () { },
215 trigger () { },
216 duration (next)
217 {
218 if (next === undefined) return durationValue;
219 durationValue = Number(next);
220 return durationValue;
221 },
222 currentTime () { return 0; },
223 volume (next)
224 {
217 225 if (next === undefined) return volumeValue;
218 226 volumeValue = Number(next);
219 227 window.__lastVideoJsVolumeSet = volumeValue;
220 228 return volumeValue;
221 },
222 dispose () { },
223 };
224 };
229 },
230 dispose () { },
231 };
232 window.__lastVideoJsPlayer = player;
233 return player;
234 };
225 235
226 236 const defaultSaved = {
227 237 token: 'saved-token',
@@ -653,11 +663,12 @@ describe('page load smoke test', () =>
653 663 mtime: Date.now(),
654 664 },
655 665 ];
656 videoStreamFixture['/data/clip.mkv'] = {
657 sessionId: 'video-session',
658 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
659 subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
660 };
666 videoStreamFixture['/data/clip.mkv'] = {
667 sessionId: 'video-session',
668 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
669 durationSeconds: 120,
670 subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
671 };
661 672
662 673 const { dom, runtimeErrors } = await bootClient();
663 674 expect(runtimeErrors).toEqual([]);
@@ -671,10 +682,17 @@ describe('page load smoke test', () =>
671 682 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
672 683
673 684 expect(dom.window.__lastVideoJsOptions).toBeTruthy();
674 expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
675 expect(dom.window.__lastVideoJsOptions.fluid).toBe(false);
676 expect(dom.window.__lastVideoJsOptions.fill).toBe(true);
677 expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
685 expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
686 expect(dom.window.__lastVideoJsOptions.fluid).toBe(false);
687 expect(dom.window.__lastVideoJsOptions.fill).toBe(true);
688 expect(dom.window.__lastVideoJsOptions.controlBar).toMatchObject({
689 currentTimeDisplay: true,
690 timeDivider: true,
691 durationDisplay: true,
692 remainingTimeDisplay: false,
693 });
694 expect(dom.window.__lastVideoJsPlayer.duration()).toBe(120);
695 expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
678 696 {
679 697 kind: 'subtitles',
680 698 src: '/api/files/video-stream/video-session/subtitle-0.vtt',
@@ -198,30 +198,40 @@ describe('page load smoke test', () =>
198 let blobCounter = 0;
198 let blobCounter = 0;
199 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
199 window.URL.createObjectURL = () => `blob:mock-${blobCounter++}`;
200 window.URL.revokeObjectURL = () => { };
200 window.URL.revokeObjectURL = () => { };
201 window.__lastVideoJsOptions = null;
201 window.__lastVideoJsOptions = null;
202 window.__lastVideoJsVolumeSet = null;
202 window.__lastVideoJsVolumeSet = null;
203 window.videojs = (element, options) =>
203 window.__lastVideoJsPlayer = null;
204 {
204 window.videojs = (element, options) =>
205 window.__lastVideoJsOptions = options;
205 {
206 let volumeValue = 1;
206 window.__lastVideoJsOptions = options;
207 return {
207 let volumeValue = 1;
208 ready (cb)
208 let durationValue = 20;
209 {
209 const player = {
210 if (typeof cb === 'function') cb();
210 ready (cb)
211 },
211 {
212 on () { },
212 if (typeof cb === 'function') cb();
213 duration () { return 100; },
213 },
214 currentTime () { return 0; },
214 on () { },
215 volume (next)
215 trigger () { },
216 {
216 duration (next)
217 {
218 if (next === undefined) return durationValue;
219 durationValue = Number(next);
220 return durationValue;
221 },
222 currentTime () { return 0; },
223 volume (next)
224 {
217 if (next === undefined) return volumeValue;
225 if (next === undefined) return volumeValue;
218 volumeValue = Number(next);
226 volumeValue = Number(next);
219 window.__lastVideoJsVolumeSet = volumeValue;
227 window.__lastVideoJsVolumeSet = volumeValue;
220 return volumeValue;
228 return volumeValue;
221 },
229 },
222 dispose () { },
230 dispose () { },
223 };
231 };
224 };
232 window.__lastVideoJsPlayer = player;
233 return player;
234 };
225
235
226 const defaultSaved = {
236 const defaultSaved = {
227 token: 'saved-token',
237 token: 'saved-token',
@@ -653,11 +663,12 @@ describe('page load smoke test', () =>
653 mtime: Date.now(),
663 mtime: Date.now(),
654 },
664 },
655 ];
665 ];
656 videoStreamFixture['/data/clip.mkv'] = {
666 videoStreamFixture['/data/clip.mkv'] = {
657 sessionId: 'video-session',
667 sessionId: 'video-session',
658 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
668 playlistUrl: '/api/files/video-stream/video-session/master.m3u8',
659 subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
669 durationSeconds: 120,
660 };
670 subtitleTracks: [{ label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/video-session/subtitle-0.vtt' }],
671 };
661
672
662 const { dom, runtimeErrors } = await bootClient();
673 const { dom, runtimeErrors } = await bootClient();
663 expect(runtimeErrors).toEqual([]);
674 expect(runtimeErrors).toEqual([]);
@@ -671,10 +682,17 @@ describe('page load smoke test', () =>
671 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
682 await waitFor(dom, () => !!dom.window.document.querySelector('.preview-video-js'));
672
683
673 expect(dom.window.__lastVideoJsOptions).toBeTruthy();
684 expect(dom.window.__lastVideoJsOptions).toBeTruthy();
674 expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
685 expect(dom.window.__lastVideoJsOptions.sources[0].src).toBe('/api/files/video-stream/video-session/master.m3u8');
675 expect(dom.window.__lastVideoJsOptions.fluid).toBe(false);
686 expect(dom.window.__lastVideoJsOptions.fluid).toBe(false);
676 expect(dom.window.__lastVideoJsOptions.fill).toBe(true);
687 expect(dom.window.__lastVideoJsOptions.fill).toBe(true);
677 expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
688 expect(dom.window.__lastVideoJsOptions.controlBar).toMatchObject({
689 currentTimeDisplay: true,
690 timeDivider: true,
691 durationDisplay: true,
692 remainingTimeDisplay: false,
693 });
694 expect(dom.window.__lastVideoJsPlayer.duration()).toBe(120);
695 expect(dom.window.__lastVideoJsOptions.tracks).toEqual([
678 {
696 {
679 kind: 'subtitles',
697 kind: 'subtitles',
680 src: '/api/files/video-stream/video-session/subtitle-0.vtt',
698 src: '/api/files/video-stream/video-session/subtitle-0.vtt',
tests/share.routes.test.js +2 −0
@@ -291,6 +291,7 @@ describe('GET /api/share/video-stream/:token', () =>
291 291 insertToken({ token: 'stream1', filePath });
292 292 mockVideoStreamSession = {
293 293 sessionId: 'share-sess-1',
294 durationSeconds: 42.25,
294 295 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
295 296 };
296 297
@@ -298,6 +299,7 @@ describe('GET /api/share/video-stream/:token', () =>
298 299 expect(res.status).toBe(200);
299 300 const body = await res.json();
300 301 expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8');
302 expect(body.durationSeconds).toBe(42.25);
301 303 expect(body.subtitleTracks).toEqual([
302 304 {
303 305 label: 'English',
@@ -291,6 +291,7 @@ describe('GET /api/share/video-stream/:token', () =>
291 insertToken({ token: 'stream1', filePath });
291 insertToken({ token: 'stream1', filePath });
292 mockVideoStreamSession = {
292 mockVideoStreamSession = {
293 sessionId: 'share-sess-1',
293 sessionId: 'share-sess-1',
294 durationSeconds: 42.25,
294 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
295 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
295 };
296 };
296
297
@@ -298,6 +299,7 @@ describe('GET /api/share/video-stream/:token', () =>
298 expect(res.status).toBe(200);
299 expect(res.status).toBe(200);
299 const body = await res.json();
300 const body = await res.json();
300 expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8');
301 expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8');
302 expect(body.durationSeconds).toBe(42.25);
301 expect(body.subtitleTracks).toEqual([
303 expect(body.subtitleTracks).toEqual([
302 {
304 {
303 label: 'English',
305 label: 'English',
tests/video-stream.test.js +46 −1
@@ -46,6 +46,7 @@ describe('video stream bootstrap', () =>
46 46 process.nextTick(() =>
47 47 {
48 48 child.stdout.emit('data', Buffer.from(JSON.stringify({
49 format: { duration: '12.5' },
49 50 streams: [
50 51 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
51 52 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
@@ -78,6 +79,7 @@ describe('video stream bootstrap', () =>
78 79
79 80 expect(session).toEqual({
80 81 sessionId: expect.any(String),
82 durationSeconds: 12.5,
81 83 subtitleTracks: [],
82 84 subtitleSummary: {
83 85 total: 0,
@@ -112,6 +114,7 @@ describe('video stream bootstrap', () =>
112 114 const segmentArgIndex = args.indexOf('-hls_segment_filename');
113 115 expect(segmentArgIndex).toBeGreaterThan(-1);
114 116 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
117 expect(args).not.toContain('-hls_playlist_type');
115 118
116 119 const playlistPath = String(args[args.length - 1] || '');
117 120 const outputDir = path.dirname(playlistPath);
@@ -127,6 +130,7 @@ describe('video stream bootstrap', () =>
127 130 const { createVideoStreamSession } = require('../server/video-stream');
128 131 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
129 132 sessionId: expect.any(String),
133 durationSeconds: null,
130 134 subtitleTracks: [],
131 135 subtitleSummary: {
132 136 total: 0,
@@ -136,6 +140,45 @@ describe('video stream bootstrap', () =>
136 140 });
137 141 });
138 142
143 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
144 {
145 mockSpawn.mockImplementation((command, args) =>
146 {
147 const child = makeChildProcess();
148 const exeName = path.basename(String(command || '')).toLowerCase();
149
150 if (exeName.includes('ffprobe'))
151 {
152 process.nextTick(() =>
153 {
154 child.stdout.emit('data', Buffer.from(JSON.stringify({
155 streams: [
156 { codec_type: 'video', codec_name: 'h264', tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
157 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
158 ],
159 })));
160 child.emit('close', 0);
161 });
162 return child;
163 }
164
165 const playlistPath = String(args[args.length - 1] || '');
166 const outputDir = path.dirname(playlistPath);
167 process.nextTick(() =>
168 {
169 fs.mkdirSync(outputDir, { recursive: true });
170 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
171 });
172
173 return child;
174 });
175
176 const { createVideoStreamSession } = require('../server/video-stream');
177 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
178 durationSeconds: 1337.5,
179 });
180 });
181
139 182 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
140 183 {
141 184 mockSpawn.mockImplementation((command, args) =>
@@ -196,6 +239,7 @@ describe('video stream bootstrap', () =>
196 239 expect(elapsedMs).toBeGreaterThanOrEqual(60);
197 240 expect(session).toEqual({
198 241 sessionId: expect.any(String),
242 durationSeconds: null,
199 243 subtitleTracks: [
200 244 expect.objectContaining({
201 245 fileName: 'subtitle-0.vtt',
@@ -261,6 +305,7 @@ describe('video stream bootstrap', () =>
261 305 const { createVideoStreamSession } = require('../server/video-stream');
262 306 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
263 307 sessionId: expect.any(String),
308 durationSeconds: null,
264 309 subtitleTracks: [],
265 310 subtitleSummary: {
266 311 total: 1,
@@ -269,4 +314,4 @@ describe('video stream bootstrap', () =>
269 314 },
270 315 });
271 316 });
272 });
317 });
@@ -46,6 +46,7 @@ describe('video stream bootstrap', () =>
46 process.nextTick(() =>
46 process.nextTick(() =>
47 {
47 {
48 child.stdout.emit('data', Buffer.from(JSON.stringify({
48 child.stdout.emit('data', Buffer.from(JSON.stringify({
49 format: { duration: '12.5' },
49 streams: [
50 streams: [
50 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
51 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
51 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
52 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
@@ -78,6 +79,7 @@ describe('video stream bootstrap', () =>
78
79
79 expect(session).toEqual({
80 expect(session).toEqual({
80 sessionId: expect.any(String),
81 sessionId: expect.any(String),
82 durationSeconds: 12.5,
81 subtitleTracks: [],
83 subtitleTracks: [],
82 subtitleSummary: {
84 subtitleSummary: {
83 total: 0,
85 total: 0,
@@ -112,6 +114,7 @@ describe('video stream bootstrap', () =>
112 const segmentArgIndex = args.indexOf('-hls_segment_filename');
114 const segmentArgIndex = args.indexOf('-hls_segment_filename');
113 expect(segmentArgIndex).toBeGreaterThan(-1);
115 expect(segmentArgIndex).toBeGreaterThan(-1);
114 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
116 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
117 expect(args).not.toContain('-hls_playlist_type');
115
118
116 const playlistPath = String(args[args.length - 1] || '');
119 const playlistPath = String(args[args.length - 1] || '');
117 const outputDir = path.dirname(playlistPath);
120 const outputDir = path.dirname(playlistPath);
@@ -127,6 +130,7 @@ describe('video stream bootstrap', () =>
127 const { createVideoStreamSession } = require('../server/video-stream');
130 const { createVideoStreamSession } = require('../server/video-stream');
128 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
131 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
129 sessionId: expect.any(String),
132 sessionId: expect.any(String),
133 durationSeconds: null,
130 subtitleTracks: [],
134 subtitleTracks: [],
131 subtitleSummary: {
135 subtitleSummary: {
132 total: 0,
136 total: 0,
@@ -136,6 +140,45 @@ describe('video stream bootstrap', () =>
136 });
140 });
137 });
141 });
138
142
143 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
144 {
145 mockSpawn.mockImplementation((command, args) =>
146 {
147 const child = makeChildProcess();
148 const exeName = path.basename(String(command || '')).toLowerCase();
149
150 if (exeName.includes('ffprobe'))
151 {
152 process.nextTick(() =>
153 {
154 child.stdout.emit('data', Buffer.from(JSON.stringify({
155 streams: [
156 { codec_type: 'video', codec_name: 'h264', tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
157 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
158 ],
159 })));
160 child.emit('close', 0);
161 });
162 return child;
163 }
164
165 const playlistPath = String(args[args.length - 1] || '');
166 const outputDir = path.dirname(playlistPath);
167 process.nextTick(() =>
168 {
169 fs.mkdirSync(outputDir, { recursive: true });
170 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
171 });
172
173 return child;
174 });
175
176 const { createVideoStreamSession } = require('../server/video-stream');
177 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
178 durationSeconds: 1337.5,
179 });
180 });
181
139 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
182 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
140 {
183 {
141 mockSpawn.mockImplementation((command, args) =>
184 mockSpawn.mockImplementation((command, args) =>
@@ -196,6 +239,7 @@ describe('video stream bootstrap', () =>
196 expect(elapsedMs).toBeGreaterThanOrEqual(60);
239 expect(elapsedMs).toBeGreaterThanOrEqual(60);
197 expect(session).toEqual({
240 expect(session).toEqual({
198 sessionId: expect.any(String),
241 sessionId: expect.any(String),
242 durationSeconds: null,
199 subtitleTracks: [
243 subtitleTracks: [
200 expect.objectContaining({
244 expect.objectContaining({
201 fileName: 'subtitle-0.vtt',
245 fileName: 'subtitle-0.vtt',
@@ -261,6 +305,7 @@ describe('video stream bootstrap', () =>
261 const { createVideoStreamSession } = require('../server/video-stream');
305 const { createVideoStreamSession } = require('../server/video-stream');
262 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
306 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
263 sessionId: expect.any(String),
307 sessionId: expect.any(String),
308 durationSeconds: null,
264 subtitleTracks: [],
309 subtitleTracks: [],
265 subtitleSummary: {
310 subtitleSummary: {
266 total: 1,
311 total: 1,
@@ -269,4 +314,4 @@ describe('video stream bootstrap', () =>
269 },
314 },
270 });
315 });
271 });
316 });
272});
317});