BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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