| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const fs = require('fs'); |
| 5 | const os = require('os'); |
| 6 | const path = require('path'); |
| 7 | |
| 8 | const router = express.Router(); |
| 9 | |
| 10 | const { getDb } = require('../db'); |
| 11 | const { loadConfig, getEffectivePaths } = require('../config'); |
| 12 | const { getImageSubtitleDebugSnapshot } = require('../image-subtitles'); |
| 13 | const { getVideoStreamDebugSnapshot } = require('../video-stream'); |
| 14 | const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log'); |
| 15 | const authModule = require('../auth'); |
| 16 | const shareRoutes = require('./share'); |
| 17 | const restartScheduler = require('../restart-scheduler'); |
| 18 | |
| 19 | const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000; |
| 20 | |
| 21 | function safeResolve (value) |
| 22 | { |
| 23 | return path.resolve(String(value || '').trim()); |
| 24 | } |
| 25 | |
| 26 | function normaliseRootsForUsage (config) |
| 27 | { |
| 28 | const rawRoots = Array.isArray(config.paths) ? config.paths : []; |
| 29 | const effective = getEffectivePaths(rawRoots); |
| 30 | const roots = new Set(effective.map((root) => safeResolve(root))); |
| 31 | |
| 32 | const userPath = String(config.userPath || '').trim(); |
| 33 | if (userPath) |
| 34 | { |
| 35 | const resolvedUserPath = safeResolve(userPath); |
| 36 | const isCovered = [...roots].some((root) => |
| 37 | resolvedUserPath === root || resolvedUserPath.startsWith(`${root}${path.sep}`)); |
| 38 | if (!isCovered) roots.add(resolvedUserPath); |
| 39 | } |
| 40 | |
| 41 | return [...roots]; |
| 42 | } |
| 43 | |
| 44 | function walkDirectorySize (rootPath) |
| 45 | { |
| 46 | let bytes = 0; |
| 47 | let files = 0; |
| 48 | let directories = 0; |
| 49 | const stack = [rootPath]; |
| 50 | |
| 51 | while (stack.length > 0) |
| 52 | { |
| 53 | const current = stack.pop(); |
| 54 | let entries = []; |
| 55 | try |
| 56 | { |
| 57 | entries = fs.readdirSync(current, { withFileTypes: true }); |
| 58 | } catch |
| 59 | { |
| 60 | continue; |
| 61 | } |
| 62 | |
| 63 | for (const entry of entries) |
| 64 | { |
| 65 | const fullPath = path.join(current, entry.name); |
| 66 | if (entry.isDirectory()) |
| 67 | { |
| 68 | directories += 1; |
| 69 | stack.push(fullPath); |
| 70 | continue; |
| 71 | } |
| 72 | |
| 73 | if (!entry.isFile()) continue; |
| 74 | try |
| 75 | { |
| 76 | const stat = fs.statSync(fullPath); |
| 77 | bytes += Number.isFinite(stat.size) ? stat.size : 0; |
| 78 | files += 1; |
| 79 | } catch |
| 80 | { |
| 81 | // Best effort; skip unreadable files. |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | return { bytes, files, directories }; |
| 87 | } |
| 88 | |
| 89 | function collectRootUsageStats () |
| 90 | { |
| 91 | const config = loadConfig(); |
| 92 | const roots = normaliseRootsForUsage(config); |
| 93 | |
| 94 | const perRoot = []; |
| 95 | let totalBytes = 0; |
| 96 | let totalFiles = 0; |
| 97 | |
| 98 | for (const root of roots) |
| 99 | { |
| 100 | const row = { |
| 101 | path: root, |
| 102 | exists: fs.existsSync(root), |
| 103 | bytes: 0, |
| 104 | files: 0, |
| 105 | directories: 0, |
| 106 | }; |
| 107 | |
| 108 | if (row.exists) |
| 109 | { |
| 110 | const usage = walkDirectorySize(root); |
| 111 | row.bytes = usage.bytes; |
| 112 | row.files = usage.files; |
| 113 | row.directories = usage.directories; |
| 114 | totalBytes += usage.bytes; |
| 115 | totalFiles += usage.files; |
| 116 | } |
| 117 | |
| 118 | perRoot.push(row); |
| 119 | } |
| 120 | |
| 121 | return { |
| 122 | roots: perRoot, |
| 123 | totalBytes, |
| 124 | totalFiles, |
| 125 | }; |
| 126 | } |
| 127 | |
| 128 | function getLoggedInUsersSnapshot () |
| 129 | { |
| 130 | const db = getDb(); |
| 131 | const now = Date.now(); |
| 132 | const activeSince = now - AUTH_IDLE_TIMEOUT_MS; |
| 133 | |
| 134 | const rows = db.prepare( |
| 135 | `SELECT username, MAX(last_seen_at) AS lastSeenAt |
| 136 | FROM auth_sessions |
| 137 | WHERE revoked_at IS NULL |
| 138 | AND last_seen_at >= ? |
| 139 | GROUP BY username |
| 140 | ORDER BY username COLLATE NOCASE ASC`, |
| 141 | ).all([activeSince]); |
| 142 | |
| 143 | return rows.map((row) => ({ |
| 144 | username: String(row.username || ''), |
| 145 | lastSeenAt: Number(row.lastSeenAt || 0), |
| 146 | })); |
| 147 | } |
| 148 | |
| 149 | function buildVideoDebugRows (videoSnapshot, subtitleSnapshot) |
| 150 | { |
| 151 | const perFile = new Map(); |
| 152 | |
| 153 | const activeStreams = Array.isArray(videoSnapshot.activeStreams) ? videoSnapshot.activeStreams : []; |
| 154 | for (const stream of activeStreams) |
| 155 | { |
| 156 | const key = safeResolve(stream.sourcePath); |
| 157 | perFile.set(key, { |
| 158 | filePath: key, |
| 159 | viewers: Number(stream.viewers || 0), |
| 160 | activeSessionIds: [stream.sessionId], |
| 161 | stream: stream, |
| 162 | subtitleCache: null, |
| 163 | }); |
| 164 | } |
| 165 | |
| 166 | const subtitleByFile = subtitleSnapshot && subtitleSnapshot.byFile ? subtitleSnapshot.byFile : {}; |
| 167 | for (const [filePath, subtitleRow] of Object.entries(subtitleByFile)) |
| 168 | { |
| 169 | const key = safeResolve(filePath); |
| 170 | const existing = perFile.get(key); |
| 171 | if (existing) |
| 172 | { |
| 173 | existing.subtitleCache = subtitleRow; |
| 174 | continue; |
| 175 | } |
| 176 | |
| 177 | perFile.set(key, { |
| 178 | filePath: key, |
| 179 | viewers: 0, |
| 180 | activeSessionIds: [], |
| 181 | stream: null, |
| 182 | subtitleCache: subtitleRow, |
| 183 | }); |
| 184 | } |
| 185 | |
| 186 | return [...perFile.values()].sort((a, b) => a.filePath.localeCompare(b.filePath)); |
| 187 | } |
| 188 | |
| 189 | function getMemorySnapshot () |
| 190 | { |
| 191 | const totalBytes = Number(os.totalmem()) || 0; |
| 192 | const freeBytes = Number(os.freemem()) || 0; |
| 193 | const usedBytes = Math.max(0, totalBytes - freeBytes); |
| 194 | |
| 195 | return { |
| 196 | totalBytes, |
| 197 | freeBytes, |
| 198 | usedBytes, |
| 199 | usedPercent: totalBytes > 0 ? Number(((usedBytes / totalBytes) * 100).toFixed(1)) : 0, |
| 200 | processRssBytes: Number(process.memoryUsage().rss || 0), |
| 201 | processHeapUsedBytes: Number(process.memoryUsage().heapUsed || 0), |
| 202 | }; |
| 203 | } |
| 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 | const uptimeMs = Math.max(0, Math.floor(Number(process.uptime()) * 1000)); |
| 243 | const startedAt = Date.now() - uptimeMs; |
| 244 | |
| 245 | return { |
| 246 | uptimeMs, |
| 247 | startedAt, |
| 248 | rows: { |
| 249 | authSessionsTotal: Number(authRows.total || 0), |
| 250 | authSessionsActive: Number(authRows.active || 0), |
| 251 | authSessionsRevoked: Number(authRows.revoked || 0), |
| 252 | activeLoggedInUsers: Number(activeUserRows.count || 0), |
| 253 | shareTokensTotal: Number(shareRows.total || 0), |
| 254 | shareTokensExpired: Number(shareRows.expired || 0), |
| 255 | }, |
| 256 | authCleanup, |
| 257 | shareMaintenance, |
| 258 | scheduledRestart, |
| 259 | }; |
| 260 | } |
| 261 | |
| 262 | router.get('/debug/stream-stats', (req, res) => |
| 263 | { |
| 264 | const rootUsage = collectRootUsageStats(); |
| 265 | const loggedInUsers = getLoggedInUsersSnapshot(); |
| 266 | const videoStream = getVideoStreamDebugSnapshot(); |
| 267 | const subtitleCache = getImageSubtitleDebugSnapshot(); |
| 268 | const subtitleDebugLog = getSubtitleDebugLogSnapshot(); |
| 269 | const videoFiles = buildVideoDebugRows(videoStream, subtitleCache); |
| 270 | const memory = getMemorySnapshot(); |
| 271 | const maintenance = getMaintenanceSnapshot(); |
| 272 | |
| 273 | res.json({ |
| 274 | generatedAt: Date.now(), |
| 275 | loggedInUsers, |
| 276 | storage: rootUsage, |
| 277 | memory, |
| 278 | videoStream, |
| 279 | subtitleCache, |
| 280 | subtitleDebugLog, |
| 281 | videoFiles, |
| 282 | maintenance, |
| 283 | }); |
| 284 | }); |
| 285 | |
| 286 | module.exports = router; |