BlueGit

timfa filemanager

Merge branch 'feat/admin-debug-menu'

timfa Tim Falken · pushed by timfa

Authored 2026-05-20 · 6 months ago

Hash
7be2c78b03644c4091e3407266f520ba3bca7e47
10 files changed +801 −0
.github/technical-reference.md +8 −0
@@ -16,6 +16,7 @@
16 16 - pruneOldImageSubtitleCaches(filePath, slowestViewerTimeSeconds) - Drops subtitle frame caches for events that have passed their retention threshold of end time + event duration + 5 seconds (e.g., event ending at 30s with 10s duration is dropped after slowest viewer reaches 45s); used during segment pruning to keep memory usage bounded on long videos, especially on resource-limited hardware like Raspberry Pi.
17 17 - purgeSubtitleCacheDir() - Removes the entire subtitle `.sup` file cache directory from disk; called once at server startup to clean up any files left over from a previous run.
18 18 - touchCachedEntry(cache, key, ttlMs) - Refreshes the TTL of an existing cache entry without changing its value; used to keep actively-watched subtitle tracks alive past their initial 5-minute TTL and prevent expensive full re-parses during long playback sessions.
19 - getImageSubtitleDebugSnapshot() - Returns event/frame cache totals and per-video cache usage ({event entries/bytes/count, frame entries/bytes}) so admin diagnostics can list cached subtitle data even when no viewer is connected.
19 20 - IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS / IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_FRAME_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES / IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES / IMAGE_SUBTITLE_RENDER_SCALE / IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS - Environment knobs for subtitle cache retention, item caps, byte caps, render resolution, and prune grace window.
20 21
21 22 ## server/thumbnail-cache.js
@@ -62,6 +63,10 @@
62 63 - GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
63 64 - PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
64 65 - GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] } where commitsAhead contains non-merge commits as {hash, subject, body}; detects systemd via INVOCATION_ID env var and runs git fetch + git log against origin/HEAD for Restart & Update messaging.
66 - GET /api/admin/debug/stream-stats - Admin diagnostics payload with active signed-in users, per-root storage usage, active stream HLS footprint, subtitle cache totals, and per-video rows that also include cached-only videos with zero active viewers.
67
68 ## server/routes/debug.js
69 - 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.
65 70
66 71 ## server/routes/files.js
67 72 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -124,6 +129,7 @@
124 129 - sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
125 130 - releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
126 131 - runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks.
132 - getVideoStreamDebugSnapshot() - Returns active stream sessions with viewer counts and output-dir stats (segment counts/bytes), plus orphaned output directories left under the stream root for diagnostics.
127 133 - STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
128 134 - STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
129 135 - STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated (5 minutes).
@@ -146,8 +152,10 @@
146 152 - Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
147 153 - Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
148 154 - User menu - Includes a Change Password action and a dedicated change-password modal with current/new/confirm fields.
155 - User menu - Admin users also get a Debug action that opens a live diagnostics dashboard modal.
149 156 - Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
150 157 - Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
158 - 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.
151 159 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
152 160 - Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
153 161
@@ -16,6 +16,7 @@
16- pruneOldImageSubtitleCaches(filePath, slowestViewerTimeSeconds) - Drops subtitle frame caches for events that have passed their retention threshold of end time + event duration + 5 seconds (e.g., event ending at 30s with 10s duration is dropped after slowest viewer reaches 45s); used during segment pruning to keep memory usage bounded on long videos, especially on resource-limited hardware like Raspberry Pi.
16- pruneOldImageSubtitleCaches(filePath, slowestViewerTimeSeconds) - Drops subtitle frame caches for events that have passed their retention threshold of end time + event duration + 5 seconds (e.g., event ending at 30s with 10s duration is dropped after slowest viewer reaches 45s); used during segment pruning to keep memory usage bounded on long videos, especially on resource-limited hardware like Raspberry Pi.
17- purgeSubtitleCacheDir() - Removes the entire subtitle `.sup` file cache directory from disk; called once at server startup to clean up any files left over from a previous run.
17- purgeSubtitleCacheDir() - Removes the entire subtitle `.sup` file cache directory from disk; called once at server startup to clean up any files left over from a previous run.
18- touchCachedEntry(cache, key, ttlMs) - Refreshes the TTL of an existing cache entry without changing its value; used to keep actively-watched subtitle tracks alive past their initial 5-minute TTL and prevent expensive full re-parses during long playback sessions.
18- touchCachedEntry(cache, key, ttlMs) - Refreshes the TTL of an existing cache entry without changing its value; used to keep actively-watched subtitle tracks alive past their initial 5-minute TTL and prevent expensive full re-parses during long playback sessions.
19- getImageSubtitleDebugSnapshot() - Returns event/frame cache totals and per-video cache usage ({event entries/bytes/count, frame entries/bytes}) so admin diagnostics can list cached subtitle data even when no viewer is connected.
19- IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS / IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_FRAME_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES / IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES / IMAGE_SUBTITLE_RENDER_SCALE / IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS - Environment knobs for subtitle cache retention, item caps, byte caps, render resolution, and prune grace window.
20- IMAGE_SUBTITLE_EVENT_CACHE_TTL_MS / IMAGE_SUBTITLE_FRAME_CACHE_TTL_MS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_FRAME_CACHE_MAX_ITEMS / IMAGE_SUBTITLE_EVENT_CACHE_MAX_BYTES / IMAGE_SUBTITLE_FRAME_CACHE_MAX_BYTES / IMAGE_SUBTITLE_RENDER_SCALE / IMAGE_SUBTITLE_PRUNE_GRACE_SECONDS - Environment knobs for subtitle cache retention, item caps, byte caps, render resolution, and prune grace window.
20
21
21## server/thumbnail-cache.js
22## server/thumbnail-cache.js
@@ -62,6 +63,10 @@
62- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
63- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
63- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
64- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
64- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] } where commitsAhead contains non-merge commits as {hash, subject, body}; detects systemd via INVOCATION_ID env var and runs git fetch + git log against origin/HEAD for Restart & Update messaging.
65- GET /api/admin/update-status - Returns { underSystemd, commitsAhead[] } where commitsAhead contains non-merge commits as {hash, subject, body}; detects systemd via INVOCATION_ID env var and runs git fetch + git log against origin/HEAD for Restart & Update messaging.
66- GET /api/admin/debug/stream-stats - Admin diagnostics payload with active signed-in users, per-root storage usage, active stream HLS footprint, subtitle cache totals, and per-video rows that also include cached-only videos with zero active viewers.
67
68## server/routes/debug.js
69- 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.
65
70
66## server/routes/files.js
71## server/routes/files.js
67- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
72- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -124,6 +129,7 @@
124- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
129- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
125- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
130- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
126- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks.
131- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks.
132- getVideoStreamDebugSnapshot() - Returns active stream sessions with viewer counts and output-dir stats (segment counts/bytes), plus orphaned output directories left under the stream root for diagnostics.
127- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
133- STREAM_ROOT_DIR - Temporary root directory for active ffmpeg-backed stream sessions.
128- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
134- STREAM_SESSION_TTL_MS - Idle lifetime for a stream session before cleanup.
129- STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated (5 minutes).
135- STREAM_IDLE_STOP_MS - Maximum client inactivity window before an active stream session is terminated (5 minutes).
@@ -146,8 +152,10 @@
146- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
152- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
147- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
153- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
148- User menu - Includes a Change Password action and a dedicated change-password modal with current/new/confirm fields.
154- User menu - Includes a Change Password action and a dedicated change-password modal with current/new/confirm fields.
155- User menu - Admin users also get a Debug action that opens a live diagnostics dashboard modal.
149- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
156- Admin panel - Includes an icon-only global favicon button that opens the shared icon picker modal.
150- Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
157- Admin panel - Users section includes a conditional orphaned-user-folders subsection that appears only when non-empty orphan folders exist.
158- 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.
151- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
159- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
152- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
160- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
153
161
.github/tests.md +1 −0
@@ -12,6 +12,7 @@
12 12 - `DELETE /api/admin/users/:id`
13 13 - `GET /api/admin/orphan-userfolders`
14 14 - `GET /api/admin/config`
15 - `GET /api/admin/debug/stream-stats`
15 16 - `PUT /api/admin/config`
16 17 - `POST /api/admin/shutdown`
17 18 - `GET /api/admin/update-status`
@@ -12,6 +12,7 @@
12- `DELETE /api/admin/users/:id`
12- `DELETE /api/admin/users/:id`
13- `GET /api/admin/orphan-userfolders`
13- `GET /api/admin/orphan-userfolders`
14- `GET /api/admin/config`
14- `GET /api/admin/config`
15- `GET /api/admin/debug/stream-stats`
15- `PUT /api/admin/config`
16- `PUT /api/admin/config`
16- `POST /api/admin/shutdown`
17- `POST /api/admin/shutdown`
17- `GET /api/admin/update-status`
18- `GET /api/admin/update-status`
public/app.js +151 −0
@@ -1694,6 +1694,7 @@ async function openShareModal (item)
1694 1694 function showAuthOverlay (setupMode = false)
1695 1695 {
1696 1696 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1697 closeDebugModal();
1697 1698 document.getElementById('app').classList.add('hidden');
1698 1699 const overlay = document.getElementById('auth-overlay');
1699 1700 const usernameInput = document.getElementById('auth-username');
@@ -1726,6 +1727,7 @@ function showApp ()
1726 1727 openFolderSidebar();
1727 1728 }
1728 1729 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1730 document.getElementById('btn-debug').classList.toggle('hidden', !STATE.isAdmin);
1729 1731 const userLabel = document.getElementById('user-menu-label');
1730 1732 if (userLabel) userLabel.textContent = STATE.username || 'User';
1731 1733 void refreshGlobalFavicon();
@@ -5790,6 +5792,141 @@ async function deleteItem (item)
5790 5792 // ───────────────────────────────────────────────────────────────────────────
5791 5793
5792 5794 let _adminUpdateStatus = null;
5795 let _debugRefreshTimer = null;
5796
5797 function formatTimestamp (ms)
5798 {
5799 const value = Number(ms || 0);
5800 if (!Number.isFinite(value) || value <= 0) return '—';
5801 try
5802 {
5803 return new Date(value).toLocaleString();
5804 } catch
5805 {
5806 return '—';
5807 }
5808 }
5809
5810 function renderDebugTable (containerId, columns, rows)
5811 {
5812 const container = document.getElementById(containerId);
5813 if (!container) return;
5814
5815 if (!Array.isArray(rows) || rows.length === 0)
5816 {
5817 container.innerHTML = '<div class="muted" style="padding:0.7rem">No data.</div>';
5818 return;
5819 }
5820
5821 const headHtml = columns.map((col) => `<th>${escapeHtml(col.label)}</th>`).join('');
5822 const bodyHtml = rows.map((row) =>
5823 `<tr>${columns.map((col) => `<td>${col.render(row)}</td>`).join('')}</tr>`).join('');
5824
5825 container.innerHTML = `<table class="debug-table"><thead><tr>${headHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>`;
5826 }
5827
5828 function renderDebugDashboardData (data)
5829 {
5830 const generatedAt = document.getElementById('debug-generated-at');
5831 if (generatedAt) generatedAt.textContent = `Last update: ${formatTimestamp(data.generatedAt)}`;
5832
5833 const usersEl = document.getElementById('debug-users');
5834 if (usersEl)
5835 {
5836 const users = Array.isArray(data.loggedInUsers) ? data.loggedInUsers : [];
5837 usersEl.innerHTML = users.length
5838 ? users.map((user) => `<span class="debug-chip">${escapeHtml(user.username || 'Unknown')} · ${escapeHtml(formatTimestamp(user.lastSeenAt))}</span>`).join('')
5839 : '<span class="muted">No active sessions.</span>';
5840 }
5841
5842 const summary = document.getElementById('debug-storage-summary');
5843 if (summary)
5844 {
5845 const storage = data.storage || {};
5846 const roots = Array.isArray(storage.roots) ? storage.roots.length : 0;
5847 const activeStreams = Number(data.videoStream && data.videoStream.activeSessionCount) || 0;
5848 const activeLeases = Number(data.videoStream && data.videoStream.activeLeaseCount) || 0;
5849 summary.innerHTML = [
5850 ['Configured roots', String(roots)],
5851 ['Total used', formatBytes(storage.totalBytes || 0)],
5852 ['Total files', String(storage.totalFiles || 0)],
5853 ['Active streams', String(activeStreams)],
5854 ['Active viewers', String(activeLeases)],
5855 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5856 }
5857
5858 renderDebugTable(
5859 'debug-roots',
5860 [
5861 { label: 'Root', render: (row) => `<span class="debug-path">${escapeHtml(row.path || '')}</span>` },
5862 { label: 'Exists', render: (row) => row.exists ? 'Yes' : 'No' },
5863 { label: 'Used', render: (row) => escapeHtml(formatBytes(row.bytes || 0)) },
5864 { label: 'Files', render: (row) => escapeHtml(String(row.files || 0)) },
5865 { label: 'Folders', render: (row) => escapeHtml(String(row.directories || 0)) },
5866 ],
5867 Array.isArray(data.storage && data.storage.roots) ? data.storage.roots : [],
5868 );
5869
5870 renderDebugTable(
5871 'debug-video-files',
5872 [
5873 { label: 'Video file', render: (row) => `<span class="debug-path">${escapeHtml(row.filePath || '')}</span>` },
5874 { label: 'Viewers', render: (row) => escapeHtml(String(row.viewers || 0)) },
5875 { label: 'Segments', render: (row) => escapeHtml(String(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0)) },
5876 { label: 'Segment bytes', render: (row) => escapeHtml(formatBytes(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0)) },
5877 { label: 'Event cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.eventEntries : 0)) },
5878 { label: 'Event bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventBytes : 0)) },
5879 { label: 'Event PNG bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0)) },
5880 { label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },
5881 { label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },
5882 { label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },
5883 ],
5884 Array.isArray(data.videoFiles) ? data.videoFiles : [],
5885 );
5886
5887 renderDebugTable(
5888 'debug-orphaned-streams',
5889 [
5890 { label: 'Output directory', render: (row) => `<span class="debug-path">${escapeHtml(row.outputDir || '')}</span>` },
5891 { label: 'Files', render: (row) => escapeHtml(String(row.output && row.output.totalFiles || 0)) },
5892 { label: 'Bytes', render: (row) => escapeHtml(formatBytes(row.output && row.output.totalBytes || 0)) },
5893 { label: 'Segments', render: (row) => escapeHtml(String(row.output && row.output.segmentFiles || 0)) },
5894 ],
5895 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5896 );
5897 }
5898
5899 async function refreshDebugDashboard ()
5900 {
5901 const data = await api('GET', '/admin/debug/stream-stats');
5902 if (!data) return;
5903 renderDebugDashboardData(data);
5904 }
5905
5906 async function openDebugModal ()
5907 {
5908 const modal = document.getElementById('debug-modal');
5909 if (!modal) return;
5910 modal.classList.remove('hidden');
5911 await refreshDebugDashboard();
5912
5913 if (_debugRefreshTimer) clearInterval(_debugRefreshTimer);
5914 _debugRefreshTimer = setInterval(() =>
5915 {
5916 void refreshDebugDashboard();
5917 }, 5000);
5918 }
5919
5920 function closeDebugModal ()
5921 {
5922 const modal = document.getElementById('debug-modal');
5923 if (modal) modal.classList.add('hidden');
5924 if (_debugRefreshTimer)
5925 {
5926 clearInterval(_debugRefreshTimer);
5927 _debugRefreshTimer = null;
5928 }
5929 }
5793 5930
5794 5931 function animateBadgeToTarget (targetEl)
5795 5932 {
@@ -7021,16 +7158,30 @@ function wireEvents ()
7021 7158 document.addEventListener('keydown', (e) =>
7022 7159 {
7023 7160 if (e.key === 'Escape') closeCustomContextMenu();
7161 if (e.key === 'Escape') closeDebugModal();
7024 7162 });
7025 7163
7026 7164 // Admin panel
7027 7165 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
7166 document.getElementById('btn-debug').addEventListener('click', () =>
7167 {
7168 void openDebugModal();
7169 });
7028 7170 document.getElementById('btn-admin-favicon').addEventListener('click', () =>
7029 7171 {
7030 7172 void openGlobalFaviconPicker();
7031 7173 });
7032 7174 document.getElementById('admin-modal-close').addEventListener('click', () =>
7033 7175 document.getElementById('admin-modal').classList.add('hidden'));
7176 document.getElementById('debug-modal-close').addEventListener('click', closeDebugModal);
7177 document.getElementById('debug-refresh').addEventListener('click', () =>
7178 {
7179 void refreshDebugDashboard();
7180 });
7181 document.getElementById('debug-modal').addEventListener('click', (e) =>
7182 {
7183 if (e.target && e.target.id === 'debug-modal') closeDebugModal();
7184 });
7034 7185
7035 7186 // Add path
7036 7187 document.getElementById('admin-add-path').addEventListener('click', () =>
@@ -1694,6 +1694,7 @@ async function openShareModal (item)
1694function showAuthOverlay (setupMode = false)
1694function showAuthOverlay (setupMode = false)
1695{
1695{
1696 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1696 if (typeof document === 'undefined' || typeof document.getElementById !== 'function') return;
1697 closeDebugModal();
1697 document.getElementById('app').classList.add('hidden');
1698 document.getElementById('app').classList.add('hidden');
1698 const overlay = document.getElementById('auth-overlay');
1699 const overlay = document.getElementById('auth-overlay');
1699 const usernameInput = document.getElementById('auth-username');
1700 const usernameInput = document.getElementById('auth-username');
@@ -1726,6 +1727,7 @@ function showApp ()
1726 openFolderSidebar();
1727 openFolderSidebar();
1727 }
1728 }
1728 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1729 document.getElementById('btn-admin').classList.toggle('hidden', !STATE.isAdmin);
1730 document.getElementById('btn-debug').classList.toggle('hidden', !STATE.isAdmin);
1729 const userLabel = document.getElementById('user-menu-label');
1731 const userLabel = document.getElementById('user-menu-label');
1730 if (userLabel) userLabel.textContent = STATE.username || 'User';
1732 if (userLabel) userLabel.textContent = STATE.username || 'User';
1731 void refreshGlobalFavicon();
1733 void refreshGlobalFavicon();
@@ -5790,6 +5792,141 @@ async function deleteItem (item)
5790// ───────────────────────────────────────────────────────────────────────────
5792// ───────────────────────────────────────────────────────────────────────────
5791
5793
5792let _adminUpdateStatus = null;
5794let _adminUpdateStatus = null;
5795let _debugRefreshTimer = null;
5796
5797function formatTimestamp (ms)
5798{
5799 const value = Number(ms || 0);
5800 if (!Number.isFinite(value) || value <= 0) return '—';
5801 try
5802 {
5803 return new Date(value).toLocaleString();
5804 } catch
5805 {
5806 return '—';
5807 }
5808}
5809
5810function renderDebugTable (containerId, columns, rows)
5811{
5812 const container = document.getElementById(containerId);
5813 if (!container) return;
5814
5815 if (!Array.isArray(rows) || rows.length === 0)
5816 {
5817 container.innerHTML = '<div class="muted" style="padding:0.7rem">No data.</div>';
5818 return;
5819 }
5820
5821 const headHtml = columns.map((col) => `<th>${escapeHtml(col.label)}</th>`).join('');
5822 const bodyHtml = rows.map((row) =>
5823 `<tr>${columns.map((col) => `<td>${col.render(row)}</td>`).join('')}</tr>`).join('');
5824
5825 container.innerHTML = `<table class="debug-table"><thead><tr>${headHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>`;
5826}
5827
5828function renderDebugDashboardData (data)
5829{
5830 const generatedAt = document.getElementById('debug-generated-at');
5831 if (generatedAt) generatedAt.textContent = `Last update: ${formatTimestamp(data.generatedAt)}`;
5832
5833 const usersEl = document.getElementById('debug-users');
5834 if (usersEl)
5835 {
5836 const users = Array.isArray(data.loggedInUsers) ? data.loggedInUsers : [];
5837 usersEl.innerHTML = users.length
5838 ? users.map((user) => `<span class="debug-chip">${escapeHtml(user.username || 'Unknown')} · ${escapeHtml(formatTimestamp(user.lastSeenAt))}</span>`).join('')
5839 : '<span class="muted">No active sessions.</span>';
5840 }
5841
5842 const summary = document.getElementById('debug-storage-summary');
5843 if (summary)
5844 {
5845 const storage = data.storage || {};
5846 const roots = Array.isArray(storage.roots) ? storage.roots.length : 0;
5847 const activeStreams = Number(data.videoStream && data.videoStream.activeSessionCount) || 0;
5848 const activeLeases = Number(data.videoStream && data.videoStream.activeLeaseCount) || 0;
5849 summary.innerHTML = [
5850 ['Configured roots', String(roots)],
5851 ['Total used', formatBytes(storage.totalBytes || 0)],
5852 ['Total files', String(storage.totalFiles || 0)],
5853 ['Active streams', String(activeStreams)],
5854 ['Active viewers', String(activeLeases)],
5855 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5856 }
5857
5858 renderDebugTable(
5859 'debug-roots',
5860 [
5861 { label: 'Root', render: (row) => `<span class="debug-path">${escapeHtml(row.path || '')}</span>` },
5862 { label: 'Exists', render: (row) => row.exists ? 'Yes' : 'No' },
5863 { label: 'Used', render: (row) => escapeHtml(formatBytes(row.bytes || 0)) },
5864 { label: 'Files', render: (row) => escapeHtml(String(row.files || 0)) },
5865 { label: 'Folders', render: (row) => escapeHtml(String(row.directories || 0)) },
5866 ],
5867 Array.isArray(data.storage && data.storage.roots) ? data.storage.roots : [],
5868 );
5869
5870 renderDebugTable(
5871 'debug-video-files',
5872 [
5873 { label: 'Video file', render: (row) => `<span class="debug-path">${escapeHtml(row.filePath || '')}</span>` },
5874 { label: 'Viewers', render: (row) => escapeHtml(String(row.viewers || 0)) },
5875 { label: 'Segments', render: (row) => escapeHtml(String(row.stream && row.stream.output ? row.stream.output.segmentFiles : 0)) },
5876 { label: 'Segment bytes', render: (row) => escapeHtml(formatBytes(row.stream && row.stream.output ? row.stream.output.segmentBytes : 0)) },
5877 { label: 'Event cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.eventEntries : 0)) },
5878 { label: 'Event bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventBytes : 0)) },
5879 { label: 'Event PNG bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.eventImageBytes : 0)) },
5880 { label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },
5881 { label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },
5882 { label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },
5883 ],
5884 Array.isArray(data.videoFiles) ? data.videoFiles : [],
5885 );
5886
5887 renderDebugTable(
5888 'debug-orphaned-streams',
5889 [
5890 { label: 'Output directory', render: (row) => `<span class="debug-path">${escapeHtml(row.outputDir || '')}</span>` },
5891 { label: 'Files', render: (row) => escapeHtml(String(row.output && row.output.totalFiles || 0)) },
5892 { label: 'Bytes', render: (row) => escapeHtml(formatBytes(row.output && row.output.totalBytes || 0)) },
5893 { label: 'Segments', render: (row) => escapeHtml(String(row.output && row.output.segmentFiles || 0)) },
5894 ],
5895 Array.isArray(data.videoStream && data.videoStream.orphanedOutputDirs) ? data.videoStream.orphanedOutputDirs : [],
5896 );
5897}
5898
5899async function refreshDebugDashboard ()
5900{
5901 const data = await api('GET', '/admin/debug/stream-stats');
5902 if (!data) return;
5903 renderDebugDashboardData(data);
5904}
5905
5906async function openDebugModal ()
5907{
5908 const modal = document.getElementById('debug-modal');
5909 if (!modal) return;
5910 modal.classList.remove('hidden');
5911 await refreshDebugDashboard();
5912
5913 if (_debugRefreshTimer) clearInterval(_debugRefreshTimer);
5914 _debugRefreshTimer = setInterval(() =>
5915 {
5916 void refreshDebugDashboard();
5917 }, 5000);
5918}
5919
5920function closeDebugModal ()
5921{
5922 const modal = document.getElementById('debug-modal');
5923 if (modal) modal.classList.add('hidden');
5924 if (_debugRefreshTimer)
5925 {
5926 clearInterval(_debugRefreshTimer);
5927 _debugRefreshTimer = null;
5928 }
5929}
5793
5930
5794function animateBadgeToTarget (targetEl)
5931function animateBadgeToTarget (targetEl)
5795{
5932{
@@ -7021,16 +7158,30 @@ function wireEvents ()
7021 document.addEventListener('keydown', (e) =>
7158 document.addEventListener('keydown', (e) =>
7022 {
7159 {
7023 if (e.key === 'Escape') closeCustomContextMenu();
7160 if (e.key === 'Escape') closeCustomContextMenu();
7161 if (e.key === 'Escape') closeDebugModal();
7024 });
7162 });
7025
7163
7026 // Admin panel
7164 // Admin panel
7027 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
7165 document.getElementById('btn-admin').addEventListener('click', openAdminModal);
7166 document.getElementById('btn-debug').addEventListener('click', () =>
7167 {
7168 void openDebugModal();
7169 });
7028 document.getElementById('btn-admin-favicon').addEventListener('click', () =>
7170 document.getElementById('btn-admin-favicon').addEventListener('click', () =>
7029 {
7171 {
7030 void openGlobalFaviconPicker();
7172 void openGlobalFaviconPicker();
7031 });
7173 });
7032 document.getElementById('admin-modal-close').addEventListener('click', () =>
7174 document.getElementById('admin-modal-close').addEventListener('click', () =>
7033 document.getElementById('admin-modal').classList.add('hidden'));
7175 document.getElementById('admin-modal').classList.add('hidden'));
7176 document.getElementById('debug-modal-close').addEventListener('click', closeDebugModal);
7177 document.getElementById('debug-refresh').addEventListener('click', () =>
7178 {
7179 void refreshDebugDashboard();
7180 });
7181 document.getElementById('debug-modal').addEventListener('click', (e) =>
7182 {
7183 if (e.target && e.target.id === 'debug-modal') closeDebugModal();
7184 });
7034
7185
7035 // Add path
7186 // Add path
7036 document.getElementById('admin-add-path').addEventListener('click', () =>
7187 document.getElementById('admin-add-path').addEventListener('click', () =>
public/index.html +46 −0
@@ -106,6 +106,16 @@
106 106 </svg>
107 107 Admin
108 108 </button>
109 <button id="btn-debug" class="topbar-menu-item hidden" type="button" role="menuitem" title="Debug dashboard"
110 aria-label="Debug dashboard">
111 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
112 stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
113 <rect x="3" y="4" width="18" height="12" rx="2" ry="2" />
114 <line x1="8" y1="20" x2="16" y2="20" />
115 <line x1="12" y1="16" x2="12" y2="20" />
116 </svg>
117 Debug
118 </button>
109 119 <button id="btn-change-password" class="topbar-menu-item" type="button" role="menuitem" title="Change Password"
110 120 aria-label="Change Password">
111 121 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
@@ -220,6 +230,42 @@
220 230 </div>
221 231 </div>
222 232
233 <!-- DEBUG MODAL -->
234 <div id="debug-modal" class="modal-overlay hidden">
235 <div class="modal debug-modal">
236 <button class="modal-close" id="debug-modal-close" aria-label="Close debug dashboard">✕</button>
237 <h2>Debug Dashboard</h2>
238 <p class="muted">Live diagnostics for active streams, cache usage and signed-in users.</p>
239
240 <div class="debug-toolbar">
241 <span id="debug-generated-at" class="muted">Last update: —</span>
242 <button id="debug-refresh" class="primary" type="button">Refresh</button>
243 </div>
244
245 <section>
246 <h3>Signed-in Users</h3>
247 <div id="debug-users" class="debug-chips"></div>
248 </section>
249
250 <section>
251 <h3>Storage Usage</h3>
252 <div id="debug-storage-summary" class="debug-summary-grid"></div>
253 <div id="debug-roots" class="debug-table-wrap"></div>
254 </section>
255
256 <section>
257 <h3>Video Streams and Caches</h3>
258 <p class="muted">Includes files with cached subtitle data even if no viewers are currently watching.</p>
259 <div id="debug-video-files" class="debug-table-wrap"></div>
260 </section>
261
262 <section>
263 <h3>Orphaned Stream Output Directories</h3>
264 <div id="debug-orphaned-streams" class="debug-table-wrap"></div>
265 </section>
266 </div>
267 </div>
268
223 269 <!-- NEW / EDIT USER MODAL -->
224 270 <div id="user-modal" class="modal-overlay hidden">
225 271 <div class="modal">
@@ -106,6 +106,16 @@
106 </svg>
106 </svg>
107 Admin
107 Admin
108 </button>
108 </button>
109 <button id="btn-debug" class="topbar-menu-item hidden" type="button" role="menuitem" title="Debug dashboard"
110 aria-label="Debug dashboard">
111 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
112 stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
113 <rect x="3" y="4" width="18" height="12" rx="2" ry="2" />
114 <line x1="8" y1="20" x2="16" y2="20" />
115 <line x1="12" y1="16" x2="12" y2="20" />
116 </svg>
117 Debug
118 </button>
109 <button id="btn-change-password" class="topbar-menu-item" type="button" role="menuitem" title="Change Password"
119 <button id="btn-change-password" class="topbar-menu-item" type="button" role="menuitem" title="Change Password"
110 aria-label="Change Password">
120 aria-label="Change Password">
111 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
121 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor"
@@ -220,6 +230,42 @@
220 </div>
230 </div>
221 </div>
231 </div>
222
232
233 <!-- DEBUG MODAL -->
234 <div id="debug-modal" class="modal-overlay hidden">
235 <div class="modal debug-modal">
236 <button class="modal-close" id="debug-modal-close" aria-label="Close debug dashboard">✕</button>
237 <h2>Debug Dashboard</h2>
238 <p class="muted">Live diagnostics for active streams, cache usage and signed-in users.</p>
239
240 <div class="debug-toolbar">
241 <span id="debug-generated-at" class="muted">Last update: —</span>
242 <button id="debug-refresh" class="primary" type="button">Refresh</button>
243 </div>
244
245 <section>
246 <h3>Signed-in Users</h3>
247 <div id="debug-users" class="debug-chips"></div>
248 </section>
249
250 <section>
251 <h3>Storage Usage</h3>
252 <div id="debug-storage-summary" class="debug-summary-grid"></div>
253 <div id="debug-roots" class="debug-table-wrap"></div>
254 </section>
255
256 <section>
257 <h3>Video Streams and Caches</h3>
258 <p class="muted">Includes files with cached subtitle data even if no viewers are currently watching.</p>
259 <div id="debug-video-files" class="debug-table-wrap"></div>
260 </section>
261
262 <section>
263 <h3>Orphaned Stream Output Directories</h3>
264 <div id="debug-orphaned-streams" class="debug-table-wrap"></div>
265 </section>
266 </div>
267 </div>
268
223 <!-- NEW / EDIT USER MODAL -->
269 <!-- NEW / EDIT USER MODAL -->
224 <div id="user-modal" class="modal-overlay hidden">
270 <div id="user-modal" class="modal-overlay hidden">
225 <div class="modal">
271 <div class="modal">
public/style.css +91 −0
@@ -981,6 +981,97 @@ button.danger.admin-update-highlight {
981 981 border-color: var(--accent);
982 982 }
983 983
984 .debug-modal {
985 width: min(980px, 96vw);
986 max-height: 92vh;
987 }
988
989 .debug-toolbar {
990 display: flex;
991 justify-content: space-between;
992 align-items: center;
993 gap: 0.8rem;
994 margin: 0.75rem 0 1rem;
995 }
996
997 .debug-summary-grid {
998 display: grid;
999 grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
1000 gap: 0.6rem;
1001 margin-bottom: 0.8rem;
1002 }
1003
1004 .debug-summary-item {
1005 background: var(--bg);
1006 border: 1px solid var(--border);
1007 border-radius: 10px;
1008 padding: 0.55rem 0.7rem;
1009 }
1010
1011 .debug-summary-item .k {
1012 display: block;
1013 color: var(--text-muted);
1014 font-size: 0.82rem;
1015 }
1016
1017 .debug-summary-item .v {
1018 display: block;
1019 color: var(--text);
1020 font-weight: 650;
1021 margin-top: 0.12rem;
1022 }
1023
1024 .debug-chips {
1025 display: flex;
1026 flex-wrap: wrap;
1027 gap: 0.45rem;
1028 }
1029
1030 .debug-chip {
1031 border: 1px solid var(--border);
1032 border-radius: 999px;
1033 padding: 0.22rem 0.6rem;
1034 background: var(--bg);
1035 font-size: 0.82rem;
1036 }
1037
1038 .debug-table-wrap {
1039 border: 1px solid var(--border);
1040 border-radius: 10px;
1041 overflow: auto;
1042 background: var(--bg);
1043 }
1044
1045 .debug-table {
1046 width: 100%;
1047 border-collapse: collapse;
1048 font-size: 0.85rem;
1049 }
1050
1051 .debug-table th,
1052 .debug-table td {
1053 border-bottom: 1px solid var(--border);
1054 text-align: left;
1055 vertical-align: top;
1056 padding: 0.45rem 0.55rem;
1057 }
1058
1059 .debug-table thead th {
1060 position: sticky;
1061 top: 0;
1062 z-index: 1;
1063 background: var(--surface);
1064 }
1065
1066 .debug-table tr:last-child td {
1067 border-bottom: 0;
1068 }
1069
1070 .debug-path {
1071 font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1072 word-break: break-word;
1073 }
1074
984 1075 .folder-icon-cell {
985 1076 display: flex;
986 1077 flex-direction: column;
@@ -981,6 +981,97 @@ button.danger.admin-update-highlight {
981 border-color: var(--accent);
981 border-color: var(--accent);
982}
982}
983
983
984.debug-modal {
985 width: min(980px, 96vw);
986 max-height: 92vh;
987}
988
989.debug-toolbar {
990 display: flex;
991 justify-content: space-between;
992 align-items: center;
993 gap: 0.8rem;
994 margin: 0.75rem 0 1rem;
995}
996
997.debug-summary-grid {
998 display: grid;
999 grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
1000 gap: 0.6rem;
1001 margin-bottom: 0.8rem;
1002}
1003
1004.debug-summary-item {
1005 background: var(--bg);
1006 border: 1px solid var(--border);
1007 border-radius: 10px;
1008 padding: 0.55rem 0.7rem;
1009}
1010
1011.debug-summary-item .k {
1012 display: block;
1013 color: var(--text-muted);
1014 font-size: 0.82rem;
1015}
1016
1017.debug-summary-item .v {
1018 display: block;
1019 color: var(--text);
1020 font-weight: 650;
1021 margin-top: 0.12rem;
1022}
1023
1024.debug-chips {
1025 display: flex;
1026 flex-wrap: wrap;
1027 gap: 0.45rem;
1028}
1029
1030.debug-chip {
1031 border: 1px solid var(--border);
1032 border-radius: 999px;
1033 padding: 0.22rem 0.6rem;
1034 background: var(--bg);
1035 font-size: 0.82rem;
1036}
1037
1038.debug-table-wrap {
1039 border: 1px solid var(--border);
1040 border-radius: 10px;
1041 overflow: auto;
1042 background: var(--bg);
1043}
1044
1045.debug-table {
1046 width: 100%;
1047 border-collapse: collapse;
1048 font-size: 0.85rem;
1049}
1050
1051.debug-table th,
1052.debug-table td {
1053 border-bottom: 1px solid var(--border);
1054 text-align: left;
1055 vertical-align: top;
1056 padding: 0.45rem 0.55rem;
1057}
1058
1059.debug-table thead th {
1060 position: sticky;
1061 top: 0;
1062 z-index: 1;
1063 background: var(--surface);
1064}
1065
1066.debug-table tr:last-child td {
1067 border-bottom: 0;
1068}
1069
1070.debug-path {
1071 font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
1072 word-break: break-word;
1073}
1074
984.folder-icon-cell {
1075.folder-icon-cell {
985 display: flex;
1076 display: flex;
986 flex-direction: column;
1077 flex-direction: column;
server/image-subtitles.js +85 −0
@@ -670,10 +670,95 @@ function clearCachesForFile (filePath)
670 670 }
671 671 }
672 672
673 function filePathFromCacheKey (key)
674 {
675 const raw = String(key || '');
676 const divider = raw.indexOf('|');
677 if (divider < 0) return '';
678 return raw.slice(0, divider);
679 }
680
681 function getImageSubtitleDebugSnapshot ()
682 {
683 const byFile = {};
684
685 for (const [key, entry] of eventCache.map.entries())
686 {
687 const filePath = filePathFromCacheKey(key);
688 if (!filePath) continue;
689
690 const row = byFile[filePath] || {
691 filePath,
692 eventEntries: 0,
693 eventBytes: 0,
694 eventCount: 0,
695 eventImageBytes: 0,
696 frameEntries: 0,
697 frameBytes: 0,
698 };
699
700 row.eventEntries += 1;
701 row.eventBytes += Number(entry && entry.sizeBytes) || 0;
702
703 const value = entry && entry.value;
704 if (value && Array.isArray(value.events))
705 {
706 row.eventCount += value.events.length;
707 for (const event of value.events)
708 {
709 if (event && Buffer.isBuffer(event.imagePng))
710 {
711 row.eventImageBytes += event.imagePng.length;
712 }
713 }
714 }
715
716 byFile[filePath] = row;
717 }
718
719 for (const [key, entry] of frameCache.map.entries())
720 {
721 const filePath = filePathFromCacheKey(key);
722 if (!filePath) continue;
723
724 const row = byFile[filePath] || {
725 filePath,
726 eventEntries: 0,
727 eventBytes: 0,
728 eventCount: 0,
729 eventImageBytes: 0,
730 frameEntries: 0,
731 frameBytes: 0,
732 };
733
734 row.frameEntries += 1;
735 row.frameBytes += Number(entry && entry.sizeBytes) || 0;
736
737 byFile[filePath] = row;
738 }
739
740 return {
741 eventCache: {
742 entries: eventCache.map.size,
743 bytes: eventCache.totalBytes,
744 maxItems: eventCache.maxItems,
745 maxBytes: eventCache.maxBytes,
746 },
747 frameCache: {
748 entries: frameCache.map.size,
749 bytes: frameCache.totalBytes,
750 maxItems: frameCache.maxItems,
751 maxBytes: frameCache.maxBytes,
752 },
753 byFile,
754 };
755 }
756
673 757 module.exports = {
674 758 parseRenderOptions,
675 759 renderImageSubtitleFrame,
676 760 clearCachesForFile,
677 761 pruneOldImageSubtitleCaches,
678 762 purgeSubtitleCacheDir,
763 getImageSubtitleDebugSnapshot,
679 764 };
@@ -670,10 +670,95 @@ function clearCachesForFile (filePath)
670 }
670 }
671}
671}
672
672
673function filePathFromCacheKey (key)
674{
675 const raw = String(key || '');
676 const divider = raw.indexOf('|');
677 if (divider < 0) return '';
678 return raw.slice(0, divider);
679}
680
681function getImageSubtitleDebugSnapshot ()
682{
683 const byFile = {};
684
685 for (const [key, entry] of eventCache.map.entries())
686 {
687 const filePath = filePathFromCacheKey(key);
688 if (!filePath) continue;
689
690 const row = byFile[filePath] || {
691 filePath,
692 eventEntries: 0,
693 eventBytes: 0,
694 eventCount: 0,
695 eventImageBytes: 0,
696 frameEntries: 0,
697 frameBytes: 0,
698 };
699
700 row.eventEntries += 1;
701 row.eventBytes += Number(entry && entry.sizeBytes) || 0;
702
703 const value = entry && entry.value;
704 if (value && Array.isArray(value.events))
705 {
706 row.eventCount += value.events.length;
707 for (const event of value.events)
708 {
709 if (event && Buffer.isBuffer(event.imagePng))
710 {
711 row.eventImageBytes += event.imagePng.length;
712 }
713 }
714 }
715
716 byFile[filePath] = row;
717 }
718
719 for (const [key, entry] of frameCache.map.entries())
720 {
721 const filePath = filePathFromCacheKey(key);
722 if (!filePath) continue;
723
724 const row = byFile[filePath] || {
725 filePath,
726 eventEntries: 0,
727 eventBytes: 0,
728 eventCount: 0,
729 eventImageBytes: 0,
730 frameEntries: 0,
731 frameBytes: 0,
732 };
733
734 row.frameEntries += 1;
735 row.frameBytes += Number(entry && entry.sizeBytes) || 0;
736
737 byFile[filePath] = row;
738 }
739
740 return {
741 eventCache: {
742 entries: eventCache.map.size,
743 bytes: eventCache.totalBytes,
744 maxItems: eventCache.maxItems,
745 maxBytes: eventCache.maxBytes,
746 },
747 frameCache: {
748 entries: frameCache.map.size,
749 bytes: frameCache.totalBytes,
750 maxItems: frameCache.maxItems,
751 maxBytes: frameCache.maxBytes,
752 },
753 byFile,
754 };
755}
756
673module.exports = {
757module.exports = {
674 parseRenderOptions,
758 parseRenderOptions,
675 renderImageSubtitleFrame,
759 renderImageSubtitleFrame,
676 clearCachesForFile,
760 clearCachesForFile,
677 pruneOldImageSubtitleCaches,
761 pruneOldImageSubtitleCaches,
678 purgeSubtitleCacheDir,
762 purgeSubtitleCacheDir,
763 getImageSubtitleDebugSnapshot,
679};
764};
server/routes/admin.js +2 −0
@@ -45,6 +45,7 @@ function ensureUserFolders (userPath)
45 45 const { getDb } = require('../db');
46 46 const { requireAuth, requireAdmin } = require('../auth');
47 47 const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48 const debugRouter = require('./debug');
48 49
49 50 const BCRYPT_ROUNDS = 12;
50 51
@@ -141,6 +142,7 @@ function listOrphanUserFolders (userFolderRoot, options = {})
141 142
142 143 // All admin routes require authentication + admin privilege
143 144 router.use(requireAuth, requireAdmin);
145 router.use(debugRouter);
144 146
145 147 // ---------------------------------------------------------------------------
146 148 // GET /api/admin/users
@@ -45,6 +45,7 @@ function ensureUserFolders (userPath)
45const { getDb } = require('../db');
45const { getDb } = require('../db');
46const { requireAuth, requireAdmin } = require('../auth');
46const { requireAuth, requireAdmin } = require('../auth');
47const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
47const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48const debugRouter = require('./debug');
48
49
49const BCRYPT_ROUNDS = 12;
50const BCRYPT_ROUNDS = 12;
50
51
@@ -141,6 +142,7 @@ function listOrphanUserFolders (userFolderRoot, options = {})
141
142
142// All admin routes require authentication + admin privilege
143// All admin routes require authentication + admin privilege
143router.use(requireAuth, requireAdmin);
144router.use(requireAuth, requireAdmin);
145router.use(debugRouter);
144
146
145// ---------------------------------------------------------------------------
147// ---------------------------------------------------------------------------
146// GET /api/admin/users
148// GET /api/admin/users
server/routes/debug.js added +202 −0
@@ -0,0 +1,202 @@
1 'use strict';
2
3 const express = require('express');
4 const fs = require('fs');
5 const path = require('path');
6
7 const router = express.Router();
8
9 const { getDb } = require('../db');
10 const { loadConfig, getEffectivePaths } = require('../config');
11 const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
12 const { getVideoStreamDebugSnapshot } = require('../video-stream');
13
14 const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
15
16 function safeResolve (value)
17 {
18 return path.resolve(String(value || '').trim());
19 }
20
21 function normaliseRootsForUsage (config)
22 {
23 const rawRoots = Array.isArray(config.paths) ? config.paths : [];
24 const effective = getEffectivePaths(rawRoots);
25 const roots = new Set(effective.map((root) => safeResolve(root)));
26
27 const userPath = String(config.userPath || '').trim();
28 if (userPath)
29 {
30 const resolvedUserPath = safeResolve(userPath);
31 const isCovered = [...roots].some((root) =>
32 resolvedUserPath === root || resolvedUserPath.startsWith(`${root}${path.sep}`));
33 if (!isCovered) roots.add(resolvedUserPath);
34 }
35
36 return [...roots];
37 }
38
39 function walkDirectorySize (rootPath)
40 {
41 let bytes = 0;
42 let files = 0;
43 let directories = 0;
44 const stack = [rootPath];
45
46 while (stack.length > 0)
47 {
48 const current = stack.pop();
49 let entries = [];
50 try
51 {
52 entries = fs.readdirSync(current, { withFileTypes: true });
53 } catch
54 {
55 continue;
56 }
57
58 for (const entry of entries)
59 {
60 const fullPath = path.join(current, entry.name);
61 if (entry.isDirectory())
62 {
63 directories += 1;
64 stack.push(fullPath);
65 continue;
66 }
67
68 if (!entry.isFile()) continue;
69 try
70 {
71 const stat = fs.statSync(fullPath);
72 bytes += Number.isFinite(stat.size) ? stat.size : 0;
73 files += 1;
74 } catch
75 {
76 // Best effort; skip unreadable files.
77 }
78 }
79 }
80
81 return { bytes, files, directories };
82 }
83
84 function collectRootUsageStats ()
85 {
86 const config = loadConfig();
87 const roots = normaliseRootsForUsage(config);
88
89 const perRoot = [];
90 let totalBytes = 0;
91 let totalFiles = 0;
92
93 for (const root of roots)
94 {
95 const row = {
96 path: root,
97 exists: fs.existsSync(root),
98 bytes: 0,
99 files: 0,
100 directories: 0,
101 };
102
103 if (row.exists)
104 {
105 const usage = walkDirectorySize(root);
106 row.bytes = usage.bytes;
107 row.files = usage.files;
108 row.directories = usage.directories;
109 totalBytes += usage.bytes;
110 totalFiles += usage.files;
111 }
112
113 perRoot.push(row);
114 }
115
116 return {
117 roots: perRoot,
118 totalBytes,
119 totalFiles,
120 };
121 }
122
123 function getLoggedInUsersSnapshot ()
124 {
125 const db = getDb();
126 const now = Date.now();
127 const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
128
129 const rows = db.prepare(
130 `SELECT username, MAX(last_seen_at) AS lastSeenAt
131 FROM auth_sessions
132 WHERE revoked_at IS NULL
133 AND last_seen_at >= ?
134 GROUP BY username
135 ORDER BY username COLLATE NOCASE ASC`,
136 ).all([activeSince]);
137
138 return rows.map((row) => ({
139 username: String(row.username || ''),
140 lastSeenAt: Number(row.lastSeenAt || 0),
141 }));
142 }
143
144 function buildVideoDebugRows (videoSnapshot, subtitleSnapshot)
145 {
146 const perFile = new Map();
147
148 const activeStreams = Array.isArray(videoSnapshot.activeStreams) ? videoSnapshot.activeStreams : [];
149 for (const stream of activeStreams)
150 {
151 const key = safeResolve(stream.sourcePath);
152 perFile.set(key, {
153 filePath: key,
154 viewers: Number(stream.viewers || 0),
155 activeSessionIds: [stream.sessionId],
156 stream: stream,
157 subtitleCache: null,
158 });
159 }
160
161 const subtitleByFile = subtitleSnapshot && subtitleSnapshot.byFile ? subtitleSnapshot.byFile : {};
162 for (const [filePath, subtitleRow] of Object.entries(subtitleByFile))
163 {
164 const key = safeResolve(filePath);
165 const existing = perFile.get(key);
166 if (existing)
167 {
168 existing.subtitleCache = subtitleRow;
169 continue;
170 }
171
172 perFile.set(key, {
173 filePath: key,
174 viewers: 0,
175 activeSessionIds: [],
176 stream: null,
177 subtitleCache: subtitleRow,
178 });
179 }
180
181 return [...perFile.values()].sort((a, b) => a.filePath.localeCompare(b.filePath));
182 }
183
184 router.get('/debug/stream-stats', (req, res) =>
185 {
186 const rootUsage = collectRootUsageStats();
187 const loggedInUsers = getLoggedInUsersSnapshot();
188 const videoStream = getVideoStreamDebugSnapshot();
189 const subtitleCache = getImageSubtitleDebugSnapshot();
190 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
191
192 res.json({
193 generatedAt: Date.now(),
194 loggedInUsers,
195 storage: rootUsage,
196 videoStream,
197 subtitleCache,
198 videoFiles,
199 });
200 });
201
202 module.exports = router;
@@ -0,0 +1,202 @@
1'use strict';
2
3const express = require('express');
4const fs = require('fs');
5const path = require('path');
6
7const router = express.Router();
8
9const { getDb } = require('../db');
10const { loadConfig, getEffectivePaths } = require('../config');
11const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
12const { getVideoStreamDebugSnapshot } = require('../video-stream');
13
14const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
15
16function safeResolve (value)
17{
18 return path.resolve(String(value || '').trim());
19}
20
21function normaliseRootsForUsage (config)
22{
23 const rawRoots = Array.isArray(config.paths) ? config.paths : [];
24 const effective = getEffectivePaths(rawRoots);
25 const roots = new Set(effective.map((root) => safeResolve(root)));
26
27 const userPath = String(config.userPath || '').trim();
28 if (userPath)
29 {
30 const resolvedUserPath = safeResolve(userPath);
31 const isCovered = [...roots].some((root) =>
32 resolvedUserPath === root || resolvedUserPath.startsWith(`${root}${path.sep}`));
33 if (!isCovered) roots.add(resolvedUserPath);
34 }
35
36 return [...roots];
37}
38
39function walkDirectorySize (rootPath)
40{
41 let bytes = 0;
42 let files = 0;
43 let directories = 0;
44 const stack = [rootPath];
45
46 while (stack.length > 0)
47 {
48 const current = stack.pop();
49 let entries = [];
50 try
51 {
52 entries = fs.readdirSync(current, { withFileTypes: true });
53 } catch
54 {
55 continue;
56 }
57
58 for (const entry of entries)
59 {
60 const fullPath = path.join(current, entry.name);
61 if (entry.isDirectory())
62 {
63 directories += 1;
64 stack.push(fullPath);
65 continue;
66 }
67
68 if (!entry.isFile()) continue;
69 try
70 {
71 const stat = fs.statSync(fullPath);
72 bytes += Number.isFinite(stat.size) ? stat.size : 0;
73 files += 1;
74 } catch
75 {
76 // Best effort; skip unreadable files.
77 }
78 }
79 }
80
81 return { bytes, files, directories };
82}
83
84function collectRootUsageStats ()
85{
86 const config = loadConfig();
87 const roots = normaliseRootsForUsage(config);
88
89 const perRoot = [];
90 let totalBytes = 0;
91 let totalFiles = 0;
92
93 for (const root of roots)
94 {
95 const row = {
96 path: root,
97 exists: fs.existsSync(root),
98 bytes: 0,
99 files: 0,
100 directories: 0,
101 };
102
103 if (row.exists)
104 {
105 const usage = walkDirectorySize(root);
106 row.bytes = usage.bytes;
107 row.files = usage.files;
108 row.directories = usage.directories;
109 totalBytes += usage.bytes;
110 totalFiles += usage.files;
111 }
112
113 perRoot.push(row);
114 }
115
116 return {
117 roots: perRoot,
118 totalBytes,
119 totalFiles,
120 };
121}
122
123function getLoggedInUsersSnapshot ()
124{
125 const db = getDb();
126 const now = Date.now();
127 const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
128
129 const rows = db.prepare(
130 `SELECT username, MAX(last_seen_at) AS lastSeenAt
131 FROM auth_sessions
132 WHERE revoked_at IS NULL
133 AND last_seen_at >= ?
134 GROUP BY username
135 ORDER BY username COLLATE NOCASE ASC`,
136 ).all([activeSince]);
137
138 return rows.map((row) => ({
139 username: String(row.username || ''),
140 lastSeenAt: Number(row.lastSeenAt || 0),
141 }));
142}
143
144function buildVideoDebugRows (videoSnapshot, subtitleSnapshot)
145{
146 const perFile = new Map();
147
148 const activeStreams = Array.isArray(videoSnapshot.activeStreams) ? videoSnapshot.activeStreams : [];
149 for (const stream of activeStreams)
150 {
151 const key = safeResolve(stream.sourcePath);
152 perFile.set(key, {
153 filePath: key,
154 viewers: Number(stream.viewers || 0),
155 activeSessionIds: [stream.sessionId],
156 stream: stream,
157 subtitleCache: null,
158 });
159 }
160
161 const subtitleByFile = subtitleSnapshot && subtitleSnapshot.byFile ? subtitleSnapshot.byFile : {};
162 for (const [filePath, subtitleRow] of Object.entries(subtitleByFile))
163 {
164 const key = safeResolve(filePath);
165 const existing = perFile.get(key);
166 if (existing)
167 {
168 existing.subtitleCache = subtitleRow;
169 continue;
170 }
171
172 perFile.set(key, {
173 filePath: key,
174 viewers: 0,
175 activeSessionIds: [],
176 stream: null,
177 subtitleCache: subtitleRow,
178 });
179 }
180
181 return [...perFile.values()].sort((a, b) => a.filePath.localeCompare(b.filePath));
182}
183
184router.get('/debug/stream-stats', (req, res) =>
185{
186 const rootUsage = collectRootUsageStats();
187 const loggedInUsers = getLoggedInUsersSnapshot();
188 const videoStream = getVideoStreamDebugSnapshot();
189 const subtitleCache = getImageSubtitleDebugSnapshot();
190 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
191
192 res.json({
193 generatedAt: Date.now(),
194 loggedInUsers,
195 storage: rootUsage,
196 videoStream,
197 subtitleCache,
198 videoFiles,
199 });
200});
201
202module.exports = router;
server/video-stream.js +111 −0
@@ -1058,6 +1058,116 @@ function releaseVideoStreamSession (sessionId)
1058 1058 return true;
1059 1059 }
1060 1060
1061 function collectOutputDirStats (outputDir)
1062 {
1063 const stats = {
1064 exists: false,
1065 totalBytes: 0,
1066 totalFiles: 0,
1067 segmentFiles: 0,
1068 segmentBytes: 0,
1069 playlistFiles: 0,
1070 subtitleFiles: 0,
1071 };
1072
1073 if (!outputDir || !fs.existsSync(outputDir)) return stats;
1074 stats.exists = true;
1075
1076 let entries = [];
1077 try
1078 {
1079 entries = fs.readdirSync(outputDir, { withFileTypes: true });
1080 } catch
1081 {
1082 return stats;
1083 }
1084
1085 for (const entry of entries)
1086 {
1087 if (!entry.isFile()) continue;
1088 const name = entry.name;
1089 const fullPath = path.join(outputDir, name);
1090 let size = 0;
1091 try
1092 {
1093 const fileStat = fs.statSync(fullPath);
1094 size = Number(fileStat.size) || 0;
1095 } catch
1096 {
1097 size = 0;
1098 }
1099
1100 stats.totalFiles += 1;
1101 stats.totalBytes += size;
1102
1103 if (/\.ts$/i.test(name))
1104 {
1105 stats.segmentFiles += 1;
1106 stats.segmentBytes += size;
1107 continue;
1108 }
1109
1110 if (/\.m3u8$/i.test(name))
1111 {
1112 stats.playlistFiles += 1;
1113 continue;
1114 }
1115
1116 if (/\.(sup|vtt)$/i.test(name))
1117 {
1118 stats.subtitleFiles += 1;
1119 }
1120 }
1121
1122 return stats;
1123 }
1124
1125 function getVideoStreamDebugSnapshot ()
1126 {
1127 const activeStreams = [];
1128
1129 for (const [sessionId, session] of sessions.entries())
1130 {
1131 activeStreams.push({
1132 sessionId,
1133 sourcePath: session.sourcePath,
1134 outputDir: session.outputDir,
1135 viewers: session.leaseIds ? session.leaseIds.size : 0,
1136 activeRequests: Number(session.activeRequests || 0),
1137 expiresAt: Number(session.expiresAt || 0),
1138 output: collectOutputDirStats(session.outputDir),
1139 });
1140 }
1141
1142 const knownSessionDirs = new Set(activeStreams.map((stream) => path.resolve(stream.outputDir || '')));
1143 const orphanedOutputDirs = [];
1144 try
1145 {
1146 const entries = fs.readdirSync(STREAM_ROOT_DIR, { withFileTypes: true });
1147 for (const entry of entries)
1148 {
1149 if (!entry.isDirectory()) continue;
1150 const dirPath = path.resolve(path.join(STREAM_ROOT_DIR, entry.name));
1151 if (knownSessionDirs.has(dirPath)) continue;
1152 orphanedOutputDirs.push({
1153 outputDir: dirPath,
1154 output: collectOutputDirStats(dirPath),
1155 });
1156 }
1157 } catch
1158 {
1159 // Stream root may not exist yet.
1160 }
1161
1162 return {
1163 streamRootDir: STREAM_ROOT_DIR,
1164 activeSessionCount: sessions.size,
1165 activeLeaseCount: leases.size,
1166 activeStreams,
1167 orphanedOutputDirs,
1168 };
1169 }
1170
1061 1171 module.exports = {
1062 1172 STREAM_ROOT_DIR,
1063 1173 STREAM_SESSION_TTL_MS,
@@ -1066,4 +1176,5 @@ module.exports = {
1066 1176 createVideoStreamSession,
1067 1177 sendVideoStreamAsset,
1068 1178 releaseVideoStreamSession,
1179 getVideoStreamDebugSnapshot,
1069 1180 };
@@ -1058,6 +1058,116 @@ function releaseVideoStreamSession (sessionId)
1058 return true;
1058 return true;
1059}
1059}
1060
1060
1061function collectOutputDirStats (outputDir)
1062{
1063 const stats = {
1064 exists: false,
1065 totalBytes: 0,
1066 totalFiles: 0,
1067 segmentFiles: 0,
1068 segmentBytes: 0,
1069 playlistFiles: 0,
1070 subtitleFiles: 0,
1071 };
1072
1073 if (!outputDir || !fs.existsSync(outputDir)) return stats;
1074 stats.exists = true;
1075
1076 let entries = [];
1077 try
1078 {
1079 entries = fs.readdirSync(outputDir, { withFileTypes: true });
1080 } catch
1081 {
1082 return stats;
1083 }
1084
1085 for (const entry of entries)
1086 {
1087 if (!entry.isFile()) continue;
1088 const name = entry.name;
1089 const fullPath = path.join(outputDir, name);
1090 let size = 0;
1091 try
1092 {
1093 const fileStat = fs.statSync(fullPath);
1094 size = Number(fileStat.size) || 0;
1095 } catch
1096 {
1097 size = 0;
1098 }
1099
1100 stats.totalFiles += 1;
1101 stats.totalBytes += size;
1102
1103 if (/\.ts$/i.test(name))
1104 {
1105 stats.segmentFiles += 1;
1106 stats.segmentBytes += size;
1107 continue;
1108 }
1109
1110 if (/\.m3u8$/i.test(name))
1111 {
1112 stats.playlistFiles += 1;
1113 continue;
1114 }
1115
1116 if (/\.(sup|vtt)$/i.test(name))
1117 {
1118 stats.subtitleFiles += 1;
1119 }
1120 }
1121
1122 return stats;
1123}
1124
1125function getVideoStreamDebugSnapshot ()
1126{
1127 const activeStreams = [];
1128
1129 for (const [sessionId, session] of sessions.entries())
1130 {
1131 activeStreams.push({
1132 sessionId,
1133 sourcePath: session.sourcePath,
1134 outputDir: session.outputDir,
1135 viewers: session.leaseIds ? session.leaseIds.size : 0,
1136 activeRequests: Number(session.activeRequests || 0),
1137 expiresAt: Number(session.expiresAt || 0),
1138 output: collectOutputDirStats(session.outputDir),
1139 });
1140 }
1141
1142 const knownSessionDirs = new Set(activeStreams.map((stream) => path.resolve(stream.outputDir || '')));
1143 const orphanedOutputDirs = [];
1144 try
1145 {
1146 const entries = fs.readdirSync(STREAM_ROOT_DIR, { withFileTypes: true });
1147 for (const entry of entries)
1148 {
1149 if (!entry.isDirectory()) continue;
1150 const dirPath = path.resolve(path.join(STREAM_ROOT_DIR, entry.name));
1151 if (knownSessionDirs.has(dirPath)) continue;
1152 orphanedOutputDirs.push({
1153 outputDir: dirPath,
1154 output: collectOutputDirStats(dirPath),
1155 });
1156 }
1157 } catch
1158 {
1159 // Stream root may not exist yet.
1160 }
1161
1162 return {
1163 streamRootDir: STREAM_ROOT_DIR,
1164 activeSessionCount: sessions.size,
1165 activeLeaseCount: leases.size,
1166 activeStreams,
1167 orphanedOutputDirs,
1168 };
1169}
1170
1061module.exports = {
1171module.exports = {
1062 STREAM_ROOT_DIR,
1172 STREAM_ROOT_DIR,
1063 STREAM_SESSION_TTL_MS,
1173 STREAM_SESSION_TTL_MS,
@@ -1066,4 +1176,5 @@ module.exports = {
1066 createVideoStreamSession,
1176 createVideoStreamSession,
1067 sendVideoStreamAsset,
1177 sendVideoStreamAsset,
1068 releaseVideoStreamSession,
1178 releaseVideoStreamSession,
1179 getVideoStreamDebugSnapshot,
1069};
1180};
tests/admin.routes.test.js +104 −0
@@ -12,6 +12,20 @@ const fs = require('fs');
12 12 const os = require('os');
13 13 const path = require('path');
14 14
15 let mockVideoStreamSnapshot = {
16 streamRootDir: '/tmp/filemanager-video-streams',
17 activeSessionCount: 0,
18 activeLeaseCount: 0,
19 activeStreams: [],
20 orphanedOutputDirs: [],
21 };
22
23 let mockSubtitleSnapshot = {
24 eventCache: { entries: 0, bytes: 0, maxItems: 3, maxBytes: 0 },
25 frameCache: { entries: 0, bytes: 0, maxItems: 50, maxBytes: 0 },
26 byFile: {},
27 };
28
15 29 // ── child_process mock — controlled per test ──────────────────────────────────
16 30 let mockExecFileImpl = null;
17 31 jest.mock('child_process', () =>
@@ -56,6 +70,16 @@ jest.mock('../server/db', () =>
56 70 uploader TEXT NOT NULL DEFAULT '',
57 71 downloaders TEXT NOT NULL DEFAULT '[]'
58 72 );
73 CREATE TABLE IF NOT EXISTS auth_sessions (
74 session_id TEXT PRIMARY KEY,
75 username TEXT NOT NULL,
76 ip TEXT NOT NULL,
77 region TEXT NOT NULL,
78 fp_hash TEXT NOT NULL,
79 created_at INTEGER NOT NULL,
80 last_seen_at INTEGER NOT NULL,
81 revoked_at INTEGER
82 );
59 83 `);
60 84 }
61 85 return db;
@@ -63,6 +87,14 @@ jest.mock('../server/db', () =>
63 87 return { getDb, initDb: getDb };
64 88 });
65 89
90 jest.mock('../server/video-stream', () => ({
91 getVideoStreamDebugSnapshot: () => mockVideoStreamSnapshot,
92 }));
93
94 jest.mock('../server/image-subtitles', () => ({
95 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
96 }));
97
66 98 // ── config mock ─────────────────────────────────────────────────────────────
67 99 const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
68 100 jest.mock('../server/config', () => ({
@@ -409,6 +441,78 @@ describe('GET /api/admin/config', () =>
409 441 });
410 442 });
411 443
444 describe('GET /api/admin/debug/stream-stats', () =>
445 {
446 test('includes active streams and cached-only video files with zero viewers', async () =>
447 {
448 const now = Date.now();
449 mockVideoStreamSnapshot = {
450 streamRootDir: '/tmp/filemanager-video-streams',
451 activeSessionCount: 1,
452 activeLeaseCount: 2,
453 activeStreams: [
454 {
455 sessionId: 'lease-live',
456 sourcePath: '/videos/live.mkv',
457 outputDir: '/tmp/filemanager-video-streams/live',
458 viewers: 2,
459 output: {
460 totalFiles: 12,
461 totalBytes: 12000000,
462 segmentFiles: 10,
463 segmentBytes: 11000000,
464 },
465 },
466 ],
467 orphanedOutputDirs: [],
468 };
469
470 mockSubtitleSnapshot = {
471 eventCache: { entries: 2, bytes: 4096, maxItems: 3, maxBytes: 52428800 },
472 frameCache: { entries: 4, bytes: 8192, maxItems: 50, maxBytes: 50331648 },
473 byFile: {
474 '/videos/live.mkv': {
475 filePath: '/videos/live.mkv',
476 eventEntries: 1,
477 eventBytes: 2048,
478 eventCount: 30,
479 eventImageBytes: 1500,
480 frameEntries: 2,
481 frameBytes: 4096,
482 },
483 '/videos/cached-only.mkv': {
484 filePath: '/videos/cached-only.mkv',
485 eventEntries: 1,
486 eventBytes: 2048,
487 eventCount: 20,
488 eventImageBytes: 1300,
489 frameEntries: 2,
490 frameBytes: 4096,
491 },
492 },
493 };
494
495 const db = getDb();
496 db.prepare(`INSERT OR REPLACE INTO auth_sessions (
497 session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at
498 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
499 .run(['sess-debug', 'admin', '127.0.0.1', 'EU', 'fp', now - 1000, now - 1000, null]);
500
501 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
502 expect(status).toBe(200);
503 expect(Array.isArray(body.videoFiles)).toBe(true);
504
505 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
506 expect(live).toBeTruthy();
507 expect(live.viewers).toBe(2);
508
509 const cachedOnly = body.videoFiles.find((row) => row.filePath === '/videos/cached-only.mkv');
510 expect(cachedOnly).toBeTruthy();
511 expect(cachedOnly.viewers).toBe(0);
512 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
513 });
514 });
515
412 516 describe('PUT /api/admin/config', () =>
413 517 {
414 518 test('saves new paths', async () =>
@@ -12,6 +12,20 @@ const fs = require('fs');
12const os = require('os');
12const os = require('os');
13const path = require('path');
13const path = require('path');
14
14
15let mockVideoStreamSnapshot = {
16 streamRootDir: '/tmp/filemanager-video-streams',
17 activeSessionCount: 0,
18 activeLeaseCount: 0,
19 activeStreams: [],
20 orphanedOutputDirs: [],
21};
22
23let mockSubtitleSnapshot = {
24 eventCache: { entries: 0, bytes: 0, maxItems: 3, maxBytes: 0 },
25 frameCache: { entries: 0, bytes: 0, maxItems: 50, maxBytes: 0 },
26 byFile: {},
27};
28
15// ── child_process mock — controlled per test ──────────────────────────────────
29// ── child_process mock — controlled per test ──────────────────────────────────
16let mockExecFileImpl = null;
30let mockExecFileImpl = null;
17jest.mock('child_process', () =>
31jest.mock('child_process', () =>
@@ -56,6 +70,16 @@ jest.mock('../server/db', () =>
56 uploader TEXT NOT NULL DEFAULT '',
70 uploader TEXT NOT NULL DEFAULT '',
57 downloaders TEXT NOT NULL DEFAULT '[]'
71 downloaders TEXT NOT NULL DEFAULT '[]'
58 );
72 );
73 CREATE TABLE IF NOT EXISTS auth_sessions (
74 session_id TEXT PRIMARY KEY,
75 username TEXT NOT NULL,
76 ip TEXT NOT NULL,
77 region TEXT NOT NULL,
78 fp_hash TEXT NOT NULL,
79 created_at INTEGER NOT NULL,
80 last_seen_at INTEGER NOT NULL,
81 revoked_at INTEGER
82 );
59 `);
83 `);
60 }
84 }
61 return db;
85 return db;
@@ -63,6 +87,14 @@ jest.mock('../server/db', () =>
63 return { getDb, initDb: getDb };
87 return { getDb, initDb: getDb };
64});
88});
65
89
90jest.mock('../server/video-stream', () => ({
91 getVideoStreamDebugSnapshot: () => mockVideoStreamSnapshot,
92}));
93
94jest.mock('../server/image-subtitles', () => ({
95 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
96}));
97
66// ── config mock ─────────────────────────────────────────────────────────────
98// ── config mock ─────────────────────────────────────────────────────────────
67const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
99const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
68jest.mock('../server/config', () => ({
100jest.mock('../server/config', () => ({
@@ -409,6 +441,78 @@ describe('GET /api/admin/config', () =>
409 });
441 });
410});
442});
411
443
444describe('GET /api/admin/debug/stream-stats', () =>
445{
446 test('includes active streams and cached-only video files with zero viewers', async () =>
447 {
448 const now = Date.now();
449 mockVideoStreamSnapshot = {
450 streamRootDir: '/tmp/filemanager-video-streams',
451 activeSessionCount: 1,
452 activeLeaseCount: 2,
453 activeStreams: [
454 {
455 sessionId: 'lease-live',
456 sourcePath: '/videos/live.mkv',
457 outputDir: '/tmp/filemanager-video-streams/live',
458 viewers: 2,
459 output: {
460 totalFiles: 12,
461 totalBytes: 12000000,
462 segmentFiles: 10,
463 segmentBytes: 11000000,
464 },
465 },
466 ],
467 orphanedOutputDirs: [],
468 };
469
470 mockSubtitleSnapshot = {
471 eventCache: { entries: 2, bytes: 4096, maxItems: 3, maxBytes: 52428800 },
472 frameCache: { entries: 4, bytes: 8192, maxItems: 50, maxBytes: 50331648 },
473 byFile: {
474 '/videos/live.mkv': {
475 filePath: '/videos/live.mkv',
476 eventEntries: 1,
477 eventBytes: 2048,
478 eventCount: 30,
479 eventImageBytes: 1500,
480 frameEntries: 2,
481 frameBytes: 4096,
482 },
483 '/videos/cached-only.mkv': {
484 filePath: '/videos/cached-only.mkv',
485 eventEntries: 1,
486 eventBytes: 2048,
487 eventCount: 20,
488 eventImageBytes: 1300,
489 frameEntries: 2,
490 frameBytes: 4096,
491 },
492 },
493 };
494
495 const db = getDb();
496 db.prepare(`INSERT OR REPLACE INTO auth_sessions (
497 session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at
498 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`)
499 .run(['sess-debug', 'admin', '127.0.0.1', 'EU', 'fp', now - 1000, now - 1000, null]);
500
501 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
502 expect(status).toBe(200);
503 expect(Array.isArray(body.videoFiles)).toBe(true);
504
505 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
506 expect(live).toBeTruthy();
507 expect(live.viewers).toBe(2);
508
509 const cachedOnly = body.videoFiles.find((row) => row.filePath === '/videos/cached-only.mkv');
510 expect(cachedOnly).toBeTruthy();
511 expect(cachedOnly.viewers).toBe(0);
512 expect(cachedOnly.subtitleCache.eventEntries).toBe(1);
513 });
514});
515
412describe('PUT /api/admin/config', () =>
516describe('PUT /api/admin/config', () =>
413{
517{
414 test('saves new paths', async () =>
518 test('saves new paths', async () =>