BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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