BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

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