BlueGit

timfa filemanager

Files

filemanager / server / routes / debug.js

debug.js

294f7ec7 History
debug.js 5.3 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const fs = require('fs');
5const os = require('os');
6const path = require('path');
7
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { loadConfig, getEffectivePaths } = require('../config');
12const { getImageSubtitleDebugSnapshot } = require('../image-subtitles');
13const { getVideoStreamDebugSnapshot } = require('../video-stream');
14const { getSubtitleDebugLogSnapshot } = require('../subtitle-debug-log');
15
16const AUTH_IDLE_TIMEOUT_MS = 60 * 60 * 1000;
17
18function safeResolve (value)
19{
20 return path.resolve(String(value || '').trim());
21}
22
23function normaliseRootsForUsage (config)
24{
25 const rawRoots = Array.isArray(config.paths) ? config.paths : [];
26 const effective = getEffectivePaths(rawRoots);
27 const roots = new Set(effective.map((root) => safeResolve(root)));
28
29 const userPath = String(config.userPath || '').trim();
30 if (userPath)
31 {
32 const resolvedUserPath = safeResolve(userPath);
33 const isCovered = [...roots].some((root) =>
34 resolvedUserPath === root || resolvedUserPath.startsWith(`${root}${path.sep}`));
35 if (!isCovered) roots.add(resolvedUserPath);
36 }
37
38 return [...roots];
39}
40
41function walkDirectorySize (rootPath)
42{
43 let bytes = 0;
44 let files = 0;
45 let directories = 0;
46 const stack = [rootPath];
47
48 while (stack.length > 0)
49 {
50 const current = stack.pop();
51 let entries = [];
52 try
53 {
54 entries = fs.readdirSync(current, { withFileTypes: true });
55 } catch
56 {
57 continue;
58 }
59
60 for (const entry of entries)
61 {
62 const fullPath = path.join(current, entry.name);
63 if (entry.isDirectory())
64 {
65 directories += 1;
66 stack.push(fullPath);
67 continue;
68 }
69
70 if (!entry.isFile()) continue;
71 try
72 {
73 const stat = fs.statSync(fullPath);
74 bytes += Number.isFinite(stat.size) ? stat.size : 0;
75 files += 1;
76 } catch
77 {
78 // Best effort; skip unreadable files.
79 }
80 }
81 }
82
83 return { bytes, files, directories };
84}
85
86function collectRootUsageStats ()
87{
88 const config = loadConfig();
89 const roots = normaliseRootsForUsage(config);
90
91 const perRoot = [];
92 let totalBytes = 0;
93 let totalFiles = 0;
94
95 for (const root of roots)
96 {
97 const row = {
98 path: root,
99 exists: fs.existsSync(root),
100 bytes: 0,
101 files: 0,
102 directories: 0,
103 };
104
105 if (row.exists)
106 {
107 const usage = walkDirectorySize(root);
108 row.bytes = usage.bytes;
109 row.files = usage.files;
110 row.directories = usage.directories;
111 totalBytes += usage.bytes;
112 totalFiles += usage.files;
113 }
114
115 perRoot.push(row);
116 }
117
118 return {
119 roots: perRoot,
120 totalBytes,
121 totalFiles,
122 };
123}
124
125function getLoggedInUsersSnapshot ()
126{
127 const db = getDb();
128 const now = Date.now();
129 const activeSince = now - AUTH_IDLE_TIMEOUT_MS;
130
131 const rows = db.prepare(
132 `SELECT username, MAX(last_seen_at) AS lastSeenAt
133 FROM auth_sessions
134 WHERE revoked_at IS NULL
135 AND last_seen_at >= ?
136 GROUP BY username
137 ORDER BY username COLLATE NOCASE ASC`,
138 ).all([activeSince]);
139
140 return rows.map((row) => ({
141 username: String(row.username || ''),
142 lastSeenAt: Number(row.lastSeenAt || 0),
143 }));
144}
145
146function buildVideoDebugRows (videoSnapshot, subtitleSnapshot)
147{
148 const perFile = new Map();
149
150 const activeStreams = Array.isArray(videoSnapshot.activeStreams) ? videoSnapshot.activeStreams : [];
151 for (const stream of activeStreams)
152 {
153 const key = safeResolve(stream.sourcePath);
154 perFile.set(key, {
155 filePath: key,
156 viewers: Number(stream.viewers || 0),
157 activeSessionIds: [stream.sessionId],
158 stream: stream,
159 subtitleCache: null,
160 });
161 }
162
163 const subtitleByFile = subtitleSnapshot && subtitleSnapshot.byFile ? subtitleSnapshot.byFile : {};
164 for (const [filePath, subtitleRow] of Object.entries(subtitleByFile))
165 {
166 const key = safeResolve(filePath);
167 const existing = perFile.get(key);
168 if (existing)
169 {
170 existing.subtitleCache = subtitleRow;
171 continue;
172 }
173
174 perFile.set(key, {
175 filePath: key,
176 viewers: 0,
177 activeSessionIds: [],
178 stream: null,
179 subtitleCache: subtitleRow,
180 });
181 }
182
183 return [...perFile.values()].sort((a, b) => a.filePath.localeCompare(b.filePath));
184}
185
186function getMemorySnapshot ()
187{
188 const totalBytes = Number(os.totalmem()) || 0;
189 const freeBytes = Number(os.freemem()) || 0;
190 const usedBytes = Math.max(0, totalBytes - freeBytes);
191
192 return {
193 totalBytes,
194 freeBytes,
195 usedBytes,
196 usedPercent: totalBytes > 0 ? Number(((usedBytes / totalBytes) * 100).toFixed(1)) : 0,
197 processRssBytes: Number(process.memoryUsage().rss || 0),
198 processHeapUsedBytes: Number(process.memoryUsage().heapUsed || 0),
199 };
200}
201
202router.get('/debug/stream-stats', (req, res) =>
203{
204 const rootUsage = collectRootUsageStats();
205 const loggedInUsers = getLoggedInUsersSnapshot();
206 const videoStream = getVideoStreamDebugSnapshot();
207 const subtitleCache = getImageSubtitleDebugSnapshot();
208 const subtitleDebugLog = getSubtitleDebugLogSnapshot();
209 const videoFiles = buildVideoDebugRows(videoStream, subtitleCache);
210 const memory = getMemorySnapshot();
211
212 res.json({
213 generatedAt: Date.now(),
214 loggedInUsers,
215 storage: rootUsage,
216 memory,
217 videoStream,
218 subtitleCache,
219 subtitleDebugLog,
220 videoFiles,
221 });
222});
223
224module.exports = router;