BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

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