BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

6d2b5978 History
files.js 53.6 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const crypto = require('crypto');
7const 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 return res.status(204).end();
1175 }
1176
1177 res.set('Content-Type', 'image/png');
1178 res.set('Cache-Control', 'private, max-age=3600');
1179 res.send(frameData);
1180 } catch (err)
1181 {
1182 logError('Subtitle frame extraction failed', err, {
1183 filePath: String(req.query.filePath || ''),
1184 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1185 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1186 });
1187 return res.status(204).end();
1188 }
1189});
1190
1191// ---------------------------------------------------------------------------
1192// GET /api/files/download-zip?dir=<absolute-path>
1193// Authenticated. Streams a zip of the given directory.
1194// ---------------------------------------------------------------------------
1195router.get('/download-zip', requireAuth, async (req, res) =>
1196{
1197 const dir = req.query.dir;
1198 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1199
1200 const { config, roots } = loadConfigAndRoots();
1201 const info = resolveRootForUser(dir, roots, req.user, config);
1202 if (!info || !canReadInfo(req.user, info))
1203 {
1204 return res.status(403).json({ error: 'Access denied.' });
1205 }
1206
1207 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1208 {
1209 return res.status(404).json({ error: 'Directory not found.' });
1210 }
1211
1212 // Use a hash of the dir path as cache key so concurrent users share the cache.
1213 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1214 try
1215 {
1216 const zipPath = await buildZip(dir, cacheKey);
1217 const zipName = `${path.basename(dir)}.zip`;
1218 res.download(zipPath, zipName);
1219 } catch (err)
1220 {
1221 res.status(500).json({ error: 'Failed to create zip archive.' });
1222 }
1223});
1224
1225// ---------------------------------------------------------------------------
1226// GET /api/files/thumbnail?file=<absolute-path>
1227// Returns a pre-generated cached thumbnail if present.
1228// ---------------------------------------------------------------------------
1229router.get('/thumbnail', requireAuth, async (req, res) =>
1230{
1231 const file = req.query.file;
1232 if (!file) return res.status(400).json({ error: 'file is required.' });
1233
1234 const { config, roots } = loadConfigAndRoots();
1235 const info = resolveRootForUser(file, roots, req.user, config);
1236 if (!info || !canReadInfo(req.user, info))
1237 {
1238 return res.status(403).json({ error: 'Access denied.' });
1239 }
1240
1241 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1242 {
1243 return res.status(404).json({ error: 'File not found.' });
1244 }
1245
1246 const thumb = await getCachedThumbnailInfo(file);
1247 if (!thumb)
1248 {
1249 return res.status(404).json({ error: 'Thumbnail not ready.' });
1250 }
1251
1252 res.type(thumb.contentType);
1253 res.set('Cache-Control', 'private, max-age=10');
1254 res.sendFile(thumb.thumbPath);
1255});
1256
1257// ---------------------------------------------------------------------------
1258// POST /api/files/upload?dir=<absolute-path>
1259// Accepts multipart file upload.
1260// ---------------------------------------------------------------------------
1261router.post('/upload', requireAuth, (req, res, next) =>
1262{
1263 const dir = req.query.dir;
1264 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1265
1266 const { config, roots } = loadConfigAndRoots();
1267 const info = resolveRootForUser(dir, roots, req.user, config);
1268 if (!info || !canWriteInfo(req.user, info))
1269 {
1270 return res.status(403).json({ error: 'Access denied.' });
1271 }
1272
1273 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1274 {
1275 return res.status(404).json({ error: 'Directory not found.' });
1276 }
1277
1278 const announcedSize = Number(req.header('x-upload-size') || 0);
1279 if (Number.isFinite(announcedSize) && announcedSize > 0)
1280 {
1281 const freeBytes = getFreeBytes(info.root);
1282 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1283 {
1284 return res.status(413).json({
1285 error: 'Upload too large for remaining free space on selected root.',
1286 freeBytes,
1287 requiredBytes: announcedSize,
1288 });
1289 }
1290 }
1291
1292 // Enforce per-user folder size limit when uploading to a user folder.
1293 if (info.isUserFolder)
1294 {
1295 const addBytes = announcedSize > 0 ? announcedSize : 0;
1296 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1297 if (limitError) return res.status(413).json({ error: limitError });
1298 }
1299
1300 req._uploadDir = dir;
1301
1302 upload.array('files')(req, res, async (err) =>
1303 {
1304 if (err) return res.status(500).json({ error: err.message });
1305
1306 const db = getDb();
1307 for (const f of (req.files || []))
1308 {
1309 const filePath = path.join(dir, f.originalname);
1310
1311 let sha256 = null;
1312 try
1313 {
1314 sha256 = await computeFileSha256(filePath);
1315 } catch
1316 {
1317 // Non-fatal — hash can be computed lazily when the file is accessed.
1318 }
1319
1320 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1321 if (existing)
1322 {
1323 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1324 .run([req.user.username, sha256, filePath]);
1325 } else
1326 {
1327 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1328 .run([filePath, req.user.username, '[]', sha256]);
1329 }
1330 }
1331 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1332 });
1333});
1334
1335// ---------------------------------------------------------------------------
1336// POST /api/files/rename
1337// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1338// ---------------------------------------------------------------------------
1339router.post('/rename', requireAuth, (req, res) =>
1340{
1341 const { from, to } = req.body;
1342 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1343
1344 // Prevent path traversal in the new name
1345 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1346 {
1347 return res.status(400).json({ error: 'Invalid name.' });
1348 }
1349
1350 const { config, roots } = loadConfigAndRoots();
1351 const info = resolveRootForUser(from, roots, req.user, config);
1352 if (!info || !canWriteInfo(req.user, info))
1353 {
1354 return res.status(403).json({ error: 'Access denied.' });
1355 }
1356
1357 const dest = path.join(path.dirname(from), to);
1358
1359 // Ensure dest is still inside the same accessible root or user folder.
1360 if (!isAccessiblePath(dest, roots, req.user, config))
1361 {
1362 return res.status(403).json({ error: 'Access denied.' });
1363 }
1364
1365 try
1366 {
1367 movePathWithFallback(from, dest);
1368 } catch (err)
1369 {
1370 return res.status(500).json({ error: err.message });
1371 }
1372
1373 rewriteMetaPaths(from, dest);
1374
1375 res.json({ ok: true });
1376});
1377
1378// ---------------------------------------------------------------------------
1379// POST /api/files/move
1380// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1381// ---------------------------------------------------------------------------
1382router.post('/move', requireAuth, (req, res) =>
1383{
1384 const { from, toDir } = req.body;
1385 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1386 const targetName = req.body && req.body.targetName != null
1387 ? String(req.body.targetName).trim()
1388 : '';
1389 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1390 if (!['error', 'overwrite', 'rename'].includes(conflict))
1391 {
1392 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1393 }
1394
1395 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1396 {
1397 return res.status(400).json({ error: 'Invalid targetName.' });
1398 }
1399
1400 const { config, roots } = loadConfigAndRoots();
1401 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1402 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1403 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1404 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1405 {
1406 return res.status(403).json({ error: 'Access denied.' });
1407 }
1408
1409 let sourceStat;
1410 let destStat;
1411 try
1412 {
1413 sourceStat = fs.statSync(from);
1414 destStat = fs.statSync(toDir);
1415 } catch
1416 {
1417 return res.status(404).json({ error: 'Source or destination not found.' });
1418 }
1419
1420 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1421
1422 const requestedName = targetName || path.basename(from);
1423 const requestedDest = path.join(toDir, requestedName);
1424 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1425
1426 // Enforce per-user folder size limit when moving into a user folder.
1427 if (toInfo.isUserFolder)
1428 {
1429 const sourceSize = getRecursiveSize(from);
1430 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1431 if (limitError) return res.status(413).json({ error: limitError });
1432 }
1433 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1434 {
1435 return res.status(400).json({ error: 'Cannot move onto itself.' });
1436 }
1437 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1438 {
1439 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1440 }
1441
1442 let dest = requestedDest;
1443 let resolvedConflict = 'none';
1444
1445 if (fs.existsSync(requestedDest))
1446 {
1447 if (conflict === 'error')
1448 {
1449 return res.status(409).json({ error: 'Destination already exists.' });
1450 }
1451
1452 if (conflict === 'rename')
1453 {
1454 dest = pickNumberedPath(toDir, requestedName);
1455 resolvedConflict = 'rename';
1456 }
1457
1458 if (conflict === 'overwrite')
1459 {
1460 try
1461 {
1462 removePathRecursive(requestedDest);
1463 } catch (err)
1464 {
1465 return res.status(500).json({ error: err.message });
1466 }
1467 resolvedConflict = 'overwrite';
1468 }
1469 }
1470
1471 if (sameResolvedPath(from, dest))
1472 {
1473 return res.status(400).json({ error: 'Cannot move onto itself.' });
1474 }
1475
1476 try
1477 {
1478 movePathWithFallback(from, dest);
1479 } catch (err)
1480 {
1481 return res.status(500).json({ error: err.message });
1482 }
1483
1484 rewriteMetaPaths(from, dest);
1485 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1486});
1487
1488// ---------------------------------------------------------------------------
1489// POST /api/files/mkdir
1490// Body: { dir: <absolute-path>, name: <folder-name> }
1491// ---------------------------------------------------------------------------
1492router.post('/mkdir', requireAuth, (req, res) =>
1493{
1494 const { dir, name } = req.body;
1495 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1496
1497 if (path.basename(name) !== name)
1498 {
1499 return res.status(400).json({ error: 'Invalid folder name.' });
1500 }
1501
1502 const { config, roots } = loadConfigAndRoots();
1503 const info = resolveRootForUser(dir, roots, req.user, config);
1504 if (!info || !canWriteInfo(req.user, info))
1505 {
1506 return res.status(403).json({ error: 'Access denied.' });
1507 }
1508
1509 const newDir = path.join(dir, name);
1510 if (!isAccessiblePath(newDir, roots, req.user, config))
1511 {
1512 return res.status(403).json({ error: 'Access denied.' });
1513 }
1514
1515 try
1516 {
1517 fs.mkdirSync(newDir, { recursive: false });
1518 } catch (err)
1519 {
1520 return res.status(500).json({ error: err.message });
1521 }
1522
1523 res.json({ ok: true, path: newDir });
1524});
1525
1526// ---------------------------------------------------------------------------
1527// POST /api/files/delete
1528// Body: { path: <absolute-path> }
1529// ---------------------------------------------------------------------------
1530router.post('/delete', requireAuth, (req, res) =>
1531{
1532 const target = req.body.path;
1533 if (!target) return res.status(400).json({ error: 'path is required.' });
1534
1535 const { config, roots } = loadConfigAndRoots();
1536 const info = resolveRootForUser(target, roots, req.user, config);
1537 if (!info || !canWriteInfo(req.user, info))
1538 {
1539 return res.status(403).json({ error: 'Access denied.' });
1540 }
1541
1542 // Do not allow deleting a configured root itself
1543 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1544 {
1545 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1546 }
1547
1548 try
1549 {
1550 const stat = fs.statSync(target);
1551 if (stat.isDirectory())
1552 {
1553 fs.rmSync(target, { recursive: true, force: true });
1554 } else
1555 {
1556 fs.unlinkSync(target);
1557 }
1558 } catch (err)
1559 {
1560 return res.status(500).json({ error: err.message });
1561 }
1562
1563 // Clean up any DB meta entries under that path
1564 const db = getDb();
1565 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1566 .run([target, target + path.sep + '%']);
1567
1568 res.json({ ok: true });
1569});
1570
1571// ---------------------------------------------------------------------------
1572// GET /api/files/folder-images?dir=<absolute-path>
1573// Returns files inside dir (recursive) that already have a cached thumbnail.
1574// Only files with a ready cached thumbnail are included.
1575// ---------------------------------------------------------------------------
1576router.get('/folder-images', requireAuth, async (req, res) =>
1577{
1578 const dir = String(req.query.dir || '').trim();
1579 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1580
1581 const { config, roots } = loadConfigAndRoots();
1582 const info = resolveRootForUser(dir, roots, req.user, config);
1583 if (!info || !canReadInfo(req.user, info))
1584 {
1585 return res.status(403).json({ error: 'Access denied.' });
1586 }
1587
1588 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1589 {
1590 return res.status(404).json({ error: 'Directory not found.' });
1591 }
1592
1593 const files = await getFilesWithThumbnailsInDir(dir);
1594 // Filter out any that escaped to a different accessible root (safety check).
1595 const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1596
1597 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1598});
1599
1600// ---------------------------------------------------------------------------
1601// GET /api/files/folder-icon?dir=<absolute-path>
1602// Returns the current icon source file for a folder (explicit or auto-first).
1603// ---------------------------------------------------------------------------
1604router.get('/folder-icon', requireAuth, async (req, res) =>
1605{
1606 const dir = String(req.query.dir || '').trim();
1607 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1608
1609 const { config, roots } = loadConfigAndRoots();
1610 const info = resolveRootForUser(dir, roots, req.user, config);
1611 if (!info || !canReadInfo(req.user, info))
1612 {
1613 return res.status(403).json({ error: 'Access denied.' });
1614 }
1615
1616 const sourceFile = await getFolderIconSourceFile(dir);
1617 if (!sourceFile) return res.json({ icon: null });
1618
1619 // Verify the source is still accessible within a configured root or user folder.
1620 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1621
1622 res.json({ icon: { filePath: sourceFile } });
1623});
1624
1625// ---------------------------------------------------------------------------
1626// POST /api/files/folder-icon
1627// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1628// Requires write access; the image must already have a cached thumbnail.
1629// ---------------------------------------------------------------------------
1630router.post('/folder-icon', requireAuth, async (req, res) =>
1631{
1632 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1633 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1634
1635 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1636
1637 const { config, roots } = loadConfigAndRoots();
1638 const info = resolveRootForUser(folderPath, roots, req.user, config);
1639 if (!info || !canWriteInfo(req.user, info))
1640 {
1641 return res.status(403).json({ error: 'Access denied.' });
1642 }
1643
1644 let stat;
1645 try { stat = fs.statSync(folderPath); }
1646 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1647 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1648
1649 if (rawImage !== null)
1650 {
1651 // Verify the image is inside a readable root or user folder.
1652 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
1653
1654 // Must already have a cached thumbnail — only thumbnailed images can be selected.
1655 const thumb = await getCachedThumbnailInfo(rawImage);
1656 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
1657 }
1658
1659 await setFolderIconAssignment(folderPath, rawImage);
1660 res.json({ ok: true });
1661});
1662
1663// ---------------------------------------------------------------------------
1664// POST /api/files/copy
1665// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1666// Copies a file (not a directory) to the destination folder.
1667// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
1668// ---------------------------------------------------------------------------
1669router.post('/copy', requireAuth, (req, res) =>
1670{
1671 const { from, toDir } = req.body;
1672 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1673 const targetName = req.body && req.body.targetName != null
1674 ? String(req.body.targetName).trim()
1675 : '';
1676 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1677 if (!['error', 'overwrite', 'rename'].includes(conflict))
1678 {
1679 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1680 }
1681
1682 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1683 {
1684 return res.status(400).json({ error: 'Invalid targetName.' });
1685 }
1686
1687 const { config, roots } = loadConfigAndRoots();
1688 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1689 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1690 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1691 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1692 {
1693 return res.status(403).json({ error: 'Access denied.' });
1694 }
1695
1696 let sourceStat;
1697 try { sourceStat = fs.statSync(from); }
1698 catch { return res.status(404).json({ error: 'Source not found.' }); }
1699
1700 if (sourceStat.isDirectory())
1701 {
1702 return res.status(400).json({ error: 'Copying directories is not supported.' });
1703 }
1704
1705 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
1706 {
1707 return res.status(404).json({ error: 'Destination directory not found.' });
1708 }
1709
1710 const requestedName = targetName || path.basename(from);
1711 const requestedDest = path.join(toDir, requestedName);
1712 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1713
1714 // Enforce per-user folder size limit when copying into a user folder.
1715 if (toInfo.isUserFolder)
1716 {
1717 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
1718 if (limitError) return res.status(413).json({ error: limitError });
1719 }
1720
1721 let dest = requestedDest;
1722 let resolvedConflict = 'none';
1723
1724 if (fs.existsSync(requestedDest))
1725 {
1726 if (conflict === 'error')
1727 {
1728 return res.status(409).json({ error: 'Destination already exists.' });
1729 }
1730 if (conflict === 'rename')
1731 {
1732 dest = pickNumberedPath(toDir, requestedName);
1733 resolvedConflict = 'rename';
1734 }
1735 if (conflict === 'overwrite')
1736 {
1737 resolvedConflict = 'overwrite';
1738 }
1739 }
1740
1741 try
1742 {
1743 fs.copyFileSync(from, dest);
1744 } catch (err)
1745 {
1746 return res.status(500).json({ error: err.message });
1747 }
1748
1749 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1750});
1751
1752module.exports = router;