BlueGit

timfa filemanager

Merge feat/scheduled-restart-debug-metrics

timfa Tim Falken · pushed by timfa

Authored 2026-05-27 · 5 months ago

Hash
d9552cc6666bb3822b782681dd0c3dbf7647bf5b
12 files changed +818 −8
.github/technical-reference.md +18 −0
@@ -9,9 +9,16 @@
9 9 - start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
10 10 - shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
11 11 - start()/shutdown() - Also starts/stops background auth-session and share-token maintenance loops so stale DB rows and zip cache files are trimmed during long uptime.
12 - start()/shutdown() - Also starts/stops the scheduled-restart coordinator, which can trigger a graceful process shutdown (for systemd restart) after scheduled windows and idle-client checks pass.
12 13 - Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
13 14 - GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
14 15
16 ## server/restart-scheduler.js
17 - startRestartScheduler({ shutdownForRestart }) - Starts a minute-based scheduler that reads persistent restart cadence/time config and triggers shutdown-for-restart only when running under systemd.
18 - Scheduled restart idle guard - After a scheduled window is reached, restart is delayed until there have been no logged-in clients (non-revoked auth sessions) for at least one hour.
19 - getRestartSchedulerSnapshot() - Returns runtime scheduler state (next due timestamp, pending state, last decision/error) for the debug dashboard.
20 - stopRestartScheduler() - Stops the scheduler interval on process shutdown.
21
15 22 ## server/logger.js
16 23 - logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
17 24
@@ -57,6 +64,7 @@
57 64 - purgeStaleSessions({ nowMs }) - Physically deletes stale `auth_sessions` rows: revoked sessions older than 24 hours and idle sessions older than idle-timeout + 24 hours.
58 65 - startAuthSessionCleanupLoop() - Starts a 15-minute background purge loop for stale `auth_sessions` rows and runs one purge immediately on startup.
59 66 - stopAuthSessionCleanupLoop() - Stops the background auth-session purge loop during server shutdown.
67 - getAuthSessionCleanupSnapshot() - Returns auth-session cleanup loop runtime diagnostics (last run time, purged row count, duration, last error).
60 68 - getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
61 69 - getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
62 70 - SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
@@ -77,9 +85,12 @@
77 85 - GET /api/admin/orphan-userfolders - Returns non-empty user folders under userPath that no longer match any account, and auto-deletes empty orphan folders.
78 86 - DELETE /api/admin/users/:id - Also removes the deleted user's personal folder when it exists and is empty.
79 87 - normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
88 - normaliseScheduledRestartConfig(value, fallback) - Validates/normalises persistent scheduled restart settings ({enabled, cadence, time}) for admin config reads/writes.
80 89 - ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
81 90 - GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
91 - GET /api/admin/config - Also returns persistent scheduled restart settings ({enabled, cadence, time}).
82 92 - PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
93 - PUT /api/admin/config - Validates and saves scheduled restart settings globally (`scheduledRestart`); rejects schedule updates when the process is not running under systemd.
83 94 - 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.
84 95 - 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.
85 96
@@ -87,6 +98,7 @@
87 98 - 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.
88 99 - 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.
89 100 - 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.
101 - GET /api/admin/debug/stream-stats - Also reports server maintenance diagnostics: auth/share row counts, auth/share cleanup loop snapshots, and scheduled-restart runtime state.
90 102
91 103 ## server/routes/files.js
92 104 - GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -156,6 +168,7 @@
156 168 - purgeExpiredShareTokens({ nowMs }) - Deletes expired `share_tokens` rows so old public links do not accumulate in SQLite.
157 169 - startShareMaintenanceLoop() / stopShareMaintenanceLoop() - Runs periodic share maintenance every 30 minutes: purge expired share tokens and prune stale zip-cache files; started/stopped from server lifecycle.
158 170 - runShareMaintenanceOnce() - Single-run helper used at startup and by the periodic share maintenance interval.
171 - getShareMaintenanceSnapshot() - Returns share-maintenance loop diagnostics (last run time, deleted token/zip counts, duration, last error).
159 172 - ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
160 173
161 174 ## server/video-stream.js
@@ -215,7 +228,9 @@
215 228 - Debug dashboard modal - Also exposes the subtitle debug cache folder with an open-folder action for admins.
216 229 - 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.
217 230 - Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
231 - Debug dashboard modal - Includes a server-maintenance section with auth/share row counts, maintenance loop last-run telemetry, and scheduled-restart state.
218 232 - Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
233 - Admin modal - Server section includes persistent scheduled-restart controls (enable toggle, cadence, time); controls are disabled when not running under systemd.
219 234 - Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
220 235
221 236 ## public/app.js
@@ -230,6 +245,7 @@
230 245 - Browser popstate navigation - Maintains an in-app folder navigation array mirrored to History API state; browser back/forward steps through folder history.
231 246 - onBrowserPopState(event) - When history reaches browse index 0, shows: "Do you want to close the application and return to the previous webpage?" and on Yes runs normal browser back navigation.
232 247 - renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
248 - renderDebugDashboardData(data) - Also renders server-maintenance diagnostics (auth/share row totals, maintenance loop last-run telemetry, scheduled restart status/timing).
233 249 - performLogout() - Explicit logout path that revokes server session and clears local session state.
234 250 - initAuth() - Restores prior session when valid and auto-logins without credential prompt.
235 251 - 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.
@@ -265,6 +281,8 @@
265 281 - openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
266 282 - refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
267 283 - refreshAdminOrphanUserFolders() - Fetches `/admin/orphan-userfolders`, conditionally renders orphaned folder rows, and wires "Open folder" navigation for admins.
284 - syncScheduledRestartControls(underSystemd) - Enables/disables admin scheduled-restart controls based on systemd availability and the local enable-toggle state.
285 - refreshAdminConfig() / refreshAdminUpdateStatus() - Populate scheduled-restart form values from persisted config and enforce systemd-only control availability.
268 286 - openAdminModal() / refreshAdminConfig() / refreshAdminUsers() / refreshAdminOrphanUserFolders() - Admin modal refresh chain now captures stable DOM references and exits safely when the document is torn down, preventing async teardown races from throwing post-close errors in tests or quick navigation flows.
269 287 - refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
270 288 - disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
@@ -9,9 +9,16 @@
9- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
9- start() - Initialises DB/keys, starts HTTP/HTTPS servers, and starts the background thumbnail cache loop.
10- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
10- shutdown(opts, ...servers) - Graceful teardown: stops thumbnail loop, closes DB/servers, exits with configurable code after drain/timeout.
11- start()/shutdown() - Also starts/stops background auth-session and share-token maintenance loops so stale DB rows and zip cache files are trimmed during long uptime.
11- start()/shutdown() - Also starts/stops background auth-session and share-token maintenance loops so stale DB rows and zip cache files are trimmed during long uptime.
12- start()/shutdown() - Also starts/stops the scheduled-restart coordinator, which can trigger a graceful process shutdown (for systemd restart) after scheduled windows and idle-client checks pass.
12- Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
13- Express error handler - Logs uncaught route errors to logs.txt before returning a JSON 500 response.
13- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
14- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
14
15
16## server/restart-scheduler.js
17- startRestartScheduler({ shutdownForRestart }) - Starts a minute-based scheduler that reads persistent restart cadence/time config and triggers shutdown-for-restart only when running under systemd.
18- Scheduled restart idle guard - After a scheduled window is reached, restart is delayed until there have been no logged-in clients (non-revoked auth sessions) for at least one hour.
19- getRestartSchedulerSnapshot() - Returns runtime scheduler state (next due timestamp, pending state, last decision/error) for the debug dashboard.
20- stopRestartScheduler() - Stops the scheduler interval on process shutdown.
21
15## server/logger.js
22## server/logger.js
16- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
23- logError(message, error, details) - Appends error lines to logs.txt, trimming old lines so the file stays under 1 MB; use for route failures and process-level exceptions.
17
24
@@ -57,6 +64,7 @@
57- purgeStaleSessions({ nowMs }) - Physically deletes stale `auth_sessions` rows: revoked sessions older than 24 hours and idle sessions older than idle-timeout + 24 hours.
64- purgeStaleSessions({ nowMs }) - Physically deletes stale `auth_sessions` rows: revoked sessions older than 24 hours and idle sessions older than idle-timeout + 24 hours.
58- startAuthSessionCleanupLoop() - Starts a 15-minute background purge loop for stale `auth_sessions` rows and runs one purge immediately on startup.
65- startAuthSessionCleanupLoop() - Starts a 15-minute background purge loop for stale `auth_sessions` rows and runs one purge immediately on startup.
59- stopAuthSessionCleanupLoop() - Stops the background auth-session purge loop during server shutdown.
66- stopAuthSessionCleanupLoop() - Stops the background auth-session purge loop during server shutdown.
67- getAuthSessionCleanupSnapshot() - Returns auth-session cleanup loop runtime diagnostics (last run time, purged row count, duration, last error).
60- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
68- getClientIp(req) - Normalizes request IP (including IPv4-mapped IPv6 loopback cases).
61- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
69- getRegion(ip) - Derives coarse region binding from geoip lookup or local fallback.
62- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
70- SESSION_IDLE_TIMEOUT_MS - Server-enforced idle timeout window (1 hour).
@@ -77,9 +85,12 @@
77- GET /api/admin/orphan-userfolders - Returns non-empty user folders under userPath that no longer match any account, and auto-deletes empty orphan folders.
85- GET /api/admin/orphan-userfolders - Returns non-empty user folders under userPath that no longer match any account, and auto-deletes empty orphan folders.
78- DELETE /api/admin/users/:id - Also removes the deleted user's personal folder when it exists and is empty.
86- DELETE /api/admin/users/:id - Also removes the deleted user's personal folder when it exists and is empty.
79- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
87- normalizePermissions(permissions) - Normalizes permission maps and enforces that write access implies read access.
88- normaliseScheduledRestartConfig(value, fallback) - Validates/normalises persistent scheduled restart settings ({enabled, cadence, time}) for admin config reads/writes.
80- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
89- ensureUserFolders(userPath) - Ensures configured userPath exists and creates per-user subfolders for all current users.
81- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
90- GET /api/admin/config - Returns admin config including userPath and userFolderSizeLimit (bytes, null for unlimited).
91- GET /api/admin/config - Also returns persistent scheduled restart settings ({enabled, cadence, time}).
82- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
92- PUT /api/admin/config - Persists paths plus userPath/userFolderSizeLimit and ensures per-user folders exist.
93- PUT /api/admin/config - Validates and saves scheduled restart settings globally (`scheduledRestart`); rejects schedule updates when the process is not running under systemd.
83- 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.
94- 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.
84- 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.
95- 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.
85
96
@@ -87,6 +98,7 @@
87- 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.
98- 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.
88- 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.
99- 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.
89- 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.
100- 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.
101- GET /api/admin/debug/stream-stats - Also reports server maintenance diagnostics: auth/share row counts, auth/share cleanup loop snapshots, and scheduled-restart runtime state.
90
102
91## server/routes/files.js
103## server/routes/files.js
92- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
104- GET /api/files/roots - Returns readable roots with display label (alias when configured), originalName, and path.
@@ -156,6 +168,7 @@
156- purgeExpiredShareTokens({ nowMs }) - Deletes expired `share_tokens` rows so old public links do not accumulate in SQLite.
168- purgeExpiredShareTokens({ nowMs }) - Deletes expired `share_tokens` rows so old public links do not accumulate in SQLite.
157- startShareMaintenanceLoop() / stopShareMaintenanceLoop() - Runs periodic share maintenance every 30 minutes: purge expired share tokens and prune stale zip-cache files; started/stopped from server lifecycle.
169- startShareMaintenanceLoop() / stopShareMaintenanceLoop() - Runs periodic share maintenance every 30 minutes: purge expired share tokens and prune stale zip-cache files; started/stopped from server lifecycle.
158- runShareMaintenanceOnce() - Single-run helper used at startup and by the periodic share maintenance interval.
170- runShareMaintenanceOnce() - Single-run helper used at startup and by the periodic share maintenance interval.
171- getShareMaintenanceSnapshot() - Returns share-maintenance loop diagnostics (last run time, deleted token/zip counts, duration, last error).
159- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
172- ZIP_CACHE_DIR - Absolute path to the zip-cache/ directory (project root).
160
173
161## server/video-stream.js
174## server/video-stream.js
@@ -215,7 +228,9 @@
215- Debug dashboard modal - Also exposes the subtitle debug cache folder with an open-folder action for admins.
228- Debug dashboard modal - Also exposes the subtitle debug cache folder with an open-folder action for admins.
216- 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.
229- 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.
217- Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
230- Debug dashboard modal - Storage cards include RAM usage and process RSS; stream/cache table includes retention and prune progress columns for troubleshooting segment buildup.
231- Debug dashboard modal - Includes a server-maintenance section with auth/share row counts, maintenance loop last-run telemetry, and scheduled-restart state.
218- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
232- Admin modal - Includes User Folders controls (user path + per-user size limit) and a dedicated save action for that config.
233- Admin modal - Server section includes persistent scheduled-restart controls (enable toggle, cadence, time); controls are disabled when not running under systemd.
219- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
234- Import map - Maps `three` and `three/addons/` to local vendored modules for client-side STL/OBJ previews.
220
235
221## public/app.js
236## public/app.js
@@ -230,6 +245,7 @@
230- Browser popstate navigation - Maintains an in-app folder navigation array mirrored to History API state; browser back/forward steps through folder history.
245- Browser popstate navigation - Maintains an in-app folder navigation array mirrored to History API state; browser back/forward steps through folder history.
231- onBrowserPopState(event) - When history reaches browse index 0, shows: "Do you want to close the application and return to the previous webpage?" and on Yes runs normal browser back navigation.
246- onBrowserPopState(event) - When history reaches browse index 0, shows: "Do you want to close the application and return to the previous webpage?" and on Yes runs normal browser back navigation.
232- renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
247- renderDebugDashboardData(data) - Renders the debug dashboard panels, including the subtitle debug cache folder summary and open-folder action.
248- renderDebugDashboardData(data) - Also renders server-maintenance diagnostics (auth/share row totals, maintenance loop last-run telemetry, scheduled restart status/timing).
233- performLogout() - Explicit logout path that revokes server session and clears local session state.
249- performLogout() - Explicit logout path that revokes server session and clears local session state.
234- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
250- initAuth() - Restores prior session when valid and auto-logins without credential prompt.
235- 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.
251- 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.
@@ -265,6 +281,8 @@
265- openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
281- openGlobalFaviconPicker() - Opens a debounced, server-backed image-search modal across all accessible roots and sets/clears global favicon via `/files/global-favicon`.
266- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
282- refreshGlobalFavicon() - Reads `/files/global-favicon`, updates admin-panel favicon preview button, and applies/removes the page `<link rel="icon">` URL.
267- refreshAdminOrphanUserFolders() - Fetches `/admin/orphan-userfolders`, conditionally renders orphaned folder rows, and wires "Open folder" navigation for admins.
283- refreshAdminOrphanUserFolders() - Fetches `/admin/orphan-userfolders`, conditionally renders orphaned folder rows, and wires "Open folder" navigation for admins.
284- syncScheduledRestartControls(underSystemd) - Enables/disables admin scheduled-restart controls based on systemd availability and the local enable-toggle state.
285- refreshAdminConfig() / refreshAdminUpdateStatus() - Populate scheduled-restart form values from persisted config and enforce systemd-only control availability.
268- openAdminModal() / refreshAdminConfig() / refreshAdminUsers() / refreshAdminOrphanUserFolders() - Admin modal refresh chain now captures stable DOM references and exits safely when the document is torn down, preventing async teardown races from throwing post-close errors in tests or quick navigation flows.
286- openAdminModal() / refreshAdminConfig() / refreshAdminUsers() / refreshAdminOrphanUserFolders() - Admin modal refresh chain now captures stable DOM references and exits safely when the document is torn down, preventing async teardown races from throwing post-close errors in tests or quick navigation flows.
269- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
287- refreshAfterIconChange(item) - Resets and reloads the folder icon in both the grid tile and sidebar after set/clear operations.
270- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
288- disconnectFolderIconObserver() - Disconnects and clears the folder icon IntersectionObserver on grid rebuild.
public/app.js +150 −0
@@ -5400,6 +5400,45 @@ async function deleteItem (item)
5400 5400 let _adminUpdateStatus = null;
5401 5401 let _debugRefreshTimer = null;
5402 5402 let _debugLatestData = null;
5403 let _adminConfigCache = null;
5404
5405 function scheduledRestartCadenceLabel (value)
5406 {
5407 const key = String(value || '').trim();
5408 if (key === 'daily') return 'Daily';
5409 if (key === 'every3days') return 'Every 3 days';
5410 if (key === 'weekly') return 'Weekly';
5411 if (key === 'biweekly') return 'Bi-weekly';
5412 if (key === 'monthly') return 'Monthly';
5413 return 'Unknown';
5414 }
5415
5416 function syncScheduledRestartControls (underSystemd)
5417 {
5418 const container = document.getElementById('admin-scheduled-restart');
5419 const enabled = document.getElementById('admin-scheduled-restart-enabled');
5420 const cadence = document.getElementById('admin-scheduled-restart-cadence');
5421 const time = document.getElementById('admin-scheduled-restart-time');
5422 const save = document.getElementById('admin-save-scheduled-restart');
5423 const help = document.getElementById('admin-scheduled-restart-help');
5424 if (!container || !enabled || !cadence || !time || !save || !help) return;
5425
5426 const disabled = !underSystemd;
5427 container.classList.toggle('admin-scheduled-restart--disabled', disabled);
5428
5429 enabled.disabled = disabled;
5430 cadence.disabled = disabled || !enabled.checked;
5431 time.disabled = disabled || !enabled.checked;
5432 save.disabled = disabled;
5433
5434 if (disabled)
5435 {
5436 help.textContent = 'Scheduled restart is available only when the server is started via the systemd service.';
5437 return;
5438 }
5439
5440 help.textContent = 'When the scheduled time is reached, restart waits until there have been no logged-in clients for at least one hour.';
5441 }
5403 5442
5404 5443 function formatTimestamp (ms)
5405 5444 {
@@ -5469,6 +5508,35 @@ function renderDebugDashboardData (data)
5469 5508 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5470 5509 }
5471 5510
5511 const maintenanceSummary = document.getElementById('debug-maintenance-summary');
5512 if (maintenanceSummary)
5513 {
5514 const maintenance = data.maintenance || {};
5515 const rows = maintenance.rows || {};
5516 const authCleanup = maintenance.authCleanup || {};
5517 const shareMaintenance = maintenance.shareMaintenance || {};
5518 const scheduledRestart = maintenance.scheduledRestart || {};
5519
5520 const scheduledLine = !scheduledRestart.underSystemd
5521 ? 'Unavailable (not systemd)'
5522 : !scheduledRestart.config || !scheduledRestart.config.enabled
5523 ? 'Disabled'
5524 : `${scheduledRestartCadenceLabel(scheduledRestart.config.cadence)} at ${scheduledRestart.config.time || '—'}`;
5525
5526 maintenanceSummary.innerHTML = [
5527 ['Auth sessions (total)', String(rows.authSessionsTotal || 0)],
5528 ['Auth sessions (active)', String(rows.authSessionsActive || 0)],
5529 ['Auth sessions (revoked)', String(rows.authSessionsRevoked || 0)],
5530 ['Share tokens (total)', String(rows.shareTokensTotal || 0)],
5531 ['Share tokens (expired)', String(rows.shareTokensExpired || 0)],
5532 ['Auth cleanup last run', formatTimestamp(authCleanup.lastRunAt)],
5533 ['Share cleanup last run', formatTimestamp(shareMaintenance.lastRunAt)],
5534 ['Scheduled restart', scheduledLine],
5535 ['Next scheduled restart', formatTimestamp(scheduledRestart.nextDueAt)],
5536 ['Pending since', formatTimestamp(scheduledRestart.pendingSinceAt)],
5537 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5538 }
5539
5472 5540 renderDebugTable(
5473 5541 'debug-roots',
5474 5542 [
@@ -5586,6 +5654,15 @@ function copyDebugStorageJson ()
5586 5654 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied storage JSON.');
5587 5655 }
5588 5656
5657 function copyDebugMaintenanceJson ()
5658 {
5659 const payload = {
5660 generatedAt: _debugLatestData && _debugLatestData.generatedAt,
5661 maintenance: _debugLatestData && _debugLatestData.maintenance,
5662 };
5663 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied maintenance JSON.');
5664 }
5665
5589 5666 function copyDebugVideoFilesCsv ()
5590 5667 {
5591 5668 const files = Array.isArray(_debugLatestData && _debugLatestData.videoFiles)
@@ -5819,6 +5896,7 @@ async function openAdminModal ()
5819 5896 await refreshAdminConfig();
5820 5897 await refreshAdminUsers();
5821 5898 await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true });
5899 syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd));
5822 5900 }
5823 5901
5824 5902 async function refreshAdminConfig ()
@@ -5827,6 +5905,7 @@ async function refreshAdminConfig ()
5827 5905 const doc = document;
5828 5906 const data = await api('GET', '/admin/config');
5829 5907 if (!data) return;
5908 _adminConfigCache = data;
5830 5909 if (!doc.defaultView || doc.defaultView.closed) return;
5831 5910
5832 5911 const userPathInput = doc.getElementById('admin-user-path');
@@ -5838,6 +5917,17 @@ async function refreshAdminConfig ()
5838 5917 updateAdminSizeFeedback(sizeInput.value);
5839 5918 }
5840 5919
5920 const srEnabled = doc.getElementById('admin-scheduled-restart-enabled');
5921 const srCadence = doc.getElementById('admin-scheduled-restart-cadence');
5922 const srTime = doc.getElementById('admin-scheduled-restart-time');
5923 const sr = data.scheduledRestart || {};
5924 if (srEnabled) srEnabled.checked = !!sr.enabled;
5925 if (srCadence) srCadence.value = sr.cadence || 'daily';
5926 if (srTime) srTime.value = sr.time || '04:00';
5927
5928 const underSystemd = !!(_adminUpdateStatus && _adminUpdateStatus.underSystemd);
5929 syncScheduledRestartControls(underSystemd);
5930
5841 5931 const container = doc.getElementById('admin-paths');
5842 5932 if (!container) return;
5843 5933 container.innerHTML = '';
@@ -5985,6 +6075,7 @@ async function refreshAdminUpdateStatus (opts = {})
5985 6075 _adminUpdateStatus = null;
5986 6076 btn.textContent = 'Shut down server';
5987 6077 setAdminUpdateBadge(0);
6078 syncScheduledRestartControls(false);
5988 6079
5989 6080 try
5990 6081 {
@@ -6000,20 +6091,24 @@ async function refreshAdminUpdateStatus (opts = {})
6000 6091 if (!data.underSystemd)
6001 6092 {
6002 6093 btn.textContent = 'Shut down server';
6094 syncScheduledRestartControls(false);
6003 6095 }
6004 6096 else if (data.commitsAhead.length === 0)
6005 6097 {
6006 6098 btn.textContent = 'Restart Server';
6099 syncScheduledRestartControls(true);
6007 6100 }
6008 6101 else
6009 6102 {
6010 6103 btn.textContent = 'Restart & Update';
6104 syncScheduledRestartControls(true);
6011 6105 if (pulseIfUpdateAvailable) pulseAdminUpdateButton();
6012 6106 }
6013 6107 }
6014 6108 catch
6015 6109 {
6016 6110 // Not critical; button stays as "Shut down server".
6111 syncScheduledRestartControls(false);
6017 6112 }
6018 6113 }
6019 6114
@@ -6975,6 +7070,8 @@ function wireEvents ()
6975 7070 if (debugCopyUsers) debugCopyUsers.addEventListener('click', copyDebugUsersJson);
6976 7071 const debugCopyStorage = document.getElementById('debug-copy-storage');
6977 7072 if (debugCopyStorage) debugCopyStorage.addEventListener('click', copyDebugStorageJson);
7073 const debugCopyMaintenance = document.getElementById('debug-copy-maintenance');
7074 if (debugCopyMaintenance) debugCopyMaintenance.addEventListener('click', copyDebugMaintenanceJson);
6978 7075 const debugCopyVideoFiles = document.getElementById('debug-copy-video-files');
6979 7076 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
6980 7077 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
@@ -7025,6 +7122,59 @@ function wireEvents ()
7025 7122 });
7026 7123 }
7027 7124
7125 const scheduledEnabledInput = document.getElementById('admin-scheduled-restart-enabled');
7126 if (scheduledEnabledInput)
7127 {
7128 scheduledEnabledInput.addEventListener('change', () =>
7129 {
7130 syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd));
7131 });
7132 }
7133
7134 document.getElementById('admin-save-scheduled-restart').addEventListener('click', async () =>
7135 {
7136 if (!(_adminUpdateStatus && _adminUpdateStatus.underSystemd))
7137 {
7138 toast('Scheduled restart is available only under systemd.', 'err');
7139 return;
7140 }
7141
7142 const rows = document.querySelectorAll('#admin-paths .path-row span');
7143 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
7144
7145 const enabled = !!document.getElementById('admin-scheduled-restart-enabled').checked;
7146 const cadence = String(document.getElementById('admin-scheduled-restart-cadence').value || '').trim();
7147 const time = String(document.getElementById('admin-scheduled-restart-time').value || '').trim();
7148
7149 if (!time)
7150 {
7151 toast('Please choose a restart time.', 'err');
7152 return;
7153 }
7154
7155 const existing = _adminConfigCache || {};
7156
7157 try
7158 {
7159 await api('PUT', '/admin/config', {
7160 paths,
7161 userPath: existing.userPath || null,
7162 userFolderSizeLimit: existing.userFolderSizeLimit || null,
7163 scheduledRestart: {
7164 enabled,
7165 cadence,
7166 time,
7167 },
7168 });
7169 toast('Scheduled restart saved.', 'ok');
7170 await refreshAdminConfig();
7171 await refreshAdminUpdateStatus();
7172 } catch (err)
7173 {
7174 toast(err.message || 'Failed to save scheduled restart settings.', 'err');
7175 }
7176 });
7177
7028 7178 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
7029 7179 {
7030 7180 const rows = document.querySelectorAll('#admin-paths .path-row span');
@@ -5400,6 +5400,45 @@ async function deleteItem (item)
5400let _adminUpdateStatus = null;
5400let _adminUpdateStatus = null;
5401let _debugRefreshTimer = null;
5401let _debugRefreshTimer = null;
5402let _debugLatestData = null;
5402let _debugLatestData = null;
5403let _adminConfigCache = null;
5404
5405function scheduledRestartCadenceLabel (value)
5406{
5407 const key = String(value || '').trim();
5408 if (key === 'daily') return 'Daily';
5409 if (key === 'every3days') return 'Every 3 days';
5410 if (key === 'weekly') return 'Weekly';
5411 if (key === 'biweekly') return 'Bi-weekly';
5412 if (key === 'monthly') return 'Monthly';
5413 return 'Unknown';
5414}
5415
5416function syncScheduledRestartControls (underSystemd)
5417{
5418 const container = document.getElementById('admin-scheduled-restart');
5419 const enabled = document.getElementById('admin-scheduled-restart-enabled');
5420 const cadence = document.getElementById('admin-scheduled-restart-cadence');
5421 const time = document.getElementById('admin-scheduled-restart-time');
5422 const save = document.getElementById('admin-save-scheduled-restart');
5423 const help = document.getElementById('admin-scheduled-restart-help');
5424 if (!container || !enabled || !cadence || !time || !save || !help) return;
5425
5426 const disabled = !underSystemd;
5427 container.classList.toggle('admin-scheduled-restart--disabled', disabled);
5428
5429 enabled.disabled = disabled;
5430 cadence.disabled = disabled || !enabled.checked;
5431 time.disabled = disabled || !enabled.checked;
5432 save.disabled = disabled;
5433
5434 if (disabled)
5435 {
5436 help.textContent = 'Scheduled restart is available only when the server is started via the systemd service.';
5437 return;
5438 }
5439
5440 help.textContent = 'When the scheduled time is reached, restart waits until there have been no logged-in clients for at least one hour.';
5441}
5403
5442
5404function formatTimestamp (ms)
5443function formatTimestamp (ms)
5405{
5444{
@@ -5469,6 +5508,35 @@ function renderDebugDashboardData (data)
5469 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5508 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5470 }
5509 }
5471
5510
5511 const maintenanceSummary = document.getElementById('debug-maintenance-summary');
5512 if (maintenanceSummary)
5513 {
5514 const maintenance = data.maintenance || {};
5515 const rows = maintenance.rows || {};
5516 const authCleanup = maintenance.authCleanup || {};
5517 const shareMaintenance = maintenance.shareMaintenance || {};
5518 const scheduledRestart = maintenance.scheduledRestart || {};
5519
5520 const scheduledLine = !scheduledRestart.underSystemd
5521 ? 'Unavailable (not systemd)'
5522 : !scheduledRestart.config || !scheduledRestart.config.enabled
5523 ? 'Disabled'
5524 : `${scheduledRestartCadenceLabel(scheduledRestart.config.cadence)} at ${scheduledRestart.config.time || '—'}`;
5525
5526 maintenanceSummary.innerHTML = [
5527 ['Auth sessions (total)', String(rows.authSessionsTotal || 0)],
5528 ['Auth sessions (active)', String(rows.authSessionsActive || 0)],
5529 ['Auth sessions (revoked)', String(rows.authSessionsRevoked || 0)],
5530 ['Share tokens (total)', String(rows.shareTokensTotal || 0)],
5531 ['Share tokens (expired)', String(rows.shareTokensExpired || 0)],
5532 ['Auth cleanup last run', formatTimestamp(authCleanup.lastRunAt)],
5533 ['Share cleanup last run', formatTimestamp(shareMaintenance.lastRunAt)],
5534 ['Scheduled restart', scheduledLine],
5535 ['Next scheduled restart', formatTimestamp(scheduledRestart.nextDueAt)],
5536 ['Pending since', formatTimestamp(scheduledRestart.pendingSinceAt)],
5537 ].map(([k, v]) => `<div class="debug-summary-item"><span class="k">${escapeHtml(k)}</span><span class="v">${escapeHtml(v)}</span></div>`).join('');
5538 }
5539
5472 renderDebugTable(
5540 renderDebugTable(
5473 'debug-roots',
5541 'debug-roots',
5474 [
5542 [
@@ -5586,6 +5654,15 @@ function copyDebugStorageJson ()
5586 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied storage JSON.');
5654 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied storage JSON.');
5587}
5655}
5588
5656
5657function copyDebugMaintenanceJson ()
5658{
5659 const payload = {
5660 generatedAt: _debugLatestData && _debugLatestData.generatedAt,
5661 maintenance: _debugLatestData && _debugLatestData.maintenance,
5662 };
5663 void copyDebugText(JSON.stringify(payload, null, 2), 'Copied maintenance JSON.');
5664}
5665
5589function copyDebugVideoFilesCsv ()
5666function copyDebugVideoFilesCsv ()
5590{
5667{
5591 const files = Array.isArray(_debugLatestData && _debugLatestData.videoFiles)
5668 const files = Array.isArray(_debugLatestData && _debugLatestData.videoFiles)
@@ -5819,6 +5896,7 @@ async function openAdminModal ()
5819 await refreshAdminConfig();
5896 await refreshAdminConfig();
5820 await refreshAdminUsers();
5897 await refreshAdminUsers();
5821 await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true });
5898 await refreshAdminUpdateStatus({ pulseIfUpdateAvailable: true });
5899 syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd));
5822}
5900}
5823
5901
5824async function refreshAdminConfig ()
5902async function refreshAdminConfig ()
@@ -5827,6 +5905,7 @@ async function refreshAdminConfig ()
5827 const doc = document;
5905 const doc = document;
5828 const data = await api('GET', '/admin/config');
5906 const data = await api('GET', '/admin/config');
5829 if (!data) return;
5907 if (!data) return;
5908 _adminConfigCache = data;
5830 if (!doc.defaultView || doc.defaultView.closed) return;
5909 if (!doc.defaultView || doc.defaultView.closed) return;
5831
5910
5832 const userPathInput = doc.getElementById('admin-user-path');
5911 const userPathInput = doc.getElementById('admin-user-path');
@@ -5838,6 +5917,17 @@ async function refreshAdminConfig ()
5838 updateAdminSizeFeedback(sizeInput.value);
5917 updateAdminSizeFeedback(sizeInput.value);
5839 }
5918 }
5840
5919
5920 const srEnabled = doc.getElementById('admin-scheduled-restart-enabled');
5921 const srCadence = doc.getElementById('admin-scheduled-restart-cadence');
5922 const srTime = doc.getElementById('admin-scheduled-restart-time');
5923 const sr = data.scheduledRestart || {};
5924 if (srEnabled) srEnabled.checked = !!sr.enabled;
5925 if (srCadence) srCadence.value = sr.cadence || 'daily';
5926 if (srTime) srTime.value = sr.time || '04:00';
5927
5928 const underSystemd = !!(_adminUpdateStatus && _adminUpdateStatus.underSystemd);
5929 syncScheduledRestartControls(underSystemd);
5930
5841 const container = doc.getElementById('admin-paths');
5931 const container = doc.getElementById('admin-paths');
5842 if (!container) return;
5932 if (!container) return;
5843 container.innerHTML = '';
5933 container.innerHTML = '';
@@ -5985,6 +6075,7 @@ async function refreshAdminUpdateStatus (opts = {})
5985 _adminUpdateStatus = null;
6075 _adminUpdateStatus = null;
5986 btn.textContent = 'Shut down server';
6076 btn.textContent = 'Shut down server';
5987 setAdminUpdateBadge(0);
6077 setAdminUpdateBadge(0);
6078 syncScheduledRestartControls(false);
5988
6079
5989 try
6080 try
5990 {
6081 {
@@ -6000,20 +6091,24 @@ async function refreshAdminUpdateStatus (opts = {})
6000 if (!data.underSystemd)
6091 if (!data.underSystemd)
6001 {
6092 {
6002 btn.textContent = 'Shut down server';
6093 btn.textContent = 'Shut down server';
6094 syncScheduledRestartControls(false);
6003 }
6095 }
6004 else if (data.commitsAhead.length === 0)
6096 else if (data.commitsAhead.length === 0)
6005 {
6097 {
6006 btn.textContent = 'Restart Server';
6098 btn.textContent = 'Restart Server';
6099 syncScheduledRestartControls(true);
6007 }
6100 }
6008 else
6101 else
6009 {
6102 {
6010 btn.textContent = 'Restart & Update';
6103 btn.textContent = 'Restart & Update';
6104 syncScheduledRestartControls(true);
6011 if (pulseIfUpdateAvailable) pulseAdminUpdateButton();
6105 if (pulseIfUpdateAvailable) pulseAdminUpdateButton();
6012 }
6106 }
6013 }
6107 }
6014 catch
6108 catch
6015 {
6109 {
6016 // Not critical; button stays as "Shut down server".
6110 // Not critical; button stays as "Shut down server".
6111 syncScheduledRestartControls(false);
6017 }
6112 }
6018}
6113}
6019
6114
@@ -6975,6 +7070,8 @@ function wireEvents ()
6975 if (debugCopyUsers) debugCopyUsers.addEventListener('click', copyDebugUsersJson);
7070 if (debugCopyUsers) debugCopyUsers.addEventListener('click', copyDebugUsersJson);
6976 const debugCopyStorage = document.getElementById('debug-copy-storage');
7071 const debugCopyStorage = document.getElementById('debug-copy-storage');
6977 if (debugCopyStorage) debugCopyStorage.addEventListener('click', copyDebugStorageJson);
7072 if (debugCopyStorage) debugCopyStorage.addEventListener('click', copyDebugStorageJson);
7073 const debugCopyMaintenance = document.getElementById('debug-copy-maintenance');
7074 if (debugCopyMaintenance) debugCopyMaintenance.addEventListener('click', copyDebugMaintenanceJson);
6978 const debugCopyVideoFiles = document.getElementById('debug-copy-video-files');
7075 const debugCopyVideoFiles = document.getElementById('debug-copy-video-files');
6979 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
7076 if (debugCopyVideoFiles) debugCopyVideoFiles.addEventListener('click', copyDebugVideoFilesCsv);
6980 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
7077 const debugCopyOrphaned = document.getElementById('debug-copy-orphaned');
@@ -7025,6 +7122,59 @@ function wireEvents ()
7025 });
7122 });
7026 }
7123 }
7027
7124
7125 const scheduledEnabledInput = document.getElementById('admin-scheduled-restart-enabled');
7126 if (scheduledEnabledInput)
7127 {
7128 scheduledEnabledInput.addEventListener('change', () =>
7129 {
7130 syncScheduledRestartControls(!!(_adminUpdateStatus && _adminUpdateStatus.underSystemd));
7131 });
7132 }
7133
7134 document.getElementById('admin-save-scheduled-restart').addEventListener('click', async () =>
7135 {
7136 if (!(_adminUpdateStatus && _adminUpdateStatus.underSystemd))
7137 {
7138 toast('Scheduled restart is available only under systemd.', 'err');
7139 return;
7140 }
7141
7142 const rows = document.querySelectorAll('#admin-paths .path-row span');
7143 const paths = [...rows].map(s => s.textContent.trim()).filter(Boolean);
7144
7145 const enabled = !!document.getElementById('admin-scheduled-restart-enabled').checked;
7146 const cadence = String(document.getElementById('admin-scheduled-restart-cadence').value || '').trim();
7147 const time = String(document.getElementById('admin-scheduled-restart-time').value || '').trim();
7148
7149 if (!time)
7150 {
7151 toast('Please choose a restart time.', 'err');
7152 return;
7153 }
7154
7155 const existing = _adminConfigCache || {};
7156
7157 try
7158 {
7159 await api('PUT', '/admin/config', {
7160 paths,
7161 userPath: existing.userPath || null,
7162 userFolderSizeLimit: existing.userFolderSizeLimit || null,
7163 scheduledRestart: {
7164 enabled,
7165 cadence,
7166 time,
7167 },
7168 });
7169 toast('Scheduled restart saved.', 'ok');
7170 await refreshAdminConfig();
7171 await refreshAdminUpdateStatus();
7172 } catch (err)
7173 {
7174 toast(err.message || 'Failed to save scheduled restart settings.', 'err');
7175 }
7176 });
7177
7028 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
7178 document.getElementById('admin-save-userpath').addEventListener('click', async () =>
7029 {
7179 {
7030 const rows = document.querySelectorAll('#admin-paths .path-row span');
7180 const rows = document.querySelectorAll('#admin-paths .path-row span');
public/index.html +30 −0
@@ -225,6 +225,28 @@
225 225 </span>
226 226 </button>
227 227 </div>
228 <div id="admin-scheduled-restart" class="admin-scheduled-restart">
229 <label class="checkbox-label admin-scheduled-restart-toggle">
230 <input id="admin-scheduled-restart-enabled" type="checkbox" />
231 Enable scheduled restart
232 </label>
233 <div class="admin-scheduled-restart-grid">
234 <label>Cadence
235 <select id="admin-scheduled-restart-cadence">
236 <option value="daily">Daily</option>
237 <option value="every3days">Every 3 days</option>
238 <option value="weekly">Weekly</option>
239 <option value="biweekly">Bi-weekly</option>
240 <option value="monthly">Monthly</option>
241 </select>
242 </label>
243 <label>Time
244 <input id="admin-scheduled-restart-time" type="time" step="60" />
245 </label>
246 </div>
247 <p id="admin-scheduled-restart-help" class="muted">When the scheduled time is reached, restart waits until there have been no logged-in clients for at least one hour.</p>
248 <button id="admin-save-scheduled-restart" class="primary">Save scheduled restart</button>
249 </div>
228 250 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
229 251 </section>
230 252 </div>
@@ -259,6 +281,14 @@
259 281 <div id="debug-roots" class="debug-table-wrap"></div>
260 282 </section>
261 283
284 <section>
285 <div class="debug-section-head">
286 <h3>Server Maintenance</h3>
287 <button id="debug-copy-maintenance" class="debug-copy-btn" type="button">Copy JSON</button>
288 </div>
289 <div id="debug-maintenance-summary" class="debug-summary-grid"></div>
290 </section>
291
262 292 <section>
263 293 <div class="debug-section-head">
264 294 <h3>Video Streams and Caches</h3>
@@ -225,6 +225,28 @@
225 </span>
225 </span>
226 </button>
226 </button>
227 </div>
227 </div>
228 <div id="admin-scheduled-restart" class="admin-scheduled-restart">
229 <label class="checkbox-label admin-scheduled-restart-toggle">
230 <input id="admin-scheduled-restart-enabled" type="checkbox" />
231 Enable scheduled restart
232 </label>
233 <div class="admin-scheduled-restart-grid">
234 <label>Cadence
235 <select id="admin-scheduled-restart-cadence">
236 <option value="daily">Daily</option>
237 <option value="every3days">Every 3 days</option>
238 <option value="weekly">Weekly</option>
239 <option value="biweekly">Bi-weekly</option>
240 <option value="monthly">Monthly</option>
241 </select>
242 </label>
243 <label>Time
244 <input id="admin-scheduled-restart-time" type="time" step="60" />
245 </label>
246 </div>
247 <p id="admin-scheduled-restart-help" class="muted">When the scheduled time is reached, restart waits until there have been no logged-in clients for at least one hour.</p>
248 <button id="admin-save-scheduled-restart" class="primary">Save scheduled restart</button>
249 </div>
228 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
250 <button id="admin-shutdown-btn" class="danger">Shut down server</button>
229 </section>
251 </section>
230 </div>
252 </div>
@@ -259,6 +281,14 @@
259 <div id="debug-roots" class="debug-table-wrap"></div>
281 <div id="debug-roots" class="debug-table-wrap"></div>
260 </section>
282 </section>
261
283
284 <section>
285 <div class="debug-section-head">
286 <h3>Server Maintenance</h3>
287 <button id="debug-copy-maintenance" class="debug-copy-btn" type="button">Copy JSON</button>
288 </div>
289 <div id="debug-maintenance-summary" class="debug-summary-grid"></div>
290 </section>
291
262 <section>
292 <section>
263 <div class="debug-section-head">
293 <div class="debug-section-head">
264 <h3>Video Streams and Caches</h3>
294 <h3>Video Streams and Caches</h3>
public/style.css +46 −0
@@ -184,6 +184,13 @@ button.danger:hover {
184 184 background: var(--border);
185 185 }
186 186
187 button:disabled,
188 input:disabled,
189 select:disabled {
190 opacity: 0.55;
191 cursor: not-allowed;
192 }
193
187 194 button.danger.admin-update-highlight {
188 195 animation: admin-update-pulse 0.9s ease-in-out 2;
189 196 }
@@ -1210,6 +1217,45 @@ button.danger.admin-update-highlight {
1210 1217 background: var(--border);
1211 1218 }
1212 1219
1220 .admin-scheduled-restart {
1221 margin: 0.4rem 0 0.8rem;
1222 padding: 0.6rem;
1223 border: 1px solid var(--border);
1224 border-radius: var(--radius);
1225 background: var(--bg);
1226 }
1227
1228 .admin-scheduled-restart.admin-scheduled-restart--disabled {
1229 opacity: 0.7;
1230 }
1231
1232 .admin-scheduled-restart-toggle {
1233 margin-bottom: 0.5rem;
1234 }
1235
1236 .admin-scheduled-restart-grid {
1237 display: grid;
1238 grid-template-columns: 1fr 1fr;
1239 gap: 0.6rem;
1240 }
1241
1242 .admin-scheduled-restart-grid label {
1243 display: flex;
1244 flex-direction: column;
1245 gap: 0.28rem;
1246 font-size: 0.82rem;
1247 color: var(--text-muted);
1248 }
1249
1250 .admin-scheduled-restart-grid input,
1251 .admin-scheduled-restart-grid select {
1252 background: var(--surface2);
1253 border: 1px solid var(--border);
1254 border-radius: 6px;
1255 color: var(--text);
1256 padding: 0.4rem 0.55rem;
1257 }
1258
1213 1259 /* User list */
1214 1260 .user-row {
1215 1261 display: flex;
@@ -184,6 +184,13 @@ button.danger:hover {
184 background: var(--border);
184 background: var(--border);
185}
185}
186
186
187button:disabled,
188input:disabled,
189select:disabled {
190 opacity: 0.55;
191 cursor: not-allowed;
192}
193
187button.danger.admin-update-highlight {
194button.danger.admin-update-highlight {
188 animation: admin-update-pulse 0.9s ease-in-out 2;
195 animation: admin-update-pulse 0.9s ease-in-out 2;
189}
196}
@@ -1210,6 +1217,45 @@ button.danger.admin-update-highlight {
1210 background: var(--border);
1217 background: var(--border);
1211}
1218}
1212
1219
1220.admin-scheduled-restart {
1221 margin: 0.4rem 0 0.8rem;
1222 padding: 0.6rem;
1223 border: 1px solid var(--border);
1224 border-radius: var(--radius);
1225 background: var(--bg);
1226}
1227
1228.admin-scheduled-restart.admin-scheduled-restart--disabled {
1229 opacity: 0.7;
1230}
1231
1232.admin-scheduled-restart-toggle {
1233 margin-bottom: 0.5rem;
1234}
1235
1236.admin-scheduled-restart-grid {
1237 display: grid;
1238 grid-template-columns: 1fr 1fr;
1239 gap: 0.6rem;
1240}
1241
1242.admin-scheduled-restart-grid label {
1243 display: flex;
1244 flex-direction: column;
1245 gap: 0.28rem;
1246 font-size: 0.82rem;
1247 color: var(--text-muted);
1248}
1249
1250.admin-scheduled-restart-grid input,
1251.admin-scheduled-restart-grid select {
1252 background: var(--surface2);
1253 border: 1px solid var(--border);
1254 border-radius: 6px;
1255 color: var(--text);
1256 padding: 0.4rem 0.55rem;
1257}
1258
1213/* User list */
1259/* User list */
1214.user-row {
1260.user-row {
1215 display: flex;
1261 display: flex;
server/auth.js +44 −2
@@ -11,6 +11,12 @@ const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
11 11 const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
12 12
13 13 let authSessionPurgeTimer = null;
14 const authSessionCleanupState = {
15 lastRunAt: null,
16 lastPurgedCount: 0,
17 lastDurationMs: 0,
18 lastError: null,
19 };
14 20
15 21 // Secret used to sign JWTs — generated fresh each server boot.
16 22 // Tokens from a previous boot are automatically invalid.
@@ -91,6 +97,27 @@ function purgeStaleSessions (opts = {})
91 97 return Number(result && result.changes || 0);
92 98 }
93 99
100 function runAuthSessionCleanupOnce ()
101 {
102 const startedAt = nowMs();
103 try
104 {
105 const purged = purgeStaleSessions();
106 authSessionCleanupState.lastRunAt = nowMs();
107 authSessionCleanupState.lastPurgedCount = Number(purged || 0);
108 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
109 authSessionCleanupState.lastError = null;
110 return purged;
111 } catch (err)
112 {
113 authSessionCleanupState.lastRunAt = nowMs();
114 authSessionCleanupState.lastPurgedCount = 0;
115 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
116 authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err);
117 throw err;
118 }
119 }
120
94 121 function startAuthSessionCleanupLoop ()
95 122 {
96 123 if (authSessionPurgeTimer) return;
@@ -98,7 +125,7 @@ function startAuthSessionCleanupLoop ()
98 125 // Run once immediately at startup to trim stale rows from earlier uptime.
99 126 try
100 127 {
101 purgeStaleSessions();
128 runAuthSessionCleanupOnce();
102 129 } catch
103 130 {
104 131 // Ignore purge failures and retry on the next interval.
@@ -108,7 +135,7 @@ function startAuthSessionCleanupLoop ()
108 135 {
109 136 try
110 137 {
111 purgeStaleSessions();
138 runAuthSessionCleanupOnce();
112 139 } catch
113 140 {
114 141 // Keep server healthy even if cleanup temporarily fails.
@@ -128,6 +155,20 @@ function stopAuthSessionCleanupLoop ()
128 155 authSessionPurgeTimer = null;
129 156 }
130 157
158 function getAuthSessionCleanupSnapshot ()
159 {
160 return {
161 running: !!authSessionPurgeTimer,
162 intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS,
163 lastRunAt: authSessionCleanupState.lastRunAt,
164 lastPurgedCount: authSessionCleanupState.lastPurgedCount,
165 lastDurationMs: authSessionCleanupState.lastDurationMs,
166 lastError: authSessionCleanupState.lastError,
167 revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS,
168 idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS,
169 };
170 }
171
131 172 // ---------------------------------------------------------------------------
132 173 // Token creation
133 174 // ---------------------------------------------------------------------------
@@ -276,6 +317,7 @@ module.exports = {
276 317 getRegion,
277 318 revokeSession,
278 319 purgeStaleSessions,
320 getAuthSessionCleanupSnapshot,
279 321 startAuthSessionCleanupLoop,
280 322 stopAuthSessionCleanupLoop,
281 323 SESSION_IDLE_TIMEOUT_MS,
@@ -11,6 +11,12 @@ const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
11const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
11const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
12
12
13let authSessionPurgeTimer = null;
13let authSessionPurgeTimer = null;
14const authSessionCleanupState = {
15 lastRunAt: null,
16 lastPurgedCount: 0,
17 lastDurationMs: 0,
18 lastError: null,
19};
14
20
15// Secret used to sign JWTs — generated fresh each server boot.
21// Secret used to sign JWTs — generated fresh each server boot.
16// Tokens from a previous boot are automatically invalid.
22// Tokens from a previous boot are automatically invalid.
@@ -91,6 +97,27 @@ function purgeStaleSessions (opts = {})
91 return Number(result && result.changes || 0);
97 return Number(result && result.changes || 0);
92}
98}
93
99
100function runAuthSessionCleanupOnce ()
101{
102 const startedAt = nowMs();
103 try
104 {
105 const purged = purgeStaleSessions();
106 authSessionCleanupState.lastRunAt = nowMs();
107 authSessionCleanupState.lastPurgedCount = Number(purged || 0);
108 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
109 authSessionCleanupState.lastError = null;
110 return purged;
111 } catch (err)
112 {
113 authSessionCleanupState.lastRunAt = nowMs();
114 authSessionCleanupState.lastPurgedCount = 0;
115 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
116 authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err);
117 throw err;
118 }
119}
120
94function startAuthSessionCleanupLoop ()
121function startAuthSessionCleanupLoop ()
95{
122{
96 if (authSessionPurgeTimer) return;
123 if (authSessionPurgeTimer) return;
@@ -98,7 +125,7 @@ function startAuthSessionCleanupLoop ()
98 // Run once immediately at startup to trim stale rows from earlier uptime.
125 // Run once immediately at startup to trim stale rows from earlier uptime.
99 try
126 try
100 {
127 {
101 purgeStaleSessions();
128 runAuthSessionCleanupOnce();
102 } catch
129 } catch
103 {
130 {
104 // Ignore purge failures and retry on the next interval.
131 // Ignore purge failures and retry on the next interval.
@@ -108,7 +135,7 @@ function startAuthSessionCleanupLoop ()
108 {
135 {
109 try
136 try
110 {
137 {
111 purgeStaleSessions();
138 runAuthSessionCleanupOnce();
112 } catch
139 } catch
113 {
140 {
114 // Keep server healthy even if cleanup temporarily fails.
141 // Keep server healthy even if cleanup temporarily fails.
@@ -128,6 +155,20 @@ function stopAuthSessionCleanupLoop ()
128 authSessionPurgeTimer = null;
155 authSessionPurgeTimer = null;
129}
156}
130
157
158function getAuthSessionCleanupSnapshot ()
159{
160 return {
161 running: !!authSessionPurgeTimer,
162 intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS,
163 lastRunAt: authSessionCleanupState.lastRunAt,
164 lastPurgedCount: authSessionCleanupState.lastPurgedCount,
165 lastDurationMs: authSessionCleanupState.lastDurationMs,
166 lastError: authSessionCleanupState.lastError,
167 revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS,
168 idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS,
169 };
170}
171
131// ---------------------------------------------------------------------------
172// ---------------------------------------------------------------------------
132// Token creation
173// Token creation
133// ---------------------------------------------------------------------------
174// ---------------------------------------------------------------------------
@@ -276,6 +317,7 @@ module.exports = {
276 getRegion,
317 getRegion,
277 revokeSession,
318 revokeSession,
278 purgeStaleSessions,
319 purgeStaleSessions,
320 getAuthSessionCleanupSnapshot,
279 startAuthSessionCleanupLoop,
321 startAuthSessionCleanupLoop,
280 stopAuthSessionCleanupLoop,
322 stopAuthSessionCleanupLoop,
281 SESSION_IDLE_TIMEOUT_MS,
323 SESSION_IDLE_TIMEOUT_MS,
server/config.js +22 −1
@@ -5,6 +5,26 @@ const path = require('path');
5 5
6 6 const CONFIG_PATH = path.join(__dirname, '../config.json');
7 7
8 const DEFAULT_SCHEDULED_RESTART = {
9 enabled: false,
10 cadence: 'daily',
11 time: '04:00',
12 };
13
14 function normalizeScheduledRestart (value)
15 {
16 const raw = value && typeof value === 'object' ? value : {};
17 const cadence = String(raw.cadence || '').trim().toLowerCase();
18 const allowedCadences = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
19 const time = String(raw.time || '').trim();
20
21 return {
22 enabled: !!raw.enabled,
23 cadence: allowedCadences.has(cadence) ? cadence : DEFAULT_SCHEDULED_RESTART.cadence,
24 time: /^([01]\d|2[0-3]):([0-5]\d)$/.test(time) ? time : DEFAULT_SCHEDULED_RESTART.time,
25 };
26 }
27
8 28 function loadConfig ()
9 29 {
10 30 try
@@ -19,10 +39,11 @@ function loadConfig ()
19 39 {
20 40 parsed.rootAliases = {};
21 41 }
42 parsed.scheduledRestart = normalizeScheduledRestart(parsed.scheduledRestart);
22 43 return parsed;
23 44 } catch
24 45 {
25 const defaults = { port: 3000, paths: [], rootAliases: {} };
46 const defaults = { port: 3000, paths: [], rootAliases: {}, scheduledRestart: { ...DEFAULT_SCHEDULED_RESTART } };
26 47 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
27 48 return defaults;
28 49 }
@@ -5,6 +5,26 @@ const path = require('path');
5
5
6const CONFIG_PATH = path.join(__dirname, '../config.json');
6const CONFIG_PATH = path.join(__dirname, '../config.json');
7
7
8const DEFAULT_SCHEDULED_RESTART = {
9 enabled: false,
10 cadence: 'daily',
11 time: '04:00',
12};
13
14function normalizeScheduledRestart (value)
15{
16 const raw = value && typeof value === 'object' ? value : {};
17 const cadence = String(raw.cadence || '').trim().toLowerCase();
18 const allowedCadences = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
19 const time = String(raw.time || '').trim();
20
21 return {
22 enabled: !!raw.enabled,
23 cadence: allowedCadences.has(cadence) ? cadence : DEFAULT_SCHEDULED_RESTART.cadence,
24 time: /^([01]\d|2[0-3]):([0-5]\d)$/.test(time) ? time : DEFAULT_SCHEDULED_RESTART.time,
25 };
26}
27
8function loadConfig ()
28function loadConfig ()
9{
29{
10 try
30 try
@@ -19,10 +39,11 @@ function loadConfig ()
19 {
39 {
20 parsed.rootAliases = {};
40 parsed.rootAliases = {};
21 }
41 }
42 parsed.scheduledRestart = normalizeScheduledRestart(parsed.scheduledRestart);
22 return parsed;
43 return parsed;
23 } catch
44 } catch
24 {
45 {
25 const defaults = { port: 3000, paths: [], rootAliases: {} };
46 const defaults = { port: 3000, paths: [], rootAliases: {}, scheduledRestart: { ...DEFAULT_SCHEDULED_RESTART } };
26 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
47 fs.writeFileSync(CONFIG_PATH, JSON.stringify(defaults, null, 2), 'utf8');
27 return defaults;
48 return defaults;
28 }
49 }
server/index.js +3 −0
@@ -10,6 +10,7 @@ const { ensureServerKeys } = require('./crypto');
10 10 const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
11 11 const { loadConfig } = require('./config');
12 12 const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
13 const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler');
13 14 const { logError } = require('./logger');
14 15 const authRoutes = require('./routes/auth');
15 16 const filesRoutes = require('./routes/files');
@@ -66,6 +67,7 @@ function shutdown (opts = {}, ...servers)
66 67 stopThumbnailCacheLoop();
67 68 stopAuthSessionCleanupLoop();
68 69 stopShareMaintenanceLoop();
70 stopRestartScheduler();
69 71
70 72 // Close DB first so file locks are released as early as possible.
71 73 closeDb();
@@ -127,6 +129,7 @@ function start ()
127 129 startThumbnailCacheLoop();
128 130 startAuthSessionCleanupLoop();
129 131 startShareMaintenanceLoop();
132 startRestartScheduler({ shutdownForRestart });
130 133
131 134 // Give the admin route access to the server handle for graceful shutdown.
132 135 app.set('server', httpServer);
@@ -10,6 +10,7 @@ const { ensureServerKeys } = require('./crypto');
10const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
10const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
11const { loadConfig } = require('./config');
11const { loadConfig } = require('./config');
12const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
12const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
13const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler');
13const { logError } = require('./logger');
14const { logError } = require('./logger');
14const authRoutes = require('./routes/auth');
15const authRoutes = require('./routes/auth');
15const filesRoutes = require('./routes/files');
16const filesRoutes = require('./routes/files');
@@ -66,6 +67,7 @@ function shutdown (opts = {}, ...servers)
66 stopThumbnailCacheLoop();
67 stopThumbnailCacheLoop();
67 stopAuthSessionCleanupLoop();
68 stopAuthSessionCleanupLoop();
68 stopShareMaintenanceLoop();
69 stopShareMaintenanceLoop();
70 stopRestartScheduler();
69
71
70 // Close DB first so file locks are released as early as possible.
72 // Close DB first so file locks are released as early as possible.
71 closeDb();
73 closeDb();
@@ -127,6 +129,7 @@ function start ()
127 startThumbnailCacheLoop();
129 startThumbnailCacheLoop();
128 startAuthSessionCleanupLoop();
130 startAuthSessionCleanupLoop();
129 startShareMaintenanceLoop();
131 startShareMaintenanceLoop();
132 startRestartScheduler({ shutdownForRestart });
130
133
131 // Give the admin route access to the server handle for graceful shutdown.
134 // Give the admin route access to the server handle for graceful shutdown.
132 app.set('server', httpServer);
135 app.set('server', httpServer);
server/restart-scheduler.js added +246 −0
@@ -0,0 +1,246 @@
1 'use strict';
2
3 const { loadConfig } = require('./config');
4 const { getDb } = require('./db');
5 const { SESSION_IDLE_TIMEOUT_MS } = require('./auth');
6
7 const SCHEDULER_INTERVAL_MS = 60 * 1000;
8
9 const CADENCE_DAYS = {
10 daily: 1,
11 every3days: 3,
12 weekly: 7,
13 biweekly: 14,
14 };
15
16 let schedulerTimer = null;
17 let shutdownForRestartFn = null;
18 let state = {
19 startedAt: null,
20 lastTickAt: null,
21 nextDueAt: null,
22 pendingSinceAt: null,
23 lastShutdownAt: null,
24 lastDecision: 'idle',
25 lastError: null,
26 configKey: null,
27 underSystemd: false,
28 };
29
30 function nowMs ()
31 {
32 return Date.now();
33 }
34
35 function parseTimeToUtcParts (value)
36 {
37 const match = String(value || '').trim().match(/^([01]\d|2[0-3]):([0-5]\d)$/);
38 if (!match) return null;
39
40 return {
41 hour: Number.parseInt(match[1], 10),
42 minute: Number.parseInt(match[2], 10),
43 };
44 }
45
46 function addCadence (date, cadence)
47 {
48 const next = new Date(date.getTime());
49 if (cadence === 'monthly')
50 {
51 next.setUTCMonth(next.getUTCMonth() + 1);
52 return next;
53 }
54
55 const days = CADENCE_DAYS[cadence] || 1;
56 next.setUTCDate(next.getUTCDate() + days);
57 return next;
58 }
59
60 function buildScheduleConfig (config)
61 {
62 const scheduled = config && config.scheduledRestart && typeof config.scheduledRestart === 'object'
63 ? config.scheduledRestart
64 : {};
65
66 return {
67 enabled: !!scheduled.enabled,
68 cadence: String(scheduled.cadence || 'daily'),
69 time: String(scheduled.time || '04:00'),
70 };
71 }
72
73 function configKeyFor (underSystemd, cfg)
74 {
75 return JSON.stringify({
76 underSystemd: !!underSystemd,
77 enabled: !!cfg.enabled,
78 cadence: cfg.cadence,
79 time: cfg.time,
80 });
81 }
82
83 function computeInitialDueAt (schedule, now)
84 {
85 const parts = parseTimeToUtcParts(schedule.time);
86 if (!parts) return null;
87
88 const current = new Date(now);
89 const due = new Date(now);
90 due.setUTCHours(parts.hour, parts.minute, 0, 0);
91
92 if (due.getTime() <= current.getTime())
93 {
94 return addCadence(due, schedule.cadence).getTime();
95 }
96
97 return due.getTime();
98 }
99
100 function advanceDueAt (currentDueAt, schedule)
101 {
102 const due = new Date(Number(currentDueAt) || nowMs());
103 return addCadence(due, schedule.cadence).getTime();
104 }
105
106 function noLoggedInClientsForIdleWindow (now)
107 {
108 const db = getDb();
109 const row = db.prepare(
110 `SELECT MAX(last_seen_at) AS lastSeenAt
111 FROM auth_sessions
112 WHERE revoked_at IS NULL`,
113 ).get();
114
115 const lastSeenAt = Number(row && row.lastSeenAt || 0);
116 if (!Number.isFinite(lastSeenAt) || lastSeenAt <= 0) return true;
117 return now - lastSeenAt >= SESSION_IDLE_TIMEOUT_MS;
118 }
119
120 function resetPendingState ()
121 {
122 state.pendingSinceAt = null;
123 }
124
125 function applyConfigState (underSystemd, schedule, now)
126 {
127 const nextKey = configKeyFor(underSystemd, schedule);
128 if (state.configKey === nextKey) return;
129
130 state.configKey = nextKey;
131 state.underSystemd = !!underSystemd;
132 state.lastError = null;
133 resetPendingState();
134
135 if (!underSystemd || !schedule.enabled)
136 {
137 state.nextDueAt = null;
138 state.lastDecision = underSystemd ? 'disabled' : 'not-systemd';
139 return;
140 }
141
142 state.nextDueAt = computeInitialDueAt(schedule, now);
143 state.lastDecision = 'scheduled';
144 }
145
146 function tick ()
147 {
148 const now = nowMs();
149 state.lastTickAt = now;
150
151 const underSystemd = !!process.env.INVOCATION_ID;
152 const schedule = buildScheduleConfig(loadConfig());
153 applyConfigState(underSystemd, schedule, now);
154
155 if (!underSystemd || !schedule.enabled || !Number.isFinite(state.nextDueAt)) return;
156
157 if (now < state.nextDueAt)
158 {
159 state.lastDecision = 'waiting-next-window';
160 return;
161 }
162
163 if (!state.pendingSinceAt) state.pendingSinceAt = now;
164
165 if (!noLoggedInClientsForIdleWindow(now))
166 {
167 state.lastDecision = 'waiting-for-idle-clients';
168 return;
169 }
170
171 state.lastDecision = 'triggering-restart';
172 state.lastShutdownAt = now;
173 state.nextDueAt = advanceDueAt(state.nextDueAt, schedule);
174 resetPendingState();
175
176 if (typeof shutdownForRestartFn === 'function')
177 {
178 shutdownForRestartFn();
179 }
180 }
181
182 function startRestartScheduler (opts = {})
183 {
184 shutdownForRestartFn = typeof opts.shutdownForRestart === 'function' ? opts.shutdownForRestart : null;
185 if (schedulerTimer) return;
186
187 state.startedAt = nowMs();
188 state.lastError = null;
189
190 try
191 {
192 tick();
193 } catch (err)
194 {
195 state.lastError = err && err.message ? String(err.message) : String(err);
196 }
197
198 schedulerTimer = setInterval(() =>
199 {
200 try
201 {
202 tick();
203 } catch (err)
204 {
205 state.lastError = err && err.message ? String(err.message) : String(err);
206 }
207 }, SCHEDULER_INTERVAL_MS);
208
209 if (schedulerTimer && typeof schedulerTimer.unref === 'function') schedulerTimer.unref();
210 }
211
212 function stopRestartScheduler ()
213 {
214 if (!schedulerTimer) return;
215 clearInterval(schedulerTimer);
216 schedulerTimer = null;
217 }
218
219 function getRestartSchedulerSnapshot ()
220 {
221 const schedule = buildScheduleConfig(loadConfig());
222
223 return {
224 running: !!schedulerTimer,
225 startedAt: state.startedAt,
226 lastTickAt: state.lastTickAt,
227 nextDueAt: state.nextDueAt,
228 pendingSinceAt: state.pendingSinceAt,
229 lastShutdownAt: state.lastShutdownAt,
230 lastDecision: state.lastDecision,
231 lastError: state.lastError,
232 underSystemd: !!process.env.INVOCATION_ID,
233 config: {
234 enabled: schedule.enabled,
235 cadence: schedule.cadence,
236 time: schedule.time,
237 },
238 intervalMs: SCHEDULER_INTERVAL_MS,
239 };
240 }
241
242 module.exports = {
243 startRestartScheduler,
244 stopRestartScheduler,
245 getRestartSchedulerSnapshot,
246 };
@@ -0,0 +1,246 @@
1'use strict';
2
3const { loadConfig } = require('./config');
4const { getDb } = require('./db');
5const { SESSION_IDLE_TIMEOUT_MS } = require('./auth');
6
7const SCHEDULER_INTERVAL_MS = 60 * 1000;
8
9const CADENCE_DAYS = {
10 daily: 1,
11 every3days: 3,
12 weekly: 7,
13 biweekly: 14,
14};
15
16let schedulerTimer = null;
17let shutdownForRestartFn = null;
18let state = {
19 startedAt: null,
20 lastTickAt: null,
21 nextDueAt: null,
22 pendingSinceAt: null,
23 lastShutdownAt: null,
24 lastDecision: 'idle',
25 lastError: null,
26 configKey: null,
27 underSystemd: false,
28};
29
30function nowMs ()
31{
32 return Date.now();
33}
34
35function parseTimeToUtcParts (value)
36{
37 const match = String(value || '').trim().match(/^([01]\d|2[0-3]):([0-5]\d)$/);
38 if (!match) return null;
39
40 return {
41 hour: Number.parseInt(match[1], 10),
42 minute: Number.parseInt(match[2], 10),
43 };
44}
45
46function addCadence (date, cadence)
47{
48 const next = new Date(date.getTime());
49 if (cadence === 'monthly')
50 {
51 next.setUTCMonth(next.getUTCMonth() + 1);
52 return next;
53 }
54
55 const days = CADENCE_DAYS[cadence] || 1;
56 next.setUTCDate(next.getUTCDate() + days);
57 return next;
58}
59
60function buildScheduleConfig (config)
61{
62 const scheduled = config && config.scheduledRestart && typeof config.scheduledRestart === 'object'
63 ? config.scheduledRestart
64 : {};
65
66 return {
67 enabled: !!scheduled.enabled,
68 cadence: String(scheduled.cadence || 'daily'),
69 time: String(scheduled.time || '04:00'),
70 };
71}
72
73function configKeyFor (underSystemd, cfg)
74{
75 return JSON.stringify({
76 underSystemd: !!underSystemd,
77 enabled: !!cfg.enabled,
78 cadence: cfg.cadence,
79 time: cfg.time,
80 });
81}
82
83function computeInitialDueAt (schedule, now)
84{
85 const parts = parseTimeToUtcParts(schedule.time);
86 if (!parts) return null;
87
88 const current = new Date(now);
89 const due = new Date(now);
90 due.setUTCHours(parts.hour, parts.minute, 0, 0);
91
92 if (due.getTime() <= current.getTime())
93 {
94 return addCadence(due, schedule.cadence).getTime();
95 }
96
97 return due.getTime();
98}
99
100function advanceDueAt (currentDueAt, schedule)
101{
102 const due = new Date(Number(currentDueAt) || nowMs());
103 return addCadence(due, schedule.cadence).getTime();
104}
105
106function noLoggedInClientsForIdleWindow (now)
107{
108 const db = getDb();
109 const row = db.prepare(
110 `SELECT MAX(last_seen_at) AS lastSeenAt
111 FROM auth_sessions
112 WHERE revoked_at IS NULL`,
113 ).get();
114
115 const lastSeenAt = Number(row && row.lastSeenAt || 0);
116 if (!Number.isFinite(lastSeenAt) || lastSeenAt <= 0) return true;
117 return now - lastSeenAt >= SESSION_IDLE_TIMEOUT_MS;
118}
119
120function resetPendingState ()
121{
122 state.pendingSinceAt = null;
123}
124
125function applyConfigState (underSystemd, schedule, now)
126{
127 const nextKey = configKeyFor(underSystemd, schedule);
128 if (state.configKey === nextKey) return;
129
130 state.configKey = nextKey;
131 state.underSystemd = !!underSystemd;
132 state.lastError = null;
133 resetPendingState();
134
135 if (!underSystemd || !schedule.enabled)
136 {
137 state.nextDueAt = null;
138 state.lastDecision = underSystemd ? 'disabled' : 'not-systemd';
139 return;
140 }
141
142 state.nextDueAt = computeInitialDueAt(schedule, now);
143 state.lastDecision = 'scheduled';
144}
145
146function tick ()
147{
148 const now = nowMs();
149 state.lastTickAt = now;
150
151 const underSystemd = !!process.env.INVOCATION_ID;
152 const schedule = buildScheduleConfig(loadConfig());
153 applyConfigState(underSystemd, schedule, now);
154
155 if (!underSystemd || !schedule.enabled || !Number.isFinite(state.nextDueAt)) return;
156
157 if (now < state.nextDueAt)
158 {
159 state.lastDecision = 'waiting-next-window';
160 return;
161 }
162
163 if (!state.pendingSinceAt) state.pendingSinceAt = now;
164
165 if (!noLoggedInClientsForIdleWindow(now))
166 {
167 state.lastDecision = 'waiting-for-idle-clients';
168 return;
169 }
170
171 state.lastDecision = 'triggering-restart';
172 state.lastShutdownAt = now;
173 state.nextDueAt = advanceDueAt(state.nextDueAt, schedule);
174 resetPendingState();
175
176 if (typeof shutdownForRestartFn === 'function')
177 {
178 shutdownForRestartFn();
179 }
180}
181
182function startRestartScheduler (opts = {})
183{
184 shutdownForRestartFn = typeof opts.shutdownForRestart === 'function' ? opts.shutdownForRestart : null;
185 if (schedulerTimer) return;
186
187 state.startedAt = nowMs();
188 state.lastError = null;
189
190 try
191 {
192 tick();
193 } catch (err)
194 {
195 state.lastError = err && err.message ? String(err.message) : String(err);
196 }
197
198 schedulerTimer = setInterval(() =>
199 {
200 try
201 {
202 tick();
203 } catch (err)
204 {
205 state.lastError = err && err.message ? String(err.message) : String(err);
206 }
207 }, SCHEDULER_INTERVAL_MS);
208
209 if (schedulerTimer && typeof schedulerTimer.unref === 'function') schedulerTimer.unref();
210}
211
212function stopRestartScheduler ()
213{
214 if (!schedulerTimer) return;
215 clearInterval(schedulerTimer);
216 schedulerTimer = null;
217}
218
219function getRestartSchedulerSnapshot ()
220{
221 const schedule = buildScheduleConfig(loadConfig());
222
223 return {
224 running: !!schedulerTimer,
225 startedAt: state.startedAt,
226 lastTickAt: state.lastTickAt,
227 nextDueAt: state.nextDueAt,
228 pendingSinceAt: state.pendingSinceAt,
229 lastShutdownAt: state.lastShutdownAt,
230 lastDecision: state.lastDecision,
231 lastError: state.lastError,
232 underSystemd: !!process.env.INVOCATION_ID,
233 config: {
234 enabled: schedule.enabled,
235 cadence: schedule.cadence,
236 time: schedule.time,
237 },
238 intervalMs: SCHEDULER_INTERVAL_MS,
239 };
240}
241
242module.exports = {
243 startRestartScheduler,
244 stopRestartScheduler,
245 getRestartSchedulerSnapshot,
246};
server/routes/admin.js +52 −1
@@ -48,6 +48,28 @@ const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48 48 const debugRouter = require('./debug');
49 49
50 50 const BCRYPT_ROUNDS = 12;
51 const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
52 const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
53
54 function normaliseScheduledRestartConfig (value, fallback = null)
55 {
56 const defaults = fallback && typeof fallback === 'object'
57 ? fallback
58 : { enabled: false, cadence: 'daily', time: '04:00' };
59 const raw = value && typeof value === 'object' ? value : {};
60
61 const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase();
62 const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence;
63
64 const timeRaw = String(raw.time || defaults.time || '').trim();
65 const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time;
66
67 return {
68 enabled: !!raw.enabled,
69 cadence,
70 time,
71 };
72 }
51 73
52 74 function normalizePermissions (permissions)
53 75 {
@@ -306,12 +328,14 @@ router.get('/config', (req, res) =>
306 328 {
307 329 const config = loadConfig();
308 330 const effective = getEffectivePaths(config.paths || []);
331 const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart);
309 332 res.json({
310 333 port: config.port || 3000,
311 334 paths: config.paths || [],
312 335 effectivePaths: effective,
313 336 userPath: config.userPath || null,
314 337 userFolderSizeLimit: config.userFolderSizeLimit || null,
338 scheduledRestart,
315 339 });
316 340 });
317 341
@@ -322,7 +346,7 @@ router.get('/config', (req, res) =>
322 346 // ---------------------------------------------------------------------------
323 347 router.put('/config', (req, res) =>
324 348 {
325 const { paths, port, userPath, userFolderSizeLimit } = req.body;
349 const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body;
326 350 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
327 351
328 352 const config = loadConfig();
@@ -357,6 +381,33 @@ router.put('/config', (req, res) =>
357 381 }
358 382 }
359 383
384 if (scheduledRestart !== undefined)
385 {
386 if (!process.env.INVOCATION_ID)
387 {
388 return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' });
389 }
390
391 if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart))
392 {
393 return res.status(400).json({ error: 'scheduledRestart must be an object.' });
394 }
395
396 const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase();
397 if (!SCHEDULED_RESTART_CADENCES.has(cadence))
398 {
399 return res.status(400).json({ error: 'Invalid scheduled restart cadence.' });
400 }
401
402 const time = String(scheduledRestart.time || '').trim();
403 if (!SCHEDULED_RESTART_TIME_RE.test(time))
404 {
405 return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' });
406 }
407
408 config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart);
409 }
410
360 411 try
361 412 {
362 413 saveConfig(config);
@@ -48,6 +48,28 @@ const { loadConfig, saveConfig, getEffectivePaths } = require('../config');
48const debugRouter = require('./debug');
48const debugRouter = require('./debug');
49
49
50const BCRYPT_ROUNDS = 12;
50const BCRYPT_ROUNDS = 12;
51const SCHEDULED_RESTART_CADENCES = new Set(['daily', 'every3days', 'weekly', 'biweekly', 'monthly']);
52const SCHEDULED_RESTART_TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/;
53
54function normaliseScheduledRestartConfig (value, fallback = null)
55{
56 const defaults = fallback && typeof fallback === 'object'
57 ? fallback
58 : { enabled: false, cadence: 'daily', time: '04:00' };
59 const raw = value && typeof value === 'object' ? value : {};
60
61 const cadenceRaw = String(raw.cadence || defaults.cadence || '').trim().toLowerCase();
62 const cadence = SCHEDULED_RESTART_CADENCES.has(cadenceRaw) ? cadenceRaw : defaults.cadence;
63
64 const timeRaw = String(raw.time || defaults.time || '').trim();
65 const time = SCHEDULED_RESTART_TIME_RE.test(timeRaw) ? timeRaw : defaults.time;
66
67 return {
68 enabled: !!raw.enabled,
69 cadence,
70 time,
71 };
72}
51
73
52function normalizePermissions (permissions)
74function normalizePermissions (permissions)
53{
75{
@@ -306,12 +328,14 @@ router.get('/config', (req, res) =>
306{
328{
307 const config = loadConfig();
329 const config = loadConfig();
308 const effective = getEffectivePaths(config.paths || []);
330 const effective = getEffectivePaths(config.paths || []);
331 const scheduledRestart = normaliseScheduledRestartConfig(config.scheduledRestart);
309 res.json({
332 res.json({
310 port: config.port || 3000,
333 port: config.port || 3000,
311 paths: config.paths || [],
334 paths: config.paths || [],
312 effectivePaths: effective,
335 effectivePaths: effective,
313 userPath: config.userPath || null,
336 userPath: config.userPath || null,
314 userFolderSizeLimit: config.userFolderSizeLimit || null,
337 userFolderSizeLimit: config.userFolderSizeLimit || null,
338 scheduledRestart,
315 });
339 });
316});
340});
317
341
@@ -322,7 +346,7 @@ router.get('/config', (req, res) =>
322// ---------------------------------------------------------------------------
346// ---------------------------------------------------------------------------
323router.put('/config', (req, res) =>
347router.put('/config', (req, res) =>
324{
348{
325 const { paths, port, userPath, userFolderSizeLimit } = req.body;
349 const { paths, port, userPath, userFolderSizeLimit, scheduledRestart } = req.body;
326 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
350 if (!Array.isArray(paths)) return res.status(400).json({ error: 'paths must be an array.' });
327
351
328 const config = loadConfig();
352 const config = loadConfig();
@@ -357,6 +381,33 @@ router.put('/config', (req, res) =>
357 }
381 }
358 }
382 }
359
383
384 if (scheduledRestart !== undefined)
385 {
386 if (!process.env.INVOCATION_ID)
387 {
388 return res.status(400).json({ error: 'Scheduled restart requires running under systemd.' });
389 }
390
391 if (!scheduledRestart || typeof scheduledRestart !== 'object' || Array.isArray(scheduledRestart))
392 {
393 return res.status(400).json({ error: 'scheduledRestart must be an object.' });
394 }
395
396 const cadence = String(scheduledRestart.cadence || '').trim().toLowerCase();
397 if (!SCHEDULED_RESTART_CADENCES.has(cadence))
398 {
399 return res.status(400).json({ error: 'Invalid scheduled restart cadence.' });
400 }
401
402 const time = String(scheduledRestart.time || '').trim();
403 if (!SCHEDULED_RESTART_TIME_RE.test(time))
404 {
405 return res.status(400).json({ error: 'Invalid scheduled restart time. Expected HH:MM (24-hour).' });
406 }
407
408 config.scheduledRestart = normaliseScheduledRestartConfig(scheduledRestart, config.scheduledRestart);
409 }
410
360 try
411 try
361 {
412 {
362 saveConfig(config);
413 saveConfig(config);
server/routes/debug.js +58 −0
@@ -12,6 +12,9 @@ const { loadConfig, getEffectivePaths } = require('../config');
12 12 const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
13 13 const { getVideoStreamDebugSnapshot } = require('../video-stream');
14 14 const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
15 const authModule = require('../auth');
16 const shareRoutes = require('./share');
17 const restartScheduler = require('../restart-scheduler');
15 18
16 19 const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
17 20
@@ -199,6 +202,59 @@ function getMemorySnapshot ()
199 202 };
200 203 }
201 204
205 function getMaintenanceSnapshot ()
206 {
207 const db = getDb();
208 const now = Date.now();
209 const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
210
211 const authRows = db.prepare(`
212 SELECT
213 COUNT(*) AS total,
214 SUM(CASE WHEN revoked_at IS NULL THEN 1 ELSE 0 END) AS active,
215 SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked
216 FROM auth_sessions
217 `).get() || {};
218
219 const shareRows = db.prepare(`
220 SELECT
221 COUNT(*) AS total,
222 SUM(CASE WHEN expires_at <= ? THEN 1 ELSE 0 END) AS expired
223 FROM share_tokens
224 `).get([now]) || {};
225
226 const activeUserRows = db.prepare(
227 `SELECT COUNT(DISTINCT username) AS count
228 FROM auth_sessions
229 WHERE revoked_at IS NULL
230 AND last_seen_at >= ?`,
231 ).get([activeSince]) || {};
232
233 const authCleanup = typeof authModule.getAuthSessionCleanupSnapshot === 'function'
234 ? authModule.getAuthSessionCleanupSnapshot()
235 : null;
236 const shareMaintenance = typeof shareRoutes.getShareMaintenanceSnapshot === 'function'
237 ? shareRoutes.getShareMaintenanceSnapshot()
238 : null;
239 const scheduledRestart = typeof restartScheduler.getRestartSchedulerSnapshot === 'function'
240 ? restartScheduler.getRestartSchedulerSnapshot()
241 : null;
242
243 return {
244 rows: {
245 authSessionsTotal: Number(authRows.total || 0),
246 authSessionsActive: Number(authRows.active || 0),
247 authSessionsRevoked: Number(authRows.revoked || 0),
248 activeLoggedInUsers: Number(activeUserRows.count || 0),
249 shareTokensTotal: Number(shareRows.total || 0),
250 shareTokensExpired: Number(shareRows.expired || 0),
251 },
252 authCleanup,
253 shareMaintenance,
254 scheduledRestart,
255 };
256 }
257
202 258 router.get('/debug/stream-stats', (req, res) =>
203 259 {
204 260 const rootUsage = collectRootUsageStats();
@@ -208,6 +264,7 @@ router.get('/debug/stream-stats', (req, res) =>
208 264 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
209 265 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
210 266 const memory = getMemorySnapshot();
267 const maintenance = getMaintenanceSnapshot();
211 268
212 269 res.json({
213 270 generatedAt: Date.now(),
@@ -218,6 +275,7 @@ router.get('/debug/stream-stats', (req, res) =>
218 275 subtitleCache,
219 276 subtitleDebugLog,
220 277 videoFiles,
278 maintenance,
221 279 });
222 280 });
223 281
@@ -12,6 +12,9 @@ const { 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');
14const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
15const authModule = require('../auth');
16const shareRoutes = require('./share');
17const restartScheduler = require('../restart-scheduler');
15
18
16const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
19const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
17
20
@@ -199,6 +202,59 @@ function getMemorySnapshot ()
199 };
202 };
200}
203}
201
204
205function getMaintenanceSnapshot ()
206{
207 const db = getDb();
208 const now = Date.now();
209 const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
210
211 const authRows = db.prepare(`
212 SELECT
213 COUNT(*) AS total,
214 SUM(CASE WHEN revoked_at IS NULL THEN 1 ELSE 0 END) AS active,
215 SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked
216 FROM auth_sessions
217 `).get() || {};
218
219 const shareRows = db.prepare(`
220 SELECT
221 COUNT(*) AS total,
222 SUM(CASE WHEN expires_at <= ? THEN 1 ELSE 0 END) AS expired
223 FROM share_tokens
224 `).get([now]) || {};
225
226 const activeUserRows = db.prepare(
227 `SELECT COUNT(DISTINCT username) AS count
228 FROM auth_sessions
229 WHERE revoked_at IS NULL
230 AND last_seen_at >= ?`,
231 ).get([activeSince]) || {};
232
233 const authCleanup = typeof authModule.getAuthSessionCleanupSnapshot === 'function'
234 ? authModule.getAuthSessionCleanupSnapshot()
235 : null;
236 const shareMaintenance = typeof shareRoutes.getShareMaintenanceSnapshot === 'function'
237 ? shareRoutes.getShareMaintenanceSnapshot()
238 : null;
239 const scheduledRestart = typeof restartScheduler.getRestartSchedulerSnapshot === 'function'
240 ? restartScheduler.getRestartSchedulerSnapshot()
241 : null;
242
243 return {
244 rows: {
245 authSessionsTotal: Number(authRows.total || 0),
246 authSessionsActive: Number(authRows.active || 0),
247 authSessionsRevoked: Number(authRows.revoked || 0),
248 activeLoggedInUsers: Number(activeUserRows.count || 0),
249 shareTokensTotal: Number(shareRows.total || 0),
250 shareTokensExpired: Number(shareRows.expired || 0),
251 },
252 authCleanup,
253 shareMaintenance,
254 scheduledRestart,
255 };
256}
257
202router.get('/debug/stream-stats', (req, res) =>
258router.get('/debug/stream-stats', (req, res) =>
203{
259{
204 const rootUsage = collectRootUsageStats();
260 const rootUsage = collectRootUsageStats();
@@ -208,6 +264,7 @@ router.get('/debug/stream-stats', (req, res) =>
208 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
264 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
209 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
265 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
210 const memory = getMemorySnapshot();
266 const memory = getMemorySnapshot();
267 const maintenance = getMaintenanceSnapshot();
211
268
212 res.json({
269 res.json({
213 generatedAt: Date.now(),
270 generatedAt: Date.now(),
@@ -218,6 +275,7 @@ router.get('/debug/stream-stats', (req, res) =>
218 subtitleCache,
275 subtitleCache,
219 subtitleDebugLog,
276 subtitleDebugLog,
220 videoFiles,
277 videoFiles,
278 maintenance,
221 });
279 });
222});
280});
223
281
server/routes/share.js +49 −3
@@ -21,6 +21,13 @@ const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
21 21 const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
22 22
23 23 let shareMaintenanceTimer = null;
24 const shareMaintenanceState = {
25 lastRunAt: null,
26 lastPurgedTokenCount: 0,
27 lastPrunedZipCount: 0,
28 lastDurationMs: 0,
29 lastError: null,
30 };
24 31
25 32 // ---------------------------------------------------------------------------
26 33 // Helpers
@@ -96,8 +103,28 @@ function purgeExpiredShareTokens (opts = {})
96 103
97 104 function runShareMaintenanceOnce ()
98 105 {
99 purgeExpiredShareTokens();
100 pruneZipCache();
106 const startedAt = Date.now();
107 try
108 {
109 const purgedTokens = purgeExpiredShareTokens();
110 const prunedZips = pruneZipCache();
111 const endedAt = Date.now();
112 shareMaintenanceState.lastRunAt = endedAt;
113 shareMaintenanceState.lastPurgedTokenCount = Number(purgedTokens || 0);
114 shareMaintenanceState.lastPrunedZipCount = Number(prunedZips || 0);
115 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
116 shareMaintenanceState.lastError = null;
117 return { purgedTokens, prunedZips };
118 } catch (err)
119 {
120 const endedAt = Date.now();
121 shareMaintenanceState.lastRunAt = endedAt;
122 shareMaintenanceState.lastPurgedTokenCount = 0;
123 shareMaintenanceState.lastPrunedZipCount = 0;
124 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
125 shareMaintenanceState.lastError = err && err.message ? String(err.message) : String(err);
126 throw err;
127 }
101 128 }
102 129
103 130 function startShareMaintenanceLoop ()
@@ -144,13 +171,14 @@ function pruneZipCache ()
144 171 {
145 172 ensureZipCacheDir();
146 173 const now = Date.now();
174 let deletedCount = 0;
147 175 let entries;
148 176 try
149 177 {
150 178 entries = fs.readdirSync(ZIP_CACHE_DIR);
151 179 } catch
152 180 {
153 return;
181 return deletedCount;
154 182 }
155 183
156 184 for (const name of entries)
@@ -164,12 +192,29 @@ function pruneZipCache ()
164 192 if (age > ZIP_MAX_AGE_MS)
165 193 {
166 194 fs.unlinkSync(fullPath);
195 deletedCount += 1;
167 196 }
168 197 } catch
169 198 {
170 199 // Ignore files that disappeared.
171 200 }
172 201 }
202
203 return deletedCount;
204 }
205
206 function getShareMaintenanceSnapshot ()
207 {
208 return {
209 running: !!shareMaintenanceTimer,
210 intervalMs: SHARE_MAINTENANCE_INTERVAL_MS,
211 lastRunAt: shareMaintenanceState.lastRunAt,
212 lastPurgedTokenCount: shareMaintenanceState.lastPurgedTokenCount,
213 lastPrunedZipCount: shareMaintenanceState.lastPrunedZipCount,
214 lastDurationMs: shareMaintenanceState.lastDurationMs,
215 lastError: shareMaintenanceState.lastError,
216 zipMaxAgeMs: ZIP_MAX_AGE_MS,
217 };
173 218 }
174 219
175 220 /**
@@ -712,6 +757,7 @@ module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
712 757 module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
713 758 module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
714 759 module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
760 module.exports.getShareMaintenanceSnapshot = getShareMaintenanceSnapshot;
715 761 module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
716 762 module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
717 763 module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
@@ -21,6 +21,13 @@ const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
21const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
21const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
22
22
23let shareMaintenanceTimer = null;
23let shareMaintenanceTimer = null;
24const shareMaintenanceState = {
25 lastRunAt: null,
26 lastPurgedTokenCount: 0,
27 lastPrunedZipCount: 0,
28 lastDurationMs: 0,
29 lastError: null,
30};
24
31
25// ---------------------------------------------------------------------------
32// ---------------------------------------------------------------------------
26// Helpers
33// Helpers
@@ -96,8 +103,28 @@ function purgeExpiredShareTokens (opts = {})
96
103
97function runShareMaintenanceOnce ()
104function runShareMaintenanceOnce ()
98{
105{
99 purgeExpiredShareTokens();
106 const startedAt = Date.now();
100 pruneZipCache();
107 try
108 {
109 const purgedTokens = purgeExpiredShareTokens();
110 const prunedZips = pruneZipCache();
111 const endedAt = Date.now();
112 shareMaintenanceState.lastRunAt = endedAt;
113 shareMaintenanceState.lastPurgedTokenCount = Number(purgedTokens || 0);
114 shareMaintenanceState.lastPrunedZipCount = Number(prunedZips || 0);
115 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
116 shareMaintenanceState.lastError = null;
117 return { purgedTokens, prunedZips };
118 } catch (err)
119 {
120 const endedAt = Date.now();
121 shareMaintenanceState.lastRunAt = endedAt;
122 shareMaintenanceState.lastPurgedTokenCount = 0;
123 shareMaintenanceState.lastPrunedZipCount = 0;
124 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
125 shareMaintenanceState.lastError = err && err.message ? String(err.message) : String(err);
126 throw err;
127 }
101}
128}
102
129
103function startShareMaintenanceLoop ()
130function startShareMaintenanceLoop ()
@@ -144,13 +171,14 @@ function pruneZipCache ()
144{
171{
145 ensureZipCacheDir();
172 ensureZipCacheDir();
146 const now = Date.now();
173 const now = Date.now();
174 let deletedCount = 0;
147 let entries;
175 let entries;
148 try
176 try
149 {
177 {
150 entries = fs.readdirSync(ZIP_CACHE_DIR);
178 entries = fs.readdirSync(ZIP_CACHE_DIR);
151 } catch
179 } catch
152 {
180 {
153 return;
181 return deletedCount;
154 }
182 }
155
183
156 for (const name of entries)
184 for (const name of entries)
@@ -164,12 +192,29 @@ function pruneZipCache ()
164 if (age > ZIP_MAX_AGE_MS)
192 if (age > ZIP_MAX_AGE_MS)
165 {
193 {
166 fs.unlinkSync(fullPath);
194 fs.unlinkSync(fullPath);
195 deletedCount += 1;
167 }
196 }
168 } catch
197 } catch
169 {
198 {
170 // Ignore files that disappeared.
199 // Ignore files that disappeared.
171 }
200 }
172 }
201 }
202
203 return deletedCount;
204}
205
206function getShareMaintenanceSnapshot ()
207{
208 return {
209 running: !!shareMaintenanceTimer,
210 intervalMs: SHARE_MAINTENANCE_INTERVAL_MS,
211 lastRunAt: shareMaintenanceState.lastRunAt,
212 lastPurgedTokenCount: shareMaintenanceState.lastPurgedTokenCount,
213 lastPrunedZipCount: shareMaintenanceState.lastPrunedZipCount,
214 lastDurationMs: shareMaintenanceState.lastDurationMs,
215 lastError: shareMaintenanceState.lastError,
216 zipMaxAgeMs: ZIP_MAX_AGE_MS,
217 };
173}
218}
174
219
175/**
220/**
@@ -712,6 +757,7 @@ module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
712module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
757module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
713module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
758module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
714module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
759module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
760module.exports.getShareMaintenanceSnapshot = getShareMaintenanceSnapshot;
715module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
761module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
716module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
762module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
717module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
763module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;
tests/admin.routes.test.js +100 −1
@@ -26,6 +26,20 @@ let mockSubtitleSnapshot = {
26 26 byFile: {},
27 27 };
28 28
29 let mockRestartSchedulerSnapshot = {
30 running: true,
31 startedAt: Date.now(),
32 lastTickAt: Date.now(),
33 nextDueAt: Date.now() + 3600000,
34 pendingSinceAt: null,
35 lastShutdownAt: null,
36 lastDecision: 'waiting-next-window',
37 lastError: null,
38 underSystemd: true,
39 config: { enabled: false, cadence: 'daily', time: '04:00' },
40 intervalMs: 60000,
41 };
42
29 43 // ── child_process mock — controlled per test ──────────────────────────────────
30 44 let mockExecFileImpl = null;
31 45 jest.mock('child_process', () =>
@@ -80,6 +94,14 @@ jest.mock('../server/db', () =>
80 94 last_seen_at INTEGER NOT NULL,
81 95 revoked_at INTEGER
82 96 );
97 CREATE TABLE IF NOT EXISTS share_tokens (
98 token TEXT PRIMARY KEY,
99 file_path TEXT NOT NULL,
100 is_dir INTEGER NOT NULL DEFAULT 0,
101 created_by TEXT NOT NULL,
102 created_at INTEGER NOT NULL,
103 expires_at INTEGER NOT NULL
104 );
83 105 `);
84 106 }
85 107 return db;
@@ -95,8 +117,17 @@ jest.mock('../server/image-subtitles', () => ({
95 117 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
96 118 }));
97 119
120 jest.mock('../server/restart-scheduler', () => ({
121 getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot,
122 }));
123
98 124 // ── config mock ─────────────────────────────────────────────────────────────
99 const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
125 const mockConfig = {
126 port: 3000,
127 paths: ['/mnt/data', '/mnt/docs'],
128 userPath: null,
129 scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' },
130 };
100 131 jest.mock('../server/config', () => ({
101 132 loadConfig: () => ({ ...mockConfig }),
102 133 saveConfig: (c) => Object.assign(mockConfig, c),
@@ -438,6 +469,11 @@ describe('GET /api/admin/config', () =>
438 469 expect(status).toBe(200);
439 470 expect(body.port).toBe(3000);
440 471 expect(Array.isArray(body.paths)).toBe(true);
472 expect(body.scheduledRestart).toEqual(expect.objectContaining({
473 enabled: expect.any(Boolean),
474 cadence: expect.any(String),
475 time: expect.any(String),
476 }));
441 477 });
442 478 });
443 479
@@ -501,6 +537,15 @@ describe('GET /api/admin/debug/stream-stats', () =>
501 537 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
502 538 expect(status).toBe(200);
503 539 expect(Array.isArray(body.videoFiles)).toBe(true);
540 expect(body.maintenance).toEqual(expect.objectContaining({
541 rows: expect.objectContaining({
542 authSessionsTotal: expect.any(Number),
543 shareTokensTotal: expect.any(Number),
544 }),
545 scheduledRestart: expect.objectContaining({
546 intervalMs: expect.any(Number),
547 }),
548 }));
504 549
505 550 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
506 551 expect(live).toBeTruthy();
@@ -540,6 +585,60 @@ describe('PUT /api/admin/config', () =>
540 585 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
541 586 expect(status).toBe(400);
542 587 });
588
589 test('saves scheduled restart config when running under systemd', async () =>
590 {
591 const origInvocationId = process.env.INVOCATION_ID;
592 process.env.INVOCATION_ID = 'test-invocation';
593
594 try
595 {
596 const { status, body } = await req('PUT', '/api/admin/config', {
597 paths: ['/mnt/data'],
598 scheduledRestart: {
599 enabled: true,
600 cadence: 'weekly',
601 time: '03:45',
602 },
603 });
604 expect(status).toBe(200);
605 expect(body.ok).toBe(true);
606
607 const readback = await req('GET', '/api/admin/config');
608 expect(readback.body.scheduledRestart).toEqual({
609 enabled: true,
610 cadence: 'weekly',
611 time: '03:45',
612 });
613 } finally
614 {
615 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
616 else process.env.INVOCATION_ID = origInvocationId;
617 }
618 });
619
620 test('rejects scheduled restart config when not running under systemd', async () =>
621 {
622 const origInvocationId = process.env.INVOCATION_ID;
623 delete process.env.INVOCATION_ID;
624
625 try
626 {
627 const { status } = await req('PUT', '/api/admin/config', {
628 paths: ['/mnt/data'],
629 scheduledRestart: {
630 enabled: true,
631 cadence: 'daily',
632 time: '02:15',
633 },
634 });
635 expect(status).toBe(400);
636 } finally
637 {
638 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
639 else process.env.INVOCATION_ID = origInvocationId;
640 }
641 });
543 642 });
544 643
545 644 describe('POST /api/admin/shutdown', () =>
@@ -26,6 +26,20 @@ let mockSubtitleSnapshot = {
26 byFile: {},
26 byFile: {},
27};
27};
28
28
29let mockRestartSchedulerSnapshot = {
30 running: true,
31 startedAt: Date.now(),
32 lastTickAt: Date.now(),
33 nextDueAt: Date.now() + 3600000,
34 pendingSinceAt: null,
35 lastShutdownAt: null,
36 lastDecision: 'waiting-next-window',
37 lastError: null,
38 underSystemd: true,
39 config: { enabled: false, cadence: 'daily', time: '04:00' },
40 intervalMs: 60000,
41};
42
29// ── child_process mock — controlled per test ──────────────────────────────────
43// ── child_process mock — controlled per test ──────────────────────────────────
30let mockExecFileImpl = null;
44let mockExecFileImpl = null;
31jest.mock('child_process', () =>
45jest.mock('child_process', () =>
@@ -80,6 +94,14 @@ jest.mock('../server/db', () =>
80 last_seen_at INTEGER NOT NULL,
94 last_seen_at INTEGER NOT NULL,
81 revoked_at INTEGER
95 revoked_at INTEGER
82 );
96 );
97 CREATE TABLE IF NOT EXISTS share_tokens (
98 token TEXT PRIMARY KEY,
99 file_path TEXT NOT NULL,
100 is_dir INTEGER NOT NULL DEFAULT 0,
101 created_by TEXT NOT NULL,
102 created_at INTEGER NOT NULL,
103 expires_at INTEGER NOT NULL
104 );
83 `);
105 `);
84 }
106 }
85 return db;
107 return db;
@@ -95,8 +117,17 @@ jest.mock('../server/image-subtitles', () => ({
95 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
117 getImageSubtitleDebugSnapshot: () => mockSubtitleSnapshot,
96}));
118}));
97
119
120jest.mock('../server/restart-scheduler', () => ({
121 getRestartSchedulerSnapshot: () => mockRestartSchedulerSnapshot,
122}));
123
98// ── config mock ─────────────────────────────────────────────────────────────
124// ── config mock ─────────────────────────────────────────────────────────────
99const mockConfig = { port: 3000, paths: ['/mnt/data', '/mnt/docs'], userPath: null };
125const mockConfig = {
126 port: 3000,
127 paths: ['/mnt/data', '/mnt/docs'],
128 userPath: null,
129 scheduledRestart: { enabled: false, cadence: 'daily', time: '04:00' },
130};
100jest.mock('../server/config', () => ({
131jest.mock('../server/config', () => ({
101 loadConfig: () => ({ ...mockConfig }),
132 loadConfig: () => ({ ...mockConfig }),
102 saveConfig: (c) => Object.assign(mockConfig, c),
133 saveConfig: (c) => Object.assign(mockConfig, c),
@@ -438,6 +469,11 @@ describe('GET /api/admin/config', () =>
438 expect(status).toBe(200);
469 expect(status).toBe(200);
439 expect(body.port).toBe(3000);
470 expect(body.port).toBe(3000);
440 expect(Array.isArray(body.paths)).toBe(true);
471 expect(Array.isArray(body.paths)).toBe(true);
472 expect(body.scheduledRestart).toEqual(expect.objectContaining({
473 enabled: expect.any(Boolean),
474 cadence: expect.any(String),
475 time: expect.any(String),
476 }));
441 });
477 });
442});
478});
443
479
@@ -501,6 +537,15 @@ describe('GET /api/admin/debug/stream-stats', () =>
501 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
537 const { status, body } = await req('GET', '/api/admin/debug/stream-stats');
502 expect(status).toBe(200);
538 expect(status).toBe(200);
503 expect(Array.isArray(body.videoFiles)).toBe(true);
539 expect(Array.isArray(body.videoFiles)).toBe(true);
540 expect(body.maintenance).toEqual(expect.objectContaining({
541 rows: expect.objectContaining({
542 authSessionsTotal: expect.any(Number),
543 shareTokensTotal: expect.any(Number),
544 }),
545 scheduledRestart: expect.objectContaining({
546 intervalMs: expect.any(Number),
547 }),
548 }));
504
549
505 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
550 const live = body.videoFiles.find((row) => row.filePath === '/videos/live.mkv');
506 expect(live).toBeTruthy();
551 expect(live).toBeTruthy();
@@ -540,6 +585,60 @@ describe('PUT /api/admin/config', () =>
540 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
585 const { status } = await req('PUT', '/api/admin/config', { paths: [], port: 99999 });
541 expect(status).toBe(400);
586 expect(status).toBe(400);
542 });
587 });
588
589 test('saves scheduled restart config when running under systemd', async () =>
590 {
591 const origInvocationId = process.env.INVOCATION_ID;
592 process.env.INVOCATION_ID = 'test-invocation';
593
594 try
595 {
596 const { status, body } = await req('PUT', '/api/admin/config', {
597 paths: ['/mnt/data'],
598 scheduledRestart: {
599 enabled: true,
600 cadence: 'weekly',
601 time: '03:45',
602 },
603 });
604 expect(status).toBe(200);
605 expect(body.ok).toBe(true);
606
607 const readback = await req('GET', '/api/admin/config');
608 expect(readback.body.scheduledRestart).toEqual({
609 enabled: true,
610 cadence: 'weekly',
611 time: '03:45',
612 });
613 } finally
614 {
615 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
616 else process.env.INVOCATION_ID = origInvocationId;
617 }
618 });
619
620 test('rejects scheduled restart config when not running under systemd', async () =>
621 {
622 const origInvocationId = process.env.INVOCATION_ID;
623 delete process.env.INVOCATION_ID;
624
625 try
626 {
627 const { status } = await req('PUT', '/api/admin/config', {
628 paths: ['/mnt/data'],
629 scheduledRestart: {
630 enabled: true,
631 cadence: 'daily',
632 time: '02:15',
633 },
634 });
635 expect(status).toBe(400);
636 } finally
637 {
638 if (origInvocationId === undefined) delete process.env.INVOCATION_ID;
639 else process.env.INVOCATION_ID = origInvocationId;
640 }
641 });
543});
642});
544
643
545describe('POST /api/admin/shutdown', () =>
644describe('POST /api/admin/shutdown', () =>