BlueGit

timfa filemanager

Files

filemanager / server / subtitle-debug-log.js

subtitle-debug-log.js

Add subtitle runtime logging
timfa Tim Falken · pushed by timfa · 5 months ago
b5c1f94d History
subtitle-debug-log.js 3.5 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 pruneSubtitleDebugLogDir ()
75{
76 ensureSubtitleDebugLogDir();
77 const entries = directoryEntriesWithStats(SUBTITLE_DEBUG_LOG_DIR).sort((a, b) => a.mtimeMs - b.mtimeMs);
78 let totalBytes = entries.reduce((sum, entry) => sum + entry.size, 0);
79
80 for (const entry of entries)
81 {
82 if (totalBytes <= MAX_SUBTITLE_DEBUG_LOG_BYTES) break;
83 try
84 {
85 fs.unlinkSync(entry.fullPath);
86 totalBytes = Math.max(0, totalBytes - entry.size);
87 } catch
88 {
89 // Ignore prune failures; logging must remain best-effort.
90 }
91 }
92}
93
94function appendSubtitleDebugEntries ({ videoName, entries, context = null })
95{
96 const rows = Array.isArray(entries) ? entries.filter(Boolean) : [];
97 if (!rows.length) return null;
98
99 const firstTimestamp = rows.find((entry) => entry && Number.isFinite(entry.loggedAtMs));
100 const targetPath = subtitleDebugLogFilePath(videoName, firstTimestamp ? firstTimestamp.loggedAtMs : Date.now());
101
102 try
103 {
104 ensureSubtitleDebugLogDir();
105 const text = rows.map((entry) =>
106 {
107 const payload = context && typeof context === 'object'
108 ? { ...context, ...(entry && typeof entry === 'object' ? entry : { value: entry }) }
109 : entry;
110 return serialiseLogEntry(payload);
111 }).join('');
112 fs.appendFileSync(targetPath, text, 'utf8');
113 pruneSubtitleDebugLogDir();
114 return targetPath;
115 } catch
116 {
117 return null;
118 }
119}
120
121module.exports = {
122 SUBTITLE_DEBUG_LOG_DIR,
123 MAX_SUBTITLE_DEBUG_LOG_BYTES,
124 subtitleDebugLogFilePath,
125 pruneSubtitleDebugLogDir,
126 appendSubtitleDebugEntries,
127};