| 1 | 'use strict'; |
| 2 | |
| 3 | const fs = require('fs'); |
| 4 | const os = require('os'); |
| 5 | const path = require('path'); |
| 6 | |
| 7 | const SUBTITLE_DEBUG_LOG_DIR = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); |
| 8 | const MAX_SUBTITLE_DEBUG_LOG_BYTES = 10 * 1024 * 1024; |
| 9 | const subtitleLogFileByContext = new Map(); |
| 10 | |
| 11 | function normaliseTimestampMs (timestampMs) |
| 12 | { |
| 13 | const parsed = Number(timestampMs); |
| 14 | return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : Date.now(); |
| 15 | } |
| 16 | |
| 17 | function 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 | |
| 24 | function 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 | |
| 31 | function 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 | |
| 40 | function 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 | |
| 51 | function ensureSubtitleDebugLogDir () |
| 52 | { |
| 53 | fs.mkdirSync(SUBTITLE_DEBUG_LOG_DIR, { recursive: true }); |
| 54 | } |
| 55 | |
| 56 | function 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 | |
| 63 | function 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 | |
| 91 | function 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 | |
| 106 | function 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 | |
| 126 | function 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 | |
| 157 | module.exports = { |
| 158 | SUBTITLE_DEBUG_LOG_DIR, |
| 159 | MAX_SUBTITLE_DEBUG_LOG_BYTES, |
| 160 | getSubtitleDebugLogSnapshot, |
| 161 | subtitleDebugLogFilePath, |
| 162 | pruneSubtitleDebugLogDir, |
| 163 | appendSubtitleDebugEntries, |
| 164 | }; |