'use strict'; const express = require('express'); const fs = require('fs'); const os = require('os'); const path = require('path'); const router = express.Router(); const { getDb } = require('../db'); const { loadConfig, getEffectivePaths } = require('../config'); const { getImageSubtitleDebugSnapshot } = require('../image-subtitles'); const { getVideoStreamDebugSnapshot } = require('../video-stream'); const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log'); const authModule = require('../auth'); const shareRoutes = require('./share'); const restartScheduler = require('../restart-scheduler'); const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000; function safeResolve (value) { return path.resolve(String(value || '').trim()); } function normaliseRootsForUsage (config) { const rawRoots = Array.isArray(config.paths) ? config.paths : []; const effective = getEffectivePaths(rawRoots); const roots = new Set(effective.map((root) => safeResolve(root))); const userPath = String(config.userPath || '').trim(); if (userPath) { const resolvedUserPath = safeResolve(userPath); const isCovered = [...roots].some((root) => resolvedUserPath === root || resolvedUserPath.startsWith(`${root}${path.sep}`)); if (!isCovered) roots.add(resolvedUserPath); } return [...roots]; } function walkDirectorySize (rootPath) { let bytes = 0; let files = 0; let directories = 0; const stack = [rootPath]; while (stack.length > 0) { const current = stack.pop(); let entries = []; try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { continue; } for (const entry of entries) { const fullPath = path.join(current, entry.name); if (entry.isDirectory()) { directories += 1; stack.push(fullPath); continue; } if (!entry.isFile()) continue; try { const stat = fs.statSync(fullPath); bytes += Number.isFinite(stat.size) ? stat.size : 0; files += 1; } catch { // Best effort; skip unreadable files. } } } return { bytes, files, directories }; } function collectRootUsageStats () { const config = loadConfig(); const roots = normaliseRootsForUsage(config); const perRoot = []; let totalBytes = 0; let totalFiles = 0; for (const root of roots) { const row = { path: root, exists: fs.existsSync(root), bytes: 0, files: 0, directories: 0, }; if (row.exists) { const usage = walkDirectorySize(root); row.bytes = usage.bytes; row.files = usage.files; row.directories = usage.directories; totalBytes += usage.bytes; totalFiles += usage.files; } perRoot.push(row); } return { roots: perRoot, totalBytes, totalFiles, }; } function getLoggedInUsersSnapshot () { const db = getDb(); const now = Date.now(); const activeSince = now - AUTH_IDLE_TIMEOUT_MS; const rows = db.prepare( `SELECT username, MAX(last_seen_at) AS lastSeenAt FROM auth_sessions WHERE revoked_at IS NULL AND last_seen_at >= ? GROUP BY username ORDER BY username COLLATE NOCASE ASC`, ).all([activeSince]); return rows.map((row) => ({ username: String(row.username || ''), lastSeenAt: Number(row.lastSeenAt || 0), })); } function buildVideoDebugRows (videoSnapshot, subtitleSnapshot) { const perFile = new Map(); const activeStreams = Array.isArray(videoSnapshot.activeStreams) ? videoSnapshot.activeStreams : []; for (const stream of activeStreams) { const key = safeResolve(stream.sourcePath); perFile.set(key, { filePath: key, viewers: Number(stream.viewers || 0), activeSessionIds: [stream.sessionId], stream: stream, subtitleCache: null, }); } const subtitleByFile = subtitleSnapshot && subtitleSnapshot.byFile ? subtitleSnapshot.byFile : {}; for (const [filePath, subtitleRow] of Object.entries(subtitleByFile)) { const key = safeResolve(filePath); const existing = perFile.get(key); if (existing) { existing.subtitleCache = subtitleRow; continue; } perFile.set(key, { filePath: key, viewers: 0, activeSessionIds: [], stream: null, subtitleCache: subtitleRow, }); } return [...perFile.values()].sort((a, b) => a.filePath.localeCompare(b.filePath)); } function getMemorySnapshot () { const totalBytes = Number(os.totalmem()) || 0; const freeBytes = Number(os.freemem()) || 0; const usedBytes = Math.max(0, totalBytes - freeBytes); return { totalBytes, freeBytes, usedBytes, usedPercent: totalBytes > 0 ? Number(((usedBytes / totalBytes) * 100).toFixed(1)) : 0, processRssBytes: Number(process.memoryUsage().rss || 0), processHeapUsedBytes: Number(process.memoryUsage().heapUsed || 0), }; } function getMaintenanceSnapshot () { const db = getDb(); const now = Date.now(); const activeSince = now - AUTH_IDLE_TIMEOUT_MS; const authRows = db.prepare(` SELECT COUNT(*) AS total, SUM(CASE WHEN revoked_at IS NULL THEN 1 ELSE 0 END) AS active, SUM(CASE WHEN revoked_at IS NOT NULL THEN 1 ELSE 0 END) AS revoked FROM auth_sessions `).get() || {}; const shareRows = db.prepare(` SELECT COUNT(*) AS total, SUM(CASE WHEN expires_at <= ? THEN 1 ELSE 0 END) AS expired FROM share_tokens `).get([now]) || {}; const activeUserRows = db.prepare( `SELECT COUNT(DISTINCT username) AS count FROM auth_sessions WHERE revoked_at IS NULL AND last_seen_at >= ?`, ).get([activeSince]) || {}; const authCleanup = typeof authModule.getAuthSessionCleanupSnapshot === 'function' ? authModule.getAuthSessionCleanupSnapshot() : null; const shareMaintenance = typeof shareRoutes.getShareMaintenanceSnapshot === 'function' ? shareRoutes.getShareMaintenanceSnapshot() : null; const scheduledRestart = typeof restartScheduler.getRestartSchedulerSnapshot === 'function' ? restartScheduler.getRestartSchedulerSnapshot() : null; return { rows: { authSessionsTotal: Number(authRows.total || 0), authSessionsActive: Number(authRows.active || 0), authSessionsRevoked: Number(authRows.revoked || 0), activeLoggedInUsers: Number(activeUserRows.count || 0), shareTokensTotal: Number(shareRows.total || 0), shareTokensExpired: Number(shareRows.expired || 0), }, authCleanup, shareMaintenance, scheduledRestart, }; } router.get('/debug/stream-stats', (req, res) => { const rootUsage = collectRootUsageStats(); const loggedInUsers = getLoggedInUsersSnapshot(); const videoStream = getVideoStreamDebugSnapshot(); const subtitleCache = getImageSubtitleDebugSnapshot(); const subtitleDebugLog = getSubtitleDebugLogSnapshot(); const videoFiles = buildVideoDebugRows(videoStream, subtitleCache); const memory = getMemorySnapshot(); const maintenance = getMaintenanceSnapshot(); res.json({ generatedAt: Date.now(), loggedInUsers, storage: rootUsage, memory, videoStream, subtitleCache, subtitleDebugLog, videoFiles, maintenance, }); }); module.exports = router;