BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

WIP: Duplicate detection
timfa Tim Falken · pushed by timfa · 6 months ago
3fcdc0ca History
files.js 40.0 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const multer = require('multer');
8const router = express.Router();
9
10const { getDb } = require('../db');
11const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config');
12const { requireAuth } = require('../auth');
13const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache');
14const { buildZip } = require('./share');
15const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream');
16
17// ---------------------------------------------------------------------------
18// SHA-256 hashing helper
19// ---------------------------------------------------------------------------
20
21/**
22 * Computes the SHA-256 hex digest of the file at `filePath`.
23 * Streams the file so it works for large files without loading them into memory.
24 * @param {string} filePath
25 * @returns {Promise<string>} hex digest
26 */
27function computeFileSha256 (filePath)
28{
29 return new Promise((resolve, reject) =>
30 {
31 const hash = crypto.createHash('sha256');
32 const stream = fs.createReadStream(filePath);
33 stream.on('error', reject);
34 stream.on('data', (chunk) => hash.update(chunk));
35 stream.on('end', () => resolve(hash.digest('hex')));
36 });
37}
38
39// ---------------------------------------------------------------------------
40// Multer storage — files are staged into temporary files and only promoted
41// to their final names after the full stream arrives.
42// ---------------------------------------------------------------------------
43function makeTempUploadPath (dir, originalName)
44{
45 const safeName = path.basename(String(originalName || 'upload'));
46 const suffix = crypto.randomUUID();
47 return path.join(dir, `.${safeName}.upload-${suffix}.part`);
48}
49
50function unlinkIfExists (targetPath, cb)
51{
52 fs.unlink(targetPath, (err) =>
53 {
54 if (!err || err.code === 'ENOENT') return cb(null);
55 cb(err);
56 });
57}
58
59function promoteUploadedFile (tempPath, finalPath, cb)
60{
61 fs.rename(tempPath, finalPath, cb);
62}
63
64const storage = {
65 _handleFile (req, file, cb)
66 {
67 if (!req._uploadDir)
68 {
69 cb(new Error('Upload directory is not set.'));
70 return;
71 }
72
73 const finalName = path.basename(String(file.originalname || 'upload'));
74 const finalPath = path.join(req._uploadDir, finalName);
75 const tempPath = makeTempUploadPath(req._uploadDir, finalName);
76 const out = fs.createWriteStream(tempPath, { flags: 'wx' });
77
78 let settled = false;
79 let cleaned = false;
80
81 const detach = () =>
82 {
83 req.off('aborted', onAbort);
84 req.off('close', onClose);
85 file.stream.off('error', onStreamError);
86 out.off('error', onWriteError);
87 out.off('finish', onFinish);
88 };
89
90 const stopPiping = () =>
91 {
92 // Prevent late file stream chunks from writing into a destroyed stream.
93 file.stream.unpipe(out);
94 if (typeof file.stream.resume === 'function') file.stream.resume();
95 };
96
97 const cleanup = (done) =>
98 {
99 if (cleaned) return done(null);
100 cleaned = true;
101 unlinkIfExists(tempPath, done);
102 };
103
104 const fail = (err) =>
105 {
106 if (settled) return;
107 settled = true;
108 stopPiping();
109 detach();
110
111 const finishFailure = () =>
112 {
113 cleanup((cleanupErr) => cb(cleanupErr || err));
114 };
115
116 if (out.destroyed || out.writableEnded)
117 {
118 finishFailure();
119 return;
120 }
121
122 out.end(finishFailure);
123 };
124
125 const succeed = () =>
126 {
127 if (settled) return;
128 settled = true;
129 detach();
130 cb(null, {
131 destination: req._uploadDir,
132 filename: finalName,
133 originalname: file.originalname,
134 path: finalPath,
135 size: out.bytesWritten,
136 });
137 };
138
139 const onAbort = () => fail(new Error('Upload aborted.'));
140 const onClose = () =>
141 {
142 if (!req.complete) onAbort();
143 };
144 const onStreamError = (err) => fail(err);
145 const onWriteError = (err) => fail(err);
146 const onFinish = () =>
147 {
148 if (req.aborted || !req.complete)
149 {
150 fail(new Error('Upload aborted.'));
151 return;
152 }
153
154 promoteUploadedFile(tempPath, finalPath, (err) =>
155 {
156 if (err)
157 {
158 fail(err);
159 return;
160 }
161 succeed();
162 });
163 };
164
165 req.on('aborted', onAbort);
166 req.on('close', onClose);
167 file.stream.on('error', onStreamError);
168 out.on('error', onWriteError);
169 out.on('finish', onFinish);
170 file.stream.pipe(out);
171 },
172
173 _removeFile (req, file, cb)
174 {
175 unlinkIfExists(file.path, cb);
176 },
177};
178
179const upload = multer({
180 storage,
181 limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB
182});
183
184// ---------------------------------------------------------------------------
185// Helpers
186// ---------------------------------------------------------------------------
187
188function effectivePaths ()
189{
190 return getEffectivePaths(loadConfig().paths || []);
191}
192
193function rootAliasesFromConfig (config)
194{
195 if (!config || typeof config !== 'object') return {};
196 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
197 return config.rootAliases;
198}
199
200function getFreeBytes (targetPath)
201{
202 if (typeof fs.statfsSync !== 'function') return null;
203 try
204 {
205 const stat = fs.statfsSync(targetPath);
206 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
207 return stat.bavail * stat.bsize;
208 } catch
209 {
210 return null;
211 }
212}
213
214function getRecursiveSize (targetPath)
215{
216 try
217 {
218 const stat = fs.statSync(targetPath);
219 if (!stat.isDirectory()) return stat.size;
220 } catch
221 {
222 return 0;
223 }
224
225 let total = 0;
226 let entries = [];
227 try
228 {
229 entries = fs.readdirSync(targetPath, { withFileTypes: true });
230 } catch
231 {
232 return 0;
233 }
234
235 for (const entry of entries)
236 {
237 const child = path.join(targetPath, entry.name);
238 if (entry.isDirectory())
239 {
240 total += getRecursiveSize(child);
241 continue;
242 }
243 try
244 {
245 total += fs.statSync(child).size;
246 } catch
247 {
248 // Ignore files that disappear during traversal.
249 }
250 }
251
252 return total;
253}
254
255/**
256 * Verify that the user has read access to the given configured-path label.
257 * `pathLabel` is the base-name of the effective path (shown in the UI).
258 */
259function canRead (user, pathLabel)
260{
261 if (user.isAdmin) return true;
262 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
263}
264
265function canWrite (user, pathLabel)
266{
267 if (user.isAdmin) return true;
268 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
269}
270
271/**
272 * Given an absolute path and the effective-paths list, return
273 * { root, label } where label is the base-name of the root, or null.
274 */
275function resolveRoot (absPath, roots)
276{
277 const matchedRoot = getAllowedRoot(absPath, roots);
278 if (!matchedRoot) return null;
279 return { root: matchedRoot, label: path.basename(matchedRoot) };
280}
281
282function sameResolvedPath (a, b)
283{
284 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
285}
286
287function pathInsideResolved (child, root)
288{
289 const relative = path.relative(path.resolve(root), path.resolve(child));
290 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
291}
292
293function rewriteMetaPaths (fromPath, toPath)
294{
295 const db = getDb();
296 const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by, sha256 FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
297 .all([fromPath, fromPath + path.sep + '%']);
298
299 if (!rows.length) return;
300
301 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
302 const upsert = db.prepare(`
303 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, sha256)
304 VALUES (?, ?, ?, ?, ?)
305 ON CONFLICT(file_path) DO UPDATE SET
306 uploader = excluded.uploader,
307 downloaders = excluded.downloaders,
308 watched_by = excluded.watched_by,
309 sha256 = excluded.sha256
310 `);
311
312 for (const row of rows)
313 {
314 const nextPath = row.file_path === fromPath
315 ? toPath
316 : toPath + row.file_path.slice(fromPath.length);
317 del.run([row.file_path]);
318 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}', row.sha256 || null]);
319 }
320}
321
322function parseJsonArray (raw)
323{
324 try
325 {
326 const value = JSON.parse(raw || '[]');
327 return Array.isArray(value) ? value : [];
328 } catch
329 {
330 return [];
331 }
332}
333
334function parseJsonObject (raw)
335{
336 try
337 {
338 const value = JSON.parse(raw || '{}');
339 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
340 return value;
341 } catch
342 {
343 return {};
344 }
345}
346
347function watchStatusForProgress (progress)
348{
349 if (!Number.isFinite(progress) || progress < 0) return null;
350 if (progress >= 0.7) return 'fully';
351 if (progress >= 0.05) return 'partway';
352 return null;
353}
354
355function splitNameExt (name)
356{
357 const dot = String(name || '').lastIndexOf('.');
358 if (dot <= 0) return { stem: String(name || ''), ext: '' };
359 return {
360 stem: String(name).slice(0, dot),
361 ext: String(name).slice(dot),
362 };
363}
364
365function pickNumberedPath (dir, requestedName)
366{
367 const parsed = splitNameExt(requestedName);
368 const stem = parsed.stem || 'file';
369 const ext = parsed.ext || '';
370 let index = 1;
371
372 while (index <= 10000)
373 {
374 const candidateName = `${stem} (${index})${ext}`;
375 const candidatePath = path.join(dir, candidateName);
376 if (!fs.existsSync(candidatePath)) return candidatePath;
377 index++;
378 }
379
380 throw new Error('Could not generate a free destination name.');
381}
382
383function removePathRecursive (targetPath)
384{
385 const stat = fs.lstatSync(targetPath);
386 if (stat.isDirectory())
387 {
388 fs.rmSync(targetPath, { recursive: true, force: true });
389 } else
390 {
391 fs.unlinkSync(targetPath);
392 }
393}
394
395// ---------------------------------------------------------------------------
396// GET /api/files/roots
397// Returns the effective configured paths the user can read.
398// ---------------------------------------------------------------------------
399router.get('/roots', requireAuth, (req, res) =>
400{
401 const config = loadConfig();
402 const roots = getEffectivePaths(config.paths || []);
403 const rootAliases = rootAliasesFromConfig(config);
404
405 const readable = roots
406 .filter(r => canRead(req.user, path.basename(r)))
407 .map(r =>
408 {
409 const originalName = path.basename(r);
410 const alias = String(rootAliases[path.resolve(r)] || '').trim();
411 return {
412 label: alias || originalName,
413 path: r,
414 originalName,
415 alias: alias || null,
416 };
417 });
418 res.json({ roots: readable });
419});
420
421// ---------------------------------------------------------------------------
422// GET /api/files/root-access?rootPath=<absolute-root-path>
423// Returns users that can access a configured root and their mode (R / R+W).
424// ---------------------------------------------------------------------------
425router.get('/root-access', requireAuth, (req, res) =>
426{
427 const rootPath = String(req.query.rootPath || '').trim();
428 if (!rootPath)
429 {
430 return res.status(400).json({ error: 'rootPath is required.' });
431 }
432
433 const config = loadConfig();
434 const roots = getEffectivePaths(config.paths || []);
435 const info = resolveRoot(rootPath, roots);
436 if (!info) return res.status(403).json({ error: 'Access denied.' });
437 if (!sameResolvedPath(rootPath, info.root))
438 {
439 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
440 }
441 if (!canRead(req.user, info.label))
442 {
443 return res.status(403).json({ error: 'Access denied.' });
444 }
445
446 const db = getDb();
447 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
448 const users = [];
449
450 for (const row of rows)
451 {
452 if (row.is_admin === 1)
453 {
454 users.push({ username: row.username, mode: 'R+W' });
455 continue;
456 }
457
458 let permissions = {};
459 try
460 {
461 permissions = JSON.parse(row.permissions || '{}');
462 } catch
463 {
464 permissions = {};
465 }
466
467 const perm = permissions[info.label];
468 if (!perm || typeof perm !== 'object') continue;
469 const canWriteRoot = !!perm.write;
470 const canReadRoot = !!perm.read || canWriteRoot;
471 if (!canReadRoot) continue;
472 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
473 }
474
475 users.sort((a, b) =>
476 {
477 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
478 const byMode = modeRank(a.mode) - modeRank(b.mode);
479 if (byMode !== 0) return byMode;
480 return String(a.username).localeCompare(String(b.username));
481 });
482
483 const rootAliases = rootAliasesFromConfig(config);
484 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
485 res.json({
486 root: {
487 path: info.root,
488 label: alias || info.label,
489 originalName: info.label,
490 alias: alias || null,
491 },
492 users,
493 });
494});
495
496// ---------------------------------------------------------------------------
497// POST /api/files/root-alias
498// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
499// Sets a display-only alias for a configured root.
500// ---------------------------------------------------------------------------
501router.post('/root-alias', requireAuth, (req, res) =>
502{
503 const rootPath = String(req.body && req.body.rootPath || '').trim();
504 const alias = String(req.body && req.body.alias || '').trim();
505 if (!rootPath || !alias)
506 {
507 return res.status(400).json({ error: 'rootPath and alias are required.' });
508 }
509
510 const roots = effectivePaths();
511 const info = resolveRoot(rootPath, roots);
512 if (!info) return res.status(403).json({ error: 'Access denied.' });
513 if (!sameResolvedPath(rootPath, info.root))
514 {
515 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
516 }
517 if (!canWrite(req.user, info.label))
518 {
519 return res.status(403).json({ error: 'Access denied.' });
520 }
521
522 const config = loadConfig();
523 const rootAliases = rootAliasesFromConfig(config);
524 const key = path.resolve(info.root);
525 if (alias === info.label)
526 {
527 delete rootAliases[key];
528 } else
529 {
530 rootAliases[key] = alias;
531 }
532 config.rootAliases = rootAliases;
533 saveConfig(config);
534
535 res.json({
536 ok: true,
537 root: {
538 path: info.root,
539 label: alias,
540 originalName: info.label,
541 alias,
542 },
543 });
544});
545
546// ---------------------------------------------------------------------------
547// GET /api/files/list?dir=<absolute-path>
548// Lists files and folders in the given directory.
549// ---------------------------------------------------------------------------
550router.get('/list', requireAuth, (req, res) =>
551{
552 const dir = req.query.dir;
553 if (!dir) return res.status(400).json({ error: 'dir is required.' });
554
555 const roots = effectivePaths();
556 const info = resolveRoot(dir, roots);
557 if (!info) return res.status(403).json({ error: 'Access denied.' });
558 if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' });
559
560 let entries;
561 try
562 {
563 entries = fs.readdirSync(dir, { withFileTypes: true });
564 } catch
565 {
566 return res.status(404).json({ error: 'Directory not found.' });
567 }
568
569 const items = entries.map(e =>
570 {
571 const fullPath = path.join(dir, e.name);
572 let size = null;
573 let mtime = null;
574 try
575 {
576 const stat = fs.statSync(fullPath);
577 size = stat.size;
578 mtime = stat.mtime.toISOString();
579 } catch { /* ignore */ }
580
581 return {
582 name: e.name,
583 isDir: e.isDirectory(),
584 size,
585 mtime,
586 path: fullPath,
587 };
588 });
589
590 res.json({ items });
591});
592
593// ---------------------------------------------------------------------------
594// GET /api/files/meta?file=<absolute-path>
595// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
596// ---------------------------------------------------------------------------
597router.get('/meta', requireAuth, async (req, res) =>
598{
599 const file = req.query.file;
600 if (!file) return res.status(400).json({ error: 'file is required.' });
601
602 const roots = effectivePaths();
603 const info = resolveRoot(file, roots);
604 if (!info || !canRead(req.user, info.label))
605 {
606 return res.status(403).json({ error: 'Access denied.' });
607 }
608
609 let stat;
610 try
611 {
612 stat = fs.statSync(file);
613 } catch
614 {
615 return res.status(404).json({ error: 'File not found.' });
616 }
617
618 const db = getDb();
619 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
620
621 // Lazily compute and persist the SHA-256 hash when it is absent.
622 let sha256 = meta ? (meta.sha256 || null) : null;
623 if (!sha256 && !stat.isDirectory())
624 {
625 try
626 {
627 sha256 = await computeFileSha256(file);
628 if (meta)
629 {
630 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
631 } else
632 {
633 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
634 .run([file, '', '[]', sha256]);
635 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
636 }
637 } catch
638 {
639 // Non-fatal — hash will be retried next time.
640 }
641 }
642
643 res.json({
644 name: path.basename(file),
645 size: stat.size,
646 mtime: stat.mtime.toISOString(),
647 uploader: meta ? meta.uploader : '',
648 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
649 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
650 sha256: sha256 || null,
651 });
652});
653
654// ---------------------------------------------------------------------------
655// GET /api/files/duplicates?file=<absolute-path>
656// Returns other files with the same SHA-256 hash that the user can access.
657// ---------------------------------------------------------------------------
658router.get('/duplicates', requireAuth, (req, res) =>
659{
660 const file = req.query.file;
661 if (!file) return res.status(400).json({ error: 'file is required.' });
662
663 const roots = effectivePaths();
664 const info = resolveRoot(file, roots);
665 if (!info || !canRead(req.user, info.label))
666 {
667 return res.status(403).json({ error: 'Access denied.' });
668 }
669
670 const db = getDb();
671 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
672 const hash = row ? (row.sha256 || null) : null;
673 if (!hash)
674 {
675 return res.json({ duplicates: [] });
676 }
677
678 // All other files sharing the same hash.
679 const candidates = db.prepare(
680 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
681 ).all([hash, file]);
682
683 const readable = roots.filter((r) => canRead(req.user, path.basename(r)));
684
685 const duplicates = [];
686 for (const { file_path } of candidates)
687 {
688 // Only return files inside a root the user can access and that still exist on disk.
689 const allowedRoot = readable.find(
690 (r) => file_path === r || (file_path.startsWith(r) && (file_path[r.length] === path.sep || file_path[r.length] === '/')),
691 );
692 if (!allowedRoot) continue;
693 if (!fs.existsSync(file_path)) continue;
694 duplicates.push({
695 path: file_path,
696 name: path.basename(file_path),
697 dir: path.dirname(file_path),
698 });
699 }
700
701 res.json({ duplicates });
702});
703
704// ---------------------------------------------------------------------------
705// GET /api/files/space?dir=<absolute-path>
706// Returns recursive used bytes for dir and available bytes on its root fs.
707// ---------------------------------------------------------------------------
708router.get('/space', requireAuth, (req, res) =>
709{
710 const dir = req.query.dir;
711 if (!dir) return res.status(400).json({ error: 'dir is required.' });
712
713 const roots = effectivePaths();
714 const info = resolveRoot(dir, roots);
715 if (!info || !canRead(req.user, info.label))
716 {
717 return res.status(403).json({ error: 'Access denied.' });
718 }
719
720 if (!fs.existsSync(dir))
721 {
722 return res.status(404).json({ error: 'Path not found.' });
723 }
724
725 const usedBytes = getRecursiveSize(dir);
726 const freeBytes = getFreeBytes(info.root);
727 res.json({
728 usedBytes,
729 freeBytes,
730 rootPath: info.root,
731 rootLabel: info.label,
732 });
733});
734
735// ---------------------------------------------------------------------------
736// GET /api/files/download?file=<absolute-path>
737// Streams the file to the client; records the download.
738// ---------------------------------------------------------------------------
739router.get('/download', requireAuth, (req, res) =>
740{
741 const file = req.query.file;
742 if (!file) return res.status(400).json({ error: 'file is required.' });
743
744 const roots = effectivePaths();
745 const info = resolveRoot(file, roots);
746 if (!info || !canRead(req.user, info.label))
747 {
748 return res.status(403).json({ error: 'Access denied.' });
749 }
750
751 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
752 {
753 return res.status(404).json({ error: 'File not found.' });
754 }
755
756 // Record download
757 const db = getDb();
758 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
759 if (meta)
760 {
761 const downloaders = parseJsonArray(meta.downloaders);
762 if (!downloaders.includes(req.user.username))
763 {
764 downloaders.push(req.user.username);
765 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
766 .run([JSON.stringify(downloaders), file]);
767 }
768 } else
769 {
770 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
771 .run([file, '', JSON.stringify([req.user.username]), '{}']);
772 }
773
774 res.download(file, path.basename(file));
775});
776
777// ---------------------------------------------------------------------------
778// POST /api/files/watch-progress
779// Body: { filePath: <absolute-path>, progress: <0..1> }
780// Records per-user video watch state for sidebar display.
781// ---------------------------------------------------------------------------
782router.post('/watch-progress', requireAuth, (req, res) =>
783{
784 const filePath = String(req.body && req.body.filePath || '').trim();
785 const progress = Number(req.body && req.body.progress);
786 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
787
788 const status = watchStatusForProgress(progress);
789 if (!status)
790 {
791 return res.json({ ok: true, updated: false });
792 }
793
794 const roots = effectivePaths();
795 const info = resolveRoot(filePath, roots);
796 if (!info || !canRead(req.user, info.label))
797 {
798 return res.status(403).json({ error: 'Access denied.' });
799 }
800
801 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
802 {
803 return res.status(404).json({ error: 'File not found.' });
804 }
805
806 const db = getDb();
807 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
808 const watchedBy = parseJsonObject(row && row.watched_by);
809 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
810 const next = prev === 'fully' ? 'fully' : status;
811 if (prev === next)
812 {
813 return res.json({ ok: true, updated: false, status: next });
814 }
815
816 watchedBy[req.user.username] = next;
817 if (row)
818 {
819 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
820 .run([JSON.stringify(watchedBy), filePath]);
821 } else
822 {
823 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
824 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
825 }
826
827 res.json({ ok: true, updated: true, status: next });
828});
829
830// ---------------------------------------------------------------------------
831// POST /api/files/video-stream
832// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
833// ---------------------------------------------------------------------------
834router.post('/video-stream', requireAuth, async (req, res, next) =>
835{
836 try
837 {
838 const filePath = String(req.body?.filePath || '').trim();
839 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
840
841 const roots = effectivePaths();
842 const info = resolveRoot(filePath, roots);
843 if (!info || !canRead(req.user, info.label))
844 {
845 return res.status(403).json({ error: 'Access denied.' });
846 }
847
848 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
849 {
850 return res.status(404).json({ error: 'File not found.' });
851 }
852
853 const session = await createVideoStreamSession(filePath);
854 res.json({
855 sessionId: session.sessionId,
856 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
857 durationSeconds: session.durationSeconds || null,
858 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 },
859 subtitleTracks: session.subtitleTracks.map((track) => ({
860 label: track.label,
861 language: track.language,
862 default: !!track.isDefault,
863 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
864 })),
865 });
866 } catch (err)
867 {
868 next(err);
869 }
870});
871
872// ---------------------------------------------------------------------------
873// GET /api/files/video-stream/:sessionId/:assetPath(*)
874// Streams HLS assets for a previously created short-lived video session.
875// ---------------------------------------------------------------------------
876router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
877{
878 try
879 {
880 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
881 } catch (err)
882 {
883 next(err);
884 }
885});
886
887// ---------------------------------------------------------------------------
888// DELETE /api/files/video-stream/:sessionId
889// Authenticated. Explicitly releases an active short-lived video session.
890// ---------------------------------------------------------------------------
891router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
892{
893 const sessionId = String(req.params.sessionId || '').trim();
894 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
895
896 releaseVideoStreamSession(sessionId);
897 res.json({ ok: true });
898});
899
900// ---------------------------------------------------------------------------
901// GET /api/files/download-zip?dir=<absolute-path>
902// Authenticated. Streams a zip of the given directory.
903// ---------------------------------------------------------------------------
904router.get('/download-zip', requireAuth, async (req, res) =>
905{
906 const dir = req.query.dir;
907 if (!dir) return res.status(400).json({ error: 'dir is required.' });
908
909 const roots = effectivePaths();
910 const info = resolveRoot(dir, roots);
911 if (!info || !canRead(req.user, info.label))
912 {
913 return res.status(403).json({ error: 'Access denied.' });
914 }
915
916 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
917 {
918 return res.status(404).json({ error: 'Directory not found.' });
919 }
920
921 // Use a hash of the dir path as cache key so concurrent users share the cache.
922 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
923 try
924 {
925 const zipPath = await buildZip(dir, cacheKey);
926 const zipName = `${path.basename(dir)}.zip`;
927 res.download(zipPath, zipName);
928 } catch (err)
929 {
930 res.status(500).json({ error: 'Failed to create zip archive.' });
931 }
932});
933
934// ---------------------------------------------------------------------------
935// GET /api/files/thumbnail?file=<absolute-path>
936// Returns a pre-generated cached thumbnail if present.
937// ---------------------------------------------------------------------------
938router.get('/thumbnail', requireAuth, async (req, res) =>
939{
940 const file = req.query.file;
941 if (!file) return res.status(400).json({ error: 'file is required.' });
942
943 const roots = effectivePaths();
944 const info = resolveRoot(file, roots);
945 if (!info || !canRead(req.user, info.label))
946 {
947 return res.status(403).json({ error: 'Access denied.' });
948 }
949
950 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
951 {
952 return res.status(404).json({ error: 'File not found.' });
953 }
954
955 const thumb = await getCachedThumbnailInfo(file);
956 if (!thumb)
957 {
958 return res.status(404).json({ error: 'Thumbnail not ready.' });
959 }
960
961 res.type(thumb.contentType);
962 res.set('Cache-Control', 'private, max-age=10');
963 res.sendFile(thumb.thumbPath);
964});
965
966// ---------------------------------------------------------------------------
967// POST /api/files/upload?dir=<absolute-path>
968// Accepts multipart file upload.
969// ---------------------------------------------------------------------------
970router.post('/upload', requireAuth, (req, res, next) =>
971{
972 const dir = req.query.dir;
973 if (!dir) return res.status(400).json({ error: 'dir is required.' });
974
975 const roots = effectivePaths();
976 const info = resolveRoot(dir, roots);
977 if (!info || !canWrite(req.user, info.label))
978 {
979 return res.status(403).json({ error: 'Access denied.' });
980 }
981
982 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
983 {
984 return res.status(404).json({ error: 'Directory not found.' });
985 }
986
987 const announcedSize = Number(req.header('x-upload-size') || 0);
988 if (Number.isFinite(announcedSize) && announcedSize > 0)
989 {
990 const freeBytes = getFreeBytes(info.root);
991 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
992 {
993 return res.status(413).json({
994 error: 'Upload too large for remaining free space on selected root.',
995 freeBytes,
996 requiredBytes: announcedSize,
997 });
998 }
999 }
1000
1001 req._uploadDir = dir;
1002
1003 upload.array('files')(req, res, async (err) =>
1004 {
1005 if (err) return res.status(500).json({ error: err.message });
1006
1007 const db = getDb();
1008 for (const f of (req.files || []))
1009 {
1010 const filePath = path.join(dir, f.originalname);
1011
1012 let sha256 = null;
1013 try
1014 {
1015 sha256 = await computeFileSha256(filePath);
1016 } catch
1017 {
1018 // Non-fatal — hash can be computed lazily when the file is accessed.
1019 }
1020
1021 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1022 if (existing)
1023 {
1024 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1025 .run([req.user.username, sha256, filePath]);
1026 } else
1027 {
1028 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1029 .run([filePath, req.user.username, '[]', sha256]);
1030 }
1031 }
1032 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1033 });
1034});
1035
1036// ---------------------------------------------------------------------------
1037// POST /api/files/rename
1038// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1039// ---------------------------------------------------------------------------
1040router.post('/rename', requireAuth, (req, res) =>
1041{
1042 const { from, to } = req.body;
1043 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1044
1045 // Prevent path traversal in the new name
1046 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1047 {
1048 return res.status(400).json({ error: 'Invalid name.' });
1049 }
1050
1051 const roots = effectivePaths();
1052 const info = resolveRoot(from, roots);
1053 if (!info || !canWrite(req.user, info.label))
1054 {
1055 return res.status(403).json({ error: 'Access denied.' });
1056 }
1057
1058 const dest = path.join(path.dirname(from), to);
1059
1060 // Ensure dest is still inside the same root
1061 if (!getAllowedRoot(dest, roots))
1062 {
1063 return res.status(403).json({ error: 'Access denied.' });
1064 }
1065
1066 try
1067 {
1068 fs.renameSync(from, dest);
1069 } catch (err)
1070 {
1071 return res.status(500).json({ error: err.message });
1072 }
1073
1074 rewriteMetaPaths(from, dest);
1075
1076 res.json({ ok: true });
1077});
1078
1079// ---------------------------------------------------------------------------
1080// POST /api/files/move
1081// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1082// ---------------------------------------------------------------------------
1083router.post('/move', requireAuth, (req, res) =>
1084{
1085 const { from, toDir } = req.body;
1086 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1087 const targetName = req.body && req.body.targetName != null
1088 ? String(req.body.targetName).trim()
1089 : '';
1090 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1091 if (!['error', 'overwrite', 'rename'].includes(conflict))
1092 {
1093 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1094 }
1095
1096 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1097 {
1098 return res.status(400).json({ error: 'Invalid targetName.' });
1099 }
1100
1101 const roots = effectivePaths();
1102 const fromInfo = resolveRoot(from, roots);
1103 const toInfo = resolveRoot(toDir, roots);
1104 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1105 if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label))
1106 {
1107 return res.status(403).json({ error: 'Access denied.' });
1108 }
1109
1110 let sourceStat;
1111 let destStat;
1112 try
1113 {
1114 sourceStat = fs.statSync(from);
1115 destStat = fs.statSync(toDir);
1116 } catch
1117 {
1118 return res.status(404).json({ error: 'Source or destination not found.' });
1119 }
1120
1121 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1122
1123 const requestedName = targetName || path.basename(from);
1124 const requestedDest = path.join(toDir, requestedName);
1125 if (!getAllowedRoot(requestedDest, roots)) return res.status(403).json({ error: 'Access denied.' });
1126 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1127 {
1128 return res.status(400).json({ error: 'Cannot move onto itself.' });
1129 }
1130 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1131 {
1132 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1133 }
1134
1135 let dest = requestedDest;
1136 let resolvedConflict = 'none';
1137
1138 if (fs.existsSync(requestedDest))
1139 {
1140 if (conflict === 'error')
1141 {
1142 return res.status(409).json({ error: 'Destination already exists.' });
1143 }
1144
1145 if (conflict === 'rename')
1146 {
1147 dest = pickNumberedPath(toDir, requestedName);
1148 resolvedConflict = 'rename';
1149 }
1150
1151 if (conflict === 'overwrite')
1152 {
1153 try
1154 {
1155 removePathRecursive(requestedDest);
1156 } catch (err)
1157 {
1158 return res.status(500).json({ error: err.message });
1159 }
1160 resolvedConflict = 'overwrite';
1161 }
1162 }
1163
1164 if (sameResolvedPath(from, dest))
1165 {
1166 return res.status(400).json({ error: 'Cannot move onto itself.' });
1167 }
1168
1169 try
1170 {
1171 fs.renameSync(from, dest);
1172 } catch (err)
1173 {
1174 return res.status(500).json({ error: err.message });
1175 }
1176
1177 rewriteMetaPaths(from, dest);
1178 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1179});
1180
1181// ---------------------------------------------------------------------------
1182// POST /api/files/mkdir
1183// Body: { dir: <absolute-path>, name: <folder-name> }
1184// ---------------------------------------------------------------------------
1185router.post('/mkdir', requireAuth, (req, res) =>
1186{
1187 const { dir, name } = req.body;
1188 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1189
1190 if (path.basename(name) !== name)
1191 {
1192 return res.status(400).json({ error: 'Invalid folder name.' });
1193 }
1194
1195 const roots = effectivePaths();
1196 const info = resolveRoot(dir, roots);
1197 if (!info || !canWrite(req.user, info.label))
1198 {
1199 return res.status(403).json({ error: 'Access denied.' });
1200 }
1201
1202 const newDir = path.join(dir, name);
1203 if (!getAllowedRoot(newDir, roots))
1204 {
1205 return res.status(403).json({ error: 'Access denied.' });
1206 }
1207
1208 try
1209 {
1210 fs.mkdirSync(newDir, { recursive: false });
1211 } catch (err)
1212 {
1213 return res.status(500).json({ error: err.message });
1214 }
1215
1216 res.json({ ok: true, path: newDir });
1217});
1218
1219// ---------------------------------------------------------------------------
1220// POST /api/files/delete
1221// Body: { path: <absolute-path> }
1222// ---------------------------------------------------------------------------
1223router.post('/delete', requireAuth, (req, res) =>
1224{
1225 const target = req.body.path;
1226 if (!target) return res.status(400).json({ error: 'path is required.' });
1227
1228 const roots = effectivePaths();
1229 const info = resolveRoot(target, roots);
1230 if (!info || !canWrite(req.user, info.label))
1231 {
1232 return res.status(403).json({ error: 'Access denied.' });
1233 }
1234
1235 // Do not allow deleting a configured root itself
1236 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1237 {
1238 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1239 }
1240
1241 try
1242 {
1243 const stat = fs.statSync(target);
1244 if (stat.isDirectory())
1245 {
1246 fs.rmSync(target, { recursive: true, force: true });
1247 } else
1248 {
1249 fs.unlinkSync(target);
1250 }
1251 } catch (err)
1252 {
1253 return res.status(500).json({ error: err.message });
1254 }
1255
1256 // Clean up any DB meta entries under that path
1257 const db = getDb();
1258 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1259 .run([target, target + path.sep + '%']);
1260
1261 res.json({ ok: true });
1262});
1263
1264// ---------------------------------------------------------------------------
1265// GET /api/files/folder-images?dir=<absolute-path>
1266// Returns images inside dir (recursive) that already have a cached thumbnail.
1267// Only images with a ready thumbnail are included (user constraint).
1268// ---------------------------------------------------------------------------
1269router.get('/folder-images', requireAuth, async (req, res) =>
1270{
1271 const dir = String(req.query.dir || '').trim();
1272 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1273
1274 const roots = effectivePaths();
1275 const info = resolveRoot(dir, roots);
1276 if (!info || !canRead(req.user, info.label))
1277 {
1278 return res.status(403).json({ error: 'Access denied.' });
1279 }
1280
1281 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1282 {
1283 return res.status(404).json({ error: 'Directory not found.' });
1284 }
1285
1286 const images = await getImagesWithThumbnailsInDir(dir);
1287 // Filter out any that escaped to a different root (safety check).
1288 const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots));
1289
1290 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1291});
1292
1293// ---------------------------------------------------------------------------
1294// GET /api/files/folder-icon?dir=<absolute-path>
1295// Returns the current icon source file for a folder (explicit or auto-first).
1296// ---------------------------------------------------------------------------
1297router.get('/folder-icon', requireAuth, async (req, res) =>
1298{
1299 const dir = String(req.query.dir || '').trim();
1300 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1301
1302 const roots = effectivePaths();
1303 const info = resolveRoot(dir, roots);
1304 if (!info || !canRead(req.user, info.label))
1305 {
1306 return res.status(403).json({ error: 'Access denied.' });
1307 }
1308
1309 const sourceFile = await getFolderIconSourceFile(dir);
1310 if (!sourceFile) return res.json({ icon: null });
1311
1312 // Verify the source is still accessible within a configured root.
1313 if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null });
1314
1315 res.json({ icon: { filePath: sourceFile } });
1316});
1317
1318// ---------------------------------------------------------------------------
1319// POST /api/files/folder-icon
1320// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1321// Requires write access; the image must already have a cached thumbnail.
1322// ---------------------------------------------------------------------------
1323router.post('/folder-icon', requireAuth, async (req, res) =>
1324{
1325 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1326 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1327
1328 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1329
1330 const roots = effectivePaths();
1331 const info = resolveRoot(folderPath, roots);
1332 if (!info || !canWrite(req.user, info.label))
1333 {
1334 return res.status(403).json({ error: 'Access denied.' });
1335 }
1336
1337 let stat;
1338 try { stat = fs.statSync(folderPath); }
1339 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1340 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1341
1342 if (rawImage !== null)
1343 {
1344 // Verify the image is inside a readable root.
1345 const imageRoot = getAllowedRoot(rawImage, roots);
1346 if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' });
1347
1348 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1349 const thumb = await getCachedThumbnailInfo(rawImage);
1350 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1351 }
1352
1353 await setFolderIconAssignment(folderPath, rawImage);
1354 res.json({ ok: true });
1355});
1356
1357module.exports = router;