BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

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