'use strict'; const express = require('express'); const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); const archiver = require('archiver'); const router = express.Router(); const { getDb } = require('../db'); const { requireAuth } = require('../auth'); const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config'); const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream'); const { renderImageSubtitleFrame, renderImageSubtitleFramesInRange } = require('../image-subtitles'); const { appendSubtitleDebugEntries } = require('../subtitle-debug-log'); const { logError } = require('../logger'); const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache'); const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes let shareMaintenanceTimer = null; const shareMaintenanceState = { lastRunAt: null, lastPurgedTokenCount: 0, lastPrunedZipCount: 0, lastDurationMs: 0, lastError: null, }; // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function effectivePaths () { return getEffectivePaths(loadConfig().paths || []); } /** Returns the configured root that contains absPath, or null. */ function resolveRoot (absPath) { return getAllowedRoot(absPath, effectivePaths()); } function getUserFolderPath (config, username) { const base = typeof config.userPath === 'string' ? config.userPath.trim() : ''; if (!base) return null; return path.join(base, String(username)); } function resolveRootForUser (absPath, roots, user, config) { const matched = getAllowedRoot(absPath, roots); if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false }; if (!user || !user.username) return null; const userFolder = getUserFolderPath(config, user.username); if (!userFolder) return null; const resolved = path.resolve(absPath); const resolvedFolder = path.resolve(userFolder); if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep)) { return { root: userFolder, label: path.basename(userFolder), isUserFolder: true }; } return null; } function canReadInfo (user, info) { if (!info) return false; if (info.isUserFolder) return true; if (user.isAdmin) return true; return !!(user.permissions[info.label] && user.permissions[info.label].read); } /** Generate a cryptographically random token. */ function generateToken () { return crypto.randomBytes(32).toString('hex'); } /** Ensure the zip cache directory exists. */ function ensureZipCacheDir () { if (!fs.existsSync(ZIP_CACHE_DIR)) { fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true }); } } function purgeExpiredShareTokens (opts = {}) { const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : Date.now(); const db = getDb(); const result = db.prepare('DELETE FROM share_tokens WHERE expires_at <= ?').run([now]); return Number(result && result.changes || 0); } function runShareMaintenanceOnce () { const startedAt = Date.now(); try { const purgedTokens = purgeExpiredShareTokens(); const prunedZips = pruneZipCache(); const endedAt = Date.now(); shareMaintenanceState.lastRunAt = endedAt; shareMaintenanceState.lastPurgedTokenCount = Number(purgedTokens || 0); shareMaintenanceState.lastPrunedZipCount = Number(prunedZips || 0); shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt); shareMaintenanceState.lastError = null; return { purgedTokens, prunedZips }; } catch (err) { const endedAt = Date.now(); shareMaintenanceState.lastRunAt = endedAt; shareMaintenanceState.lastPurgedTokenCount = 0; shareMaintenanceState.lastPrunedZipCount = 0; shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt); shareMaintenanceState.lastError = err && err.message ? String(err.message) : String(err); throw err; } } function startShareMaintenanceLoop () { if (shareMaintenanceTimer) return; try { runShareMaintenanceOnce(); } catch { // Ignore startup cleanup failures and continue serving requests. } shareMaintenanceTimer = setInterval(() => { try { runShareMaintenanceOnce(); } catch { // Keep serving requests even if periodic maintenance fails. } }, SHARE_MAINTENANCE_INTERVAL_MS); if (shareMaintenanceTimer && typeof shareMaintenanceTimer.unref === 'function') { shareMaintenanceTimer.unref(); } } function stopShareMaintenanceLoop () { if (!shareMaintenanceTimer) return; clearInterval(shareMaintenanceTimer); shareMaintenanceTimer = null; } /** * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS. * Also delete zip files whose corresponding share token has expired. */ function pruneZipCache () { ensureZipCacheDir(); const now = Date.now(); let deletedCount = 0; let entries; try { entries = fs.readdirSync(ZIP_CACHE_DIR); } catch { return deletedCount; } for (const name of entries) { if (!name.endsWith('.zip')) continue; const fullPath = path.join(ZIP_CACHE_DIR, name); try { const stat = fs.statSync(fullPath); const age = now - stat.mtimeMs; if (age > ZIP_MAX_AGE_MS) { fs.unlinkSync(fullPath); deletedCount += 1; } } catch { // Ignore files that disappeared. } } return deletedCount; } function getShareMaintenanceSnapshot () { return { running: !!shareMaintenanceTimer, intervalMs: SHARE_MAINTENANCE_INTERVAL_MS, lastRunAt: shareMaintenanceState.lastRunAt, lastPurgedTokenCount: shareMaintenanceState.lastPurgedTokenCount, lastPrunedZipCount: shareMaintenanceState.lastPrunedZipCount, lastDurationMs: shareMaintenanceState.lastDurationMs, lastError: shareMaintenanceState.lastError, zipMaxAgeMs: ZIP_MAX_AGE_MS, }; } /** * Create (or return cached) zip for the given directory. * cacheKey is used as the filename stem. * Returns the full path to the zip file. */ function buildZip (dirPath, cacheKey) { return new Promise((resolve, reject) => { ensureZipCacheDir(); pruneZipCache(); const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`); // Serve cached version if it exists and is not too old. if (fs.existsSync(zipPath)) { try { const stat = fs.statSync(zipPath); if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS) { return resolve(zipPath); } fs.unlinkSync(zipPath); } catch { /* fall through to rebuild */ } } const tmpPath = zipPath + '.tmp'; const output = fs.createWriteStream(tmpPath); const archive = archiver('zip', { zlib: { level: 6 } }); output.on('close', () => { try { fs.renameSync(tmpPath, zipPath); resolve(zipPath); } catch (err) { reject(err); } }); archive.on('error', (err) => { try { fs.unlinkSync(tmpPath); } catch { /* ignore */ } reject(err); }); archive.pipe(output); archive.directory(dirPath, path.basename(dirPath)); archive.finalize(); }); } // --------------------------------------------------------------------------- // POST /api/share/create // Body: { filePath: } // Authenticated. Creates a 24-hour share token for a file or directory. // --------------------------------------------------------------------------- router.post('/create', requireAuth, (req, res) => { const filePath = String((req.body && req.body.filePath) || '').trim(); if (!filePath) { return res.status(400).json({ error: 'filePath is required.' }); } const config = loadConfig(); const roots = effectivePaths(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } let stat; try { stat = fs.statSync(filePath); } catch { return res.status(404).json({ error: 'File or folder not found.' }); } const isDir = stat.isDirectory() ? 1 : 0; const now = Date.now(); const expiresAt = now + SHARE_TTL_MS; const token = generateToken(); const user = req.user; const db = getDb(); db.prepare(` INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?) `).run([token, filePath, isDir, user.username, now, expiresAt]); res.json({ token, expiresAt }); }); // --------------------------------------------------------------------------- // GET /api/share/info/:token // Public (no auth). Returns metadata about the shared item. // --------------------------------------------------------------------------- router.get('/info/:token', (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) { return res.status(410).json({ error: 'Share link has expired.' }); } const name = path.basename(row.file_path); res.json({ name, isDir: !!row.is_dir, expiresAt: row.expires_at, }); }); // --------------------------------------------------------------------------- // GET /api/share/preview/:token // Public (no auth). Streams a file for inline preview (non-directory only). // --------------------------------------------------------------------------- router.get('/preview/:token', (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path)) { return res.status(404).json({ error: 'File not found.' }); } // Limit preview size to 50 MB to prevent accidental large file streaming. const MAX_PREVIEW_BYTES = 50 * 1024 * 1024; let stat; try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); } if (stat.size > MAX_PREVIEW_BYTES) { return res.status(413).json({ error: 'File too large for inline preview.' }); } res.set('Cache-Control', 'private, no-store'); res.sendFile(row.file_path); }); // --------------------------------------------------------------------------- // GET /api/share/video-stream/:token // Public (no auth). Creates a short-lived ffmpeg-backed HLS session. // --------------------------------------------------------------------------- router.get('/video-stream/:token', async (req, res, next) => { try { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const session = await createVideoStreamSession(row.file_path); res.json({ sessionId: session.sessionId, playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`, durationSeconds: session.durationSeconds || null, subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 }, subtitleTracks: session.subtitleTracks.map((track) => ({ label: track.label, language: track.language, default: !!track.isDefault, src: `/api/share/video-stream/session/${session.sessionId}/${track.fileName}`, })), imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({ label: track.label, language: track.language, default: !!track.isDefault, streamIndex: track.streamIndex, })), }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // GET /api/share/video-stream/session/:sessionId/:assetPath(*) // Public. Serves HLS assets from an already-created share video session. // --------------------------------------------------------------------------- router.get('/video-stream/session/:sessionId/:assetPath(*)', async (req, res, next) => { try { await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // DELETE /api/share/video-stream/session/:sessionId // Public. Explicitly releases an active shared video-stream lease. // --------------------------------------------------------------------------- router.delete('/video-stream/session/:sessionId', async (req, res, next) => { try { releaseVideoStreamSession(String(req.params.sessionId || '')); res.json({ ok: true }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // GET /api/share/video-stream-subtitle-frame/:token // Public. Returns a rendered PNG subtitle bitmap for shared video playback. // Query params: streamIndex, timeSeconds, videoWidth, videoHeight // --------------------------------------------------------------------------- router.get('/video-stream-subtitle-frame/:token', async (req, res) => { const requestReceivedAtMs = Date.now(); try { const token = String(req.params.token || '').trim(); const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10); const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10); const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10); const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10); if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0) { return res.status(400).json({ error: 'token, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' }); } const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280; const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720; const frameData = await renderImageSubtitleFrame({ filePath: row.file_path, streamIndex, timeSeconds, canvasWidth, canvasHeight, }); if (!frameData || !frameData.frame) { res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'none'); return res.status(204).end(); } res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'ok'); res.set('X-Subtitle-Frame-Left', String(frameData.left || 0)); res.set('X-Subtitle-Frame-Top', String(frameData.top || 0)); res.set('X-Subtitle-Frame-Width', String(frameData.width || 0)); res.set('X-Subtitle-Frame-Height', String(frameData.height || 0)); res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280)); res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720)); res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0)); res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0)); res.set('Content-Type', 'image/png'); res.set('Cache-Control', 'private, max-age=3600'); res.send(frameData.frame); } catch (err) { logError('Shared subtitle frame extraction failed', err, { token: String(req.params.token || ''), streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10), timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10), }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'error'); return res.status(204).end(); } }); // --------------------------------------------------------------------------- // GET /api/share/video-stream-subtitle-range/:token // Public. Returns rendered PNG subtitle bitmaps for a shared-video time range. // Query params: streamIndex, startTimeSeconds, endTimeSeconds, videoWidth, videoHeight // --------------------------------------------------------------------------- router.get('/video-stream-subtitle-range/:token', async (req, res) => { const requestReceivedAtMs = Date.now(); try { const token = String(req.params.token || '').trim(); const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10); const startTimeSeconds = Number.parseFloat(String(req.query.startTimeSeconds || ''), 10); const endTimeSeconds = Number.parseFloat(String(req.query.endTimeSeconds || ''), 10); const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10); const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10); if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds) { return res.status(400).json({ error: 'token, streamIndex, startTimeSeconds, and endTimeSeconds are required.' }); } const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280; const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720; const result = await renderImageSubtitleFramesInRange({ filePath: row.file_path, streamIndex, startTimeSeconds, endTimeSeconds, canvasWidth, canvasHeight, }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.json({ status: 'ok', startTimeSeconds, endTimeSeconds, frames: Array.isArray(result && result.frames) ? result.frames.map((frame) => ({ left: frame.left || 0, top: frame.top || 0, width: frame.width || 0, height: frame.height || 0, canvasWidth: frame.canvasWidth || canvasWidth, canvasHeight: frame.canvasHeight || canvasHeight, startTimeSeconds: frame.startTimeSeconds || 0, endTimeSeconds: frame.endTimeSeconds || 0, contentType: 'image/png', frameBase64: Buffer.from(frame.frame || Buffer.alloc(0)).toString('base64'), })) : [], }); } catch (err) { logError('Shared subtitle range extraction failed', err, { token: String(req.params.token || ''), streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10), startTimeSeconds: Number.parseFloat(String(req.query.startTimeSeconds || ''), 10), endTimeSeconds: Number.parseFloat(String(req.query.endTimeSeconds || ''), 10), }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); return res.status(200).json({ status: 'error', frames: [] }); } }); // --------------------------------------------------------------------------- // POST /api/share/video-stream-subtitle-log/:token // Public. Persists client-side subtitle timing diagnostics for a share playback. // Body: { sessionId?, entries[] } // --------------------------------------------------------------------------- router.post('/video-stream-subtitle-log/:token', express.json(), (req, res) => { try { const token = String(req.params.token || '').trim(); const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null; const sessionId = String(req.body && req.body.sessionId || '').trim(); if (!token || !entries || !entries.length) { return res.status(400).json({ error: 'token and entries are required.' }); } const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot log subtitle timing for a directory.' }); appendSubtitleDebugEntries({ videoName: path.basename(row.file_path), entries, context: { source: 'share', filePath: row.file_path, sessionId: sessionId || null, shareToken: token, }, }); return res.json({ ok: true }); } catch (err) { logError('Shared subtitle debug log write failed', err, { token: String(req.params.token || ''), entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0, }); return res.status(500).json({ error: 'Subtitle debug log write failed.' }); } }); // --------------------------------------------------------------------------- // GET /api/share/download/:token // Public (no auth). Streams the file or a zip of the directory. // --------------------------------------------------------------------------- router.get('/download/:token', async (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) { if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } try { const zipPath = await buildZip(row.file_path, token); const zipName = `${path.basename(row.file_path)}.zip`; res.download(zipPath, zipName); } catch (err) { res.status(500).json({ error: 'Failed to create zip archive.' }); } } else { if (!fs.existsSync(row.file_path)) { return res.status(404).json({ error: 'File not found.' }); } res.download(row.file_path, path.basename(row.file_path)); } }); // --------------------------------------------------------------------------- // Open Graph helpers // --------------------------------------------------------------------------- const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html'); const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp', 'heif', 'heic']); function ogEsc (s) { return String(s || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function fileExtLower (name) { const i = String(name || '').lastIndexOf('.'); return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; } function formatOgValidity (expiresAt) { const ms = expiresAt - Date.now(); if (ms <= 0) return null; const h = Math.floor(ms / 3600000); const m = Math.floor((ms % 3600000) / 60000); if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`; return `${m} minute${m !== 1 ? 's' : ''}`; } /** * Reads share.html, injects Open Graph meta tags for the given token, and * returns the resulting HTML string. Works for all visitors — crawlers get * the OG data they need; browsers get the same interactive page but with a * dynamic title and preview metadata already in the . */ function buildShareOpenGraphPage (token, req) { const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); const baseUrl = `${req.protocol}://${req.get('host')}`; const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`; let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard; if (!row) { pageTitle = 'Link Not Found'; ogTitle = 'Link Not Found'; ogDesc = 'This shared file link does not exist.'; twitterCard = 'summary'; } else { const name = path.basename(row.file_path); const expired = Date.now() > row.expires_at; if (expired) { pageTitle = `Link Expired \u2014 ${name}`; ogTitle = 'Link Expired'; ogDesc = `This shared link for \u201C${name}\u201D has expired.`; twitterCard = 'summary'; } else { pageTitle = name; ogTitle = name; const validity = formatOgValidity(row.expires_at); const typeLabel = row.is_dir ? 'folder' : 'file'; ogDesc = validity ? `Shared ${typeLabel} \u00B7 Valid for ${validity}` : `Shared ${typeLabel}`; if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name))) { ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`; twitterCard = 'summary_large_image'; } else { twitterCard = 'summary'; } } } const metaLines = [ ``, ``, ``, ``, ``, ``, ``, ]; if (ogImageUrl) { metaLines.push(``); metaLines.push(``); } const ogBlock = metaLines.join('\n '); let html; try { html = fs.readFileSync(SHARE_HTML_PATH, 'utf8'); } catch { html = ''; } html = html.replace( 'Shared file', `${ogEsc(pageTitle)}\n ${ogBlock}`, ); return html; } module.exports = router; module.exports.buildZip = buildZip; module.exports.pruneZipCache = pruneZipCache; module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens; module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce; module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop; module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop; module.exports.getShareMaintenanceSnapshot = getShareMaintenanceSnapshot; module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS; module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR; module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;