BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

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