BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

Add scheduled restart backend
timfa Tim Falken · pushed by timfa · 5 months ago
9e526bef History
share.js 24.7 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
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// POST /api/share/video-stream-subtitle-log/:token
541// Public. Persists client-side subtitle timing diagnostics for a share playback.
542// Body: { sessionId?, entries[] }
543// ---------------------------------------------------------------------------
544router.post('/video-stream-subtitle-log/:token', express.json(), (req, res) =>
545{
546 try
547 {
548 const token = String(req.params.token || '').trim();
549 const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null;
550 const sessionId = String(req.body && req.body.sessionId || '').trim();
551
552 if (!token || !entries || !entries.length)
553 {
554 return res.status(400).json({ error: 'token and entries are required.' });
555 }
556
557 const db = getDb();
558 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
559 if (!row) return res.status(404).json({ error: 'Share link not found.' });
560 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
561 if (row.is_dir) return res.status(400).json({ error: 'Cannot log subtitle timing for a directory.' });
562
563 appendSubtitleDebugEntries({
564 videoName: path.basename(row.file_path),
565 entries,
566 context: {
567 source: 'share',
568 filePath: row.file_path,
569 sessionId: sessionId || null,
570 shareToken: token,
571 },
572 });
573
574 return res.json({ ok: true });
575 } catch (err)
576 {
577 logError('Shared subtitle debug log write failed', err, {
578 token: String(req.params.token || ''),
579 entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0,
580 });
581 return res.status(500).json({ error: 'Subtitle debug log write failed.' });
582 }
583});
584
585// ---------------------------------------------------------------------------
586// GET /api/share/download/:token
587// Public (no auth). Streams the file or a zip of the directory.
588// ---------------------------------------------------------------------------
589router.get('/download/:token', async (req, res) =>
590{
591 const token = String(req.params.token || '').trim();
592 if (!token) return res.status(400).json({ error: 'Token is required.' });
593
594 const db = getDb();
595 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
596
597 if (!row) return res.status(404).json({ error: 'Share link not found.' });
598 if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' });
599
600 if (row.is_dir)
601 {
602 if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory())
603 {
604 return res.status(404).json({ error: 'Directory not found.' });
605 }
606
607 try
608 {
609 const zipPath = await buildZip(row.file_path, token);
610 const zipName = `${path.basename(row.file_path)}.zip`;
611 res.download(zipPath, zipName);
612 } catch (err)
613 {
614 res.status(500).json({ error: 'Failed to create zip archive.' });
615 }
616 } else
617 {
618 if (!fs.existsSync(row.file_path))
619 {
620 return res.status(404).json({ error: 'File not found.' });
621 }
622
623 res.download(row.file_path, path.basename(row.file_path));
624 }
625});
626
627// ---------------------------------------------------------------------------
628// Open Graph helpers
629// ---------------------------------------------------------------------------
630
631const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html');
632const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']);
633
634function ogEsc (s)
635{
636 return String(s || '')
637 .replace(/&/g, '&amp;')
638 .replace(/</g, '&lt;')
639 .replace(/>/g, '&gt;')
640 .replace(/"/g, '&quot;');
641}
642
643function fileExtLower (name)
644{
645 const i = String(name || '').lastIndexOf('.');
646 return i >= 0 ? name.slice(i + 1).toLowerCase() : '';
647}
648
649function formatOgValidity (expiresAt)
650{
651 const ms = expiresAt - Date.now();
652 if (ms <= 0) return null;
653 const h = Math.floor(ms / 3600000);
654 const m = Math.floor((ms % 3600000) / 60000);
655 if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`;
656 return `${m} minute${m !== 1 ? 's' : ''}`;
657}
658
659/**
660 * Reads share.html, injects Open Graph meta tags for the given token, and
661 * returns the resulting HTML string. Works for all visitors — crawlers get
662 * the OG data they need; browsers get the same interactive page but with a
663 * dynamic title and preview metadata already in the <head>.
664 */
665function buildShareOpenGraphPage (token, req)
666{
667 const db = getDb();
668 const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]);
669
670 const baseUrl = `${req.protocol}://${req.get('host')}`;
671 const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`;
672
673 let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard;
674
675 if (!row)
676 {
677 pageTitle = 'Link Not Found';
678 ogTitle = 'Link Not Found';
679 ogDesc = 'This shared file link does not exist.';
680 twitterCard = 'summary';
681 }
682 else
683 {
684 const name = path.basename(row.file_path);
685 const expired = Date.now() > row.expires_at;
686
687 if (expired)
688 {
689 pageTitle = `Link Expired \u2014 ${name}`;
690 ogTitle = 'Link Expired';
691 ogDesc = `This shared link for \u201C${name}\u201D has expired.`;
692 twitterCard = 'summary';
693 }
694 else
695 {
696 pageTitle = name;
697 ogTitle = name;
698
699 const validity = formatOgValidity(row.expires_at);
700 const typeLabel = row.is_dir ? 'folder' : 'file';
701 ogDesc = validity
702 ? `Shared ${typeLabel} \u00B7 Valid for ${validity}`
703 : `Shared ${typeLabel}`;
704
705 if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name)))
706 {
707 ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`;
708 twitterCard = 'summary_large_image';
709 }
710 else
711 {
712 twitterCard = 'summary';
713 }
714 }
715 }
716
717 const metaLines = [
718 `<meta property="og:title" content="${ogEsc(ogTitle)}" />`,
719 `<meta property="og:description" content="${ogEsc(ogDesc)}" />`,
720 `<meta property="og:url" content="${ogEsc(shareUrl)}" />`,
721 `<meta property="og:type" content="website" />`,
722 `<meta name="twitter:card" content="${ogEsc(twitterCard)}" />`,
723 `<meta name="twitter:title" content="${ogEsc(ogTitle)}" />`,
724 `<meta name="twitter:description" content="${ogEsc(ogDesc)}" />`,
725 ];
726
727 if (ogImageUrl)
728 {
729 metaLines.push(`<meta property="og:image" content="${ogEsc(ogImageUrl)}" />`);
730 metaLines.push(`<meta name="twitter:image" content="${ogEsc(ogImageUrl)}" />`);
731 }
732
733 const ogBlock = metaLines.join('\n ');
734
735 let html;
736 try
737 {
738 html = fs.readFileSync(SHARE_HTML_PATH, 'utf8');
739 }
740 catch
741 {
742 html = '<!DOCTYPE html><html lang="en-GB"><head><meta charset="UTF-8" /></head><body></body></html>';
743 }
744
745 html = html.replace(
746 '<title>Shared file</title>',
747 `<title>${ogEsc(pageTitle)}</title>\n ${ogBlock}`,
748 );
749
750 return html;
751}
752
753module.exports = router;
754module.exports.buildZip = buildZip;
755module.exports.pruneZipCache = pruneZipCache;
756module.exports.purgeExpiredShareTokens = purgeExpiredShareTokens;
757module.exports.runShareMaintenanceOnce = runShareMaintenanceOnce;
758module.exports.startShareMaintenanceLoop = startShareMaintenanceLoop;
759module.exports.stopShareMaintenanceLoop = stopShareMaintenanceLoop;
760module.exports.getShareMaintenanceSnapshot = getShareMaintenanceSnapshot;
761module.exports.SHARE_MAINTENANCE_INTERVAL_MS = SHARE_MAINTENANCE_INTERVAL_MS;
762module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;
763module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;