const crypto = require("node:crypto"); const fs = require("node:fs"); const path = require("node:path"); const { getDb } = require("../config/db"); const { paths } = require("../config/paths"); const { nowIso } = require("../utils/time"); function getCached(inputHash, mode) { const db = getDb(); const row = db.prepare("SELECT * FROM cache WHERE input_hash = ? AND mode = ?").get(inputHash, mode); if (!row) return null; // If we have a Telegram file_id, we can return a cache hit immediately even if files are not on disk! if (row.file_id) { db.prepare("UPDATE cache SET last_used_at = ? WHERE id = ?").run(nowIso(), row.id); const files = row.output_paths ? JSON.parse(row.output_paths) : []; return { ...row, outputPaths: files }; } // Otherwise, we require local files to exist on disk const files = row.output_paths ? JSON.parse(row.output_paths) : []; if (files.length === 0 || !files.every((file) => fs.existsSync(file))) return null; db.prepare("UPDATE cache SET last_used_at = ? WHERE id = ?").run(nowIso(), row.id); return { ...row, outputPaths: files }; } function saveCache({ inputHash, mode, fileId = null, outputPaths = [], sizeBefore = 0, sizeAfter = 0, duration = 0, platform = null, metadata = {} }) { const db = getDb(); const id = crypto.randomUUID(); const now = nowIso(); db.prepare(` INSERT OR REPLACE INTO cache (id, input_hash, mode, file_id, output_paths, metadata, size_before, size_after, duration, platform, created_at, last_used_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run( id, inputHash, mode, fileId, JSON.stringify(outputPaths), JSON.stringify(metadata), sizeBefore, sizeAfter, duration, platform, now, now ); } function cachePathFor(hash, name) { const dir = path.join(paths.cache, hash.slice(0, 2), hash); fs.mkdirSync(dir, { recursive: true }); return path.join(dir, name); } module.exports = { getCached, saveCache, cachePathFor };