Merge fix/subtitle-runtime-logging
Add subtitle runtime logging for file and share playback, including capped local subtitle debug log files and tests.
@@ -9,6 +9,11 @@
9
9
## server/logger.js
10
10
- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
11
11
12
## server/subtitle-debug-log.js
13
- appendSubtitleDebugEntries({ videoName, entries, context }) - Appends client-side subtitle timing events to a dated per-video text log under the local temp cache (`yyyy-mm-dd-videoname-subtitlelog.txt`), merging static context into each line and pruning the oldest files when the subtitle log cache exceeds 10 MB.
14
- pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15
- subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16
12
17
## server/image-subtitles.js
13
18
- parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
14
19
- renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; request/build/render timing counters are tracked for debug diagnostics.
@@ -106,7 +111,8 @@
106
111
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
107
112
- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
108
113
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
109
- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height} to communicate frame placement and dimensions for client-side upscaling; on failures or no active subtitle it returns 204 so the client can stop retrying.
114
- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height,Start-Time,End-Time} plus X-Subtitle-{Request-Received-At-Ms,Response-Sent-At-Ms} so the client can log subtitle timing against server send time; on failures or no active subtitle it returns 204 so the client can stop retrying.
115
- POST /api/files/video-stream-subtitle-log - Authenticated. Accepts batched client-side subtitle timing events for an authorised file and appends them to the local subtitle debug-log cache with file path, username, and stream session context.
110
116
- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
111
117
- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
112
118
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -120,7 +126,8 @@
120
126
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121
127
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122
128
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
129
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns the same subtitle timing headers as the authenticated route and 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
130
- POST /api/share/video-stream-subtitle-log/:token - Public. Accepts batched client-side subtitle timing events for a valid shared-video token and appends them to the local subtitle debug-log cache with share-token and stream-session context.
124
131
- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
125
132
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
126
133
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
@@ -161,7 +168,7 @@
161
168
## public/shared-video-player.js
162
169
- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
163
170
- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
164
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), aborts stale current/prefetch fetches on seek/track-switch/dispose, and disables the track after the first hard failure.
171
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), aborts stale current/prefetch fetches on seek/track-switch/dispose, logs current subtitle request/send/receive/show timing to the browser console and optional batch sink, and disables the track after the first hard failure.
165
172
- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
166
173
- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
167
174
@@ -229,7 +236,7 @@
229
236
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
230
237
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
231
238
- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
232
- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), and disables the track after the first failed frame request to avoid repeated polling; reads X-Subtitle-Frame-* headers from server responses and calculates percentage-based sizing (frameWidth / canvasWidth * 100%) to properly upscale downscaled frames while maintaining proportions.
239
- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
233
240
- 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), wires the image-subtitle overlay controller, 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.
234
241
- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
235
242
- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
@@ -9,6 +9,11 @@9
## server/logger.js
9
## server/logger.js
10
- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
10
- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
11
11
12
## server/subtitle-debug-log.js
13
- appendSubtitleDebugEntries({ videoName, entries, context }) - Appends client-side subtitle timing events to a dated per-video text log under the local temp cache (`yyyy-mm-dd-videoname-subtitlelog.txt`), merging static context into each line and pruning the oldest files when the subtitle log cache exceeds 10 MB.
14
- pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15
- subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16
12
## server/image-subtitles.js
17
## server/image-subtitles.js
13
- parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
18
- parseRenderOptions(options) - Normalises subtitle-frame request options and validates filePath/streamIndex/time/canvas dimensions; stream index `0` is valid and must not be treated as missing; canvas is scaled down within a 1280x720 ceiling, then multiplied by `IMAGE_SUBTITLE_RENDER_SCALE` (default `0.75`) while preserving requested aspect ratio.
14
- renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; request/build/render timing counters are tracked for debug diagnostics.
19
- renderImageSubtitleFrame(options) - Extracts bitmap subtitle streams to cached `.sup`, parses PGS display sets, and returns {frame: PNG buffer, left, top, width, height, canvasWidth, canvasHeight} with metadata for proper client-side upscaling; the server preserves positioning info instead of throwing it away, allowing the client to calculate percentage-based sizing for downscaled frames; request/build/render timing counters are tracked for debug diagnostics.
@@ -106,7 +111,8 @@106
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
111
- POST /api/files/move - Moves file/folder; supports conflict strategies: `error` (default), `overwrite`, or `rename` with optional `targetName`.
107
- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
112
- POST /api/files/copy - Copies a file to a destination folder with conflict strategies (`error`, `overwrite`, `rename`) and user-folder size-limit checks.
108
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
113
- POST /api/files/video-stream - Creates a short-lived HLS session for a video and returns playlistUrl, durationSeconds, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
109
- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height} to communicate frame placement and dimensions for client-side upscaling; on failures or no active subtitle it returns 204 so the client can stop retrying.
114
- GET /api/files/video-stream-subtitle-frame - Authenticated. Renders a PNG subtitle frame for bitmap subtitle tracks via cached PGS decode/composite flow; returns {frame, left, top, width, height, canvasWidth, canvasHeight}; sends response headers X-Subtitle-Frame-{Left,Top,Width,Height,Canvas-Width,Canvas-Height,Start-Time,End-Time} plus X-Subtitle-{Request-Received-At-Ms,Response-Sent-At-Ms} so the client can log subtitle timing against server send time; on failures or no active subtitle it returns 204 so the client can stop retrying.
115
- POST /api/files/video-stream-subtitle-log - Authenticated. Accepts batched client-side subtitle timing events for an authorised file and appends them to the local subtitle debug-log cache with file path, username, and stream session context.
110
- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
116
- DELETE /api/files/video-stream/:sessionId - Explicitly releases an active short-lived video stream session and stops backend processing.
111
- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
117
- POST /api/files/watched-statuses - Returns fast per-user watched statuses for up to 500 file paths without triggering expensive metadata/hash work; response is { statuses: { [filePath]: 'fully'|'partway' } }.
112
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
118
- POST /api/files/watch-progress - Records per-user watch status (`partway` >=10%, `fully` >=70%) for sidebar "Watched by" display.
@@ -120,7 +126,8 @@120
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
126
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
127
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
128
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
129
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns the same subtitle timing headers as the authenticated route and 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
130
- POST /api/share/video-stream-subtitle-log/:token - Public. Accepts batched client-side subtitle timing events for a valid shared-video token and appends them to the local subtitle debug-log cache with share-token and stream-session context.
124
- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
131
- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
125
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
132
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
126
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
133
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
@@ -161,7 +168,7 @@161
## public/shared-video-player.js
168
## public/shared-video-player.js
162
- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
169
- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
163
- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
170
- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
164
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), aborts stale current/prefetch fetches on seek/track-switch/dispose, and disables the track after the first hard failure.
171
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), aborts stale current/prefetch fetches on seek/track-switch/dispose, logs current subtitle request/send/receive/show timing to the browser console and optional batch sink, and disables the track after the first hard failure.
165
- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
172
- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
166
- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
173
- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
167
174
@@ -229,7 +236,7 @@229
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
236
- setThumbnailPending(iconEl, pending) - Toggles per-icon pending spinner state while a cached image thumbnail is not ready yet.
230
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
237
- buildThumbnailSource(item, blob, kind) - Produces thumbnail image source (data/blob URL) for icon injection.
231
- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
238
- buildAuthHeaders() - Builds the authenticated fetch headers used by preview-side API calls that need the bearer token plus fingerprint header.
232
- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), and disables the track after the first failed frame request to avoid repeated polling; reads X-Subtitle-Frame-* headers from server responses and calculates percentage-based sizing (frameWidth / canvasWidth * 100%) to properly upscale downscaled frames while maintaining proportions.
239
- bindImageSubtitleOverlay(player, videojs, prefs, session, item) - Adds the fullscreen-safe image-subtitle button, menu, and bottom overlay used to fetch and display subtitle frames for image-based tracks; keeps subtitle bitmaps horizontally centred at the bottom, highlights the currently selected IM menu option, persists per-user image subtitle stream index + track name, restores by saved track name first (then stream index), batches subtitle timing diagnostics to `/api/files/video-stream-subtitle-log`, and reads X-Subtitle-Frame-* headers from server responses to properly upscale downscaled frames while maintaining proportions.
233
- 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), wires the image-subtitle overlay controller, 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.
240
- 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), wires the image-subtitle overlay controller, 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.
234
- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
241
- modelPreviewType(name) - Classifies direct client-side 3D preview support for `.stl` and `.obj`.
235
- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
242
- loadThreePreviewModules() - Lazy-loads Three.js plus OrbitControls/STLLoader/OBJLoader via import map aliases.
@@ -89,6 +89,11 @@
89
89
90
90
---
91
91
92
## `test/subtitle-debug-log.test.js`
93
- `subtitle debug log writer`
94
95
---
96
92
97
## `test/thumbnail-cache.test.js`
93
98
- `thumbnail cache worker`
94
99
@@ -89,6 +89,11 @@89
89
90
---90
---91
91
92
## `test/subtitle-debug-log.test.js`93
- `subtitle debug log writer`94
95
---96
92
## `test/thumbnail-cache.test.js`97
## `test/thumbnail-cache.test.js`93
- `thumbnail cache worker`98
- `thumbnail cache worker`94
99
@@ -400,9 +400,32 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
400
400
const shared = sharedVideoPlayer();
401
401
if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
402
402
403
const sendSubtitleLogBatch = (entries) =>
404
{
405
if (!Array.isArray(entries) || !entries.length) return Promise.resolve();
406
407
const headers = {
408
...buildAuthHeaders(),
409
'Content-Type': 'application/json',
410
};
411
412
return fetch('/api/files/video-stream-subtitle-log', {
413
method: 'POST',
414
headers,
415
credentials: 'same-origin',
416
keepalive: true,
417
body: JSON.stringify({
418
filePath: item.path,
419
sessionId: session.sessionId || null,
420
entries,
421
}),
422
}).catch(() => null);
423
};
424
403
425
return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
404
426
savePrefs: saveUserVideoPrefs,
405
427
lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,
428
sendSubtitleLogBatch,
406
429
buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
407
430
url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
408
431
headers: buildAuthHeaders(),
@@ -400,9 +400,32 @@ function bindImageSubtitleOverlay (player, videojs, prefs, session, item)400
const shared = sharedVideoPlayer();400
const shared = sharedVideoPlayer();401
if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;401
if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;402
402
403
const sendSubtitleLogBatch = (entries) =>404
{405
if (!Array.isArray(entries) || !entries.length) return Promise.resolve();406
407
const headers = {408
...buildAuthHeaders(),409
'Content-Type': 'application/json',410
};411
412
return fetch('/api/files/video-stream-subtitle-log', {413
method: 'POST',414
headers,415
credentials: 'same-origin',416
keepalive: true,417
body: JSON.stringify({418
filePath: item.path,419
sessionId: session.sessionId || null,420
entries,421
}),422
}).catch(() => null);423
};424
403
return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {425
return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {404
savePrefs: saveUserVideoPrefs,426
savePrefs: saveUserVideoPrefs,405
lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,427
lookaheadSeconds: IMAGE_SUBTITLE_LOOKAHEAD_SECONDS,428
sendSubtitleLogBatch,406
buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({429
buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({407
url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,430
url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,408
headers: buildAuthHeaders(),431
headers: buildAuthHeaders(),@@ -13,6 +13,7 @@ const { requireAuth } = require('../auth');
13
13
const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14
14
const { logError } = require('../logger');
15
15
const { renderImageSubtitleFrame } = require('../image-subtitles');
16
const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
16
17
const { buildZip } = require('./share');
17
18
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
18
19
@@ -1553,6 +1554,7 @@ router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1553
1554
// ---------------------------------------------------------------------------
1554
1555
router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1555
1556
{
1557
const requestReceivedAtMs = Date.now();
1556
1558
try
1557
1559
{
1558
1560
const filePath = String(req.query.filePath || '').trim();
@@ -1590,10 +1592,14 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1590
1592
1591
1593
if (!frameData || !frameData.frame)
1592
1594
{
1595
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1596
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1593
1597
res.set('X-Subtitle-Frame-Status', 'none');
1594
1598
return res.status(204).end();
1595
1599
}
1596
1600
1601
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1602
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1597
1603
res.set('X-Subtitle-Frame-Status', 'ok');
1598
1604
res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
1599
1605
res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
@@ -1601,6 +1607,8 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1601
1607
res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
1602
1608
res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
1603
1609
res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
1610
res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
1611
res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
1604
1612
res.set('Content-Type', 'image/png');
1605
1613
res.set('Cache-Control', 'private, max-age=3600');
1606
1614
res.send(frameData.frame);
@@ -1611,11 +1619,60 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =
1611
1619
streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1612
1620
timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1613
1621
});
1622
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
1623
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
1614
1624
res.set('X-Subtitle-Frame-Status', 'error');
1615
1625
return res.status(204).end();
1616
1626
}
1617
1627
});
1618
1628
1629
// ---------------------------------------------------------------------------
1630
// POST /api/files/video-stream-subtitle-log
1631
// Authenticated. Persists client-side subtitle timing diagnostics to local cache.
1632
// Body: { filePath, sessionId?, entries[] }
1633
// ---------------------------------------------------------------------------
1634
router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>
1635
{
1636
try
1637
{
1638
const filePath = String(req.body && req.body.filePath || '').trim();
1639
const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
1640
const sessionId = String(req.body && req.body.sessionId || '').trim();
1641
1642
if (!filePath || !entries || !entries.length)
1643
{
1644
return res.status(400).json({ error: 'filePath and entries are required.' });
1645
}
1646
1647
const { config, roots } = loadConfigAndRoots();
1648
const info = resolveRootForUser(filePath, roots, req.user, config);
1649
if (!info || !canReadInfo(req.user, info))
1650
{
1651
return res.status(403).json({ error: 'Access denied.' });
1652
}
1653
1654
appendSubtitleDebugEntries({
1655
videoName: path.basename(filePath),
1656
entries,
1657
context: {
1658
source: 'app',
1659
filePath,
1660
sessionId: sessionId || null,
1661
username: String(req.user && req.user.username || '').trim() || null,
1662
},
1663
});
1664
1665
return res.json({ ok: true });
1666
} catch (err)
1667
{
1668
logError('Subtitle debug log write failed', err, {
1669
filePath: String(req.body && req.body.filePath || ''),
1670
entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
1671
});
1672
return res.status(500).json({ error: 'Subtitle debug log write failed.' });
1673
}
1674
});
1675
1619
1676
// ---------------------------------------------------------------------------
1620
1677
// GET /api/files/download-zip?dir=<absolute-path>
1621
1678
// Authenticated. Streams a zip of the given directory.
@@ -13,6 +13,7 @@ const { requireAuth } = require('../auth');13
const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');13
const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');14
const { logError } = require('../logger');14
const { logError } = require('../logger');15
const { renderImageSubtitleFrame } = require('../image-subtitles');15
const { renderImageSubtitleFrame } = require('../image-subtitles');16
const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');16
const { buildZip } = require('./share');17
const { buildZip } = require('./share');17
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');18
const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');18
19
@@ -1553,6 +1554,7 @@ router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>1553
// ---------------------------------------------------------------------------1554
// ---------------------------------------------------------------------------1554
router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>1555
router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>1555
{1556
{1557
const requestReceivedAtMs = Date.now();1556
try1558
try1557
{1559
{1558
const filePath = String(req.query.filePath || '').trim();1560
const filePath = String(req.query.filePath || '').trim();@@ -1590,10 +1592,14 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =1590
1592
1591
if (!frameData || !frameData.frame)1593
if (!frameData || !frameData.frame)1592
{1594
{1595
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));1596
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));1593
res.set('X-Subtitle-Frame-Status', 'none');1597
res.set('X-Subtitle-Frame-Status', 'none');1594
return res.status(204).end();1598
return res.status(204).end();1595
}1599
}1596
1600
1601
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));1602
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));1597
res.set('X-Subtitle-Frame-Status', 'ok');1603
res.set('X-Subtitle-Frame-Status', 'ok');1598
res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));1604
res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));1599
res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));1605
res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));@@ -1601,6 +1607,8 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =1601
res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));1607
res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));1602
res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));1608
res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));1603
res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));1609
res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));1610
res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));1611
res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));1604
res.set('Content-Type', 'image/png');1612
res.set('Content-Type', 'image/png');1605
res.set('Cache-Control', 'private, max-age=3600');1613
res.set('Cache-Control', 'private, max-age=3600');1606
res.send(frameData.frame);1614
res.send(frameData.frame);@@ -1611,11 +1619,60 @@ router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =1611
streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),1619
streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),1612
timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),1620
timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),1613
});1621
});1622
res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));1623
res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));1614
res.set('X-Subtitle-Frame-Status', 'error');1624
res.set('X-Subtitle-Frame-Status', 'error');1615
return res.status(204).end();1625
return res.status(204).end();1616
}1626
}1617
});1627
});1618
1628
1629
// ---------------------------------------------------------------------------1630
// POST /api/files/video-stream-subtitle-log1631
// Authenticated. Persists client-side subtitle timing diagnostics to local cache.1632
// Body: { filePath, sessionId?, entries[] }1633
// ---------------------------------------------------------------------------1634
router.post('/video-stream-subtitle-log', requireAuth, (req, res) =>1635
{1636
try1637
{1638
const filePath = String(req.body && req.body.filePath || '').trim();1639
const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;1640
const sessionId = String(req.body && req.body.sessionId || '').trim();1641
1642
if (!filePath || !entries || !entries.length)1643
{1644
return res.status(400).json({ error: 'filePath and entries are required.' });1645
}1646
1647
const { config, roots } = loadConfigAndRoots();1648
const info = resolveRootForUser(filePath, roots, req.user, config);1649
if (!info || !canReadInfo(req.user, info))1650
{1651
return res.status(403).json({ error: 'Access denied.' });1652
}1653
1654
appendSubtitleDebugEntries({1655
videoName: path.basename(filePath),1656
entries,1657
context: {1658
source: 'app',1659
filePath,1660
sessionId: sessionId || null,1661
username: String(req.user && req.user.username || '').trim() || null,1662
},1663
});1664
1665
return res.json({ ok: true });1666
} catch (err)1667
{1668
logError('Subtitle debug log write failed', err, {1669
filePath: String(req.body && req.body.filePath || ''),1670
entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,1671
});1672
return res.status(500).json({ error: 'Subtitle debug log write failed.' });1673
}1674
});1675
1619
// ---------------------------------------------------------------------------1676
// ---------------------------------------------------------------------------1620
// GET /api/files/download-zip?dir=<absolute-path>1677
// GET /api/files/download-zip?dir=<absolute-path>1621
// Authenticated. Streams a zip of the given directory.1678
// Authenticated. Streams a zip of the given directory.@@ -0,0 +1,127 @@
1
'use strict';
2
3
const fs = require('fs');
4
const os = require('os');
5
const path = require('path');
6
7
const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
8
const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024;
9
10
function padNumber (value)
11
{
12
return String(Math.max(0, Number(value) || 0)).padStart(2, '0');
13
}
14
15
function localDateStamp (timestampMs)
16
{
17
const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now());
18
return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`;
19
}
20
21
function sanitiseVideoName (videoName)
22
{
23
const raw = path.basename(String(videoName || '').trim() || 'unknown-video');
24
const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
25
return cleaned || 'unknown-video';
26
}
27
28
function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())
29
{
30
const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;
31
return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);
32
}
33
34
function ensureSubtitleDebugLogDir ()
35
{
36
fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });
37
}
38
39
function serialiseLogEntry (entry)
40
{
41
const payload = entry && typeof entry === 'object' ? entry : { value: entry };
42
const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();
43
return `[${timestamp}] ${JSON.stringify(payload)}\n`;
44
}
45
46
function directoryEntriesWithStats (dirPath)
47
{
48
let entries = [];
49
try
50
{
51
entries = fs.readdirSync(dirPath, { withFileTypes: true });
52
} catch
53
{
54
return [];
55
}
56
57
const out = [];
58
for (const entry of entries)
59
{
60
if (!entry.isFile()) continue;
61
const fullPath = path.join(dirPath, entry.name);
62
try
63
{
64
const stat = fs.statSync(fullPath);
65
out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });
66
} catch
67
{
68
// Ignore files that disappear mid-scan.
69
}
70
}
71
return out;
72
}
73
74
function pruneSubtitleDebugLogDir ()
75
{
76
ensureSubtitleDebugLogDir();
77
const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
78
let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
79
80
for (const entry of entries)
81
{
82
if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
83
try
84
{
85
fs.unlinkSync(entry.fullPath);
86
totalBytes = Math.max(0, totalBytes - entry.size);
87
} catch
88
{
89
// Ignore prune failures; logging must remain best-effort.
90
}
91
}
92
}
93
94
function appendSubtitleDebugEntries ({ videoName, entries, context = null })
95
{
96
const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
97
if (!rows.length) return null;
98
99
const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
100
const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());
101
102
try
103
{
104
ensureSubtitleDebugLogDir();
105
const text = rows.map((entry) =>
106
{
107
const payload = context && typeof context === 'object'
108
? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
109
: entry;
110
return serialiseLogEntry(payload);
111
}).join('');
112
fs.appendFileSync(targetPath, text, 'utf8');
113
pruneSubtitleDebugLogDir();
114
return targetPath;
115
} catch
116
{
117
return null;
118
}
119
}
120
121
module.exports = {
122
SUBTITLE_DEBUG_LOG_DIR,
123
MAX_SUBTITLE_DEBUG_LOG_BYTES,
124
subtitleDebugLogFilePath,
125
pruneSubtitleDebugLogDir,
126
appendSubtitleDebugEntries,
127
};
@@ -0,0 +1,127 @@1
'use strict';2
3
const fs = require('fs');4
const os = require('os');5
const path = require('path');6
7
const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');8
const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024;9
10
function padNumber (value)11
{12
return String(Math.max(0, Number(value) || 0)).padStart(2, '0');13
}14
15
function localDateStamp (timestampMs)16
{17
const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now());18
return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`;19
}20
21
function sanitiseVideoName (videoName)22
{23
const raw = path.basename(String(videoName || '').trim() || 'unknown-video');24
const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');25
return cleaned || 'unknown-video';26
}27
28
function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())29
{30
const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;31
return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);32
}33
34
function ensureSubtitleDebugLogDir ()35
{36
fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });37
}38
39
function serialiseLogEntry (entry)40
{41
const payload = entry && typeof entry === 'object' ? entry : { value: entry };42
const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();43
return `[${timestamp}] ${JSON.stringify(payload)}\n`;44
}45
46
function directoryEntriesWithStats (dirPath)47
{48
let entries = [];49
try50
{51
entries = fs.readdirSync(dirPath, { withFileTypes: true });52
} catch53
{54
return [];55
}56
57
const out = [];58
for (const entry of entries)59
{60
if (!entry.isFile()) continue;61
const fullPath = path.join(dirPath, entry.name);62
try63
{64
const stat = fs.statSync(fullPath);65
out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });66
} catch67
{68
// Ignore files that disappear mid-scan.69
}70
}71
return out;72
}73
74
function pruneSubtitleDebugLogDir ()75
{76
ensureSubtitleDebugLogDir();77
const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);78
let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);79
80
for (const entry of entries)81
{82
if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;83
try84
{85
fs.unlinkSync(entry.fullPath);86
totalBytes = Math.max(0, totalBytes - entry.size);87
} catch88
{89
// Ignore prune failures; logging must remain best-effort.90
}91
}92
}93
94
function appendSubtitleDebugEntries ({ videoName, entries, context = null })95
{96
const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];97
if (!rows.length) return null;98
99
const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));100
const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());101
102
try103
{104
ensureSubtitleDebugLogDir();105
const text = rows.map((entry) =>106
{107
const payload = context && typeof context === 'object'108
? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }109
: entry;110
return serialiseLogEntry(payload);111
}).join('');112
fs.appendFileSync(targetPath, text, 'utf8');113
pruneSubtitleDebugLogDir();114
return targetPath;115
} catch116
{117
return null;118
}119
}120
121
module.exports = {122
SUBTITLE_DEBUG_LOG_DIR,123
MAX_SUBTITLE_DEBUG_LOG_BYTES,124
subtitleDebugLogFilePath,125
pruneSubtitleDebugLogDir,126
appendSubtitleDebugEntries,127
};@@ -130,6 +130,10 @@ jest.mock('../server/image-subtitles', () => ({
130
130
}),
131
131
}));
132
132
133
jest.mock('../server/subtitle-debug-log', () => ({
134
appendSubtitleDebugEntries: jest.fn(),
135
}));
136
133
137
const filesRoutes = require('../server/routes/files');
134
138
const { getDb } = require('../server/db');
135
139
@@ -1013,6 +1017,8 @@ describe('video streaming routes', () =>
1013
1017
height: 180,
1014
1018
canvasWidth: 640,
1015
1019
canvasHeight: 360,
1020
startTimeSeconds: 1.5,
1021
endTimeSeconds: 3.2,
1016
1022
};
1017
1023
1018
1024
const { status, headers, body } = await reqRaw(
@@ -1029,9 +1035,39 @@ describe('video streaming routes', () =>
1029
1035
expect(headers['x-subtitle-frame-height']).toBe('180');
1030
1036
expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1031
1037
expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1038
expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1039
expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1040
expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1041
expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1032
1042
expect(body.equals(Buffer.from('png-data'))).toBe(true);
1033
1043
});
1034
1044
1045
test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1046
{
1047
const filePath = path.join(rootDir, 'movie.mkv');
1048
fs.writeFileSync(filePath, 'video');
1049
const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1050
1051
const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1052
filePath,
1053
sessionId: 'sess-123',
1054
entries: [
1055
{ loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1056
],
1057
});
1058
1059
expect(status).toBe(200);
1060
expect(body).toEqual({ ok: true });
1061
expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1062
videoName: 'movie.mkv',
1063
context: expect.objectContaining({
1064
filePath,
1065
sessionId: 'sess-123',
1066
source: 'app',
1067
}),
1068
}));
1069
});
1070
1035
1071
test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1036
1072
{
1037
1073
const filePath = path.join(rootDir, 'clip.mkv');
@@ -130,6 +130,10 @@ jest.mock('../server/image-subtitles', () => ({130
}),130
}),131
}));131
}));132
132
133
jest.mock('../server/subtitle-debug-log', () => ({134
appendSubtitleDebugEntries: jest.fn(),135
}));136
133
const filesRoutes = require('../server/routes/files');137
const filesRoutes = require('../server/routes/files');134
const { getDb } = require('../server/db');138
const { getDb } = require('../server/db');135
139
@@ -1013,6 +1017,8 @@ describe('video streaming routes', () =>1013
height: 180,1017
height: 180,1014
canvasWidth: 640,1018
canvasWidth: 640,1015
canvasHeight: 360,1019
canvasHeight: 360,1020
startTimeSeconds: 1.5,1021
endTimeSeconds: 3.2,1016
};1022
};1017
1023
1018
const { status, headers, body } = await reqRaw(1024
const { status, headers, body } = await reqRaw(@@ -1029,9 +1035,39 @@ describe('video streaming routes', () =>1029
expect(headers['x-subtitle-frame-height']).toBe('180');1035
expect(headers['x-subtitle-frame-height']).toBe('180');1030
expect(headers['x-subtitle-frame-canvas-width']).toBe('640');1036
expect(headers['x-subtitle-frame-canvas-width']).toBe('640');1031
expect(headers['x-subtitle-frame-canvas-height']).toBe('360');1037
expect(headers['x-subtitle-frame-canvas-height']).toBe('360');1038
expect(headers['x-subtitle-frame-start-time']).toBe('1.5');1039
expect(headers['x-subtitle-frame-end-time']).toBe('3.2');1040
expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);1041
expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);1032
expect(body.equals(Buffer.from('png-data'))).toBe(true);1042
expect(body.equals(Buffer.from('png-data'))).toBe(true);1033
});1043
});1034
1044
1045
test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>1046
{1047
const filePath = path.join(rootDir, 'movie.mkv');1048
fs.writeFileSync(filePath, 'video');1049
const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');1050
1051
const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {1052
filePath,1053
sessionId: 'sess-123',1054
entries: [1055
{ loggedAtMs: 1000, eventType: 'subtitle_png_requested' },1056
],1057
});1058
1059
expect(status).toBe(200);1060
expect(body).toEqual({ ok: true });1061
expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({1062
videoName: 'movie.mkv',1063
context: expect.objectContaining({1064
filePath,1065
sessionId: 'sess-123',1066
source: 'app',1067
}),1068
}));1069
});1070
1035
test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>1071
test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>1036
{1072
{1037
const filePath = path.join(rootDir, 'clip.mkv');1073
const filePath = path.join(rootDir, 'clip.mkv');@@ -0,0 +1,60 @@
1
'use strict';
2
3
const fs = require('fs');
4
const os = require('os');
5
const path = require('path');
6
7
describe('subtitle debug log writer', () =>
8
{
9
const modulePath = require.resolve('../server/subtitle-debug-log');
10
const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
11
12
beforeEach(() =>
13
{
14
jest.resetModules();
15
fs.rmSync(logDir, { recursive: true, force: true });
16
});
17
18
test('writes dated per-video subtitle log files', () =>
19
{
20
const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
21
22
const targetPath = appendSubtitleDebugEntries({
23
videoName: 'My Film.mkv',
24
context: { source: 'app' },
25
entries: [
26
{ loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'subtitle_png_requested' },
27
],
28
});
29
30
expect(targetPath).toContain('2026-05-25-My-Film.mkv-subtitlelog.txt');
31
const text = fs.readFileSync(targetPath, 'utf8');
32
expect(text).toContain('subtitle_png_requested');
33
expect(text).toContain('"source":"app"');
34
});
35
36
test('prunes oldest subtitle log files when cache exceeds 10 MB', () =>
37
{
38
const logModule = require('../server/subtitle-debug-log');
39
40
const oldPath = logModule.appendSubtitleDebugEntries({
41
videoName: 'old-video.mkv',
42
entries: [
43
{ loggedAtMs: new Date('2026-05-24T10:00:00Z').getTime(), eventType: 'old-log', payload: 'x'.repeat(6 * 1024 * 1024) },
44
],
45
});
46
const newPath = logModule.appendSubtitleDebugEntries({
47
videoName: 'new-video.mkv',
48
entries: [
49
{ loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'new-log', payload: 'y'.repeat(6 * 1024 * 1024) },
50
],
51
});
52
53
expect(fs.existsSync(newPath)).toBe(true);
54
expect(fs.existsSync(oldPath)).toBe(false);
55
56
const entries = fs.readdirSync(logDir);
57
expect(entries).toHaveLength(1);
58
expect(entries[0]).toContain('new-video.mkv-subtitlelog.txt');
59
});
60
});
@@ -0,0 +1,60 @@1
'use strict';2
3
const fs = require('fs');4
const os = require('os');5
const path = require('path');6
7
describe('subtitle debug log writer', () =>8
{9
const modulePath = require.resolve('../server/subtitle-debug-log');10
const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');11
12
beforeEach(() =>13
{14
jest.resetModules();15
fs.rmSync(logDir, { recursive: true, force: true });16
});17
18
test('writes dated per-video subtitle log files', () =>19
{20
const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');21
22
const targetPath = appendSubtitleDebugEntries({23
videoName: 'My Film.mkv',24
context: { source: 'app' },25
entries: [26
{ loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'subtitle_png_requested' },27
],28
});29
30
expect(targetPath).toContain('2026-05-25-My-Film.mkv-subtitlelog.txt');31
const text = fs.readFileSync(targetPath, 'utf8');32
expect(text).toContain('subtitle_png_requested');33
expect(text).toContain('"source":"app"');34
});35
36
test('prunes oldest subtitle log files when cache exceeds 10 MB', () =>37
{38
const logModule = require('../server/subtitle-debug-log');39
40
const oldPath = logModule.appendSubtitleDebugEntries({41
videoName: 'old-video.mkv',42
entries: [43
{ loggedAtMs: new Date('2026-05-24T10:00:00Z').getTime(), eventType: 'old-log', payload: 'x'.repeat(6 * 1024 * 1024) },44
],45
});46
const newPath = logModule.appendSubtitleDebugEntries({47
videoName: 'new-video.mkv',48
entries: [49
{ loggedAtMs: new Date('2026-05-25T10:00:00Z').getTime(), eventType: 'new-log', payload: 'y'.repeat(6 * 1024 * 1024) },50
],51
});52
53
expect(fs.existsSync(newPath)).toBe(true);54
expect(fs.existsSync(oldPath)).toBe(false);55
56
const entries = fs.readdirSync(logDir);57
expect(entries).toHaveLength(1);58
expect(entries[0]).toContain('new-video.mkv-subtitlelog.txt');59
});60
});