BlueGit

timfa filemanager

Files

filemanager / server / routes / files.js

files.js

files.js 66.1 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 let uploadedAt = null;
1018 try
1019 {
1020 const stat = fs.statSync(fullPath);
1021 size = stat.size;
1022 mtime = stat.mtime.toISOString();
1023 // Approximate upload time from file creation metadata when available.
1024 const uploadDate = (stat.birthtime && Number.isFinite(stat.birthtimeMs) && stat.birthtimeMs > 0)
1025 ? stat.birthtime
1026 : stat.ctime;
1027 uploadedAt = uploadDate instanceof Date ? uploadDate.toISOString() : null;
1028 } catch { /* ignore */ }
1029
1030 return {
1031 name: e.name,
1032 isDir: e.isDirectory(),
1033 size,
1034 mtime,
1035 uploadedAt,
1036 path: fullPath,
1037 };
1038 });
1039
1040 res.json({ items });
1041});
1042
1043// ---------------------------------------------------------------------------
1044// GET /api/files/search?query=<text>&limit=<number>
1045// Fuzzy-searches all readable roots for files.
1046// ---------------------------------------------------------------------------
1047router.get('/search', requireAuth, (req, res) =>
1048{
1049 const query = String(req.query.query || '').trim();
1050 if (!query) return res.status(400).json({ error: 'query is required.' });
1051
1052 const { config, roots } = loadConfigAndRoots();
1053 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1054 .filter((rootPath) =>
1055 {
1056 try
1057 {
1058 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1059 } catch
1060 {
1061 return false;
1062 }
1063 });
1064
1065 const results = searchFilesInRoots(query, readableRoots, req.query.limit);
1066 res.json({
1067 query,
1068 results,
1069 });
1070});
1071
1072// ---------------------------------------------------------------------------
1073// GET /api/files/search-images?query=<text>&limit=<number>
1074// Fuzzy-searches readable roots for image files that have ready thumbnails.
1075// ---------------------------------------------------------------------------
1076router.get('/search-images', requireAuth, async (req, res) =>
1077{
1078 const query = String(req.query.query || '').trim();
1079 if (!query) return res.status(400).json({ error: 'query is required.' });
1080 if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' });
1081
1082 const { config, roots } = loadConfigAndRoots();
1083 const readableRoots = readableSearchRootsForUser(req.user, config, roots)
1084 .filter((rootPath) =>
1085 {
1086 try
1087 {
1088 return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory();
1089 } catch
1090 {
1091 return false;
1092 }
1093 });
1094
1095 const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots(
1096 query,
1097 readableRoots,
1098 req.query.limit,
1099 );
1100
1101 res.json({
1102 query,
1103 results,
1104 scannedFiles,
1105 truncated,
1106 });
1107});
1108
1109// ---------------------------------------------------------------------------
1110// GET /api/files/meta?file=<absolute-path>
1111// Returns file metadata from the DB. Lazily computes SHA-256 when missing.
1112// ---------------------------------------------------------------------------
1113router.get('/meta', requireAuth, async (req, res) =>
1114{
1115 const file = req.query.file;
1116 if (!file) return res.status(400).json({ error: 'file is required.' });
1117
1118 const { config, roots } = loadConfigAndRoots();
1119 const info = resolveRootForUser(file, roots, req.user, config);
1120 if (!info || !canReadInfo(req.user, info))
1121 {
1122 return res.status(403).json({ error: 'Access denied.' });
1123 }
1124
1125 let stat;
1126 try
1127 {
1128 stat = fs.statSync(file);
1129 } catch
1130 {
1131 return res.status(404).json({ error: 'File not found.' });
1132 }
1133
1134 const db = getDb();
1135 let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1136
1137 // Lazily compute and persist the SHA-256 hash when it is absent.
1138 let sha256 = meta ? (meta.sha256 || null) : null;
1139 if (!sha256 && !stat.isDirectory())
1140 {
1141 try
1142 {
1143 sha256 = await computeFileSha256(file);
1144 if (meta)
1145 {
1146 db.prepare('UPDATE file_meta SET sha256 = ? WHERE file_path = ?').run([sha256, file]);
1147 } else
1148 {
1149 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1150 .run([file, '', '[]', sha256]);
1151 meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1152 }
1153 } catch
1154 {
1155 // Non-fatal — hash will be retried next time.
1156 }
1157 }
1158
1159 res.json({
1160 name: path.basename(file),
1161 size: stat.size,
1162 mtime: stat.mtime.toISOString(),
1163 uploader: meta ? meta.uploader : '',
1164 downloaders: meta ? parseJsonArray(meta.downloaders) : [],
1165 watchedBy: meta ? parseJsonObject(meta.watched_by) : {},
1166 sha256: sha256 || null,
1167 });
1168});
1169
1170// ---------------------------------------------------------------------------
1171// GET /api/files/duplicates?file=<absolute-path>
1172// Returns other files with the same SHA-256 hash that the user can access.
1173// ---------------------------------------------------------------------------
1174router.get('/duplicates', requireAuth, (req, res) =>
1175{
1176 const file = req.query.file;
1177 if (!file) return res.status(400).json({ error: 'file is required.' });
1178
1179 const { config, roots } = loadConfigAndRoots();
1180 const info = resolveRootForUser(file, roots, req.user, config);
1181 if (!info || !canReadInfo(req.user, info))
1182 {
1183 return res.status(403).json({ error: 'Access denied.' });
1184 }
1185
1186 const db = getDb();
1187 const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]);
1188 const hash = row ? (row.sha256 || null) : null;
1189 if (!hash)
1190 {
1191 return res.json({ duplicates: [] });
1192 }
1193
1194 // All other files sharing the same hash.
1195 const candidates = db.prepare(
1196 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?',
1197 ).all([hash, file]);
1198
1199 const duplicates = [];
1200 for (const { file_path } of candidates)
1201 {
1202 // Only return files inside a root the user can access and that still exist on disk.
1203 const dupInfo = resolveRootForUser(file_path, roots, req.user, config);
1204 if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue;
1205 if (!fs.existsSync(file_path)) continue;
1206
1207 const rel = path.relative(dupInfo.root, file_path);
1208 const relativePath = rel && rel !== '' ? rel : path.basename(file_path);
1209
1210 duplicates.push({
1211 path: file_path,
1212 name: path.basename(file_path),
1213 dir: path.dirname(file_path),
1214 rootPath: dupInfo.root,
1215 relativePath,
1216 });
1217 }
1218
1219 res.json({ duplicates });
1220});
1221
1222// ---------------------------------------------------------------------------
1223// GET /api/files/space?dir=<absolute-path>
1224// Returns recursive used bytes for dir and available bytes on its root fs.
1225// ---------------------------------------------------------------------------
1226router.get('/space', requireAuth, (req, res) =>
1227{
1228 const dir = req.query.dir;
1229 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1230
1231 const { config, roots } = loadConfigAndRoots();
1232 const info = resolveRootForUser(dir, roots, req.user, config);
1233 if (!info || !canReadInfo(req.user, info))
1234 {
1235 return res.status(403).json({ error: 'Access denied.' });
1236 }
1237
1238 if (!fs.existsSync(dir))
1239 {
1240 return res.status(404).json({ error: 'Path not found.' });
1241 }
1242
1243 const usedBytes = getRecursiveSize(dir);
1244 const freeBytes = getFreeBytes(info.root);
1245 const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null;
1246 const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes);
1247 res.json({
1248 usedBytes,
1249 freeBytes,
1250 userLimitBytes,
1251 userFreeBytes,
1252 rootPath: info.root,
1253 rootLabel: info.label,
1254 });
1255});
1256
1257// ---------------------------------------------------------------------------
1258// GET /api/files/download?file=<absolute-path>
1259// Streams the file to the client; records the download.
1260// ---------------------------------------------------------------------------
1261router.get('/download', requireAuth, (req, res) =>
1262{
1263 const file = req.query.file;
1264 if (!file) return res.status(400).json({ error: 'file is required.' });
1265
1266 const { config, roots } = loadConfigAndRoots();
1267 const info = resolveRootForUser(file, roots, req.user, config);
1268 if (!info || !canReadInfo(req.user, info))
1269 {
1270 return res.status(403).json({ error: 'Access denied.' });
1271 }
1272
1273 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1274 {
1275 return res.status(404).json({ error: 'File not found.' });
1276 }
1277
1278 // Record download
1279 const db = getDb();
1280 const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]);
1281 if (meta)
1282 {
1283 const downloaders = parseJsonArray(meta.downloaders);
1284 if (!downloaders.includes(req.user.username))
1285 {
1286 downloaders.push(req.user.username);
1287 db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?')
1288 .run([JSON.stringify(downloaders), file]);
1289 }
1290 } else
1291 {
1292 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1293 .run([file, '', JSON.stringify([req.user.username]), '{}']);
1294 }
1295
1296 res.download(file, path.basename(file));
1297});
1298
1299// ---------------------------------------------------------------------------
1300// POST /api/files/watched-statuses
1301// Body: { filePaths: [<absolute-path>, ...] }
1302// Returns per-path watched status for the authenticated user.
1303// ---------------------------------------------------------------------------
1304router.post('/watched-statuses', requireAuth, (req, res) =>
1305{
1306 const rawPaths = req.body && Array.isArray(req.body.filePaths) ? req.body.filePaths : null;
1307 if (!rawPaths)
1308 {
1309 return res.status(400).json({ error: 'filePaths array is required.' });
1310 }
1311
1312 const paths = rawPaths
1313 .map((p) => String(p || '').trim())
1314 .filter(Boolean)
1315 .slice(0, 500);
1316
1317 const { config, roots } = loadConfigAndRoots();
1318 const db = getDb();
1319 const statuses = {};
1320 const selectMeta = db.prepare('SELECT watched_by FROM file_meta WHERE file_path = ?');
1321
1322 for (const filePath of paths)
1323 {
1324 const info = resolveRootForUser(filePath, roots, req.user, config);
1325 if (!info || !canReadInfo(req.user, info)) continue;
1326
1327 let stat;
1328 try
1329 {
1330 stat = fs.statSync(filePath);
1331 } catch
1332 {
1333 continue;
1334 }
1335 if (stat.isDirectory()) continue;
1336
1337 const row = selectMeta.get([filePath]);
1338 const watchedBy = parseJsonObject(row && row.watched_by);
1339 const status = normalisedWatchedStatus(watchedBy[req.user.username]);
1340 if (status) statuses[filePath] = status;
1341 }
1342
1343 res.json({ statuses });
1344});
1345
1346// ---------------------------------------------------------------------------
1347// POST /api/files/watch-progress
1348// Body: { filePath: <absolute-path>, progress: <0..1> }
1349// Records per-user video watch state for sidebar display.
1350// ---------------------------------------------------------------------------
1351router.post('/watch-progress', requireAuth, (req, res) =>
1352{
1353 const filePath = String(req.body && req.body.filePath || '').trim();
1354 const progress = Number(req.body && req.body.progress);
1355 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1356
1357 const status = watchStatusForProgress(progress);
1358 if (!status)
1359 {
1360 return res.json({ ok: true, updated: false });
1361 }
1362
1363 const { config, roots } = loadConfigAndRoots();
1364 const info = resolveRootForUser(filePath, roots, req.user, config);
1365 if (!info || !canReadInfo(req.user, info))
1366 {
1367 return res.status(403).json({ error: 'Access denied.' });
1368 }
1369
1370 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1371 {
1372 return res.status(404).json({ error: 'File not found.' });
1373 }
1374
1375 const db = getDb();
1376 const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]);
1377 const watchedBy = parseJsonObject(row && row.watched_by);
1378 const prev = String(watchedBy[req.user.username] || '').toLowerCase();
1379 const next = prev === 'fully' ? 'fully' : status;
1380 if (prev === next)
1381 {
1382 return res.json({ ok: true, updated: false, status: next });
1383 }
1384
1385 watchedBy[req.user.username] = next;
1386 if (row)
1387 {
1388 db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?')
1389 .run([JSON.stringify(watchedBy), filePath]);
1390 } else
1391 {
1392 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1393 .run([filePath, '', '[]', JSON.stringify(watchedBy)]);
1394 }
1395
1396 res.json({ ok: true, updated: true, status: next });
1397});
1398
1399// ---------------------------------------------------------------------------
1400// POST /api/files/video-stream
1401// Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video.
1402// ---------------------------------------------------------------------------
1403router.post('/video-stream', requireAuth, async (req, res, next) =>
1404{
1405 try
1406 {
1407 const filePath = String(req.body?.filePath || '').trim();
1408 if (!filePath) return res.status(400).json({ error: 'filePath is required.' });
1409
1410 const { config, roots } = loadConfigAndRoots();
1411 const info = resolveRootForUser(filePath, roots, req.user, config);
1412 if (!info || !canReadInfo(req.user, info))
1413 {
1414 return res.status(403).json({ error: 'Access denied.' });
1415 }
1416
1417 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1418 {
1419 return res.status(404).json({ error: 'File not found.' });
1420 }
1421
1422 const session = await createVideoStreamSession(filePath);
1423 res.json({
1424 sessionId: session.sessionId,
1425 playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`,
1426 durationSeconds: session.durationSeconds || null,
1427 videoWidth: session.videoWidth || null,
1428 videoHeight: session.videoHeight || null,
1429 subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 },
1430 subtitleTracks: session.subtitleTracks.map((track) => ({
1431 label: track.label,
1432 language: track.language,
1433 default: !!track.isDefault,
1434 src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`,
1435 })),
1436 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({
1437 label: track.label,
1438 language: track.language,
1439 default: !!track.isDefault,
1440 streamIndex: track.streamIndex,
1441 })),
1442 });
1443 } catch (err)
1444 {
1445 next(err);
1446 }
1447});
1448
1449// ---------------------------------------------------------------------------
1450// GET /api/files/video-stream/:sessionId/:assetPath(*)
1451// Streams HLS assets for a previously created short-lived video session.
1452// ---------------------------------------------------------------------------
1453router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) =>
1454{
1455 try
1456 {
1457 await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res);
1458 } catch (err)
1459 {
1460 next(err);
1461 }
1462});
1463
1464// ---------------------------------------------------------------------------
1465// DELETE /api/files/video-stream/:sessionId
1466// Authenticated. Explicitly releases an active short-lived video session.
1467// ---------------------------------------------------------------------------
1468router.delete('/video-stream/:sessionId', requireAuth, (req, res) =>
1469{
1470 const sessionId = String(req.params.sessionId || '').trim();
1471 if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' });
1472
1473 releaseVideoStreamSession(sessionId);
1474 res.json({ ok: true });
1475});
1476
1477// ---------------------------------------------------------------------------
1478// GET /api/files/video-stream-subtitle-frame
1479// Authenticated. Returns a composited PNG subtitle frame at a given timestamp.
1480// Query params: filePath, streamIndex, timeSeconds
1481// ---------------------------------------------------------------------------
1482router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) =>
1483{
1484 try
1485 {
1486 const filePath = String(req.query.filePath || '').trim();
1487 const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10);
1488 const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10);
1489 const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10);
1490 const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10);
1491
1492 if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0)
1493 {
1494 return res.status(400).json({ error: 'filePath, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' });
1495 }
1496
1497 const { config, roots } = loadConfigAndRoots();
1498 const info = resolveRootForUser(filePath, roots, req.user, config);
1499 if (!info || !canReadInfo(req.user, info))
1500 {
1501 return res.status(403).json({ error: 'Access denied.' });
1502 }
1503
1504 if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory())
1505 {
1506 return res.status(404).json({ error: 'File not found.' });
1507 }
1508
1509 const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280;
1510 const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720;
1511 const frameData = await renderImageSubtitleFrame({
1512 filePath,
1513 streamIndex,
1514 timeSeconds,
1515 canvasWidth,
1516 canvasHeight,
1517 });
1518
1519 if (!frameData || frameData.length === 0)
1520 {
1521 res.set('X-Subtitle-Frame-Status', 'none');
1522 return res.status(204).end();
1523 }
1524
1525 res.set('X-Subtitle-Frame-Status', 'ok');
1526 res.set('Content-Type', 'image/png');
1527 res.set('Cache-Control', 'private, max-age=3600');
1528 res.send(frameData);
1529 } catch (err)
1530 {
1531 logError('Subtitle frame extraction failed', err, {
1532 filePath: String(req.query.filePath || ''),
1533 streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10),
1534 timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10),
1535 });
1536 res.set('X-Subtitle-Frame-Status', 'error');
1537 return res.status(204).end();
1538 }
1539});
1540
1541// ---------------------------------------------------------------------------
1542// GET /api/files/download-zip?dir=<absolute-path>
1543// Authenticated. Streams a zip of the given directory.
1544// ---------------------------------------------------------------------------
1545router.get('/download-zip', requireAuth, async (req, res) =>
1546{
1547 const dir = req.query.dir;
1548 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1549
1550 const { config, roots } = loadConfigAndRoots();
1551 const info = resolveRootForUser(dir, roots, req.user, config);
1552 if (!info || !canReadInfo(req.user, info))
1553 {
1554 return res.status(403).json({ error: 'Access denied.' });
1555 }
1556
1557 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1558 {
1559 return res.status(404).json({ error: 'Directory not found.' });
1560 }
1561
1562 // Use a hash of the dir path as cache key so concurrent users share the cache.
1563 const cacheKey = crypto.createHash('sha256').update(dir).digest('hex');
1564 try
1565 {
1566 const zipPath = await buildZip(dir, cacheKey);
1567 const zipName = `${path.basename(dir)}.zip`;
1568 res.download(zipPath, zipName);
1569 } catch (err)
1570 {
1571 res.status(500).json({ error: 'Failed to create zip archive.' });
1572 }
1573});
1574
1575// ---------------------------------------------------------------------------
1576// GET /api/files/thumbnail?file=<absolute-path>
1577// Returns a pre-generated cached thumbnail if present.
1578// ---------------------------------------------------------------------------
1579router.get('/thumbnail', requireAuth, async (req, res) =>
1580{
1581 const file = req.query.file;
1582 if (!file) return res.status(400).json({ error: 'file is required.' });
1583
1584 const { config, roots } = loadConfigAndRoots();
1585 const info = resolveRootForUser(file, roots, req.user, config);
1586 if (!info || !canReadInfo(req.user, info))
1587 {
1588 return res.status(403).json({ error: 'Access denied.' });
1589 }
1590
1591 if (!fs.existsSync(file) || fs.statSync(file).isDirectory())
1592 {
1593 return res.status(404).json({ error: 'File not found.' });
1594 }
1595
1596 const thumb = await getCachedThumbnailInfo(file);
1597 if (!thumb)
1598 {
1599 return res.status(404).json({ error: 'Thumbnail not ready.' });
1600 }
1601
1602 res.type(thumb.contentType);
1603 res.set('Cache-Control', 'private, max-age=10');
1604 res.sendFile(thumb.thumbPath);
1605});
1606
1607// ---------------------------------------------------------------------------
1608// POST /api/files/upload?dir=<absolute-path>
1609// Accepts multipart file upload.
1610// ---------------------------------------------------------------------------
1611router.post('/upload', requireAuth, (req, res, next) =>
1612{
1613 const dir = req.query.dir;
1614 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1615
1616 const { config, roots } = loadConfigAndRoots();
1617 const info = resolveRootForUser(dir, roots, req.user, config);
1618 if (!info || !canWriteInfo(req.user, info))
1619 {
1620 return res.status(403).json({ error: 'Access denied.' });
1621 }
1622
1623 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1624 {
1625 return res.status(404).json({ error: 'Directory not found.' });
1626 }
1627
1628 const announcedSize = Number(req.header('x-upload-size') || 0);
1629 if (Number.isFinite(announcedSize) && announcedSize > 0)
1630 {
1631 const freeBytes = getFreeBytes(info.root);
1632 if (typeof freeBytes === 'number' && announcedSize > freeBytes)
1633 {
1634 return res.status(413).json({
1635 error: 'Upload too large for remaining free space on selected root.',
1636 freeBytes,
1637 requiredBytes: announcedSize,
1638 });
1639 }
1640 }
1641
1642 // Enforce per-user folder size limit when uploading to a user folder.
1643 if (info.isUserFolder)
1644 {
1645 const addBytes = announcedSize > 0 ? announcedSize : 0;
1646 const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes);
1647 if (limitError) return res.status(413).json({ error: limitError });
1648 }
1649
1650 req._uploadDir = dir;
1651
1652 upload.array('files')(req, res, async (err) =>
1653 {
1654 if (err) return res.status(500).json({ error: err.message });
1655
1656 const db = getDb();
1657 for (const f of (req.files || []))
1658 {
1659 const filePath = path.join(dir, f.originalname);
1660
1661 let sha256 = null;
1662 try
1663 {
1664 sha256 = await computeFileSha256(filePath);
1665 } catch
1666 {
1667 // Non-fatal — hash can be computed lazily when the file is accessed.
1668 }
1669
1670 const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]);
1671 if (existing)
1672 {
1673 db.prepare('UPDATE file_meta SET uploader = ?, sha256 = ? WHERE file_path = ?')
1674 .run([req.user.username, sha256, filePath]);
1675 } else
1676 {
1677 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1678 .run([filePath, req.user.username, '[]', sha256]);
1679 }
1680 }
1681 res.json({ uploaded: (req.files || []).map(f => f.originalname) });
1682 });
1683});
1684
1685// ---------------------------------------------------------------------------
1686// POST /api/files/rename
1687// Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path)
1688// ---------------------------------------------------------------------------
1689router.post('/rename', requireAuth, (req, res) =>
1690{
1691 const { from, to } = req.body;
1692 if (!from || !to) return res.status(400).json({ error: 'from and to are required.' });
1693
1694 // Prevent path traversal in the new name
1695 if (path.basename(to) !== to || to.includes('/') || to.includes('\\'))
1696 {
1697 return res.status(400).json({ error: 'Invalid name.' });
1698 }
1699
1700 const { config, roots } = loadConfigAndRoots();
1701 const info = resolveRootForUser(from, roots, req.user, config);
1702 if (!info || !canWriteInfo(req.user, info))
1703 {
1704 return res.status(403).json({ error: 'Access denied.' });
1705 }
1706
1707 const dest = path.join(path.dirname(from), to);
1708
1709 // Ensure dest is still inside the same accessible root or user folder.
1710 if (!isAccessiblePath(dest, roots, req.user, config))
1711 {
1712 return res.status(403).json({ error: 'Access denied.' });
1713 }
1714
1715 try
1716 {
1717 movePathWithFallback(from, dest);
1718 } catch (err)
1719 {
1720 return res.status(500).json({ error: err.message });
1721 }
1722
1723 rewriteMetaPaths(from, dest);
1724
1725 res.json({ ok: true });
1726});
1727
1728// ---------------------------------------------------------------------------
1729// POST /api/files/move
1730// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
1731// ---------------------------------------------------------------------------
1732router.post('/move', requireAuth, (req, res) =>
1733{
1734 const { from, toDir } = req.body;
1735 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
1736 const targetName = req.body && req.body.targetName != null
1737 ? String(req.body.targetName).trim()
1738 : '';
1739 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
1740 if (!['error', 'overwrite', 'rename'].includes(conflict))
1741 {
1742 return res.status(400).json({ error: 'Invalid conflict strategy.' });
1743 }
1744
1745 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
1746 {
1747 return res.status(400).json({ error: 'Invalid targetName.' });
1748 }
1749
1750 const { config, roots } = loadConfigAndRoots();
1751 const fromInfo = resolveRootForUser(from, roots, req.user, config);
1752 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
1753 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
1754 if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
1755 {
1756 return res.status(403).json({ error: 'Access denied.' });
1757 }
1758
1759 let sourceStat;
1760 let destStat;
1761 try
1762 {
1763 sourceStat = fs.statSync(from);
1764 destStat = fs.statSync(toDir);
1765 } catch
1766 {
1767 return res.status(404).json({ error: 'Source or destination not found.' });
1768 }
1769
1770 if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' });
1771
1772 const requestedName = targetName || path.basename(from);
1773 const requestedDest = path.join(toDir, requestedName);
1774 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
1775
1776 // Enforce per-user folder size limit when moving into a user folder.
1777 if (toInfo.isUserFolder)
1778 {
1779 const sourceSize = getRecursiveSize(from);
1780 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize);
1781 if (limitError) return res.status(413).json({ error: limitError });
1782 }
1783 if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest))
1784 {
1785 return res.status(400).json({ error: 'Cannot move onto itself.' });
1786 }
1787 if (sourceStat.isDirectory() && pathInsideResolved(toDir, from))
1788 {
1789 return res.status(400).json({ error: 'Cannot move a folder into itself.' });
1790 }
1791
1792 let dest = requestedDest;
1793 let resolvedConflict = 'none';
1794
1795 if (fs.existsSync(requestedDest))
1796 {
1797 if (conflict === 'error')
1798 {
1799 return res.status(409).json({ error: 'Destination already exists.' });
1800 }
1801
1802 if (conflict === 'rename')
1803 {
1804 dest = pickNumberedPath(toDir, requestedName);
1805 resolvedConflict = 'rename';
1806 }
1807
1808 if (conflict === 'overwrite')
1809 {
1810 try
1811 {
1812 removePathRecursive(requestedDest);
1813 } catch (err)
1814 {
1815 return res.status(500).json({ error: err.message });
1816 }
1817 resolvedConflict = 'overwrite';
1818 }
1819 }
1820
1821 if (sameResolvedPath(from, dest))
1822 {
1823 return res.status(400).json({ error: 'Cannot move onto itself.' });
1824 }
1825
1826 try
1827 {
1828 movePathWithFallback(from, dest);
1829 } catch (err)
1830 {
1831 return res.status(500).json({ error: err.message });
1832 }
1833
1834 rewriteMetaPaths(from, dest);
1835 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
1836});
1837
1838// ---------------------------------------------------------------------------
1839// POST /api/files/mkdir
1840// Body: { dir: <absolute-path>, name: <folder-name> }
1841// ---------------------------------------------------------------------------
1842router.post('/mkdir', requireAuth, (req, res) =>
1843{
1844 const { dir, name } = req.body;
1845 if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' });
1846
1847 if (path.basename(name) !== name)
1848 {
1849 return res.status(400).json({ error: 'Invalid folder name.' });
1850 }
1851
1852 const { config, roots } = loadConfigAndRoots();
1853 const info = resolveRootForUser(dir, roots, req.user, config);
1854 if (!info || !canWriteInfo(req.user, info))
1855 {
1856 return res.status(403).json({ error: 'Access denied.' });
1857 }
1858
1859 const newDir = path.join(dir, name);
1860 if (!isAccessiblePath(newDir, roots, req.user, config))
1861 {
1862 return res.status(403).json({ error: 'Access denied.' });
1863 }
1864
1865 try
1866 {
1867 fs.mkdirSync(newDir, { recursive: false });
1868 } catch (err)
1869 {
1870 return res.status(500).json({ error: err.message });
1871 }
1872
1873 res.json({ ok: true, path: newDir });
1874});
1875
1876// ---------------------------------------------------------------------------
1877// POST /api/files/delete
1878// Body: { path: <absolute-path> }
1879// ---------------------------------------------------------------------------
1880router.post('/delete', requireAuth, (req, res) =>
1881{
1882 const target = req.body.path;
1883 if (!target) return res.status(400).json({ error: 'path is required.' });
1884
1885 const { config, roots } = loadConfigAndRoots();
1886 const info = resolveRootForUser(target, roots, req.user, config);
1887 if (!info || !canWriteInfo(req.user, info))
1888 {
1889 return res.status(403).json({ error: 'Access denied.' });
1890 }
1891
1892 // Do not allow deleting a configured root itself
1893 if (roots.map(r => path.resolve(r)).includes(path.resolve(target)))
1894 {
1895 return res.status(403).json({ error: 'Cannot delete a configured root path.' });
1896 }
1897
1898 try
1899 {
1900 const stat = fs.statSync(target);
1901 if (stat.isDirectory())
1902 {
1903 fs.rmSync(target, { recursive: true, force: true });
1904 } else
1905 {
1906 fs.unlinkSync(target);
1907 }
1908 } catch (err)
1909 {
1910 return res.status(500).json({ error: err.message });
1911 }
1912
1913 // Clean up any DB meta entries under that path
1914 const db = getDb();
1915 db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?")
1916 .run([target, target + path.sep + '%']);
1917
1918 res.json({ ok: true });
1919});
1920
1921// ---------------------------------------------------------------------------
1922// GET /api/files/folder-images?dir=<absolute-path>
1923// Returns files inside dir (recursive) that already have a cached thumbnail.
1924// Only files with a ready cached thumbnail are included.
1925// ---------------------------------------------------------------------------
1926router.get('/folder-images', requireAuth, async (req, res) =>
1927{
1928 const dir = String(req.query.dir || '').trim();
1929 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1930
1931 const { config, roots } = loadConfigAndRoots();
1932 const info = resolveRootForUser(dir, roots, req.user, config);
1933 if (!info || !canReadInfo(req.user, info))
1934 {
1935 return res.status(403).json({ error: 'Access denied.' });
1936 }
1937
1938 if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory())
1939 {
1940 return res.status(404).json({ error: 'Directory not found.' });
1941 }
1942
1943 const files = await getFilesWithThumbnailsInDir(dir);
1944 // Filter out any that escaped to a different accessible root (safety check).
1945 const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config));
1946
1947 res.json({ images: filtered.map(({ filePath }) => ({ filePath })) });
1948});
1949
1950// ---------------------------------------------------------------------------
1951// GET /api/files/folder-icon?dir=<absolute-path>
1952// Returns the current icon source file for a folder (explicit or auto-first).
1953// ---------------------------------------------------------------------------
1954router.get('/folder-icon', requireAuth, async (req, res) =>
1955{
1956 const dir = String(req.query.dir || '').trim();
1957 if (!dir) return res.status(400).json({ error: 'dir is required.' });
1958
1959 const { config, roots } = loadConfigAndRoots();
1960 const info = resolveRootForUser(dir, roots, req.user, config);
1961 if (!info || !canReadInfo(req.user, info))
1962 {
1963 return res.status(403).json({ error: 'Access denied.' });
1964 }
1965
1966 const sourceFile = await getFolderIconSourceFile(dir);
1967 if (!sourceFile) return res.json({ icon: null });
1968
1969 // Verify the source is still accessible within a configured root or user folder.
1970 if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null });
1971
1972 res.json({ icon: { filePath: sourceFile } });
1973});
1974
1975// ---------------------------------------------------------------------------
1976// POST /api/files/folder-icon
1977// Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment.
1978// Requires write access; the image must already have a cached thumbnail.
1979// ---------------------------------------------------------------------------
1980router.post('/folder-icon', requireAuth, async (req, res) =>
1981{
1982 const folderPath = String((req.body && req.body.folderPath) || '').trim();
1983 const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null;
1984
1985 if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' });
1986
1987 const { config, roots } = loadConfigAndRoots();
1988 const info = resolveRootForUser(folderPath, roots, req.user, config);
1989 if (!info || !canWriteInfo(req.user, info))
1990 {
1991 return res.status(403).json({ error: 'Access denied.' });
1992 }
1993
1994 let stat;
1995 try { stat = fs.statSync(folderPath); }
1996 catch { return res.status(404).json({ error: 'Folder not found.' }); }
1997 if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' });
1998
1999 if (rawImage !== null)
2000 {
2001 // Verify the image is inside a readable root or user folder.
2002 if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' });
2003
2004 // Must already have a cached thumbnail — only thumbnailed images can be selected.
2005 const thumb = await getCachedThumbnailInfo(rawImage);
2006 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2007 }
2008
2009 await setFolderIconAssignment(folderPath, rawImage);
2010 res.json({ ok: true });
2011});
2012
2013// ---------------------------------------------------------------------------
2014// GET /api/files/global-favicon-image
2015// Serves the configured global favicon thumbnail file (cache-backed).
2016// Public so <link rel="icon"> can fetch it without auth headers.
2017// ---------------------------------------------------------------------------
2018router.get('/global-favicon-image', async (req, res) =>
2019{
2020 const config = loadConfig();
2021 const filePath = config && typeof config.globalFaviconPath === 'string'
2022 ? config.globalFaviconPath.trim()
2023 : '';
2024 if (!filePath) return res.status(404).end();
2025
2026 const thumb = await getCachedThumbnailInfo(filePath);
2027 if (!thumb || !thumb.thumbPath) return res.status(404).end();
2028 if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end();
2029
2030 res.type(thumb.contentType || 'image/webp');
2031 res.sendFile(thumb.thumbPath);
2032});
2033
2034// ---------------------------------------------------------------------------
2035// GET /api/files/global-favicon
2036// Returns the configured global favicon source file path, if any.
2037// ---------------------------------------------------------------------------
2038router.get('/global-favicon', requireAuth, async (req, res) =>
2039{
2040 const config = loadConfig();
2041 const filePath = config && typeof config.globalFaviconPath === 'string'
2042 ? config.globalFaviconPath.trim()
2043 : '';
2044 if (!filePath) return res.json({ favicon: null });
2045
2046 const thumb = await getCachedThumbnailInfo(filePath);
2047 if (!thumb) return res.json({ favicon: null });
2048
2049 res.json({ favicon: { filePath } });
2050});
2051
2052// ---------------------------------------------------------------------------
2053// POST /api/files/global-favicon
2054// Body: { imagePath } where imagePath may be null to clear.
2055// Admin-only route for setting the global favicon source image.
2056// ---------------------------------------------------------------------------
2057router.post('/global-favicon', requireAuth, async (req, res) =>
2058{
2059 if (!req.user || !req.user.isAdmin)
2060 {
2061 return res.status(403).json({ error: 'Admin access required.' });
2062 }
2063
2064 const rawImage = req.body && req.body.imagePath != null
2065 ? String(req.body.imagePath).trim()
2066 : null;
2067
2068 const config = loadConfig();
2069 const roots = getEffectivePaths(config.paths || []);
2070
2071 if (rawImage !== null)
2072 {
2073 const info = resolveRootForUser(rawImage, roots, req.user, config);
2074 if (!info || !canReadInfo(req.user, info))
2075 {
2076 return res.status(403).json({ error: 'Image not accessible.' });
2077 }
2078
2079 const thumb = await getCachedThumbnailInfo(rawImage);
2080 if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' });
2081 }
2082
2083 config.globalFaviconPath = rawImage;
2084 saveConfig(config);
2085 res.json({ ok: true });
2086});
2087
2088// ---------------------------------------------------------------------------
2089// POST /api/files/copy
2090// Body: { from: <absolute-path>, toDir: <absolute-destination-directory> }
2091// Copies a file (not a directory) to the destination folder.
2092// Supports conflict: 'error' (default) | 'overwrite' | 'rename'
2093// ---------------------------------------------------------------------------
2094router.post('/copy', requireAuth, (req, res) =>
2095{
2096 const { from, toDir } = req.body;
2097 const conflict = String(req.body && req.body.conflict || 'error').toLowerCase();
2098 const targetName = req.body && req.body.targetName != null
2099 ? String(req.body.targetName).trim()
2100 : '';
2101 if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' });
2102 if (!['error', 'overwrite', 'rename'].includes(conflict))
2103 {
2104 return res.status(400).json({ error: 'Invalid conflict strategy.' });
2105 }
2106
2107 if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\')))
2108 {
2109 return res.status(400).json({ error: 'Invalid targetName.' });
2110 }
2111
2112 const { config, roots } = loadConfigAndRoots();
2113 const fromInfo = resolveRootForUser(from, roots, req.user, config);
2114 const toInfo = resolveRootForUser(toDir, roots, req.user, config);
2115 if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' });
2116 if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo))
2117 {
2118 return res.status(403).json({ error: 'Access denied.' });
2119 }
2120
2121 let sourceStat;
2122 try { sourceStat = fs.statSync(from); }
2123 catch { return res.status(404).json({ error: 'Source not found.' }); }
2124
2125 if (sourceStat.isDirectory())
2126 {
2127 return res.status(400).json({ error: 'Copying directories is not supported.' });
2128 }
2129
2130 if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory())
2131 {
2132 return res.status(404).json({ error: 'Destination directory not found.' });
2133 }
2134
2135 const requestedName = targetName || path.basename(from);
2136 const requestedDest = path.join(toDir, requestedName);
2137 if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' });
2138
2139 // Enforce per-user folder size limit when copying into a user folder.
2140 if (toInfo.isUserFolder)
2141 {
2142 const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size);
2143 if (limitError) return res.status(413).json({ error: limitError });
2144 }
2145
2146 let dest = requestedDest;
2147 let resolvedConflict = 'none';
2148
2149 if (fs.existsSync(requestedDest))
2150 {
2151 if (conflict === 'error')
2152 {
2153 return res.status(409).json({ error: 'Destination already exists.' });
2154 }
2155 if (conflict === 'rename')
2156 {
2157 dest = pickNumberedPath(toDir, requestedName);
2158 resolvedConflict = 'rename';
2159 }
2160 if (conflict === 'overwrite')
2161 {
2162 resolvedConflict = 'overwrite';
2163 }
2164 }
2165
2166 try
2167 {
2168 fs.copyFileSync(from, dest);
2169 } catch (err)
2170 {
2171 return res.status(500).json({ error: err.message });
2172 }
2173
2174 res.json({ ok: true, path: dest, conflictResolution: resolvedConflict });
2175});
2176
2177module.exports = router;