BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

dl video fix
timfa Tim Falken · pushed by timfa · 5 months ago
a0162cfc History
share.js 28.4 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const archiver = require('archiver');
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { requireAuth } = require('../auth');
12const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config');
13const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
14const { renderImageSubtitleFrame, renderImageSubtitleFramesInRange } = require('../image-subtitles');
15const { appendSubtitleDebugEntries } = require('../subtitle-debug-log');
16const { logError } = require('../logger');
17
18const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
19const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache');
20const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
21const SHARE_MAINTENANCE_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes
22
23let shareMaintenanceTimer = null;
24const shareMaintenanceState = {
25 lastRunAt: null,
26 lastPurgedTokenCount: 0,
27 lastPrunedZipCount: 0,
28 lastDurationMs: 0,
29 lastError: null,
30};
31
32// ---------------------------------------------------------------------------
33// Helpers
34// ---------------------------------------------------------------------------
35
36function effectivePaths ()
37{
38 return getEffectivePaths(loadConfig().paths || []);
39}
40
41/** Returns the configured root that contains absPath, or null. */
42function resolveRoot (absPath)
43{
44 return getAllowedRoot(absPath, effectivePaths());
45}
46
47function getUserFolderPath (config, username)
48{
49 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
50 if (!base) return null;
51 return path.join(base, String(username));
52}
53
54function resolveRootForUser (absPath, roots, user, config)
55{
56 const matched = getAllowedRoot(absPath, roots);
57 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
58
59 if (!user || !user.username) return null;
60 const userFolder = getUserFolderPath(config, user.username);
61 if (!userFolder) return null;
62
63 const resolved = path.resolve(absPath);
64 const resolvedFolder = path.resolve(userFolder);
65 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
66 {
67 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
68 }
69
70 return null;
71}
72
73function canReadInfo (user, info)
74{
75 if (!info) return false;
76 if (info.isUserFolder) return true;
77 if (user.isAdmin) return true;
78 return !!(user.permissions[info.label] && user.permissions[info.label].read);
79}
80
81/** Generate a cryptographically random token. */
82function generateToken ()
83{
84 return crypto.randomBytes(32).toString('hex');
85}
86
87/** Ensure the zip cache directory exists. */
88function ensureZipCacheDir ()
89{
90 if (!fs.existsSync(ZIP_CACHE_DIR))
91 {
92 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
93 }
94}
95
96function purgeExpiredShareTokens (opts = {})
97{
98 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : Date.now();
99 const db = getDb();
100 const result = db.prepare('DELETE FROM share_tokens WHERE expires_at <= ?').run([now]);
101 return Number(result && result.changes || 0);
102}
103
104function runShareMaintenanceOnce ()
105{
106 const startedAt = Date.now();
107 try
108 {
109 const purgedTokens = purgeExpiredShareTokens();
110 const prunedZips = pruneZipCache();
111 const endedAt = Date.now();
112 shareMaintenanceState.lastRunAt = endedAt;
113 shareMaintenanceState.lastPurgedTokenCount = Number(purgedTokens || 0);
114 shareMaintenanceState.lastPrunedZipCount = Number(prunedZips || 0);
115 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
116 shareMaintenanceState.lastError = null;
117 return { purgedTokens, prunedZips };
118 } catch (err)
119 {
120 const endedAt = Date.now();
121 shareMaintenanceState.lastRunAt = endedAt;
122 shareMaintenanceState.lastPurgedTokenCount = 0;
123 shareMaintenanceState.lastPrunedZipCount = 0;
124 shareMaintenanceState.lastDurationMs = Math.max(0, endedAt - startedAt);
125 shareMaintenanceState.lastError = err && err.message ? String(err.message) : String(err);
126 throw err;
127 }
128}
129
130function startShareMaintenanceLoop ()
131{
132 if (shareMaintenanceTimer) return;
133
134 try
135 {
136 runShareMaintenanceOnce();
137 } catch
138 {
139 // Ignore startup cleanup failures and continue serving requests.
140 }
141
142 shareMaintenanceTimer = setInterval(() =>
143 {
144 try
145 {
146 runShareMaintenanceOnce();
147 } catch
148 {
149 // Keep serving requests even if periodic maintenance fails.
150 }
151 }, SHARE_MAINTENANCE_INTERVAL_MS);
152
153 if (shareMaintenanceTimer && typeof shareMaintenanceTimer.unref === 'function')
154 {
155 shareMaintenanceTimer.unref();
156 }
157}
158
159function stopShareMaintenanceLoop ()
160{
161 if (!shareMaintenanceTimer) return;
162 clearInterval(shareMaintenanceTimer);
163 shareMaintenanceTimer = null;
164}
165
166/**
167 * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS.
168 * Also delete zip files whose corresponding share token has expired.
169 */
170function pruneZipCache ()
171{
172 ensureZipCacheDir();
173 const now = Date.now();
174 let deletedCount = 0;
175 let entries;
176 try
177 {
178 entries = fs.readdirSync(ZIP_CACHE_DIR);
179 } catch
180 {
181 return deletedCount;
182 }
183
184 for (const name of entries)
185 {
186 if (!name.endsWith('.zip')) continue;
187 const fullPath = path.join(ZIP_CACHE_DIR, name);
188 try
189 {
190 const stat = fs.statSync(fullPath);
191 const age = now - stat.mtimeMs;
192 if (age > ZIP_MAX_AGE_MS)
193 {
194 fs.unlinkSync(fullPath);
195 deletedCount += 1;
196 }
197 } catch
198 {
199 // Ignore files that disappeared.
200 }
201 }
202
203 return deletedCount;
204}
205
206function getShareMaintenanceSnapshot ()
207{
208 return {
209 running: !!shareMaintenanceTimer,
210 intervalMs: SHARE_MAINTENANCE_INTERVAL_MS,
211 lastRunAt: shareMaintenanceState.lastRunAt,
212 lastPurgedTokenCount: shareMaintenanceState.lastPurgedTokenCount,
213 lastPrunedZipCount: shareMaintenanceState.lastPrunedZipCount,
214 lastDurationMs: shareMaintenanceState.lastDurationMs,
215 lastError: shareMaintenanceState.lastError,
216 zipMaxAgeMs: ZIP_MAX_AGE_MS,
217 };
218}
219
220/**
221 * Create (or return cached) zip for the given directory.
222 * cacheKey is used as the filename stem.
223 * Returns the full path to the zip file.
224 */
225function buildZip (dirPath, cacheKey)
226{
227 return new Promise((resolve, reject) =>
228 {
229 ensureZipCacheDir();
230 pruneZipCache();
231
232 const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`);
233
234 // Serve cached version if it exists and is not too old.
235 if (fs.existsSync(zipPath))
236 {
237 try
238 {
239 const stat = fs.statSync(zipPath);
240 if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS)
241 {
242 return resolve(zipPath);
243 }
244 fs.unlinkSync(zipPath);
245 } catch { /* fall through to rebuild */ }
246 }
247
248 const tmpPath = zipPath + '.tmp';
249 const output = fs.createWriteStream(tmpPath);
250 const archive = archiver('zip', { zlib: { level: 6 } });
251
252 output.on('close', () =>
253 {
254 try
255 {
256 fs.renameSync(tmpPath, zipPath);
257 resolve(zipPath);
258 } catch (err)
259 {
260 reject(err);
261 }
262 });
263
264 archive.on('error', (err) =>
265 {
266 try { fs.unlinkSync(tmpPath); } catch { /* ignore */ }
267 reject(err);
268 });
269
270 archive.pipe(output);
271 archive.directory(dirPath, path.basename(dirPath));
272 archive.finalize();
273 });
274}
275
276// ---------------------------------------------------------------------------
277// POST /api/share/create
278// Body: { filePath: <absolute-path> }
279// Authenticated. Creates a 24-hour share token for a file or directory.
280// ---------------------------------------------------------------------------
281router.post('/create', requireAuth, (req, res) =>
282{
283 const filePath = String((req.body && req.body.filePath) || '').trim();
284 if (!filePath)
285 {
286 return res.status(400).json({ error: 'filePath is required.' });
287 }
288
289 const config = loadConfig();
290 const roots = effectivePaths();
291 const info = resolveRootForUser(filePath, roots, req.user, config);
292 if (!info || !canReadInfo(req.user, info))
293 {
294 return res.status(403).json({ error: 'Access denied.' });
295 }
296
297 let stat;
298 try
299 {
300 stat = fs.statSync(filePath);
301 } catch
302 {
303 return res.status(404).json({ error: 'File or folder not found.' });
304 }
305
306 const isDir = stat.isDirectory() ? 1 : 0;
307 const now = Date.now();
308 const expiresAt = now + SHARE_TTL_MS;
309 const token = generateToken();
310 const user = req.user;
311
312 const db = getDb();
313 db.prepare(`
314 INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at)
315 VALUES (?, ?, ?, ?, ?, ?)
316 `).run([token, filePath, isDir, user.username, now, expiresAt]);
317
318 res.json({ token, expiresAt });
319});
320
321// ---------------------------------------------------------------------------
322// GET /api/share/info/:token
323// Public (no auth). Returns metadata about the shared item.
324// ---------------------------------------------------------------------------
325router.get('/info/:token', (req, res) =>
326{
327 const token = String(req.params.token || '').trim();
328 if (!token) return res.status(400).json({ error: 'Token is required.' });
329
330 const db = getDb();
331 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
332
333 if (!row) return res.status(404).json({ error: 'Share link not found.' });
334 if (Date.now() > row.expires_at)
335 {
336 return res.status(410).json({ error: 'Share link has expired.' });
337 }
338
339 const name = path.basename(row.file_path);
340 res.json({
341 name,
342 isDir: !!row.is_dir,
343 expiresAt: row.expires_at,
344 });
345});
346
347// ---------------------------------------------------------------------------
348// GET /api/share/preview/:token
349// Public (no auth). Streams a file for inline preview (non-directory only).
350// ---------------------------------------------------------------------------
351router.get('/preview/:token', (req, res) =>
352{
353 const token = String(req.params.token || '').trim();
354 if (!token) return res.status(400).json({ error: 'Token is required.' });
355
356 const db = getDb();
357 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
358
359 if (!row) return res.status(404).json({ error: 'Share link not found.' });
360 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
361 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
362
363 if (!fs.existsSync(row.file_path))
364 {
365 return res.status(404).json({ error: 'File not found.' });
366 }
367
368 // Limit preview size to 50 MB to prevent accidental large file streaming.
369 const MAX_PREVIEW_BYTES = 50 * 1024 * 1024;
370 let stat;
371 try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); }
372
373 if (stat.size > MAX_PREVIEW_BYTES)
374 {
375 return res.status(413).json({ error: 'File too large for inline preview.' });
376 }
377
378 res.set('Cache-Control', 'private, no-store');
379 res.sendFile(row.file_path);
380});
381
382// ---------------------------------------------------------------------------
383// GET /api/share/video-stream/:token
384// Public (no auth). Creates a short-lived ffmpeg-backed HLS session.
385// ---------------------------------------------------------------------------
386router.get('/video-stream/:token', async (req, res, next) =>
387{
388 try
389 {
390 const token = String(req.params.token || '').trim();
391 if (!token) return res.status(400).json({ error: 'Token is required.' });
392
393 const db = getDb();
394 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
395
396 if (!row) return res.status(404).json({ error: 'Share link not found.' });
397 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
398 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
399
400 if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory())
401 {
402 return res.status(404).json({ error: 'File not found.' });
403 }
404
405 const session = await createVideoStreamSession(row.file_path);
406 res.json({
407 sessionId: session.sessionId,
408 playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`,
409 durationSeconds: session.durationSeconds || null,
410 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 },
411 subtitleTracks: session.subtitleTracks.map((track) => ({
412 label: track.label,
413 language: track.language,
414 default: !!track.isDefault,
415 src: `/api/share/video-stream/session/${session.sessionId}/${track.fileName}`,
416 })),
417 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({
418 label: track.label,
419 language: track.language,
420 default: !!track.isDefault,
421 streamIndex: track.streamIndex,
422 })),
423 });
424 } catch (err)
425 {
426 next(err);
427 }
428});
429
430// ---------------------------------------------------------------------------
431// GET /api/share/video-stream/session/:sessionId/:assetPath(*)
432// Public. Serves HLS assets from an already-created share video session.
433// ---------------------------------------------------------------------------
434router.get('/video-stream/session/:sessionId/:assetPath(*)', async (req, res, next) =>
435{
436 try
437 {
438 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
439 } catch (err)
440 {
441 next(err);
442 }
443});
444
445// ---------------------------------------------------------------------------
446// DELETE /api/share/video-stream/session/:sessionId
447// Public. Explicitly releases an active shared video-stream lease.
448// ---------------------------------------------------------------------------
449router.delete('/video-stream/session/:sessionId', async (req, res, next) =>
450{
451 try
452 {
453 releaseVideoStreamSession(String(req.params.sessionId || ''));
454 res.json({ ok: true });
455 } catch (err)
456 {
457 next(err);
458 }
459});
460
461// ---------------------------------------------------------------------------
462// GET /api/share/video-stream-subtitle-frame/:token
463// Public. Returns a rendered PNG subtitle bitmap for shared video playback.
464// Query params: streamIndex, timeSeconds, videoWidth, videoHeight
465// ---------------------------------------------------------------------------
466router.get('/video-stream-subtitle-frame/:token', async (req, res) =>
467{
468 const requestReceivedAtMs = Date.now();
469 try
470 {
471 const token = String(req.params.token || '').trim();
472 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
473 const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10);
474 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
475 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
476
477 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0)
478 {
479 return res.status(400).json({ error: 'token, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' });
480 }
481
482 const db = getDb();
483 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
484 if (!row) return res.status(404).json({ error: 'Share link not found.' });
485 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
486 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
487
488 if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory())
489 {
490 return res.status(404).json({ error: 'File not found.' });
491 }
492
493 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
494 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
495 const frameData = await renderImageSubtitleFrame({
496 filePath: row.file_path,
497 streamIndex,
498 timeSeconds,
499 canvasWidth,
500 canvasHeight,
501 });
502
503 if (!frameData || !frameData.frame)
504 {
505 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
506 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
507 res.set('X-Subtitle-Frame-Status', 'none');
508 return res.status(204).end();
509 }
510
511 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
512 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
513 res.set('X-Subtitle-Frame-Status', 'ok');
514 res.set('X-Subtitle-Frame-Left', String(frameData.left || 0));
515 res.set('X-Subtitle-Frame-Top', String(frameData.top || 0));
516 res.set('X-Subtitle-Frame-Width', String(frameData.width || 0));
517 res.set('X-Subtitle-Frame-Height', String(frameData.height || 0));
518 res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280));
519 res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720));
520 res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0));
521 res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0));
522 res.set('Content-Type', 'image/png');
523 res.set('Cache-Control', 'private, max-age=3600');
524 res.send(frameData.frame);
525 } catch (err)
526 {
527 logError('Shared subtitle frame extraction failed', err, {
528 token: String(req.params.token || ''),
529 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
530 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
531 });
532 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
533 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
534 res.set('X-Subtitle-Frame-Status', 'error');
535 return res.status(204).end();
536 }
537});
538
539// ---------------------------------------------------------------------------
540// GET /api/share/video-stream-subtitle-range/:token
541// Public. Returns rendered PNG subtitle bitmaps for a shared-video time range.
542// Query params: streamIndex, startTimeSeconds, endTimeSeconds, videoWidth, videoHeight
543// ---------------------------------------------------------------------------
544router.get('/video-stream-subtitle-range/:token', async (req, res) =>
545{
546 const requestReceivedAtMs = Date.now();
547 try
548 {
549 const token = String(req.params.token || '').trim();
550 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
551 const startTimeSeconds = Number.parseFloat(String(req.query.startTimeSeconds || ''), 10);
552 const endTimeSeconds = Number.parseFloat(String(req.query.endTimeSeconds || ''), 10);
553 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
554 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
555
556 if (!token || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds)
557 {
558 return res.status(400).json({ error: 'token, streamIndex, startTimeSeconds, and endTimeSeconds are required.' });
559 }
560
561 const db = getDb();
562 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
563 if (!row) return res.status(404).json({ error: 'Share link not found.' });
564 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
565 if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' });
566
567 if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory())
568 {
569 return res.status(404).json({ error: 'File not found.' });
570 }
571
572 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
573 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
574 const result = await renderImageSubtitleFramesInRange({
575 filePath: row.file_path,
576 streamIndex,
577 startTimeSeconds,
578 endTimeSeconds,
579 canvasWidth,
580 canvasHeight,
581 });
582
583 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
584 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
585 res.json({
586 status: 'ok',
587 startTimeSeconds,
588 endTimeSeconds,
589 frames: Array.isArray(result && result.frames)
590 ? result.frames.map((frame) => ({
591 left: frame.left || 0,
592 top: frame.top || 0,
593 width: frame.width || 0,
594 height: frame.height || 0,
595 canvasWidth: frame.canvasWidth || canvasWidth,
596 canvasHeight: frame.canvasHeight || canvasHeight,
597 startTimeSeconds: frame.startTimeSeconds || 0,
598 endTimeSeconds: frame.endTimeSeconds || 0,
599 contentType: 'image/png',
600 frameBase64: Buffer.from(frame.frame || Buffer.alloc(0)).toString('base64'),
601 }))
602 : [],
603 });
604 } catch (err)
605 {
606 logError('Shared subtitle range extraction failed', err, {
607 token: String(req.params.token || ''),
608 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
609 startTimeSeconds: Number.parseFloat(String(req.query.startTimeSeconds || ''), 10),
610 endTimeSeconds: Number.parseFloat(String(req.query.endTimeSeconds || ''), 10),
611 });
612 res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs));
613 res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now()));
614 return res.status(200).json({ status: 'error', frames: [] });
615 }
616});
617
618// ---------------------------------------------------------------------------
619// POST /api/share/video-stream-subtitle-log/:token
620// Public. Persists client-side subtitle timing diagnostics for a share playback.
621// Body: { sessionId?, entries[] }
622// ---------------------------------------------------------------------------
623router.post('/video-stream-subtitle-log/:token', express.json(), (req, res) =>
624{
625 try
626 {
627 const token = String(req.params.token || '').trim();
628 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
629 const sessionId = String(req.body && req.body.sessionId || '').trim();
630
631 if (!token || !entries || !entries.length)
632 {
633 return res.status(400).json({ error: 'token and entries are required.' });
634 }
635
636 const db = getDb();
637 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
638 if (!row) return res.status(404).json({ error: 'Share link not found.' });
639 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
640 if (row.is_dir) return res.status(400).json({ error: 'Cannot log subtitle timing for a directory.' });
641
642 appendSubtitleDebugEntries({
643 videoName: path.basename(row.file_path),
644 entries,
645 context: {
646 source: 'share',
647 filePath: row.file_path,
648 sessionId: sessionId || null,
649 shareToken: token,
650 },
651 });
652
653 return res.json({ ok: true });
654 } catch (err)
655 {
656 logError('Shared subtitle debug log write failed', err, {
657 token: String(req.params.token || ''),
658 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
659 });
660 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
661 }
662});
663
664// ---------------------------------------------------------------------------
665// GET /api/share/download/:token
666// Public (no auth). Streams the file or a zip of the directory.
667// ---------------------------------------------------------------------------
668router.get('/download/:token', async (req, res) =>
669{
670 const token = String(req.params.token || '').trim();
671 if (!token) return res.status(400).json({ error: 'Token is required.' });
672
673 const db = getDb();
674 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
675
676 if (!row) return res.status(404).json({ error: 'Share link not found.' });
677 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
678
679 if (row.is_dir)
680 {
681 if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory())
682 {
683 return res.status(404).json({ error: 'Directory not found.' });
684 }
685
686 try
687 {
688 const zipPath = await buildZip(row.file_path, token);
689 const zipName = `${path.basename(row.file_path)}.zip`;
690 res.download(zipPath, zipName);
691 } catch (err)
692 {
693 res.status(500).json({ error: 'Failed to create zip archive.' });
694 }
695 } else
696 {
697 if (!fs.existsSync(row.file_path))
698 {
699 return res.status(404).json({ error: 'File not found.' });
700 }
701
702 res.download(row.file_path, path.basename(row.file_path));
703 }
704});
705
706// ---------------------------------------------------------------------------
707// Open Graph helpers
708// ---------------------------------------------------------------------------
709
710const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
711const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp', 'heif', 'heic']);
712
713function ogEsc (s)
714{
715 return String(s || '')
716 .replace(/&/g, '&amp;')
717 .replace(/</g, '&lt;')
718 .replace(/>/g, '&gt;')
719 .replace(/"/g, '&quot;');
720}
721
722function fileExtLower (name)
723{
724 const i = String(name || '').lastIndexOf('.');
725 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
726}
727
728function formatOgValidity (expiresAt)
729{
730 const ms = expiresAt - Date.now();
731 if (ms <= 0) return null;
732 const h = Math.floor(ms / 3600000);
733 const m = Math.floor((ms % 3600000) / 60000);
734 if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`;
735 return `${m} minute${m !== 1 ? 's' : ''}`;
736}
737
738/**
739 * Reads share.html, injects Open Graph meta tags for the given token, and
740 * returns the resulting HTML string. Works for all visitors — crawlers get
741 * the OG data they need; browsers get the same interactive page but with a
742 * dynamic title and preview metadata already in the <head>.
743 */
744function buildShareOpenGraphPage (token, req)
745{
746 const db = getDb();
747 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
748
749 const baseUrl = `${req.protocol}://${req.get('host')}`;
750 const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`;
751
752 let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard;
753
754 if (!row)
755 {
756 pageTitle = 'Link Not Found';
757 ogTitle = 'Link Not Found';
758 ogDesc = 'This shared file link does not exist.';
759 twitterCard = 'summary';
760 }
761 else
762 {
763 const name = path.basename(row.file_path);
764 const expired = Date.now() > row.expires_at;
765
766 if (expired)
767 {
768 pageTitle = `Link Expired \u2014 ${name}`;
769 ogTitle = 'Link Expired';
770 ogDesc = `This shared link for \u201C${name}\u201D has expired.`;
771 twitterCard = 'summary';
772 }
773 else
774 {
775 pageTitle = name;
776 ogTitle = name;
777
778 const validity = formatOgValidity(row.expires_at);
779 const typeLabel = row.is_dir ? 'folder' : 'file';
780 ogDesc = validity
781 ? `Shared ${typeLabel} \u00B7 Valid for ${validity}`
782 : `Shared ${typeLabel}`;
783
784 if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name)))
785 {
786 ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`;
787 twitterCard = 'summary_large_image';
788 }
789 else
790 {
791 twitterCard = 'summary';
792 }
793 }
794 }
795
796 const metaLines = [
797 `<meta property="og:title" content="${ogEsc(ogTitle)}" />`,
798 `<meta property="og:description" content="${ogEsc(ogDesc)}" />`,
799 `<meta property="og:url" content="${ogEsc(shareUrl)}" />`,
800 `<meta property="og:type" content="website" />`,
801 `<meta name="twitter:card" content="${ogEsc(twitterCard)}" />`,
802 `<meta name="twitter:title" content="${ogEsc(ogTitle)}" />`,
803 `<meta name="twitter:description" content="${ogEsc(ogDesc)}" />`,
804 ];
805
806 if (ogImageUrl)
807 {
808 metaLines.push(`<meta property="og:image" content="${ogEsc(ogImageUrl)}" />`);
809 metaLines.push(`<meta name="twitter:image" content="${ogEsc(ogImageUrl)}" />`);
810 }
811
812 const ogBlock = metaLines.join('\n ');
813
814 let html;
815 try
816 {
817 html = fs.readFileSync(SHARE_HTML_PATH, 'utf8');
818 }
819 catch
820 {
821 html = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8" /></head><body></body></html>';
822 }
823
824 html = html.replace(
825 '<title>Shared file</title>',
826 `<title>${ogEsc(pageTitle)}</title>\n ${ogBlock}`,
827 );
828
829 return html;
830}
831
832module.exports = router;
833module.exports.buildZip = buildZip;
834module.exports.pruneZipCache = pruneZipCache;
835module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
836module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
837module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
838module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
839module.exports.getShareMaintenanceSnapshot = getShareMaintenanceSnapshot;
840module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
841module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
842module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;