BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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