BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

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