BlueGit

timfa filemanager

Files

filemanager / server / subtitle-debug-log.js

subtitle-debug-log.js

test
timfa Tim Falken · pushed by timfa · 5 months ago
3a9cbe01 History
subtitle-debug-log.js 4.6 KiB Download Raw
1'use strict';
2
3const fs = require('fs');
4const os = require('os');
5const path = require('path');
6
7const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
8const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024;
9const subtitleLogFileByContext = new Map();
10
11function normaliseTimestampMs (timestampMs)
12{
13 const parsed = Number(timestampMs);
14 return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : Date.now();
15}
16
17function sanitiseVideoName (videoName)
18{
19 const raw = path.basename(String(videoName || '').trim() || 'unknown-video');
20 const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
21 return cleaned || 'unknown-video';
22}
23
24function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())
25{
26 const stamp = normaliseTimestampMs(timestampMs);
27 const fileName = `${stamp}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;
28 return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);
29}
30
31function subtitleLogContextKey (videoName, context)
32{
33 const source = context && context.source ? String(context.source) : 'unknown';
34 const sessionHint = context && (context.sessionId || context.shareToken)
35 ? String(context.sessionId || context.shareToken)
36 : 'no-session';
37 return `${sanitiseVideoName(videoName)}|${source}|${sessionHint}`;
38}
39
40function resolveSubtitleLogPath (videoName, timestampMs, context)
41{
42 const key = subtitleLogContextKey(videoName, context);
43 const existing = subtitleLogFileByContext.get(key);
44 if (existing) return existing;
45
46 const targetPath = subtitleDebugLogFilePath(videoName, timestampMs);
47 subtitleLogFileByContext.set(key, targetPath);
48 return targetPath;
49}
50
51function ensureSubtitleDebugLogDir ()
52{
53 fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });
54}
55
56function serialiseLogEntry (entry)
57{
58 const payload = entry && typeof entry === 'object' ? entry : { value: entry };
59 const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();
60 return `[${timestamp}] ${JSON.stringify(payload)}\n`;
61}
62
63function directoryEntriesWithStats (dirPath)
64{
65 let entries = [];
66 try
67 {
68 entries = fs.readdirSync(dirPath, { withFileTypes: true });
69 } catch
70 {
71 return [];
72 }
73
74 const out = [];
75 for (const entry of entries)
76 {
77 if (!entry.isFile()) continue;
78 const fullPath = path.join(dirPath, entry.name);
79 try
80 {
81 const stat = fs.statSync(fullPath);
82 out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });
83 } catch
84 {
85 // Ignore files that disappear mid-scan.
86 }
87 }
88 return out;
89}
90
91function getSubtitleDebugLogSnapshot ()
92{
93 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR);
94 const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null;
95
96 return {
97 path: SUBTITLE_DEBUG_LOG_DIR,
98 exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR),
99 bytes: entries.reduce((sum, entry) => sum + entry.size, 0),
100 files: entries.length,
101 directories: 0,
102 latestFile,
103 };
104}
105
106function pruneSubtitleDebugLogDir ()
107{
108 ensureSubtitleDebugLogDir();
109 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
110 let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
111
112 for (const entry of entries)
113 {
114 if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
115 try
116 {
117 fs.unlinkSync(entry.fullPath);
118 totalBytes = Math.max(0, totalBytes - entry.size);
119 } catch
120 {
121 // Ignore prune failures; logging must remain best-effort.
122 }
123 }
124}
125
126function appendSubtitleDebugEntries ({ videoName, entries, context = null })
127{
128 const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
129 if (!rows.length) return null;
130
131 const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
132 const targetPath = resolveSubtitleLogPath(
133 videoName,
134 firstTimestamp ? firstTimestamp.loggedAtMs : Date.now(),
135 context,
136 );
137
138 try
139 {
140 ensureSubtitleDebugLogDir();
141 const text = rows.map((entry) =>
142 {
143 const payload = context && typeof context === 'object'
144 ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
145 : entry;
146 return serialiseLogEntry(payload);
147 }).join('');
148 fs.appendFileSync(targetPath, text, 'utf8');
149 pruneSubtitleDebugLogDir();
150 return targetPath;
151 } catch
152 {
153 return null;
154 }
155}
156
157module.exports = {
158 SUBTITLE_DEBUG_LOG_DIR,
159 MAX_SUBTITLE_DEBUG_LOG_BYTES,
160 getSubtitleDebugLogSnapshot,
161 subtitleDebugLogFilePath,
162 pruneSubtitleDebugLogDir,
163 appendSubtitleDebugEntries,
164};