BlueGit

timfa filemanager

Expose subtitle debug cache folder

Let admins open the subtitle timing log cache from the debug dashboard and browse it through the file navigator for easier retrieval.

timfa Tim Falken · pushed by timfa

Authored 2026-05-25 · 5 months ago

Hash
294f7ec7271a3ad336e7a8579ab04be737304eeb
Parent
b1c6c78b
9 files changed +155 −2
.github/technical-reference.md +5 −0
@@ -11,6 +11,7 @@
11 11
12 12 ## server/subtitle-debug-log.js
13 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 - getSubtitleDebugLogSnapshot() - Reports the subtitle log cache directory path, existence, file count, byte total, and latest file so the debug dashboard can expose it as a folder.
14 15 - pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15 16 - subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16 17
@@ -73,6 +74,7 @@
73 74 ## server/routes/debug.js
74 75 - GET /api/admin/debug/stream-stats - Computes debug dashboard data by combining auth_sessions activity, root disk usage scans, stream snapshot data, and subtitle cache snapshot data into a per-video view for leak/performance monitoring.
75 76 - GET /api/admin/debug/stream-stats - Also reports host/process memory ({total, free, used, usedPercent, processRssBytes, processHeapUsedBytes}) so streaming lag can be correlated with RAM pressure.
77 - GET /api/admin/debug/stream-stats - Also reports the subtitle debug cache directory metadata so admins can open the local subtitle log folder from the debug dashboard.
76 78
77 79 ## server/routes/files.js
78 80 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -80,6 +82,7 @@
80 82 - loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
81 83 - resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
82 84 - resolveRootForUser(absPath, roots, user, config) - Allows admins to access orphaned user folders (deleted-account folders) under userPath.
85 - resolveRootForUser(absPath, roots, user, config) - Treats the local subtitle debug log directory as an admin-only read-only browse root for the debug menu.
83 86 - canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
84 87 - checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
85 88 - POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
@@ -180,6 +183,7 @@
180 183 - Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
181 184 - Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
182 185 - Debug dashboard modal - Shows active signed-in users, total/per-root storage usage, active stream footprint, cached subtitle usage by video, and orphaned stream output directories.
186 - Debug dashboard modal - Also exposes the subtitle debug cache folder with an open-folder action for admins.
183 187 - Debug dashboard modal - Each diagnostics sub-panel includes a copy action for quick report sharing: users/storage copy JSON, stream/cache and orphaned output tables copy CSV.
184 188 - Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
185 189 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
@@ -193,6 +197,7 @@
193 197 - saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
194 198 - loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
195 199 - api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
200 - renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
196 201 - performLogout() - Explicit logout path that revokes server session and clears local session state.
197 202 - initAuth() - Restores prior session when valid and auto-logins without credential prompt.
198 203 - showConfirm(title, message, { html, okLabel, modalClass }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data), `okLabel` overrides the OK button text, and `modalClass` temporarily widens/restyles the dialog for rich content.
@@ -11,6 +11,7 @@
11
11
12## server/subtitle-debug-log.js
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.
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- getSubtitleDebugLogSnapshot() - Reports the subtitle log cache directory path, existence, file count, byte total, and latest file so the debug dashboard can expose it as a folder.
14- pruneSubtitleDebugLogDir() - Enforces the 10 MB total subtitle-log cache budget by deleting the oldest log files first.
15- 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- subtitleDebugLogFilePath(videoName, timestampMs) - Resolves the per-day subtitle timing log path for a video name using a filesystem-safe filename.
16
17
@@ -73,6 +74,7 @@
73## server/routes/debug.js
74## server/routes/debug.js
74- GET /api/admin/debug/stream-stats - Computes debug dashboard data by combining auth_sessions activity, root disk usage scans, stream snapshot data, and subtitle cache snapshot data into a per-video view for leak/performance monitoring.
75- GET /api/admin/debug/stream-stats - Computes debug dashboard data by combining auth_sessions activity, root disk usage scans, stream snapshot data, and subtitle cache snapshot data into a per-video view for leak/performance monitoring.
75- GET /api/admin/debug/stream-stats - Also reports host/process memory ({total, free, used, usedPercent, processRssBytes, processHeapUsedBytes}) so streaming lag can be correlated with RAM pressure.
76- GET /api/admin/debug/stream-stats - Also reports host/process memory ({total, free, used, usedPercent, processRssBytes, processHeapUsedBytes}) so streaming lag can be correlated with RAM pressure.
77- GET /api/admin/debug/stream-stats - Also reports the subtitle debug cache directory metadata so admins can open the local subtitle log folder from the debug dashboard.
76
78
77## server/routes/files.js
79## server/routes/files.js
78- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
80- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -80,6 +82,7 @@
80- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
82- loadConfigAndRoots() - Loads config and effective roots together so route access checks stay consistent.
81- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
83- resolveRootForUser(absPath, roots, user, config) - Resolves access for configured roots plus user-owned personal folder.
82- resolveRootForUser(absPath, roots, user, config) - Allows admins to access orphaned user folders (deleted-account folders) under userPath.
84- resolveRootForUser(absPath, roots, user, config) - Allows admins to access orphaned user folders (deleted-account folders) under userPath.
85- resolveRootForUser(absPath, roots, user, config) - Treats the local subtitle debug log directory as an admin-only read-only browse root for the debug menu.
83- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
86- canReadInfo(user, info) / canWriteInfo(user, info) - Permission checks that automatically allow access for personal user-folder roots.
84- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
87- checkUserFolderSizeLimit(config, username, addedBytes) - Validates a user-folder capacity limit against current usage.
85- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
88- POST /api/files/root-alias - Sets a display-only alias for an exact configured root path (no filesystem rename).
@@ -180,6 +183,7 @@
180- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
183- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
181- Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
184- Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
182- Debug dashboard modal - Shows active signed-in users, total/per-root storage usage, active stream footprint, cached subtitle usage by video, and orphaned stream output directories.
185- Debug dashboard modal - Shows active signed-in users, total/per-root storage usage, active stream footprint, cached subtitle usage by video, and orphaned stream output directories.
186- Debug dashboard modal - Also exposes the subtitle debug cache folder with an open-folder action for admins.
183- Debug dashboard modal - Each diagnostics sub-panel includes a copy action for quick report sharing: users/storage copy JSON, stream/cache and orphaned output tables copy CSV.
187- Debug dashboard modal - Each diagnostics sub-panel includes a copy action for quick report sharing: users/storage copy JSON, stream/cache and orphaned output tables copy CSV.
184- Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
188- Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
185- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
189- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
@@ -193,6 +197,7 @@
193- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
197- saveSessionState() - Persists token, selected path, and last operation timestamp in localStorage.
194- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
198- loadSessionState() - Restores persisted state only when the last operation is within the 1-hour local idle window.
195- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
199- api(method, path, body, opts) - Central API caller; refreshes local session timestamp on successful authenticated calls.
200- renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
196- performLogout() - Explicit logout path that revokes server session and clears local session state.
201- performLogout() - Explicit logout path that revokes server session and clears local session state.
197- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
202- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
198- showConfirm(title, message, { html, okLabel, modalClass }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data), `okLabel` overrides the OK button text, and `modalClass` temporarily widens/restyles the dialog for rich content.
203- showConfirm(title, message, { html, okLabel, modalClass }) - In-page confirm dialog; returns Promise<boolean>. `html=true` renders message as innerHTML (caller must escape user data), `okLabel` overrides the OK button text, and `modalClass` temporarily widens/restyles the dialog for rich content.
.github/tests.md +1 −0
@@ -47,6 +47,7 @@
47 47 - `GET /api/files/thumbnail`
48 48 - `GET /api/files/root-access`
49 49 - `orphaned user folder access`
50 - `subtitle debug cache access`
50 51 - `folder icon endpoints`
51 52 - `file search endpoint`
52 53 - `image search endpoint`
@@ -47,6 +47,7 @@
47- `GET /api/files/thumbnail`
47- `GET /api/files/thumbnail`
48- `GET /api/files/root-access`
48- `GET /api/files/root-access`
49- `orphaned user folder access`
49- `orphaned user folder access`
50- `subtitle debug cache access`
50- `folder icon endpoints`
51- `folder icon endpoints`
51- `file search endpoint`
52- `file search endpoint`
52- `image search endpoint`
53- `image search endpoint`
public/app.js +50 −0
@@ -5283,6 +5283,28 @@ function renderDebugDashboardData (data)
5283 5283 ],
5284 5284 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5285 5285 );
5286
5287 const subtitleSection = document.getElementById('debug-subtitle-log-section');
5288 const subtitlePath = document.getElementById('debug-subtitle-log-path');
5289 const subtitleMeta = document.getElementById('debug-subtitle-log-meta');
5290 const subtitleOpen = document.getElementById('debug-open-subtitle-log-folder');
5291 const subtitleLog = data.subtitleDebugLog || {};
5292
5293 if (subtitleSection && subtitlePath && subtitleMeta && subtitleOpen)
5294 {
5295 if (!subtitleLog.exists)
5296 {
5297 subtitleSection.classList.add('hidden');
5298 } else
5299 {
5300 subtitleSection.classList.remove('hidden');
5301 subtitlePath.textContent = subtitleLog.path || 'Unknown path';
5302 const fileCount = Number(subtitleLog.files || 0);
5303 subtitleMeta.textContent = `${fileCount} log file${fileCount === 1 ? '' : 's'} · ${formatBytes(subtitleLog.bytes || 0)}`;
5304 subtitleOpen.dataset.subtitleLogPath = subtitleLog.path || '';
5305 subtitleOpen.disabled = !subtitleLog.path;
5306 }
5307 }
5286 5308 }
5287 5309
5288 5310 function csvEscape (value)
@@ -5394,6 +5416,29 @@ function copyDebugOrphanedCsv ()
5394 5416 void copyDebugText(csv, 'Copied orphaned output CSV.');
5395 5417 }
5396 5418
5419 async function openSubtitleDebugLogFolder ()
5420 {
5421 const button = document.getElementById('debug-open-subtitle-log-folder');
5422 const targetPath = String(button && button.dataset && button.dataset.subtitleLogPath || '').trim();
5423 if (!targetPath) return;
5424
5425 try
5426 {
5427 await navigateTo(targetPath, {
5428 label: 'Subtitle Logs',
5429 originalName: 'Subtitle Logs',
5430 alias: null,
5431 path: targetPath,
5432 isUserFolder: false,
5433 isDebugLogFolder: true,
5434 });
5435 closeDebugModal();
5436 } catch (err)
5437 {
5438 toast(err.message || 'Failed to open subtitle log folder.', 'err');
5439 }
5440 }
5441
5397 5442 async function refreshDebugDashboard ()
5398 5443 {
5399 5444 const data = await api('GET', '/admin/debug/stream-stats');
@@ -6689,6 +6734,11 @@ function wireEvents ()
6689 6734 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
6690 6735 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
6691 6736 if (debugCopyOrphaned) debugCopyOrphaned.addEventListener('click', copyDebugOrphanedCsv);
6737 const debugOpenSubtitleLog = document.getElementById('debug-open-subtitle-log-folder');
6738 if (debugOpenSubtitleLog) debugOpenSubtitleLog.addEventListener('click', () =>
6739 {
6740 void openSubtitleDebugLogFolder();
6741 });
6692 6742 const debugModal = document.getElementById('debug-modal');
6693 6743 if (debugModal) debugModal.addEventListener('click', (e) =>
6694 6744 {
@@ -5283,6 +5283,28 @@ function renderDebugDashboardData (data)
5283 ],
5283 ],
5284 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5284 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5285 );
5285 );
5286
5287 const subtitleSection = document.getElementById('debug-subtitle-log-section');
5288 const subtitlePath = document.getElementById('debug-subtitle-log-path');
5289 const subtitleMeta = document.getElementById('debug-subtitle-log-meta');
5290 const subtitleOpen = document.getElementById('debug-open-subtitle-log-folder');
5291 const subtitleLog = data.subtitleDebugLog || {};
5292
5293 if (subtitleSection && subtitlePath && subtitleMeta && subtitleOpen)
5294 {
5295 if (!subtitleLog.exists)
5296 {
5297 subtitleSection.classList.add('hidden');
5298 } else
5299 {
5300 subtitleSection.classList.remove('hidden');
5301 subtitlePath.textContent = subtitleLog.path || 'Unknown path';
5302 const fileCount = Number(subtitleLog.files || 0);
5303 subtitleMeta.textContent = `${fileCount} log file${fileCount === 1 ? '' : 's'} · ${formatBytes(subtitleLog.bytes || 0)}`;
5304 subtitleOpen.dataset.subtitleLogPath = subtitleLog.path || '';
5305 subtitleOpen.disabled = !subtitleLog.path;
5306 }
5307 }
5286}
5308}
5287
5309
5288function csvEscape (value)
5310function csvEscape (value)
@@ -5394,6 +5416,29 @@ function copyDebugOrphanedCsv ()
5394 void copyDebugText(csv, 'Copied orphaned output CSV.');
5416 void copyDebugText(csv, 'Copied orphaned output CSV.');
5395}
5417}
5396
5418
5419async function openSubtitleDebugLogFolder ()
5420{
5421 const button = document.getElementById('debug-open-subtitle-log-folder');
5422 const targetPath = String(button && button.dataset && button.dataset.subtitleLogPath || '').trim();
5423 if (!targetPath) return;
5424
5425 try
5426 {
5427 await navigateTo(targetPath, {
5428 label: 'Subtitle Logs',
5429 originalName: 'Subtitle Logs',
5430 alias: null,
5431 path: targetPath,
5432 isUserFolder: false,
5433 isDebugLogFolder: true,
5434 });
5435 closeDebugModal();
5436 } catch (err)
5437 {
5438 toast(err.message || 'Failed to open subtitle log folder.', 'err');
5439 }
5440}
5441
5397async function refreshDebugDashboard ()
5442async function refreshDebugDashboard ()
5398{
5443{
5399 const data = await api('GET', '/admin/debug/stream-stats');
5444 const data = await api('GET', '/admin/debug/stream-stats');
@@ -6689,6 +6734,11 @@ function wireEvents ()
6689 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
6734 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
6690 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
6735 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
6691 if (debugCopyOrphaned) debugCopyOrphaned.addEventListener('click', copyDebugOrphanedCsv);
6736 if (debugCopyOrphaned) debugCopyOrphaned.addEventListener('click', copyDebugOrphanedCsv);
6737 const debugOpenSubtitleLog = document.getElementById('debug-open-subtitle-log-folder');
6738 if (debugOpenSubtitleLog) debugOpenSubtitleLog.addEventListener('click', () =>
6739 {
6740 void openSubtitleDebugLogFolder();
6741 });
6692 const debugModal = document.getElementById('debug-modal');
6742 const debugModal = document.getElementById('debug-modal');
6693 if (debugModal) debugModal.addEventListener('click', (e) =>
6743 if (debugModal) debugModal.addEventListener('click', (e) =>
6694 {
6744 {
public/index.html +9 −0
@@ -275,6 +275,15 @@
275 275 </div>
276 276 <div id="debug-orphaned-streams" class="debug-table-wrap"></div>
277 277 </section>
278
279 <section id="debug-subtitle-log-section" class="hidden">
280 <div class="debug-section-head">
281 <h3>Subtitle Debug Cache</h3>
282 <button id="debug-open-subtitle-log-folder" class="debug-copy-btn" type="button">Open folder</button>
283 </div>
284 <p id="debug-subtitle-log-meta" class="muted"></p>
285 <p class="muted"><span id="debug-subtitle-log-path" class="debug-path"></span></p>
286 </section>
278 287 </div>
279 288 </div>
280 289
@@ -275,6 +275,15 @@
275 </div>
275 </div>
276 <div id="debug-orphaned-streams" class="debug-table-wrap"></div>
276 <div id="debug-orphaned-streams" class="debug-table-wrap"></div>
277 </section>
277 </section>
278
279 <section id="debug-subtitle-log-section" class="hidden">
280 <div class="debug-section-head">
281 <h3>Subtitle Debug Cache</h3>
282 <button id="debug-open-subtitle-log-folder" class="debug-copy-btn" type="button">Open folder</button>
283 </div>
284 <p id="debug-subtitle-log-meta" class="muted"></p>
285 <p class="muted"><span id="debug-subtitle-log-path" class="debug-path"></span></p>
286 </section>
278 </div>
287 </div>
279 </div>
288 </div>
280
289
server/routes/debug.js +3 −0
@@ -11,6 +11,7 @@ const { getDb } = require('../db');
11 11 const { loadConfig, getEffectivePaths } = require('../config');
12 12 const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
13 13 const { getVideoStreamDebugSnapshot } = require('../video-stream');
14 const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
14 15
15 16 const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
16 17
@@ -204,6 +205,7 @@ router.get('/debug/stream-stats', (req, res) =>
204 205 const loggedInUsers = getLoggedInUsersSnapshot();
205 206 const videoStream = getVideoStreamDebugSnapshot();
206 207 const subtitleCache = getImageSubtitleDebugSnapshot();
208 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
207 209 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
208 210 const memory = getMemorySnapshot();
209 211
@@ -214,6 +216,7 @@ router.get('/debug/stream-stats', (req, res) =>
214 216 memory,
215 217 videoStream,
216 218 subtitleCache,
219 subtitleDebugLog,
217 220 videoFiles,
218 221 });
219 222 });
@@ -11,6 +11,7 @@ const { getDb } = require('../db');
11const { loadConfig, getEffectivePaths } = require('../config');
11const { loadConfig, getEffectivePaths } = require('../config');
12const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
12const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
13const { getVideoStreamDebugSnapshot } = require('../video-stream');
13const { getVideoStreamDebugSnapshot } = require('../video-stream');
14const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
14
15
15const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
16const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
16
17
@@ -204,6 +205,7 @@ router.get('/debug/stream-stats', (req, res) =>
204 const loggedInUsers = getLoggedInUsersSnapshot();
205 const loggedInUsers = getLoggedInUsersSnapshot();
205 const videoStream = getVideoStreamDebugSnapshot();
206 const videoStream = getVideoStreamDebugSnapshot();
206 const subtitleCache = getImageSubtitleDebugSnapshot();
207 const subtitleCache = getImageSubtitleDebugSnapshot();
208 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
207 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
209 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
208 const memory = getMemorySnapshot();
210 const memory = getMemorySnapshot();
209
211
@@ -214,6 +216,7 @@ router.get('/debug/stream-stats', (req, res) =>
214 memory,
216 memory,
215 videoStream,
217 videoStream,
216 subtitleCache,
218 subtitleCache,
219 subtitleDebugLog,
217 videoFiles,
220 videoFiles,
218 });
221 });
219});
222});
server/routes/files.js +14 −2
@@ -13,7 +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 const { appendSubtitleDebugEntries, SUBTITLE_DEBUG_LOG_DIR } = require('../subtitle-debug-log');
17 17 const { buildZip } = require('./share');
18 18 const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
19 19
@@ -559,6 +559,16 @@ function existingUsernamesLowerSet ()
559 559 */
560 560 function resolveRootForUser (absPath, roots, user, config)
561 561 {
562 if (user && user.isAdmin && pathInsideResolved(absPath, SUBTITLE_DEBUG_LOG_DIR))
563 {
564 return {
565 root: SUBTITLE_DEBUG_LOG_DIR,
566 label: 'Subtitle Logs',
567 isUserFolder: false,
568 isDebugLogFolder: true,
569 };
570 }
571
562 572 // Regular configured roots first.
563 573 const matched = getAllowedRoot(absPath, roots);
564 574 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
@@ -612,6 +622,7 @@ function canReadInfo (user, info)
612 622 if (!info) return false;
613 623 if (info.isUserFolder) return true; // owner always has full access
614 624 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
625 if (info.isDebugLogFolder) return !!(user && user.isAdmin);
615 626 return canRead(user, info.label);
616 627 }
617 628
@@ -623,6 +634,7 @@ function canWriteInfo (user, info)
623 634 if (!info) return false;
624 635 if (info.isUserFolder) return true;
625 636 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
637 if (info.isDebugLogFolder) return false;
626 638 return canWrite(user, info.label);
627 639 }
628 640
@@ -680,7 +692,7 @@ function sameResolvedPath (a, b)
680 692 function pathInsideResolved (child, root)
681 693 {
682 694 const relative = path.relative(path.resolve(root), path.resolve(child));
683 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
695 return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
684 696 }
685 697
686 698 function uploadedAtFromStat (stat)
@@ -13,7 +13,7 @@ const { requireAuth } = require('../auth');
13const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
13const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14const { logError } = require('../logger');
14const { logError } = require('../logger');
15const { renderImageSubtitleFrame } = require('../image-subtitles');
15const { renderImageSubtitleFrame } = require('../image-subtitles');
16const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
16const { appendSubtitleDebugEntries, SUBTITLE_DEBUG_LOG_DIR } = require('../subtitle-debug-log');
17const { buildZip } = require('./share');
17const { buildZip } = require('./share');
18const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
18const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
19
19
@@ -559,6 +559,16 @@ function existingUsernamesLowerSet ()
559 */
559 */
560function resolveRootForUser (absPath, roots, user, config)
560function resolveRootForUser (absPath, roots, user, config)
561{
561{
562 if (user && user.isAdmin && pathInsideResolved(absPath, SUBTITLE_DEBUG_LOG_DIR))
563 {
564 return {
565 root: SUBTITLE_DEBUG_LOG_DIR,
566 label: 'Subtitle Logs',
567 isUserFolder: false,
568 isDebugLogFolder: true,
569 };
570 }
571
562 // Regular configured roots first.
572 // Regular configured roots first.
563 const matched = getAllowedRoot(absPath, roots);
573 const matched = getAllowedRoot(absPath, roots);
564 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
574 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
@@ -612,6 +622,7 @@ function canReadInfo (user, info)
612 if (!info) return false;
622 if (!info) return false;
613 if (info.isUserFolder) return true; // owner always has full access
623 if (info.isUserFolder) return true; // owner always has full access
614 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
624 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
625 if (info.isDebugLogFolder) return !!(user && user.isAdmin);
615 return canRead(user, info.label);
626 return canRead(user, info.label);
616}
627}
617
628
@@ -623,6 +634,7 @@ function canWriteInfo (user, info)
623 if (!info) return false;
634 if (!info) return false;
624 if (info.isUserFolder) return true;
635 if (info.isUserFolder) return true;
625 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
636 if (info.isOrphanUserFolder) return !!(user && user.isAdmin);
637 if (info.isDebugLogFolder) return false;
626 return canWrite(user, info.label);
638 return canWrite(user, info.label);
627}
639}
628
640
@@ -680,7 +692,7 @@ function sameResolvedPath (a, b)
680function pathInsideResolved (child, root)
692function pathInsideResolved (child, root)
681{
693{
682 const relative = path.relative(path.resolve(root), path.resolve(child));
694 const relative = path.relative(path.resolve(root), path.resolve(child));
683 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
695 return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
684}
696}
685
697
686function uploadedAtFromStat (stat)
698function uploadedAtFromStat (stat)
server/subtitle-debug-log.js +16 −0
@@ -71,6 +71,21 @@ function directoryEntriesWithStats (dirPath)
71 71 return out;
72 72 }
73 73
74 function getSubtitleDebugLogSnapshot ()
75 {
76 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR);
77 const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null;
78
79 return {
80 path: SUBTITLE_DEBUG_LOG_DIR,
81 exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR),
82 bytes: entries.reduce((sum, entry) => sum + entry.size, 0),
83 files: entries.length,
84 directories: 0,
85 latestFile,
86 };
87 }
88
74 89 function pruneSubtitleDebugLogDir ()
75 90 {
76 91 ensureSubtitleDebugLogDir();
@@ -121,6 +136,7 @@ function appendSubtitleDebugEntries ({ videoName, entries, context = null })
121 136 module.exports = {
122 137 SUBTITLE_DEBUG_LOG_DIR,
123 138 MAX_SUBTITLE_DEBUG_LOG_BYTES,
139 getSubtitleDebugLogSnapshot,
124 140 subtitleDebugLogFilePath,
125 141 pruneSubtitleDebugLogDir,
126 142 appendSubtitleDebugEntries,
@@ -71,6 +71,21 @@ function directoryEntriesWithStats (dirPath)
71 return out;
71 return out;
72}
72}
73
73
74function getSubtitleDebugLogSnapshot ()
75{
76 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR);
77 const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null;
78
79 return {
80 path: SUBTITLE_DEBUG_LOG_DIR,
81 exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR),
82 bytes: entries.reduce((sum, entry) => sum + entry.size, 0),
83 files: entries.length,
84 directories: 0,
85 latestFile,
86 };
87}
88
74function pruneSubtitleDebugLogDir ()
89function pruneSubtitleDebugLogDir ()
75{
90{
76 ensureSubtitleDebugLogDir();
91 ensureSubtitleDebugLogDir();
@@ -121,6 +136,7 @@ function appendSubtitleDebugEntries ({ videoName, entries, context = null })
121module.exports = {
136module.exports = {
122 SUBTITLE_DEBUG_LOG_DIR,
137 SUBTITLE_DEBUG_LOG_DIR,
123 MAX_SUBTITLE_DEBUG_LOG_BYTES,
138 MAX_SUBTITLE_DEBUG_LOG_BYTES,
139 getSubtitleDebugLogSnapshot,
124 subtitleDebugLogFilePath,
140 subtitleDebugLogFilePath,
125 pruneSubtitleDebugLogDir,
141 pruneSubtitleDebugLogDir,
126 appendSubtitleDebugEntries,
142 appendSubtitleDebugEntries,
tests/admin.routes.test.js +5 −0
@@ -510,6 +510,11 @@ describe('GET /api/admin/debug/stream-stats', () =>
510 510 expect(cachedOnly).toBeTruthy();
511 511 expect(cachedOnly.viewers).toBe(0);
512 512 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
513 expect(body.subtitleDebugLog).toEqual(expect.objectContaining({
514 path: expect.stringContaining('filemanager-subtitle-debug-logs'),
515 files: expect.any(Number),
516 bytes: expect.any(Number),
517 }));
513 518 });
514 519 });
515 520
@@ -510,6 +510,11 @@ describe('GET /api/admin/debug/stream-stats', () =>
510 expect(cachedOnly).toBeTruthy();
510 expect(cachedOnly).toBeTruthy();
511 expect(cachedOnly.viewers).toBe(0);
511 expect(cachedOnly.viewers).toBe(0);
512 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
512 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
513 expect(body.subtitleDebugLog).toEqual(expect.objectContaining({
514 path: expect.stringContaining('filemanager-subtitle-debug-logs'),
515 files: expect.any(Number),
516 bytes: expect.any(Number),
517 }));
513 });
518 });
514});
519});
515
520
tests/files.routes.test.js +52 −0
@@ -21,6 +21,7 @@ let mockVideoStreamAsset = null;
21 21 let releasedVideoStreamSessionId = null;
22 22 let mockSubtitleFrameResult = null;
23 23 let mockSubtitleFrameError = null;
24 const mockSubtitleDebugLogDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
24 25
25 26 jest.mock('../server/db', () =>
26 27 {
@@ -131,6 +132,7 @@ jest.mock('../server/image-subtitles', () => ({
131 132 }));
132 133
133 134 jest.mock('../server/subtitle-debug-log', () => ({
135 SUBTITLE_DEBUG_LOG_DIR: mockSubtitleDebugLogDir,
134 136 appendSubtitleDebugEntries: jest.fn(),
135 137 }));
136 138
@@ -683,6 +685,56 @@ describe('orphaned user folder access', () =>
683 685 });
684 686 });
685 687
688 describe('subtitle debug cache access', () =>
689 {
690 test('admins can browse the subtitle debug cache folder', async () =>
691 {
692 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
693 fs.rmSync(logDir, { recursive: true, force: true });
694 fs.mkdirSync(logDir, { recursive: true });
695 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
696
697 mockUser = {
698 username: 'admin',
699 isAdmin: true,
700 permissions: {},
701 };
702
703 try
704 {
705 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
706 expect(listRes.status).toBe(200);
707 expect(Array.isArray(listRes.body.items)).toBe(true);
708 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
709 } finally
710 {
711 fs.rmSync(logDir, { recursive: true, force: true });
712 }
713 });
714
715 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
716 {
717 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
718 fs.rmSync(logDir, { recursive: true, force: true });
719 fs.mkdirSync(logDir, { recursive: true });
720
721 mockUser = {
722 username: 'alice',
723 isAdmin: false,
724 permissions: {},
725 };
726
727 try
728 {
729 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
730 expect(listRes.status).toBe(403);
731 } finally
732 {
733 fs.rmSync(logDir, { recursive: true, force: true });
734 }
735 });
736 });
737
686 738 describe('folder icon endpoints', () =>
687 739 {
688 740 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
@@ -21,6 +21,7 @@ let mockVideoStreamAsset = null;
21let releasedVideoStreamSessionId = null;
21let releasedVideoStreamSessionId = null;
22let mockSubtitleFrameResult = null;
22let mockSubtitleFrameResult = null;
23let mockSubtitleFrameError = null;
23let mockSubtitleFrameError = null;
24const mockSubtitleDebugLogDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
24
25
25jest.mock('../server/db', () =>
26jest.mock('../server/db', () =>
26{
27{
@@ -131,6 +132,7 @@ jest.mock('../server/image-subtitles', () => ({
131}));
132}));
132
133
133jest.mock('../server/subtitle-debug-log', () => ({
134jest.mock('../server/subtitle-debug-log', () => ({
135 SUBTITLE_DEBUG_LOG_DIR: mockSubtitleDebugLogDir,
134 appendSubtitleDebugEntries: jest.fn(),
136 appendSubtitleDebugEntries: jest.fn(),
135}));
137}));
136
138
@@ -683,6 +685,56 @@ describe('orphaned user folder access', () =>
683 });
685 });
684});
686});
685
687
688describe('subtitle debug cache access', () =>
689{
690 test('admins can browse the subtitle debug cache folder', async () =>
691 {
692 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
693 fs.rmSync(logDir, { recursive: true, force: true });
694 fs.mkdirSync(logDir, { recursive: true });
695 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
696
697 mockUser = {
698 username: 'admin',
699 isAdmin: true,
700 permissions: {},
701 };
702
703 try
704 {
705 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
706 expect(listRes.status).toBe(200);
707 expect(Array.isArray(listRes.body.items)).toBe(true);
708 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
709 } finally
710 {
711 fs.rmSync(logDir, { recursive: true, force: true });
712 }
713 });
714
715 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
716 {
717 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
718 fs.rmSync(logDir, { recursive: true, force: true });
719 fs.mkdirSync(logDir, { recursive: true });
720
721 mockUser = {
722 username: 'alice',
723 isAdmin: false,
724 permissions: {},
725 };
726
727 try
728 {
729 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
730 expect(listRes.status).toBe(403);
731 } finally
732 {
733 fs.rmSync(logDir, { recursive: true, force: true });
734 }
735 });
736});
737
686describe('folder icon endpoints', () =>
738describe('folder icon endpoints', () =>
687{
739{
688 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
740 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>