BlueGit

timfa filemanager

Files

filemanager / server / routes / share.js

share.js

share.js 10.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 } = 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
353module.exports = router;
354module.exports.buildZip = buildZip;
355module.exports.pruneZipCache = pruneZipCache;
356module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;