BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

test
timfa Tim Falken · pushed by timfa · 6 months ago
2c0e0fdd History
files.js 53.8 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, getFilesWithThumbnailsInDir, 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
193/**
194 * Loads config and returns { config, roots } together so both are consistent
195 * and user-folder checks can be performed in route handlers.
196 */
197function loadConfigAndRoots ()
198{
199 const config = loadConfig();
200 return { config, roots: getEffectivePaths(config.paths || []) };
201}
202
203/**
204 * Returns true when absPath is accessible to the user (either via a
205 * configured root or their personal folder).
206 */
207function isAccessiblePath (absPath, roots, user, config)
208{
209 return resolveRootForUser(absPath, roots, user, config) !== null;
210}
211
212function rootAliasesFromConfig (config)
213{
214 if (!config || typeof config !== 'object') return {};
215 if (!config.rootAliases || typeof config.rootAliases !== 'object') return {};
216 return config.rootAliases;
217}
218
219function getFreeBytes (targetPath)
220{
221 if (typeof fs.statfsSync !== 'function') return null;
222 try
223 {
224 const stat = fs.statfsSync(targetPath);
225 if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null;
226 return stat.bavail * stat.bsize;
227 } catch
228 {
229 return null;
230 }
231}
232
233function getRecursiveSize (targetPath)
234{
235 try
236 {
237 const stat = fs.statSync(targetPath);
238 if (!stat.isDirectory()) return stat.size;
239 } catch
240 {
241 return 0;
242 }
243
244 let total = 0;
245 let entries = [];
246 try
247 {
248 entries = fs.readdirSync(targetPath, { withFileTypes: true });
249 } catch
250 {
251 return 0;
252 }
253
254 for (const entry of entries)
255 {
256 const child = path.join(targetPath, entry.name);
257 if (entry.isDirectory())
258 {
259 total += getRecursiveSize(child);
260 continue;
261 }
262 try
263 {
264 total += fs.statSync(child).size;
265 } catch
266 {
267 // Ignore files that disappear during traversal.
268 }
269 }
270
271 return total;
272}
273
274/**
275 * Verify that the user has read access to the given configured-path label.
276 * `pathLabel` is the base-name of the effective path (shown in the UI).
277 */
278function canRead (user, pathLabel)
279{
280 if (user.isAdmin) return true;
281 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read);
282}
283
284function canWrite (user, pathLabel)
285{
286 if (user.isAdmin) return true;
287 return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write);
288}
289
290// ---------------------------------------------------------------------------
291// User folder helpers
292// ---------------------------------------------------------------------------
293
294/**
295 * Returns the absolute path of the user's personal folder, or null.
296 * e.g. /data/userfolders/<username>
297 */
298function getUserFolderPath (config, username)
299{
300 const base = typeof config.userPath === 'string' ? config.userPath.trim() : '';
301 if (!base) return null;
302 return path.join(base, String(username));
303}
304
305/**
306 * Resolves a request path against both the configured roots AND the user's
307 * personal folder. Returns { root, label, isUserFolder } or null.
308 * - isUserFolder: true when the path is inside the user's personal folder.
309 */
310function resolveRootForUser (absPath, roots, user, config)
311{
312 // Regular configured roots first.
313 const matched = getAllowedRoot(absPath, roots);
314 if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false };
315
316 // Check user personal folder.
317 if (!user || !user.username) return null;
318 const userFolder = getUserFolderPath(config, user.username);
319 if (!userFolder) return null;
320
321 const resolved = path.resolve(absPath);
322 const resolvedFolder = path.resolve(userFolder);
323 if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep))
324 {
325 return { root: userFolder, label: path.basename(userFolder), isUserFolder: true };
326 }
327
328 return null;
329}
330
331/**
332 * Checks whether the user has READ access to the resolved root info object
333 * returned by resolveRootForUser.
334 */
335function canReadInfo (user, info)
336{
337 if (!info) return false;
338 if (info.isUserFolder) return true; // owner always has full access
339 return canRead(user, info.label);
340}
341
342/**
343 * Checks whether the user has WRITE access to the resolved root info object.
344 */
345function canWriteInfo (user, info)
346{
347 if (!info) return false;
348 if (info.isUserFolder) return true;
349 return canWrite(user, info.label);
350}
351
352/**
353 * Returns the size limit (bytes) for the user's personal folder, or null = unlimited.
354 */
355function getUserFolderSizeLimit (config)
356{
357 const lim = Number(config.userFolderSizeLimit);
358 return Number.isFinite(lim) && lim > 0 ? lim : null;
359}
360
361/**
362 * Returns an error message if adding `addedBytes` to the user's folder would
363 * exceed the size limit, or null if within limits.
364 */
365function checkUserFolderSizeLimit (config, username, addedBytes)
366{
367 const limit = getUserFolderSizeLimit(config);
368 if (!limit) return null;
369 const userFolder = getUserFolderPath(config, username);
370 if (!userFolder) return null;
371 const currentSize = getRecursiveSize(userFolder);
372 if (currentSize + addedBytes > limit)
373 {
374 return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`;
375 }
376 return null;
377}
378
379function formatBytesServer (bytes)
380{
381 if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
382 if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`;
383 if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
384 return `${bytes} B`;
385}
386
387/**
388 * Given an absolute path and the effective-paths list, return
389 * { root, label } where label is the base-name of the root, or null.
390 */
391function resolveRoot (absPath, roots)
392{
393 const matchedRoot = getAllowedRoot(absPath, roots);
394 if (!matchedRoot) return null;
395 return { root: matchedRoot, label: path.basename(matchedRoot) };
396}
397
398function sameResolvedPath (a, b)
399{
400 return path.resolve(String(a || '')) === path.resolve(String(b || ''));
401}
402
403function pathInsideResolved (child, root)
404{
405 const relative = path.relative(path.resolve(root), path.resolve(child));
406 return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
407}
408
409function rewriteMetaPaths (fromPath, toPath)
410{
411 const db = getDb();
412 const rows = db.prepare('SELECT file_path, uploader, downloaders, watched_by, sha256 FROM file_meta WHERE file_path = ? OR file_path LIKE ?')
413 .all([fromPath, fromPath + path.sep + '%']);
414
415 if (!rows.length) return;
416
417 const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?');
418 const upsert = db.prepare(`
419 INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, sha256)
420 VALUES (?, ?, ?, ?, ?)
421 ON CONFLICT(file_path) DO UPDATE SET
422 uploader = excluded.uploader,
423 downloaders = excluded.downloaders,
424 watched_by = excluded.watched_by,
425 sha256 = excluded.sha256
426 `);
427
428 for (const row of rows)
429 {
430 const nextPath = row.file_path === fromPath
431 ? toPath
432 : toPath + row.file_path.slice(fromPath.length);
433 del.run([row.file_path]);
434 upsert.run([nextPath, row.uploader, row.downloaders, row.watched_by || '{}', row.sha256 || null]);
435 }
436}
437
438function parseJsonArray (raw)
439{
440 try
441 {
442 const value = JSON.parse(raw || '[]');
443 return Array.isArray(value) ? value : [];
444 } catch
445 {
446 return [];
447 }
448}
449
450function parseJsonObject (raw)
451{
452 try
453 {
454 const value = JSON.parse(raw || '{}');
455 if (!value || typeof value !== 'object' || Array.isArray(value)) return {};
456 return value;
457 } catch
458 {
459 return {};
460 }
461}
462
463function watchStatusForProgress (progress)
464{
465 if (!Number.isFinite(progress) || progress < 0) return null;
466 if (progress >= 0.7) return 'fully';
467 if (progress >= 0.05) return 'partway';
468 return null;
469}
470
471function normalisedWatchedStatus (value)
472{
473 const status = String(value || '').toLowerCase();
474 return status === 'fully' || status === 'partway' ? status : null;
475}
476
477function splitNameExt (name)
478{
479 const dot = String(name || '').lastIndexOf('.');
480 if (dot <= 0) return { stem: String(name || ''), ext: '' };
481 return {
482 stem: String(name).slice(0, dot),
483 ext: String(name).slice(dot),
484 };
485}
486
487function pickNumberedPath (dir, requestedName)
488{
489 const parsed = splitNameExt(requestedName);
490 const stem = parsed.stem || 'file';
491 const ext = parsed.ext || '';
492 let index = 1;
493
494 while (index <= 10000)
495 {
496 const candidateName = `${stem} (${index})${ext}`;
497 const candidatePath = path.join(dir, candidateName);
498 if (!fs.existsSync(candidatePath)) return candidatePath;
499 index++;
500 }
501
502 throw new Error('Could not generate a free destination name.');
503}
504
505function removePathRecursive (targetPath)
506{
507 const stat = fs.lstatSync(targetPath);
508 if (stat.isDirectory())
509 {
510 fs.rmSync(targetPath, { recursive: true, force: true });
511 } else
512 {
513 fs.unlinkSync(targetPath);
514 }
515}
516
517function movePathWithFallback (from, dest)
518{
519 const stat = fs.lstatSync(from);
520 try
521 {
522 fs.renameSync(from, dest);
523 return 'rename';
524 } catch (err)
525 {
526 try
527 {
528 if (stat.isDirectory())
529 {
530 fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true });
531 } else
532 {
533 fs.copyFileSync(from, dest);
534 }
535 fs.rmSync(from, { recursive: true, force: true });
536 return 'copy-delete';
537 } catch (fallbackErr)
538 {
539 throw fallbackErr || err;
540 }
541 }
542}
543
544// ---------------------------------------------------------------------------
545// GET /api/files/roots
546// Returns the effective configured paths the user can read.
547// Also injects the user's personal folder when userPath is configured.
548// ---------------------------------------------------------------------------
549router.get('/roots', requireAuth, (req, res) =>
550{
551 const config = loadConfig();
552 const roots = getEffectivePaths(config.paths || []);
553 const rootAliases = rootAliasesFromConfig(config);
554
555 const readable = roots
556 .filter(r => canRead(req.user, path.basename(r)))
557 .map(r =>
558 {
559 const originalName = path.basename(r);
560 const alias = String(rootAliases[path.resolve(r)] || '').trim();
561 return {
562 label: alias || originalName,
563 path: r,
564 originalName,
565 alias: alias || null,
566 };
567 });
568
569 // Inject the user's personal folder when a userPath is configured.
570 if (req.user && req.user.username)
571 {
572 const userFolder = getUserFolderPath(config, req.user.username);
573 if (userFolder)
574 {
575 try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ }
576 readable.unshift({
577 label: 'My Folder',
578 path: userFolder,
579 originalName: req.user.username,
580 alias: 'My Folder',
581 isUserFolder: true,
582 });
583 }
584 }
585
586 res.json({ roots: readable });
587});
588
589// ---------------------------------------------------------------------------
590// GET /api/files/root-access?rootPath=<absolute-root-path>
591// Returns users that can access a configured root and their mode (R / R+W).
592// ---------------------------------------------------------------------------
593router.get('/root-access', requireAuth, (req, res) =>
594{
595 const rootPath = String(req.query.rootPath || '').trim();
596 if (!rootPath)
597 {
598 return res.status(400).json({ error: 'rootPath is required.' });
599 }
600
601 const config = loadConfig();
602 const roots = getEffectivePaths(config.paths || []);
603 const info = resolveRoot(rootPath, roots);
604 if (!info) return res.status(403).json({ error: 'Access denied.' });
605 if (!sameResolvedPath(rootPath, info.root))
606 {
607 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
608 }
609 if (!canRead(req.user, info.label))
610 {
611 return res.status(403).json({ error: 'Access denied.' });
612 }
613
614 const db = getDb();
615 const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all();
616 const users = [];
617
618 for (const row of rows)
619 {
620 if (row.is_admin === 1)
621 {
622 users.push({ username: row.username, mode: 'R+W' });
623 continue;
624 }
625
626 let permissions = {};
627 try
628 {
629 permissions = JSON.parse(row.permissions || '{}');
630 } catch
631 {
632 permissions = {};
633 }
634
635 const perm = permissions[info.label];
636 if (!perm || typeof perm !== 'object') continue;
637 const canWriteRoot = !!perm.write;
638 const canReadRoot = !!perm.read || canWriteRoot;
639 if (!canReadRoot) continue;
640 users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' });
641 }
642
643 users.sort((a, b) =>
644 {
645 const modeRank = (mode) => mode === 'R+W' ? 0 : 1;
646 const byMode = modeRank(a.mode) - modeRank(b.mode);
647 if (byMode !== 0) return byMode;
648 return String(a.username).localeCompare(String(b.username));
649 });
650
651 const rootAliases = rootAliasesFromConfig(config);
652 const alias = String(rootAliases[path.resolve(info.root)] || '').trim();
653 res.json({
654 root: {
655 path: info.root,
656 label: alias || info.label,
657 originalName: info.label,
658 alias: alias || null,
659 },
660 users,
661 });
662});
663
664// ---------------------------------------------------------------------------
665// POST /api/files/root-alias
666// Body: { rootPath: <absolute-root-path>, alias: <display-alias> }
667// Sets a display-only alias for a configured root.
668// ---------------------------------------------------------------------------
669router.post('/root-alias', requireAuth, (req, res) =>
670{
671 const rootPath = String(req.body && req.body.rootPath || '').trim();
672 const alias = String(req.body && req.body.alias || '').trim();
673 if (!rootPath || !alias)
674 {
675 return res.status(400).json({ error: 'rootPath and alias are required.' });
676 }
677
678 const roots = effectivePaths();
679 const info = resolveRoot(rootPath, roots);
680 if (!info) return res.status(403).json({ error: 'Access denied.' });
681 if (!sameResolvedPath(rootPath, info.root))
682 {
683 return res.status(400).json({ error: 'rootPath must be an exact configured root.' });
684 }
685 if (!canWrite(req.user, info.label))
686 {
687 return res.status(403).json({ error: 'Access denied.' });
688 }
689
690 const config = loadConfig();
691 const rootAliases = rootAliasesFromConfig(config);
692 const key = path.resolve(info.root);
693 if (alias === info.label)
694 {
695 delete rootAliases[key];
696 } else
697 {
698 rootAliases[key] = alias;
699 }
700 config.rootAliases = rootAliases;
701 saveConfig(config);
702
703 res.json({
704 ok: true,
705 root: {
706 path: info.root,
707 label: alias,
708 originalName: info.label,
709 alias,
710 },
711 });
712});
713
714// ---------------------------------------------------------------------------
715// GET /api/files/list?dir=<absolute-path>
716// Lists files and folders in the given directory.
717// ---------------------------------------------------------------------------
718router.get('/list', requireAuth, (req, res) =>
719{
720 const dir = req.query.dir;
721 if (!dir) return res.status(400).json({ error: 'dir is required.' });
722
723 const { config, roots } = loadConfigAndRoots();
724 const info = resolveRootForUser(dir, roots, req.user, config);
725 if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' });
726
727 let entries;
728 try
729 {
730 entries = fs.readdirSync(dir, { withFileTypes: true });
731 } catch
732 {
733 return res.status(404).json({ error: 'Directory not found.' });
734 }
735
736 const items = entries.map(e =>
737 {
738 const fullPath = path.join(dir, e.name);
739 let size = null;
740 let mtime = null;
741 try
742 {
743 const stat = fs.statSync(fullPath);
744 size = stat.size;
745 mtime = stat.mtime.toISOString();
746 } catch { /* ignore */ }
747
748 return {
749 name: e.name,
750 isDir: e.isDirectory(),
751 size,
752 mtime,
753 path: fullPath,
754 };
755 });
756
757 res.json({ items });
758});
759
760// ---------------------------------------------------------------------------
761// GET /api/files/meta?file=<absolute-path>
762// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
763// ---------------------------------------------------------------------------
764router.get('/meta', requireAuth, async (req, res) =>
765{
766 const file = req.query.file;
767 if (!file) return res.status(400).json({ error: 'file is required.' });
768
769 const { config, roots } = loadConfigAndRoots();
770 const info = resolveRootForUser(file, roots, req.user, config);
771 if (!info || !canReadInfo(req.user, info))
772 {
773 return res.status(403).json({ error: 'Access denied.' });
774 }
775
776 let stat;
777 try
778 {
779 stat = fs.statSync(file);
780 } catch
781 {
782 return res.status(404).json({ error: 'File not found.' });
783 }
784
785 const db = getDb();
786 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
787
788 // Lazily compute and persist the SHA-256 hash when it is absent.
789 let sha256 = meta ? (meta.sha256 || null) : null;
790 if (!sha256 && !stat.isDirectory())
791 {
792 try
793 {
794 sha256 = await computeFileSha256(file);
795 if (meta)
796 {
797 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
798 } else
799 {
800 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
801 .run([file, '', '[]', sha256]);
802 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
803 }
804 } catch
805 {
806 // Non-fatal — hash will be retried next time.
807 }
808 }
809
810 res.json({
811 name: path.basename(file),
812 size: stat.size,
813 mtime: stat.mtime.toISOString(),
814 uploader: meta ? meta.uploader : '',
815 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
816 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
817 sha256: sha256 || null,
818 });
819});
820
821// ---------------------------------------------------------------------------
822// GET /api/files/duplicates?file=<absolute-path>
823// Returns other files with the same SHA-256 hash that the user can access.
824// ---------------------------------------------------------------------------
825router.get('/duplicates', requireAuth, (req, res) =>
826{
827 const file = req.query.file;
828 if (!file) return res.status(400).json({ error: 'file is required.' });
829
830 const { config, roots } = loadConfigAndRoots();
831 const info = resolveRootForUser(file, roots, req.user, config);
832 if (!info || !canReadInfo(req.user, info))
833 {
834 return res.status(403).json({ error: 'Access denied.' });
835 }
836
837 const db = getDb();
838 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
839 const hash = row ? (row.sha256 || null) : null;
840 if (!hash)
841 {
842 return res.json({ duplicates: [] });
843 }
844
845 // All other files sharing the same hash.
846 const candidates = db.prepare(
847 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
848 ).all([hash, file]);
849
850 const duplicates = [];
851 for (const { file_path } of candidates)
852 {
853 // Only return files inside a root the user can access and that still exist on disk.
854 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
855 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
856 if (!fs.existsSync(file_path)) continue;
857
858 const rel = path.relative(dupInfo.root, file_path);
859 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
860
861 duplicates.push({
862 path: file_path,
863 name: path.basename(file_path),
864 dir: path.dirname(file_path),
865 rootPath: dupInfo.root,
866 relativePath,
867 });
868 }
869
870 res.json({ duplicates });
871});
872
873// ---------------------------------------------------------------------------
874// GET /api/files/space?dir=<absolute-path>
875// Returns recursive used bytes for dir and available bytes on its root fs.
876// ---------------------------------------------------------------------------
877router.get('/space', requireAuth, (req, res) =>
878{
879 const dir = req.query.dir;
880 if (!dir) return res.status(400).json({ error: 'dir is required.' });
881
882 const { config, roots } = loadConfigAndRoots();
883 const info = resolveRootForUser(dir, roots, req.user, config);
884 if (!info || !canReadInfo(req.user, info))
885 {
886 return res.status(403).json({ error: 'Access denied.' });
887 }
888
889 if (!fs.existsSync(dir))
890 {
891 return res.status(404).json({ error: 'Path not found.' });
892 }
893
894 const usedBytes = getRecursiveSize(dir);
895 const freeBytes = getFreeBytes(info.root);
896 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
897 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
898 res.json({
899 usedBytes,
900 freeBytes,
901 userLimitBytes,
902 userFreeBytes,
903 rootPath: info.root,
904 rootLabel: info.label,
905 });
906});
907
908// ---------------------------------------------------------------------------
909// GET /api/files/download?file=<absolute-path>
910// Streams the file to the client; records the download.
911// ---------------------------------------------------------------------------
912router.get('/download', requireAuth, (req, res) =>
913{
914 const file = req.query.file;
915 if (!file) return res.status(400).json({ error: 'file is required.' });
916
917 const { config, roots } = loadConfigAndRoots();
918 const info = resolveRootForUser(file, roots, req.user, config);
919 if (!info || !canReadInfo(req.user, info))
920 {
921 return res.status(403).json({ error: 'Access denied.' });
922 }
923
924 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
925 {
926 return res.status(404).json({ error: 'File not found.' });
927 }
928
929 // Record download
930 const db = getDb();
931 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
932 if (meta)
933 {
934 const downloaders = parseJsonArray(meta.downloaders);
935 if (!downloaders.includes(req.user.username))
936 {
937 downloaders.push(req.user.username);
938 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
939 .run([JSON.stringify(downloaders), file]);
940 }
941 } else
942 {
943 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
944 .run([file, '', JSON.stringify([req.user.username]), '{}']);
945 }
946
947 res.download(file, path.basename(file));
948});
949
950// ---------------------------------------------------------------------------
951// POST /api/files/watched-statuses
952// Body: { filePaths: [<absolute-path>, ...] }
953// Returns per-path watched status for the authenticated user.
954// ---------------------------------------------------------------------------
955router.post('/watched-statuses', requireAuth, (req, res) =>
956{
957 const rawPaths = req.body && Array.isArray(req.body.filePaths) ? req.body.filePaths : null;
958 if (!rawPaths)
959 {
960 return res.status(400).json({ error: 'filePaths array is required.' });
961 }
962
963 const paths = rawPaths
964 .map((p) => String(p || '').trim())
965 .filter(Boolean)
966 .slice(0, 500);
967
968 const { config, roots } = loadConfigAndRoots();
969 const db = getDb();
970 const statuses = {};
971 const selectMeta = db.prepare('SELECT watched_by FROM file_meta WHERE file_path = ?');
972
973 for (const filePath of paths)
974 {
975 const info = resolveRootForUser(filePath, roots, req.user, config);
976 if (!info || !canReadInfo(req.user, info)) continue;
977
978 let stat;
979 try
980 {
981 stat = fs.statSync(filePath);
982 } catch
983 {
984 continue;
985 }
986 if (stat.isDirectory()) continue;
987
988 const row = selectMeta.get([filePath]);
989 const watchedBy = parseJsonObject(row && row.watched_by);
990 const status = normalisedWatchedStatus(watchedBy[req.user.username]);
991 if (status) statuses[filePath] = status;
992 }
993
994 res.json({ statuses });
995});
996
997// ---------------------------------------------------------------------------
998// POST /api/files/watch-progress
999// Body: { filePath: <absolute-path>, progress: <0..1> }
1000// Records per-user video watch state for sidebar display.
1001// ---------------------------------------------------------------------------
1002router.post('/watch-progress', requireAuth, (req, res) =>
1003{
1004 const filePath = String(req.body && req.body.filePath || '').trim();
1005 const progress = Number(req.body && req.body.progress);
1006 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1007
1008 const status = watchStatusForProgress(progress);
1009 if (!status)
1010 {
1011 return res.json({ ok: true, updated: false });
1012 }
1013
1014 const { config, roots } = loadConfigAndRoots();
1015 const info = resolveRootForUser(filePath, roots, req.user, config);
1016 if (!info || !canReadInfo(req.user, info))
1017 {
1018 return res.status(403).json({ error: 'Access denied.' });
1019 }
1020
1021 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1022 {
1023 return res.status(404).json({ error: 'File not found.' });
1024 }
1025
1026 const db = getDb();
1027 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
1028 const watchedBy = parseJsonObject(row && row.watched_by);
1029 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
1030 const next = prev === 'fully' ? 'fully' : status;
1031 if (prev === next)
1032 {
1033 return res.json({ ok: true, updated: false, status: next });
1034 }
1035
1036 watchedBy[req.user.username] = next;
1037 if (row)
1038 {
1039 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
1040 .run([JSON.stringify(watchedBy), filePath]);
1041 } else
1042 {
1043 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1044 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
1045 }
1046
1047 res.json({ ok: true, updated: true, status: next });
1048});
1049
1050// ---------------------------------------------------------------------------
1051// POST /api/files/video-stream
1052// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
1053// ---------------------------------------------------------------------------
1054router.post('/video-stream', requireAuth, async (req, res, next) =>
1055{
1056 try
1057 {
1058 const filePath = String(req.body?.filePath || '').trim();
1059 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1060
1061 const { config, roots } = loadConfigAndRoots();
1062 const info = resolveRootForUser(filePath, roots, req.user, config);
1063 if (!info || !canReadInfo(req.user, info))
1064 {
1065 return res.status(403).json({ error: 'Access denied.' });
1066 }
1067
1068 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1069 {
1070 return res.status(404).json({ error: 'File not found.' });
1071 }
1072
1073 const session = await createVideoStreamSession(filePath);
1074 res.json({
1075 sessionId: session.sessionId,
1076 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
1077 durationSeconds: session.durationSeconds || null,
1078 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 },
1079 subtitleTracks: session.subtitleTracks.map((track) => ({
1080 label: track.label,
1081 language: track.language,
1082 default: !!track.isDefault,
1083 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1084 })),
1085 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({
1086 label: track.label,
1087 language: track.language,
1088 default: !!track.isDefault,
1089 streamIndex: track.streamIndex,
1090 })),
1091 });
1092 } catch (err)
1093 {
1094 next(err);
1095 }
1096});
1097
1098// ---------------------------------------------------------------------------
1099// GET /api/files/video-stream/:sessionId/:assetPath(*)
1100// Streams HLS assets for a previously created short-lived video session.
1101// ---------------------------------------------------------------------------
1102router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1103{
1104 try
1105 {
1106 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1107 } catch (err)
1108 {
1109 next(err);
1110 }
1111});
1112
1113// ---------------------------------------------------------------------------
1114// DELETE /api/files/video-stream/:sessionId
1115// Authenticated. Explicitly releases an active short-lived video session.
1116// ---------------------------------------------------------------------------
1117router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1118{
1119 const sessionId = String(req.params.sessionId || '').trim();
1120 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1121
1122 releaseVideoStreamSession(sessionId);
1123 res.json({ ok: true });
1124});
1125
1126// ---------------------------------------------------------------------------
1127// GET /api/files/video-stream-subtitle-frame
1128// Authenticated. Extracts a subtitle frame (image) at a given timestamp.
1129// Query params: filePath, streamIndex, timeSeconds
1130// ---------------------------------------------------------------------------
1131router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1132{
1133 try
1134 {
1135 const filePath = String(req.query.filePath || '').trim();
1136 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
1137 const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10);
1138
1139 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0)
1140 {
1141 return res.status(400).json({ error: 'filePath, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' });
1142 }
1143
1144 const { config, roots } = loadConfigAndRoots();
1145 const info = resolveRootForUser(filePath, roots, req.user, config);
1146 if (!info || !canReadInfo(req.user, info))
1147 {
1148 return res.status(403).json({ error: 'Access denied.' });
1149 }
1150
1151 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1152 {
1153 return res.status(404).json({ error: 'File not found.' });
1154 }
1155
1156 // Extract frame at the given timestamp using ffmpeg
1157 const { spawn } = require('child_process');
1158 const ffmpegPath = process.env.FFMPEG_PATH || 'ffmpeg';
1159 const timeStr = `${Math.floor(timeSeconds / 3600)}:${Math.floor((timeSeconds % 3600) / 60)}:${(timeSeconds % 60).toFixed(3)}`;
1160
1161 const child = spawn(ffmpegPath, [
1162 '-hide_banner',
1163 '-loglevel', 'error',
1164 '-ss', timeStr,
1165 '-i', filePath,
1166 '-map', `0:s:${streamIndex}`,
1167 '-frames:v', '1',
1168 '-c:v', 'png',
1169 '-f', 'image2pipe',
1170 'pipe:1',
1171 ]);
1172
1173 let frameData = Buffer.alloc(0);
1174 let stderr = '';
1175
1176 child.stdout.on('data', (chunk) =>
1177 {
1178 frameData = Buffer.concat([frameData, chunk]);
1179 });
1180
1181 child.stderr.on('data', (chunk) =>
1182 {
1183 stderr += chunk.toString();
1184 });
1185
1186 child.on('close', (code) =>
1187 {
1188 if (code !== 0)
1189 {
1190 return res.status(500).json({ error: 'Failed to extract subtitle frame.' });
1191 }
1192
1193 if (frameData.length === 0)
1194 {
1195 return res.status(404).json({ error: 'No subtitle frame at this timestamp.' });
1196 }
1197
1198 res.set('Content-Type', 'image/png');
1199 res.set('Cache-Control', 'private, max-age=3600');
1200 res.send(frameData);
1201 });
1202
1203 child.on('error', (err) =>
1204 {
1205 return res.status(503).json({ error: 'ffmpeg unavailable.' });
1206 });
1207 } catch (err)
1208 {
1209 next(err);
1210 }
1211});
1212
1213// ---------------------------------------------------------------------------
1214// GET /api/files/download-zip?dir=<absolute-path>
1215// Authenticated. Streams a zip of the given directory.
1216// ---------------------------------------------------------------------------
1217router.get('/download-zip', requireAuth, async (req, res) =>
1218{
1219 const dir = req.query.dir;
1220 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1221
1222 const { config, roots } = loadConfigAndRoots();
1223 const info = resolveRootForUser(dir, roots, req.user, config);
1224 if (!info || !canReadInfo(req.user, info))
1225 {
1226 return res.status(403).json({ error: 'Access denied.' });
1227 }
1228
1229 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1230 {
1231 return res.status(404).json({ error: 'Directory not found.' });
1232 }
1233
1234 // Use a hash of the dir path as cache key so concurrent users share the cache.
1235 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1236 try
1237 {
1238 const zipPath = await buildZip(dir, cacheKey);
1239 const zipName = `${path.basename(dir)}.zip`;
1240 res.download(zipPath, zipName);
1241 } catch (err)
1242 {
1243 res.status(500).json({ error: 'Failed to create zip archive.' });
1244 }
1245});
1246
1247// ---------------------------------------------------------------------------
1248// GET /api/files/thumbnail?file=<absolute-path>
1249// Returns a pre-generated cached thumbnail if present.
1250// ---------------------------------------------------------------------------
1251router.get('/thumbnail', requireAuth, async (req, res) =>
1252{
1253 const file = req.query.file;
1254 if (!file) return res.status(400).json({ error: 'file is required.' });
1255
1256 const { config, roots } = loadConfigAndRoots();
1257 const info = resolveRootForUser(file, roots, req.user, config);
1258 if (!info || !canReadInfo(req.user, info))
1259 {
1260 return res.status(403).json({ error: 'Access denied.' });
1261 }
1262
1263 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1264 {
1265 return res.status(404).json({ error: 'File not found.' });
1266 }
1267
1268 const thumb = await getCachedThumbnailInfo(file);
1269 if (!thumb)
1270 {
1271 return res.status(404).json({ error: 'Thumbnail not ready.' });
1272 }
1273
1274 res.type(thumb.contentType);
1275 res.set('Cache-Control', 'private, max-age=10');
1276 res.sendFile(thumb.thumbPath);
1277});
1278
1279// ---------------------------------------------------------------------------
1280// POST /api/files/upload?dir=<absolute-path>
1281// Accepts multipart file upload.
1282// ---------------------------------------------------------------------------
1283router.post('/upload', requireAuth, (req, res, next) =>
1284{
1285 const dir = req.query.dir;
1286 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1287
1288 const { config, roots } = loadConfigAndRoots();
1289 const info = resolveRootForUser(dir, roots, req.user, config);
1290 if (!info || !canWriteInfo(req.user, info))
1291 {
1292 return res.status(403).json({ error: 'Access denied.' });
1293 }
1294
1295 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1296 {
1297 return res.status(404).json({ error: 'Directory not found.' });
1298 }
1299
1300 const announcedSize = Number(req.header('x-upload-size') || 0);
1301 if (Number.isFinite(announcedSize) && announcedSize > 0)
1302 {
1303 const freeBytes = getFreeBytes(info.root);
1304 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1305 {
1306 return res.status(413).json({
1307 error: 'Upload too large for remaining free space on selected root.',
1308 freeBytes,
1309 requiredBytes: announcedSize,
1310 });
1311 }
1312 }
1313
1314 // Enforce per-user folder size limit when uploading to a user folder.
1315 if (info.isUserFolder)
1316 {
1317 const addBytes = announcedSize > 0 ? announcedSize : 0;
1318 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1319 if (limitError) return res.status(413).json({ error: limitError });
1320 }
1321
1322 req._uploadDir = dir;
1323
1324 upload.array('files')(req, res, async (err) =>
1325 {
1326 if (err) return res.status(500).json({ error: err.message });
1327
1328 const db = getDb();
1329 for (const f of (req.files || []))
1330 {
1331 const filePath = path.join(dir, f.originalname);
1332
1333 let sha256 = null;
1334 try
1335 {
1336 sha256 = await computeFileSha256(filePath);
1337 } catch
1338 {
1339 // Non-fatal — hash can be computed lazily when the file is accessed.
1340 }
1341
1342 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1343 if (existing)
1344 {
1345 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1346 .run([req.user.username, sha256, filePath]);
1347 } else
1348 {
1349 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1350 .run([filePath, req.user.username, '[]', sha256]);
1351 }
1352 }
1353 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1354 });
1355});
1356
1357// ---------------------------------------------------------------------------
1358// POST /api/files/rename
1359// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1360// ---------------------------------------------------------------------------
1361router.post('/rename', requireAuth, (req, res) =>
1362{
1363 const { from, to } = req.body;
1364 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1365
1366 // Prevent path traversal in the new name
1367 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1368 {
1369 return res.status(400).json({ error: 'Invalid name.' });
1370 }
1371
1372 const { config, roots } = loadConfigAndRoots();
1373 const info = resolveRootForUser(from, roots, req.user, config);
1374 if (!info || !canWriteInfo(req.user, info))
1375 {
1376 return res.status(403).json({ error: 'Access denied.' });
1377 }
1378
1379 const dest = path.join(path.dirname(from), to);
1380
1381 // Ensure dest is still inside the same accessible root or user folder.
1382 if (!isAccessiblePath(dest, roots, req.user, config))
1383 {
1384 return res.status(403).json({ error: 'Access denied.' });
1385 }
1386
1387 try
1388 {
1389 movePathWithFallback(from, dest);
1390 } catch (err)
1391 {
1392 return res.status(500).json({ error: err.message });
1393 }
1394
1395 rewriteMetaPaths(from, dest);
1396
1397 res.json({ ok: true });
1398});
1399
1400// ---------------------------------------------------------------------------
1401// POST /api/files/move
1402// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1403// ---------------------------------------------------------------------------
1404router.post('/move', requireAuth, (req, res) =>
1405{
1406 const { from, toDir } = req.body;
1407 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1408 const targetName = req.body && req.body.targetName != null
1409 ? String(req.body.targetName).trim()
1410 : '';
1411 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1412 if (!['error', 'overwrite', 'rename'].includes(conflict))
1413 {
1414 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1415 }
1416
1417 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1418 {
1419 return res.status(400).json({ error: 'Invalid targetName.' });
1420 }
1421
1422 const { config, roots } = loadConfigAndRoots();
1423 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1424 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1425 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1426 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1427 {
1428 return res.status(403).json({ error: 'Access denied.' });
1429 }
1430
1431 let sourceStat;
1432 let destStat;
1433 try
1434 {
1435 sourceStat = fs.statSync(from);
1436 destStat = fs.statSync(toDir);
1437 } catch
1438 {
1439 return res.status(404).json({ error: 'Source or destination not found.' });
1440 }
1441
1442 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1443
1444 const requestedName = targetName || path.basename(from);
1445 const requestedDest = path.join(toDir, requestedName);
1446 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1447
1448 // Enforce per-user folder size limit when moving into a user folder.
1449 if (toInfo.isUserFolder)
1450 {
1451 const sourceSize = getRecursiveSize(from);
1452 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1453 if (limitError) return res.status(413).json({ error: limitError });
1454 }
1455 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1456 {
1457 return res.status(400).json({ error: 'Cannot move onto itself.' });
1458 }
1459 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1460 {
1461 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1462 }
1463
1464 let dest = requestedDest;
1465 let resolvedConflict = 'none';
1466
1467 if (fs.existsSync(requestedDest))
1468 {
1469 if (conflict === 'error')
1470 {
1471 return res.status(409).json({ error: 'Destination already exists.' });
1472 }
1473
1474 if (conflict === 'rename')
1475 {
1476 dest = pickNumberedPath(toDir, requestedName);
1477 resolvedConflict = 'rename';
1478 }
1479
1480 if (conflict === 'overwrite')
1481 {
1482 try
1483 {
1484 removePathRecursive(requestedDest);
1485 } catch (err)
1486 {
1487 return res.status(500).json({ error: err.message });
1488 }
1489 resolvedConflict = 'overwrite';
1490 }
1491 }
1492
1493 if (sameResolvedPath(from, dest))
1494 {
1495 return res.status(400).json({ error: 'Cannot move onto itself.' });
1496 }
1497
1498 try
1499 {
1500 movePathWithFallback(from, dest);
1501 } catch (err)
1502 {
1503 return res.status(500).json({ error: err.message });
1504 }
1505
1506 rewriteMetaPaths(from, dest);
1507 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1508});
1509
1510// ---------------------------------------------------------------------------
1511// POST /api/files/mkdir
1512// Body: { dir: <absolute-path>, name: <folder-name> }
1513// ---------------------------------------------------------------------------
1514router.post('/mkdir', requireAuth, (req, res) =>
1515{
1516 const { dir, name } = req.body;
1517 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1518
1519 if (path.basename(name) !== name)
1520 {
1521 return res.status(400).json({ error: 'Invalid folder name.' });
1522 }
1523
1524 const { config, roots } = loadConfigAndRoots();
1525 const info = resolveRootForUser(dir, roots, req.user, config);
1526 if (!info || !canWriteInfo(req.user, info))
1527 {
1528 return res.status(403).json({ error: 'Access denied.' });
1529 }
1530
1531 const newDir = path.join(dir, name);
1532 if (!isAccessiblePath(newDir, roots, req.user, config))
1533 {
1534 return res.status(403).json({ error: 'Access denied.' });
1535 }
1536
1537 try
1538 {
1539 fs.mkdirSync(newDir, { recursive: false });
1540 } catch (err)
1541 {
1542 return res.status(500).json({ error: err.message });
1543 }
1544
1545 res.json({ ok: true, path: newDir });
1546});
1547
1548// ---------------------------------------------------------------------------
1549// POST /api/files/delete
1550// Body: { path: <absolute-path> }
1551// ---------------------------------------------------------------------------
1552router.post('/delete', requireAuth, (req, res) =>
1553{
1554 const target = req.body.path;
1555 if (!target) return res.status(400).json({ error: 'path is required.' });
1556
1557 const { config, roots } = loadConfigAndRoots();
1558 const info = resolveRootForUser(target, roots, req.user, config);
1559 if (!info || !canWriteInfo(req.user, info))
1560 {
1561 return res.status(403).json({ error: 'Access denied.' });
1562 }
1563
1564 // Do not allow deleting a configured root itself
1565 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1566 {
1567 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1568 }
1569
1570 try
1571 {
1572 const stat = fs.statSync(target);
1573 if (stat.isDirectory())
1574 {
1575 fs.rmSync(target, { recursive: true, force: true });
1576 } else
1577 {
1578 fs.unlinkSync(target);
1579 }
1580 } catch (err)
1581 {
1582 return res.status(500).json({ error: err.message });
1583 }
1584
1585 // Clean up any DB meta entries under that path
1586 const db = getDb();
1587 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1588 .run([target, target + path.sep + '%']);
1589
1590 res.json({ ok: true });
1591});
1592
1593// ---------------------------------------------------------------------------
1594// GET /api/files/folder-images?dir=<absolute-path>
1595// Returns files inside dir (recursive) that already have a cached thumbnail.
1596// Only files with a ready cached thumbnail are included.
1597// ---------------------------------------------------------------------------
1598router.get('/folder-images', requireAuth, async (req, res) =>
1599{
1600 const dir = String(req.query.dir || '').trim();
1601 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1602
1603 const { config, roots } = loadConfigAndRoots();
1604 const info = resolveRootForUser(dir, roots, req.user, config);
1605 if (!info || !canReadInfo(req.user, info))
1606 {
1607 return res.status(403).json({ error: 'Access denied.' });
1608 }
1609
1610 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1611 {
1612 return res.status(404).json({ error: 'Directory not found.' });
1613 }
1614
1615 const files = await getFilesWithThumbnailsInDir(dir);
1616 // Filter out any that escaped to a different accessible root (safety check).
1617 const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1618
1619 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1620});
1621
1622// ---------------------------------------------------------------------------
1623// GET /api/files/folder-icon?dir=<absolute-path>
1624// Returns the current icon source file for a folder (explicit or auto-first).
1625// ---------------------------------------------------------------------------
1626router.get('/folder-icon', requireAuth, async (req, res) =>
1627{
1628 const dir = String(req.query.dir || '').trim();
1629 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1630
1631 const { config, roots } = loadConfigAndRoots();
1632 const info = resolveRootForUser(dir, roots, req.user, config);
1633 if (!info || !canReadInfo(req.user, info))
1634 {
1635 return res.status(403).json({ error: 'Access denied.' });
1636 }
1637
1638 const sourceFile = await getFolderIconSourceFile(dir);
1639 if (!sourceFile) return res.json({ icon: null });
1640
1641 // Verify the source is still accessible within a configured root or user folder.
1642 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1643
1644 res.json({ icon: { filePath: sourceFile } });
1645});
1646
1647// ---------------------------------------------------------------------------
1648// POST /api/files/folder-icon
1649// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1650// Requires write access; the image must already have a cached thumbnail.
1651// ---------------------------------------------------------------------------
1652router.post('/folder-icon', requireAuth, async (req, res) =>
1653{
1654 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1655 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1656
1657 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1658
1659 const { config, roots } = loadConfigAndRoots();
1660 const info = resolveRootForUser(folderPath, roots, req.user, config);
1661 if (!info || !canWriteInfo(req.user, info))
1662 {
1663 return res.status(403).json({ error: 'Access denied.' });
1664 }
1665
1666 let stat;
1667 try { stat = fs.statSync(folderPath); }
1668 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1669 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1670
1671 if (rawImage !== null)
1672 {
1673 // Verify the image is inside a readable root or user folder.
1674 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1675
1676 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1677 const thumb = await getCachedThumbnailInfo(rawImage);
1678 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1679 }
1680
1681 await setFolderIconAssignment(folderPath, rawImage);
1682 res.json({ ok: true });
1683});
1684
1685// ---------------------------------------------------------------------------
1686// POST /api/files/copy
1687// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1688// Copies a file (not a directory) to the destination folder.
1689// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1690// ---------------------------------------------------------------------------
1691router.post('/copy', requireAuth, (req, res) =>
1692{
1693 const { from, toDir } = req.body;
1694 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1695 const targetName = req.body && req.body.targetName != null
1696 ? String(req.body.targetName).trim()
1697 : '';
1698 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1699 if (!['error', 'overwrite', 'rename'].includes(conflict))
1700 {
1701 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1702 }
1703
1704 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1705 {
1706 return res.status(400).json({ error: 'Invalid targetName.' });
1707 }
1708
1709 const { config, roots } = loadConfigAndRoots();
1710 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1711 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1712 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1713 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1714 {
1715 return res.status(403).json({ error: 'Access denied.' });
1716 }
1717
1718 let sourceStat;
1719 try { sourceStat = fs.statSync(from); }
1720 catch { return res.status(404).json({ error: 'Source not found.' }); }
1721
1722 if (sourceStat.isDirectory())
1723 {
1724 return res.status(400).json({ error: 'Copying directories is not supported.' });
1725 }
1726
1727 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1728 {
1729 return res.status(404).json({ error: 'Destination directory not found.' });
1730 }
1731
1732 const requestedName = targetName || path.basename(from);
1733 const requestedDest = path.join(toDir, requestedName);
1734 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1735
1736 // Enforce per-user folder size limit when copying into a user folder.
1737 if (toInfo.isUserFolder)
1738 {
1739 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1740 if (limitError) return res.status(413).json({ error: limitError });
1741 }
1742
1743 let dest = requestedDest;
1744 let resolvedConflict = 'none';
1745
1746 if (fs.existsSync(requestedDest))
1747 {
1748 if (conflict === 'error')
1749 {
1750 return res.status(409).json({ error: 'Destination already exists.' });
1751 }
1752 if (conflict === 'rename')
1753 {
1754 dest = pickNumberedPath(toDir, requestedName);
1755 resolvedConflict = 'rename';
1756 }
1757 if (conflict === 'overwrite')
1758 {
1759 resolvedConflict = 'overwrite';
1760 }
1761 }
1762
1763 try
1764 {
1765 fs.copyFileSync(from, dest);
1766 } catch (err)
1767 {
1768 return res.status(500).json({ error: err.message });
1769 }
1770
1771 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1772});
1773
1774module.exports = router;