BlueGit

timfa filemanager

Files

filemanager / server / subtitle-debug-log.js

subtitle-debug-log.js

294f7ec7 History
subtitle-debug-log.js 4.0 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;
9
10function padNumber (value)
11{
12 return String(Math.max(0, Number(value) || 0)).padStart(2, '0');
13}
14
15function localDateStamp (timestampMs)
16{
17 const date = new Date(Number.isFinite(timestampMs) ? timestampMs : Date.now());
18 return `${date.getFullYear()}-${padNumber(date.getMonth() + 1)}-${padNumber(date.getDate())}`;
19}
20
21function sanitiseVideoName (videoName)
22{
23 const raw = path.basename(String(videoName || '').trim() || 'unknown-video');
24 const cleaned = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/-+/g, '-').replace(/^-+|-+$/g, '');
25 return cleaned || 'unknown-video';
26}
27
28function subtitleDebugLogFilePath (videoName, timestampMs = Date.now())
29{
30 const fileName = `${localDateStamp(timestampMs)}-${sanitiseVideoName(videoName)}-subtitlelog.txt`;
31 return path.join(SUBTITLE_DEBUG_LOG_DIR, fileName);
32}
33
34function ensureSubtitleDebugLogDir ()
35{
36 fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true });
37}
38
39function serialiseLogEntry (entry)
40{
41 const payload = entry && typeof entry === 'object' ? entry : { value: entry };
42 const timestamp = new Date(Number.isFinite(payload.loggedAtMs) ? payload.loggedAtMs : Date.now()).toISOString();
43 return `[${timestamp}] ${JSON.stringify(payload)}\n`;
44}
45
46function directoryEntriesWithStats (dirPath)
47{
48 let entries = [];
49 try
50 {
51 entries = fs.readdirSync(dirPath, { withFileTypes: true });
52 } catch
53 {
54 return [];
55 }
56
57 const out = [];
58 for (const entry of entries)
59 {
60 if (!entry.isFile()) continue;
61 const fullPath = path.join(dirPath, entry.name);
62 try
63 {
64 const stat = fs.statSync(fullPath);
65 out.push({ fullPath, name: entry.name, size: Number(stat.size) || 0, mtimeMs: Number(stat.mtimeMs) || 0 });
66 } catch
67 {
68 // Ignore files that disappear mid-scan.
69 }
70 }
71 return out;
72}
73
74function getSubtitleDebugLogSnapshot ()
75{
76 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR);
77 const latestFile = entries.slice().sort((a, b) => b.mtimeMs - a.mtimeMs)[0] || null;
78
79 return {
80 path: SUBTITLE_DEBUG_LOG_DIR,
81 exists: fs.existsSync(SUBTITLE_DEBUG_LOG_DIR),
82 bytes: entries.reduce((sum, entry) => sum + entry.size, 0),
83 files: entries.length,
84 directories: 0,
85 latestFile,
86 };
87}
88
89function pruneSubtitleDebugLogDir ()
90{
91 ensureSubtitleDebugLogDir();
92 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
93 let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
94
95 for (const entry of entries)
96 {
97 if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
98 try
99 {
100 fs.unlinkSync(entry.fullPath);
101 totalBytes = Math.max(0, totalBytes - entry.size);
102 } catch
103 {
104 // Ignore prune failures; logging must remain best-effort.
105 }
106 }
107}
108
109function appendSubtitleDebugEntries ({ videoName, entries, context = null })
110{
111 const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
112 if (!rows.length) return null;
113
114 const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
115 const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());
116
117 try
118 {
119 ensureSubtitleDebugLogDir();
120 const text = rows.map((entry) =>
121 {
122 const payload = context && typeof context === 'object'
123 ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
124 : entry;
125 return serialiseLogEntry(payload);
126 }).join('');
127 fs.appendFileSync(targetPath, text, 'utf8');
128 pruneSubtitleDebugLogDir();
129 return targetPath;
130 } catch
131 {
132 return null;
133 }
134}
135
136module.exports = {
137 SUBTITLE_DEBUG_LOG_DIR,
138 MAX_SUBTITLE_DEBUG_LOG_BYTES,
139 getSubtitleDebugLogSnapshot,
140 subtitleDebugLogFilePath,
141 pruneSubtitleDebugLogDir,
142 appendSubtitleDebugEntries,
143};