'use strict'; const express = require('express'); const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); const multer = require('multer'); const router = express.Router(); const { getDb } = require('../db'); const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config'); const { requireAuth } = require('../auth'); const { getCachedThumbnailInfo, getFilesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment, getThumbnailManifestSourcePathSet, needsPreviewImageConversion, streamPreviewImage, MAX_PREVIEW_IMAGE_BYTES, THUMB_HTTP_MAX_AGE_SEC, } = require('../thumbnail-cache'); const { searchFiles, deleteIndexPath, deleteIndexUnder, rewriteIndexPaths, reindexDirectoryTree, } = require('../search-index'); const { logError } = require('../logger'); const { renderImageSubtitleFrame, renderImageSubtitleFramesInRange } = require('../image-subtitles'); const { appendSubtitleDebugEntries, SUBTITLE_DEBUG_LOG_DIR } = require('../subtitle-debug-log'); const { buildZip } = require('./share'); const { createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession } = require('../video-stream'); const { enqueueFileHash } = require('../file-hash-queue'); // --------------------------------------------------------------------------- // Multer storage — files are staged into temporary files and only promoted // to their final names after the full stream arrives. // --------------------------------------------------------------------------- function makeTempUploadPath (dir, originalName) { const safeName = path.basename(String(originalName || 'upload')); const suffix = crypto.randomUUID(); return path.join(dir, `.${safeName}.upload-${suffix}.part`); } function unlinkIfExists (targetPath, cb) { fs.unlink(targetPath, (err) => { if (!err || err.code === 'ENOENT') return cb(null); cb(err); }); } function promoteUploadedFile (tempPath, finalPath, cb) { fs.rename(tempPath, finalPath, cb); } const storage = { _handleFile (req, file, cb) { if (!req._uploadDir) { cb(new Error('Upload directory is not set.')); return; } const finalName = path.basename(String(file.originalname || 'upload')); const finalPath = path.join(req._uploadDir, finalName); const tempPath = makeTempUploadPath(req._uploadDir, finalName); const out = fs.createWriteStream(tempPath, { flags: 'wx' }); let settled = false; let cleaned = false; const detach = () => { req.off('aborted', onAbort); req.off('close', onClose); file.stream.off('error', onStreamError); out.off('error', onWriteError); out.off('finish', onFinish); }; const stopPiping = () => { // Prevent late file stream chunks from writing into a destroyed stream. file.stream.unpipe(out); if (typeof file.stream.resume === 'function') file.stream.resume(); }; const cleanup = (done) => { if (cleaned) return done(null); cleaned = true; const removeTempFile = () => unlinkIfExists(tempPath, done); if (out.closed) { removeTempFile(); return; } out.once('close', removeTempFile); out.once('error', () => { // The upload is already failing; close will drive temp-file cleanup. }); if (!out.destroyed) out.destroy(); }; const fail = (err) => { if (settled) return; settled = true; stopPiping(); detach(); cleanup((cleanupErr) => cb(cleanupErr || err)); }; const succeed = () => { if (settled) return; settled = true; detach(); cb(null, { destination: req._uploadDir, filename: finalName, originalname: file.originalname, path: finalPath, size: out.bytesWritten, }); }; const onAbort = () => fail(new Error('Upload aborted.')); const onClose = () => { if (!req.complete) onAbort(); }; const onStreamError = (err) => fail(err); const onWriteError = (err) => fail(err); const onFinish = () => { if (req.aborted || !req.complete) { fail(new Error('Upload aborted.')); return; } promoteUploadedFile(tempPath, finalPath, (err) => { if (err) { fail(err); return; } succeed(); }); }; req.on('aborted', onAbort); req.on('close', onClose); file.stream.on('error', onStreamError); out.on('error', onWriteError); out.on('finish', onFinish); file.stream.pipe(out); }, _removeFile (req, file, cb) { unlinkIfExists(file.path, cb); }, }; const upload = multer({ storage, limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB }); function parseOctalMode (rawValue, fallback) { const trimmed = String(rawValue || '').trim(); if (!trimmed) return fallback; if (!/^[0-7]{3,4}$/.test(trimmed)) return fallback; const parsed = Number.parseInt(trimmed, 8); if (!Number.isInteger(parsed) || parsed < 0 || parsed > 0o7777) return fallback; return parsed; } function envFlagEnabled (name) { const value = String(process.env[name] || '').trim().toLowerCase(); return value === '1' || value === 'true' || value === 'yes' || value === 'on'; } function applyListAccessChmod (startDir) { const dirMode = parseOctalMode(process.env.FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE, 0o777); const fileMode = parseOctalMode(process.env.FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE, 0o666); const rootDir = path.resolve(startDir); let rootStat; try { rootStat = fs.lstatSync(rootDir); } catch { return; } if (rootStat.isSymbolicLink()) return; try { fs.chmodSync(rootDir, rootStat.isDirectory() ? dirMode : fileMode); } catch { // Continue best-effort; listing should still work when possible. } if (!rootStat.isDirectory()) return; let entries = []; try { entries = fs.readdirSync(rootDir, { withFileTypes: true }); } catch { return; } for (const entry of entries) { const childPath = path.join(rootDir, entry.name); let childStat; try { childStat = fs.lstatSync(childPath); } catch { continue; } if (childStat.isSymbolicLink()) continue; try { fs.chmodSync(childPath, childStat.isDirectory() ? dirMode : fileMode); } catch { // Continue best-effort; listing should still work when possible. } } } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function effectivePaths () { return getEffectivePaths(loadConfig().paths || []); } const META_BATCH_SIZE = 400; function loadUploadedAtByPaths (db, paths) { const map = new Map(); const unique = [...new Set(paths.map((p) => String(p || '')).filter(Boolean))]; for (let i = 0; i < unique.length; i += META_BATCH_SIZE) { const chunk = unique.slice(i, i + META_BATCH_SIZE); const placeholders = chunk.map(() => '?').join(', '); const rows = db.prepare(`SELECT file_path, uploaded_at FROM file_meta WHERE file_path IN (${placeholders})`) .all(chunk); for (const row of rows) { map.set(row.file_path, String(row.uploaded_at || '').trim()); } } return map; } function persistMissingUploadedAt (db, rows) { if (!rows.length) return; const stmt = db.prepare(` INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(file_path) DO UPDATE SET uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at) `); for (const row of rows) stmt.run(row); } function setUserLastDir (username, dirPath) { if (!username) return; const db = getDb(); db.prepare(` INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?) ON CONFLICT(username) DO UPDATE SET last_dir = excluded.last_dir, updated_at = excluded.updated_at `).run([String(username), String(dirPath || ''), Date.now()]); } function getUserLastDir (username) { if (!username) return null; const db = getDb(); const row = db.prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get([String(username)]); const value = String(row && row.last_dir || '').trim(); return value || null; } function clearUserLastDir (username) { if (!username) return; const db = getDb(); db.prepare('DELETE FROM user_last_navigation WHERE username = ?').run([String(username)]); } /** * Loads config and returns { config, roots } together so both are consistent * and user-folder checks can be performed in route handlers. */ function loadConfigAndRoots () { const config = loadConfig(); return { config, roots: getEffectivePaths(config.paths || []) }; } /** * Returns true when absPath is accessible to the user (either via a * configured root or their personal folder). */ function isAccessiblePath (absPath, roots, user, config) { return resolveRootForUser(absPath, roots, user, config) !== null; } function readableSearchRootsForUser (user, config, roots) { const out = []; for (const root of roots) { const label = path.basename(root); if (canRead(user, label)) out.push(root); } const personal = getUserFolderPath(config, user && user.username); if (personal) out.push(personal); // Deduplicate by resolved path. const seen = new Set(); return out.filter((p) => { const key = path.resolve(p); if (seen.has(key)) return false; seen.add(key); return true; }); } const SEARCHABLE_IMAGE_EXTS = new Set([ '.png', '.jpg', '.jpeg', '.webp', '.gif', '.bmp', '.svg', '.avif', '.ico', '.tif', '.tiff', '.heif', '.heic', ]); function isSearchableImageFileName (name) { const ext = path.extname(String(name || '')).toLowerCase(); return SEARCHABLE_IMAGE_EXTS.has(ext); } async function searchImagesWithThumbnailsInRoots (query, roots, maxResults) { const limit = Math.max(1, Math.min(120, Number(maxResults) || 60)); const candidateLimit = Math.min(250, Math.max(limit * 4, 80)); const indexed = await searchFiles(query, roots, candidateLimit); const thumbnailedPaths = await getThumbnailManifestSourcePathSet(); const results = []; for (const item of indexed) { if (!isSearchableImageFileName(item.name)) continue; if (!thumbnailedPaths.has(path.resolve(item.path))) continue; const { score, ...rest } = item; results.push(rest); if (results.length >= limit) break; } return { results, scannedFiles: indexed.length, truncated: indexed.length >= candidateLimit, }; } function rootAliasesFromConfig (config) { if (!config || typeof config !== 'object') return {}; if (!config.rootAliases || typeof config.rootAliases !== 'object') return {}; return config.rootAliases; } function getFreeBytes (targetPath) { if (typeof fs.statfsSync !== 'function') return null; try { const stat = fs.statfsSync(targetPath); if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null; return stat.bavail * stat.bsize; } catch { return null; } } function getRecursiveSize (targetPath) { try { const stat = fs.statSync(targetPath); if (!stat.isDirectory()) return stat.size; } catch { return 0; } let total = 0; let entries = []; try { entries = fs.readdirSync(targetPath, { withFileTypes: true }); } catch { return 0; } for (const entry of entries) { const child = path.join(targetPath, entry.name); if (entry.isDirectory()) { total += getRecursiveSize(child); continue; } try { total += fs.statSync(child).size; } catch { // Ignore files that disappear during traversal. } } return total; } /** * Verify that the user has read access to the given configured-path label. * `pathLabel` is the base-name of the effective path (shown in the UI). */ function canRead (user, pathLabel) { if (user.isAdmin) return true; return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read); } function canWrite (user, pathLabel) { if (user.isAdmin) return true; return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write); } // --------------------------------------------------------------------------- // User folder helpers // --------------------------------------------------------------------------- /** * Returns the absolute path of the user's personal folder, or null. * e.g. /data/userfolders/ */ function getUserFolderPath (config, username) { const base = typeof config.userPath === 'string' ? config.userPath.trim() : ''; if (!base) return null; return path.join(base, String(username)); } function getUserFolderRootPath (config) { const base = typeof config.userPath === 'string' ? config.userPath.trim() : ''; if (!base) return null; return path.resolve(base); } function existingUsernamesLowerSet () { const db = getDb(); const rows = db.prepare('SELECT username FROM users').all(); return new Set(rows.map((row) => String(row.username || '').toLowerCase())); } /** * Resolves a request path against both the configured roots AND the user's * personal folder. Returns { root, label, isUserFolder } or null. * - isUserFolder: true when the path is inside the user's personal folder. */ function resolveRootForUser (absPath, roots, user, config) { if (user && user.isAdmin && pathInsideResolved(absPath, SUBTITLE_DEBUG_LOG_DIR)) { return { root: SUBTITLE_DEBUG_LOG_DIR, label: 'Subtitle Logs', isUserFolder: false, isDebugLogFolder: true, }; } // Regular configured roots first. const matched = getAllowedRoot(absPath, roots); if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false }; // Check user personal folder. if (!user || !user.username) return null; const userFolder = getUserFolderPath(config, user.username); if (!userFolder) return null; const resolved = path.resolve(absPath); const resolvedFolder = path.resolve(userFolder); if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep)) { return { root: userFolder, label: path.basename(userFolder), isUserFolder: true }; } // Admins can access orphaned user folders (folders without a matching account). if (user && user.isAdmin) { const userFolderRoot = getUserFolderRootPath(config); if (!userFolderRoot) return null; const relative = path.relative(userFolderRoot, resolved); if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null; const parts = relative.split(path.sep).filter(Boolean); if (!parts.length) return null; const folderName = parts[0]; const usernames = existingUsernamesLowerSet(); if (usernames.has(String(folderName).toLowerCase())) return null; const orphanRoot = path.join(userFolderRoot, folderName); return { root: orphanRoot, label: folderName, isUserFolder: false, isOrphanUserFolder: true, }; } return null; } /** * Checks whether the user has READ access to the resolved root info object * returned by resolveRootForUser. */ function canReadInfo (user, info) { if (!info) return false; if (info.isUserFolder) return true; // owner always has full access if (info.isOrphanUserFolder) return !!(user && user.isAdmin); if (info.isDebugLogFolder) return !!(user && user.isAdmin); return canRead(user, info.label); } /** * Checks whether the user has WRITE access to the resolved root info object. */ function canWriteInfo (user, info) { if (!info) return false; if (info.isUserFolder) return true; if (info.isOrphanUserFolder) return !!(user && user.isAdmin); if (info.isDebugLogFolder) return !!(user && user.isAdmin); return canWrite(user, info.label); } /** * Returns the size limit (bytes) for the user's personal folder, or null = unlimited. */ function getUserFolderSizeLimit (config) { const lim = Number(config.userFolderSizeLimit); return Number.isFinite(lim) && lim > 0 ? lim : null; } /** * Returns an error message if adding `addedBytes` to the user's folder would * exceed the size limit, or null if within limits. */ function checkUserFolderSizeLimit (config, username, addedBytes) { const limit = getUserFolderSizeLimit(config); if (!limit) return null; const userFolder = getUserFolderPath(config, username); if (!userFolder) return null; const currentSize = getRecursiveSize(userFolder); if (currentSize + addedBytes > limit) { return `Your personal folder is full (limit ${formatBytesServer(limit)}, used ${formatBytesServer(currentSize)}).`; } return null; } function formatBytesServer (bytes) { if (bytes >= 1024 ** 3) return `${(bytes / 1024 ** 3).toFixed(1)} GB`; if (bytes >= 1024 ** 2) return `${(bytes / 1024 ** 2).toFixed(1)} MB`; if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`; return `${bytes} B`; } /** * Given an absolute path and the effective-paths list, return * { root, label } where label is the base-name of the root, or null. */ function resolveRoot (absPath, roots) { const matchedRoot = getAllowedRoot(absPath, roots); if (!matchedRoot) return null; return { root: matchedRoot, label: path.basename(matchedRoot) }; } function sameResolvedPath (a, b) { return path.resolve(String(a || '')) === path.resolve(String(b || '')); } function pathInsideResolved (child, root) { const relative = path.relative(path.resolve(root), path.resolve(child)); return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative)); } function uploadedAtFromStat (stat) { if (!stat || typeof stat !== 'object') return null; const birthtimeMs = Number(stat.birthtimeMs); const ctimeMs = Number(stat.ctimeMs); const mtimeMs = Number(stat.mtimeMs); const chosenMs = (Number.isFinite(birthtimeMs) && birthtimeMs > 0) ? birthtimeMs : (Number.isFinite(ctimeMs) && ctimeMs > 0) ? ctimeMs : (Number.isFinite(mtimeMs) && mtimeMs > 0) ? mtimeMs : null; if (!Number.isFinite(chosenMs) || chosenMs <= 0) return null; return new Date(chosenMs).toISOString(); } function rewriteMetaPaths (fromPath, toPath) { const db = getDb(); const columns = db.prepare('PRAGMA table_info(file_meta)').all() .map((col) => String(col.name || '')) .filter(Boolean); if (!columns.includes('file_path')) return; const quotedColumns = columns.map((col) => `"${col}"`).join(', '); const rows = db.prepare(`SELECT ${quotedColumns} FROM file_meta WHERE file_path = ? OR file_path LIKE ?`) .all([fromPath, fromPath + path.sep + '%']); if (!rows.length) return; const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?'); const placeholders = columns.map(() => '?').join(', '); const updateAssignments = columns .filter((col) => col !== 'file_path') .map((col) => `"${col}" = excluded."${col}"`) .join(',\n '); const upsert = db.prepare(` INSERT INTO file_meta (${quotedColumns}) VALUES (${placeholders}) ON CONFLICT(file_path) DO UPDATE SET ${updateAssignments} `); for (const row of rows) { const nextPath = row.file_path === fromPath ? toPath : toPath + row.file_path.slice(fromPath.length); del.run([row.file_path]); const movedRow = { ...row, file_path: nextPath, }; upsert.run(columns.map((col) => movedRow[col])); } } function parseJsonArray (raw) { try { const value = JSON.parse(raw || '[]'); return Array.isArray(value) ? value : []; } catch { return []; } } function parseJsonObject (raw) { try { const value = JSON.parse(raw || '{}'); if (!value || typeof value !== 'object' || Array.isArray(value)) return {}; return value; } catch { return {}; } } function watchStatusForProgress (progress) { if (!Number.isFinite(progress) || progress < 0) return null; if (progress >= 0.7) return 'fully'; if (progress >= 0.05) return 'partway'; return null; } function normalisedWatchedStatus (value) { const status = String(value || '').toLowerCase(); return status === 'fully' || status === 'partway' ? status : null; } function splitNameExt (name) { const dot = String(name || '').lastIndexOf('.'); if (dot <= 0) return { stem: String(name || ''), ext: '' }; return { stem: String(name).slice(0, dot), ext: String(name).slice(dot), }; } function pickNumberedPath (dir, requestedName) { const parsed = splitNameExt(requestedName); const stem = parsed.stem || 'file'; const ext = parsed.ext || ''; let index = 1; while (index <= 10000) { const candidateName = `${stem} (${index})${ext}`; const candidatePath = path.join(dir, candidateName); if (!fs.existsSync(candidatePath)) return candidatePath; index++; } throw new Error('Could not generate a free destination name.'); } function removePathRecursive (targetPath) { const stat = fs.lstatSync(targetPath); if (stat.isDirectory()) { fs.rmSync(targetPath, { recursive: true, force: true }); } else { fs.unlinkSync(targetPath); } } function movePathWithFallback (from, dest) { const stat = fs.lstatSync(from); try { fs.renameSync(from, dest); return 'rename'; } catch (err) { try { if (stat.isDirectory()) { fs.cpSync(from, dest, { recursive: true, force: true, preserveTimestamps: true }); } else { fs.copyFileSync(from, dest); } fs.rmSync(from, { recursive: true, force: true }); return 'copy-delete'; } catch (fallbackErr) { throw fallbackErr || err; } } } // --------------------------------------------------------------------------- // GET /api/files/roots // Returns the effective configured paths the user can read. // Also injects the user's personal folder when userPath is configured. // --------------------------------------------------------------------------- router.get('/roots', requireAuth, (req, res) => { const config = loadConfig(); const roots = getEffectivePaths(config.paths || []); const rootAliases = rootAliasesFromConfig(config); const readable = roots .filter(r => canRead(req.user, path.basename(r))) .map(r => { const originalName = path.basename(r); const alias = String(rootAliases[path.resolve(r)] || '').trim(); return { label: alias || originalName, path: r, originalName, alias: alias || null, }; }); // Inject the user's personal folder when a userPath is configured. if (req.user && req.user.username) { const userFolder = getUserFolderPath(config, req.user.username); if (userFolder) { try { fs.mkdirSync(userFolder, { recursive: true }); } catch { /* non-fatal */ } readable.unshift({ label: 'My Folder', path: userFolder, originalName: req.user.username, alias: 'My Folder', isUserFolder: true, }); } } let lastDir = getUserLastDir(req.user && req.user.username); if (lastDir) { const info = resolveRootForUser(lastDir, roots, req.user, config); const hasAccess = !!(info && canReadInfo(req.user, info)); let isDir = false; if (hasAccess) { try { isDir = fs.statSync(lastDir).isDirectory(); } catch { isDir = false; } } if (!hasAccess || !isDir) { clearUserLastDir(req.user && req.user.username); lastDir = null; } } res.json({ roots: readable, lastDir }); }); // --------------------------------------------------------------------------- // GET /api/files/root-access?rootPath= // Returns users that can access a configured root and their mode (R / R+W). // --------------------------------------------------------------------------- router.get('/root-access', requireAuth, (req, res) => { const rootPath = String(req.query.rootPath || '').trim(); if (!rootPath) { return res.status(400).json({ error: 'rootPath is required.' }); } const config = loadConfig(); const roots = getEffectivePaths(config.paths || []); const info = resolveRoot(rootPath, roots); if (!info) return res.status(403).json({ error: 'Access denied.' }); if (!sameResolvedPath(rootPath, info.root)) { return res.status(400).json({ error: 'rootPath must be an exact configured root.' }); } if (!canRead(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } const db = getDb(); const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all(); const users = []; for (const row of rows) { if (row.is_admin === 1) { users.push({ username: row.username, mode: 'R+W' }); continue; } let permissions = {}; try { permissions = JSON.parse(row.permissions || '{}'); } catch { permissions = {}; } const perm = permissions[info.label]; if (!perm || typeof perm !== 'object') continue; const canWriteRoot = !!perm.write; const canReadRoot = !!perm.read || canWriteRoot; if (!canReadRoot) continue; users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' }); } users.sort((a, b) => { const modeRank = (mode) => mode === 'R+W' ? 0 : 1; const byMode = modeRank(a.mode) - modeRank(b.mode); if (byMode !== 0) return byMode; return String(a.username).localeCompare(String(b.username)); }); const rootAliases = rootAliasesFromConfig(config); const alias = String(rootAliases[path.resolve(info.root)] || '').trim(); res.json({ root: { path: info.root, label: alias || info.label, originalName: info.label, alias: alias || null, }, users, }); }); // --------------------------------------------------------------------------- // POST /api/files/root-alias // Body: { rootPath: , alias: } // Sets a display-only alias for a configured root. // --------------------------------------------------------------------------- router.post('/root-alias', requireAuth, (req, res) => { const rootPath = String(req.body && req.body.rootPath || '').trim(); const alias = String(req.body && req.body.alias || '').trim(); if (!rootPath || !alias) { return res.status(400).json({ error: 'rootPath and alias are required.' }); } const roots = effectivePaths(); const info = resolveRoot(rootPath, roots); if (!info) return res.status(403).json({ error: 'Access denied.' }); if (!sameResolvedPath(rootPath, info.root)) { return res.status(400).json({ error: 'rootPath must be an exact configured root.' }); } if (!canWrite(req.user, info.label)) { return res.status(403).json({ error: 'Access denied.' }); } const config = loadConfig(); const rootAliases = rootAliasesFromConfig(config); const key = path.resolve(info.root); if (alias === info.label) { delete rootAliases[key]; } else { rootAliases[key] = alias; } config.rootAliases = rootAliases; saveConfig(config); res.json({ ok: true, root: { path: info.root, label: alias, originalName: info.label, alias, }, }); }); // --------------------------------------------------------------------------- // GET /api/files/list?dir= // Lists files and folders in the given directory. // --------------------------------------------------------------------------- router.get('/list', requireAuth, async (req, res) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) return res.status(403).json({ error: 'Access denied.' }); if (envFlagEnabled('FILEMANAGER_LIST_ACCESS_CHMOD')) { try { applyListAccessChmod(dir); } catch (err) { logError('Best-effort shallow chmod pass failed before directory listing.', err, { dir: String(dir || '') }); } } let entries; try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { return res.status(404).json({ error: 'Directory not found.' }); } const fullPaths = entries.map((e) => path.join(dir, e.name)); const db = getDb(); const uploadedAtByPath = loadUploadedAtByPaths(db, fullPaths); const metaUpserts = []; const statResults = await Promise.all(fullPaths.map(async (fullPath) => { try { return { fullPath, stat: await fs.promises.stat(fullPath) }; } catch { return { fullPath, stat: null }; } })); const statByPath = new Map(statResults.map((row) => [row.fullPath, row.stat])); const items = entries.map((e) => { const fullPath = path.join(dir, e.name); const stat = statByPath.get(fullPath); let size = null; let mtime = null; let uploadedAt = null; if (stat) { size = stat.size; mtime = stat.mtime.toISOString(); uploadedAt = uploadedAtByPath.get(fullPath) || uploadedAtFromStat(stat) || null; if (uploadedAt && !uploadedAtByPath.has(fullPath)) { metaUpserts.push([fullPath, '', '[]', '{}', uploadedAt]); } } return { name: e.name, isDir: e.isDirectory(), size, mtime, uploadedAt, path: fullPath, }; }); try { persistMissingUploadedAt(db, metaUpserts); } catch { // Non-fatal metadata persistence. } try { setUserLastDir(req.user && req.user.username, dir); } catch { // Non-fatal preference persistence. } res.json({ items }); }); // --------------------------------------------------------------------------- // GET /api/files/search?query=&limit= // Fuzzy-searches all readable roots for files. // --------------------------------------------------------------------------- router.get('/search', requireAuth, async (req, res) => { const query = String(req.query.query || '').trim(); if (!query) return res.status(400).json({ error: 'query is required.' }); const { config, roots } = loadConfigAndRoots(); const readableRoots = readableSearchRootsForUser(req.user, config, roots) .filter((rootPath) => { try { return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory(); } catch { return false; } }); const results = await searchFiles(query, readableRoots, req.query.limit); res.json({ query, results, }); }); // --------------------------------------------------------------------------- // GET /api/files/search-images?query=&limit= // Fuzzy-searches readable roots for image files that have ready thumbnails. // --------------------------------------------------------------------------- router.get('/search-images', requireAuth, async (req, res) => { const query = String(req.query.query || '').trim(); if (!query) return res.status(400).json({ error: 'query is required.' }); if (query.length < 2) return res.status(400).json({ error: 'query must be at least 2 characters.' }); const { config, roots } = loadConfigAndRoots(); const readableRoots = readableSearchRootsForUser(req.user, config, roots) .filter((rootPath) => { try { return fs.existsSync(rootPath) && fs.statSync(rootPath).isDirectory(); } catch { return false; } }); const { results, scannedFiles, truncated } = await searchImagesWithThumbnailsInRoots( query, readableRoots, req.query.limit, ); res.json({ query, results, scannedFiles, truncated, }); }); // --------------------------------------------------------------------------- // GET /api/files/meta?file= // Returns file metadata from the DB. Lazily computes SHA-256 when missing. // --------------------------------------------------------------------------- router.get('/meta', requireAuth, async (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(file, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } let stat; try { stat = fs.statSync(file); } catch { return res.status(404).json({ error: 'File not found.' }); } const db = getDb(); let meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); let uploadedAt = meta ? String(meta.uploaded_at || '').trim() : ''; if (!uploadedAt) { uploadedAt = uploadedAtFromStat(stat) || ''; if (uploadedAt) { db.prepare(` INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(file_path) DO UPDATE SET uploaded_at = COALESCE(NULLIF(file_meta.uploaded_at, ''), excluded.uploaded_at) `).run([file, '', '[]', '{}', uploadedAt]); meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); } } let sha256 = meta ? (meta.sha256 || null) : null; if (!sha256 && !stat.isDirectory()) { enqueueFileHash(file); } res.json({ name: path.basename(file), size: stat.size, mtime: stat.mtime.toISOString(), uploadedAt: uploadedAt || null, uploader: meta ? meta.uploader : '', downloaders: meta ? parseJsonArray(meta.downloaders) : [], watchedBy: meta ? parseJsonObject(meta.watched_by) : {}, sha256: sha256 || null, }); }); // --------------------------------------------------------------------------- // GET /api/files/duplicates?file= // Returns other files with the same SHA-256 hash that the user can access. // --------------------------------------------------------------------------- router.get('/duplicates', requireAuth, (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(file, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } const db = getDb(); const row = db.prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([file]); const hash = row ? (row.sha256 || null) : null; if (!hash) { enqueueFileHash(file); return res.json({ duplicates: [] }); } // All other files sharing the same hash. const candidates = db.prepare( 'SELECT file_path FROM file_meta WHERE sha256 = ? AND file_path != ?', ).all([hash, file]); const duplicates = []; for (const { file_path } of candidates) { // Only return files inside a root the user can access and that still exist on disk. const dupInfo = resolveRootForUser(file_path, roots, req.user, config); if (!dupInfo || !canReadInfo(req.user, dupInfo)) continue; if (!fs.existsSync(file_path)) continue; const rel = path.relative(dupInfo.root, file_path); const relativePath = rel && rel !== '' ? rel : path.basename(file_path); duplicates.push({ path: file_path, name: path.basename(file_path), dir: path.dirname(file_path), rootPath: dupInfo.root, relativePath, }); } res.json({ duplicates }); }); // --------------------------------------------------------------------------- // GET /api/files/space?dir= // Returns recursive used bytes for dir and available bytes on its root fs. // --------------------------------------------------------------------------- router.get('/space', requireAuth, (req, res) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(dir)) { return res.status(404).json({ error: 'Path not found.' }); } const usedBytes = getRecursiveSize(dir); const freeBytes = getFreeBytes(info.root); const userLimitBytes = info.isUserFolder ? getUserFolderSizeLimit(config) : null; const userFreeBytes = userLimitBytes == null ? null : Math.max(0, userLimitBytes - usedBytes); res.json({ usedBytes, freeBytes, userLimitBytes, userFreeBytes, rootPath: info.root, rootLabel: info.label, }); }); // --------------------------------------------------------------------------- // GET /api/files/download?file= // Streams the file to the client; records the download. // --------------------------------------------------------------------------- router.get('/download', requireAuth, (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(file, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } // Record download const db = getDb(); const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); const uploadedAt = (() => { try { return uploadedAtFromStat(fs.statSync(file)); } catch { return null; } })(); if (meta) { const downloaders = parseJsonArray(meta.downloaders); if (!downloaders.includes(req.user.username)) { downloaders.push(req.user.username); db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?') .run([JSON.stringify(downloaders), file]); } } else { db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)') .run([file, '', JSON.stringify([req.user.username]), '{}', uploadedAt]); } res.download(file, path.basename(file)); }); // --------------------------------------------------------------------------- // POST /api/files/watched-statuses // Body: { filePaths: [, ...] } // Returns per-path watched status for the authenticated user. // --------------------------------------------------------------------------- router.post('/watched-statuses', requireAuth, (req, res) => { const rawPaths = req.body && Array.isArray(req.body.filePaths) ? req.body.filePaths : null; if (!rawPaths) { return res.status(400).json({ error: 'filePaths array is required.' }); } const paths = rawPaths .map((p) => String(p || '').trim()) .filter(Boolean) .slice(0, 500); const { config, roots } = loadConfigAndRoots(); const db = getDb(); const statuses = {}; const selectMeta = db.prepare('SELECT watched_by FROM file_meta WHERE file_path = ?'); for (const filePath of paths) { const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) continue; let stat; try { stat = fs.statSync(filePath); } catch { continue; } if (stat.isDirectory()) continue; const row = selectMeta.get([filePath]); const watchedBy = parseJsonObject(row && row.watched_by); const status = normalisedWatchedStatus(watchedBy[req.user.username]); if (status) statuses[filePath] = status; } res.json({ statuses }); }); // --------------------------------------------------------------------------- // POST /api/files/watch-progress // Body: { filePath: , progress: <0..1> } // Records per-user video watch state for sidebar display. // --------------------------------------------------------------------------- router.post('/watch-progress', requireAuth, (req, res) => { const filePath = String(req.body && req.body.filePath || '').trim(); const progress = Number(req.body && req.body.progress); if (!filePath) return res.status(400).json({ error: 'filePath is required.' }); const status = watchStatusForProgress(progress); if (!status) { return res.json({ ok: true, updated: false }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } let fileStat; try { fileStat = fs.statSync(filePath); } catch { return res.status(404).json({ error: 'File not found.' }); } if (fileStat.isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const db = getDb(); const row = db.prepare('SELECT uploader, downloaders, watched_by FROM file_meta WHERE file_path = ?').get([filePath]); const watchedBy = parseJsonObject(row && row.watched_by); const prev = String(watchedBy[req.user.username] || '').toLowerCase(); const next = prev === 'fully' ? 'fully' : status; if (prev === next) { return res.json({ ok: true, updated: false, status: next }); } watchedBy[req.user.username] = next; if (row) { db.prepare('UPDATE file_meta SET watched_by = ? WHERE file_path = ?') .run([JSON.stringify(watchedBy), filePath]); } else { db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at) VALUES (?, ?, ?, ?, ?)') .run([filePath, '', '[]', JSON.stringify(watchedBy), uploadedAtFromStat(fileStat)]); } res.json({ ok: true, updated: true, status: next }); }); // --------------------------------------------------------------------------- // POST /api/files/video-stream // Authenticated. Creates a short-lived ffmpeg-backed HLS session for a video. // --------------------------------------------------------------------------- router.post('/video-stream', requireAuth, async (req, res, next) => { try { const filePath = String(req.body?.filePath || '').trim(); if (!filePath) return res.status(400).json({ error: 'filePath is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const session = await createVideoStreamSession(filePath); res.json({ sessionId: session.sessionId, playlistUrl: `/api/files/video-stream/${session.sessionId}/master.m3u8`, durationSeconds: session.durationSeconds || null, videoWidth: session.videoWidth || null, videoHeight: session.videoHeight || null, subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, imageBased: 0, skipped: 0 }, subtitleTracks: session.subtitleTracks.map((track) => ({ label: track.label, language: track.language, default: !!track.isDefault, src: `/api/files/video-stream/${session.sessionId}/${track.fileName}`, })), imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({ label: track.label, language: track.language, default: !!track.isDefault, streamIndex: track.streamIndex, })), }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // GET /api/files/video-stream/:sessionId/:assetPath(*) // Streams HLS assets for a previously created short-lived video session. // --------------------------------------------------------------------------- router.get('/video-stream/:sessionId/:assetPath(*)', async (req, res, next) => { try { await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, req, res); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // DELETE /api/files/video-stream/:sessionId // Authenticated. Explicitly releases an active short-lived video session. // --------------------------------------------------------------------------- router.delete('/video-stream/:sessionId', requireAuth, (req, res) => { const sessionId = String(req.params.sessionId || '').trim(); if (!sessionId) return res.status(400).json({ error: 'sessionId is required.' }); releaseVideoStreamSession(sessionId); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // GET /api/files/video-stream-subtitle-frame // Authenticated. Returns a rendered PNG subtitle bitmap at a given timestamp. // Query params: filePath, streamIndex, timeSeconds // --------------------------------------------------------------------------- router.get('/video-stream-subtitle-frame', requireAuth, async (req, res, next) => { const requestReceivedAtMs = Date.now(); try { const filePath = String(req.query.filePath || '').trim(); const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10); const timeSeconds = Number.parseFloat(String(req.query.timeSeconds || ''), 10); const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10); const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10); if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(timeSeconds) || timeSeconds < 0) { return res.status(400).json({ error: 'filePath, streamIndex (non-negative int), and timeSeconds (non-negative number) are required.' }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280; const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720; const frameData = await renderImageSubtitleFrame({ filePath, streamIndex, timeSeconds, canvasWidth, canvasHeight, }); if (!frameData || !frameData.frame) { res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'none'); return res.status(204).end(); } res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'ok'); res.set('X-Subtitle-Frame-Left', String(frameData.left || 0)); res.set('X-Subtitle-Frame-Top', String(frameData.top || 0)); res.set('X-Subtitle-Frame-Width', String(frameData.width || 0)); res.set('X-Subtitle-Frame-Height', String(frameData.height || 0)); res.set('X-Subtitle-Frame-Canvas-Width', String(frameData.canvasWidth || 1280)); res.set('X-Subtitle-Frame-Canvas-Height', String(frameData.canvasHeight || 720)); res.set('X-Subtitle-Frame-Start-Time', String(frameData.startTimeSeconds || 0)); res.set('X-Subtitle-Frame-End-Time', String(frameData.endTimeSeconds || 0)); res.set('Content-Type', 'image/png'); res.set('Cache-Control', 'private, max-age=3600'); res.send(frameData.frame); } catch (err) { logError('Subtitle frame extraction failed', err, { filePath: String(req.query.filePath || ''), streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10), timeSeconds: Number.parseFloat(String(req.query.timeSeconds || ''), 10), }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.set('X-Subtitle-Frame-Status', 'error'); return res.status(204).end(); } }); // --------------------------------------------------------------------------- // GET /api/files/video-stream-subtitle-range // Authenticated. Returns rendered PNG subtitle bitmaps overlapping a time range. // Query params: filePath, streamIndex, startTimeSeconds, endTimeSeconds // --------------------------------------------------------------------------- router.get('/video-stream-subtitle-range', requireAuth, async (req, res) => { const requestReceivedAtMs = Date.now(); try { const filePath = String(req.query.filePath || '').trim(); const streamIndex = Number.parseInt(String(req.query.streamIndex || ''), 10); const startTimeSeconds = Number.parseFloat(String(req.query.startTimeSeconds || ''), 10); const endTimeSeconds = Number.parseFloat(String(req.query.endTimeSeconds || ''), 10); const videoWidth = Number.parseInt(String(req.query.videoWidth || ''), 10); const videoHeight = Number.parseInt(String(req.query.videoHeight || ''), 10); if (!filePath || !Number.isInteger(streamIndex) || streamIndex < 0 || !Number.isFinite(startTimeSeconds) || startTimeSeconds < 0 || !Number.isFinite(endTimeSeconds) || endTimeSeconds < startTimeSeconds) { return res.status(400).json({ error: 'filePath, streamIndex, startTimeSeconds, and endTimeSeconds are required.' }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const canvasWidth = Number.isInteger(videoWidth) && videoWidth > 0 ? videoWidth : 1280; const canvasHeight = Number.isInteger(videoHeight) && videoHeight > 0 ? videoHeight : 720; const result = await renderImageSubtitleFramesInRange({ filePath, streamIndex, startTimeSeconds, endTimeSeconds, canvasWidth, canvasHeight, }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); res.json({ status: 'ok', startTimeSeconds, endTimeSeconds, frames: Array.isArray(result && result.frames) ? result.frames.map((frame) => ({ left: frame.left || 0, top: frame.top || 0, width: frame.width || 0, height: frame.height || 0, canvasWidth: frame.canvasWidth || canvasWidth, canvasHeight: frame.canvasHeight || canvasHeight, startTimeSeconds: frame.startTimeSeconds || 0, endTimeSeconds: frame.endTimeSeconds || 0, contentType: 'image/png', frameBase64: Buffer.from(frame.frame || Buffer.alloc(0)).toString('base64'), })) : [], }); } catch (err) { logError('Subtitle range extraction failed', err, { filePath: String(req.query.filePath || ''), streamIndex: Number.parseInt(String(req.query.streamIndex || ''), 10), startTimeSeconds: Number.parseFloat(String(req.query.startTimeSeconds || ''), 10), endTimeSeconds: Number.parseFloat(String(req.query.endTimeSeconds || ''), 10), }); res.set('X-Subtitle-Request-Received-At-Ms', String(requestReceivedAtMs)); res.set('X-Subtitle-Response-Sent-At-Ms', String(Date.now())); return res.status(200).json({ status: 'error', frames: [] }); } }); // --------------------------------------------------------------------------- // POST /api/files/video-stream-subtitle-log // Authenticated. Persists client-side subtitle timing diagnostics to local cache. // Body: { filePath, sessionId?, entries[] } // --------------------------------------------------------------------------- router.post('/video-stream-subtitle-log', requireAuth, (req, res) => { try { const filePath = String(req.body && req.body.filePath || '').trim(); const entries = Array.isArray(req.body && req.body.entries) ? req.body.entries : null; const sessionId = String(req.body && req.body.sessionId || '').trim(); if (!filePath || !entries || !entries.length) { return res.status(400).json({ error: 'filePath and entries are required.' }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } appendSubtitleDebugEntries({ videoName: path.basename(filePath), entries, context: { source: 'app', filePath, sessionId: sessionId || null, username: String(req.user && req.user.username || '').trim() || null, }, }); return res.json({ ok: true }); } catch (err) { logError('Subtitle debug log write failed', err, { filePath: String(req.body && req.body.filePath || ''), entryCount: Array.isArray(req.body && req.body.entries) ? req.body.entries.length : 0, }); return res.status(500).json({ error: 'Subtitle debug log write failed.' }); } }); // --------------------------------------------------------------------------- // GET /api/files/download-zip?dir= // Authenticated. Streams a zip of the given directory. // --------------------------------------------------------------------------- router.get('/download-zip', requireAuth, async (req, res) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } // Use a hash of the dir path as cache key so concurrent users share the cache. const cacheKey = crypto.createHash('sha256').update(dir).digest('hex'); try { const zipPath = await buildZip(dir, cacheKey); const zipName = `${path.basename(dir)}.zip`; res.download(zipPath, zipName); } catch (err) { res.status(500).json({ error: 'Failed to create zip archive.' }); } }); // --------------------------------------------------------------------------- // GET /api/files/preview-image?file= // Converts HEIF/HEIC sources to WebP for in-browser preview. // --------------------------------------------------------------------------- router.get('/preview-image', requireAuth, async (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(file, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } if (!needsPreviewImageConversion(file)) { return res.status(400).json({ error: 'Preview conversion is not available for this file type.' }); } let stat; try { stat = fs.statSync(file); } catch { return res.status(404).json({ error: 'File not found.' }); } if (stat.size > MAX_PREVIEW_IMAGE_BYTES) { return res.status(413).json({ error: 'File too large for inline preview.' }); } try { await streamPreviewImage(file, res); } catch (err) { logError('preview-image', err); if (!res.headersSent) { res.status(500).json({ error: 'Failed to generate preview image.' }); } } }); // --------------------------------------------------------------------------- // GET /api/files/thumbnail?file= // Returns a pre-generated cached thumbnail if present. // --------------------------------------------------------------------------- router.get('/thumbnail', requireAuth, async (req, res) => { const file = req.query.file; if (!file) return res.status(400).json({ error: 'file is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(file, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const thumb = await getCachedThumbnailInfo(file); if (!thumb) { return res.status(404).json({ error: 'Thumbnail not ready.' }); } res.type(thumb.contentType); res.set('Cache-Control', `private, max-age=${THUMB_HTTP_MAX_AGE_SEC}`); res.sendFile(thumb.thumbPath); }); // --------------------------------------------------------------------------- // POST /api/files/upload?dir= // Accepts multipart file upload. // --------------------------------------------------------------------------- router.post('/upload', requireAuth, (req, res, next) => { const dir = req.query.dir; if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canWriteInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } const announcedSize = Number(req.header('x-upload-size') || 0); if (Number.isFinite(announcedSize) && announcedSize > 0) { const freeBytes = getFreeBytes(info.root); if (typeof freeBytes === 'number' && announcedSize > freeBytes) { return res.status(413).json({ error: 'Upload too large for remaining free space on selected root.', freeBytes, requiredBytes: announcedSize, }); } } // Enforce per-user folder size limit when uploading to a user folder. if (info.isUserFolder) { const addBytes = announcedSize > 0 ? announcedSize : 0; const limitError = checkUserFolderSizeLimit(config, req.user.username, addBytes); if (limitError) return res.status(413).json({ error: limitError }); } req._uploadDir = dir; upload.array('files')(req, res, async (err) => { if (err) return res.status(500).json({ error: err.message }); const db = getDb(); for (const f of (req.files || [])) { const filePath = path.join(dir, f.originalname); const uploadedAt = new Date().toISOString(); const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]); if (existing) { db.prepare('UPDATE file_meta SET uploader = ?, sha256 = NULL, uploaded_at = ? WHERE file_path = ?') .run([req.user.username, uploadedAt, filePath]); } else { db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)') .run([filePath, req.user.username, '[]', '{}', uploadedAt, null]); } enqueueFileHash(filePath); } try { await reindexDirectoryTree(dir); } catch { // Non-fatal search index refresh. } res.json({ uploaded: (req.files || []).map(f => f.originalname) }); }); }); // --------------------------------------------------------------------------- // POST /api/files/rename // Body: { from: , to: } (to = just the filename, not full path) // --------------------------------------------------------------------------- router.post('/rename', requireAuth, (req, res) => { const { from, to } = req.body; if (!from || !to) return res.status(400).json({ error: 'from and to are required.' }); // Prevent path traversal in the new name if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) { return res.status(400).json({ error: 'Invalid name.' }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(from, roots, req.user, config); if (!info || !canWriteInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } const dest = path.join(path.dirname(from), to); // Ensure dest is still inside the same accessible root or user folder. if (!isAccessiblePath(dest, roots, req.user, config)) { return res.status(403).json({ error: 'Access denied.' }); } try { movePathWithFallback(from, dest); } catch (err) { return res.status(500).json({ error: err.message }); } rewriteMetaPaths(from, dest); rewriteIndexPaths(from, dest); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // POST /api/files/move // Body: { from: , toDir: } // --------------------------------------------------------------------------- router.post('/move', requireAuth, (req, res) => { const { from, toDir } = req.body; const conflict = String(req.body && req.body.conflict || 'error').toLowerCase(); const targetName = req.body && req.body.targetName != null ? String(req.body.targetName).trim() : ''; if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' }); if (!['error', 'overwrite', 'rename'].includes(conflict)) { return res.status(400).json({ error: 'Invalid conflict strategy.' }); } if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\'))) { return res.status(400).json({ error: 'Invalid targetName.' }); } const { config, roots } = loadConfigAndRoots(); const fromInfo = resolveRootForUser(from, roots, req.user, config); const toInfo = resolveRootForUser(toDir, roots, req.user, config); if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' }); if (!canWriteInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo)) { return res.status(403).json({ error: 'Access denied.' }); } let sourceStat; let destStat; try { sourceStat = fs.statSync(from); destStat = fs.statSync(toDir); } catch { return res.status(404).json({ error: 'Source or destination not found.' }); } if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' }); const requestedName = targetName || path.basename(from); const requestedDest = path.join(toDir, requestedName); if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' }); // Enforce per-user folder size limit when moving into a user folder. if (toInfo.isUserFolder) { const sourceSize = getRecursiveSize(from); const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceSize); if (limitError) return res.status(413).json({ error: limitError }); } if (sameResolvedPath(from, toDir) || sameResolvedPath(from, requestedDest)) { return res.status(400).json({ error: 'Cannot move onto itself.' }); } if (sourceStat.isDirectory() && pathInsideResolved(toDir, from)) { return res.status(400).json({ error: 'Cannot move a folder into itself.' }); } let dest = requestedDest; let resolvedConflict = 'none'; if (fs.existsSync(requestedDest)) { if (conflict === 'error') { return res.status(409).json({ error: 'Destination already exists.' }); } if (conflict === 'rename') { dest = pickNumberedPath(toDir, requestedName); resolvedConflict = 'rename'; } if (conflict === 'overwrite') { try { removePathRecursive(requestedDest); } catch (err) { return res.status(500).json({ error: err.message }); } resolvedConflict = 'overwrite'; } } if (sameResolvedPath(from, dest)) { return res.status(400).json({ error: 'Cannot move onto itself.' }); } try { movePathWithFallback(from, dest); } catch (err) { return res.status(500).json({ error: err.message }); } rewriteMetaPaths(from, dest); rewriteIndexPaths(from, dest); res.json({ ok: true, path: dest, conflictResolution: resolvedConflict }); }); // --------------------------------------------------------------------------- // POST /api/files/mkdir // Body: { dir: , name: } // --------------------------------------------------------------------------- router.post('/mkdir', requireAuth, (req, res) => { const { dir, name } = req.body; if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' }); if (path.basename(name) !== name) { return res.status(400).json({ error: 'Invalid folder name.' }); } const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canWriteInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } const newDir = path.join(dir, name); if (!isAccessiblePath(newDir, roots, req.user, config)) { return res.status(403).json({ error: 'Access denied.' }); } try { fs.mkdirSync(newDir, { recursive: false }); } catch (err) { return res.status(500).json({ error: err.message }); } res.json({ ok: true, path: newDir }); }); // --------------------------------------------------------------------------- // POST /api/files/delete // Body: { path: } // --------------------------------------------------------------------------- router.post('/delete', requireAuth, (req, res) => { const target = req.body.path; if (!target) return res.status(400).json({ error: 'path is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(target, roots, req.user, config); if (!info || !canWriteInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } // Do not allow deleting a configured root itself if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) { return res.status(403).json({ error: 'Cannot delete a configured root path.' }); } try { const stat = fs.statSync(target); if (stat.isDirectory()) { fs.rmSync(target, { recursive: true, force: true }); } else { fs.unlinkSync(target); } } catch (err) { return res.status(500).json({ error: err.message }); } // Clean up any DB meta entries under that path const db = getDb(); db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?") .run([target, target + path.sep + '%']); deleteIndexUnder(target); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // GET /api/files/folder-images?dir= // Returns files inside dir (recursive) that already have a cached thumbnail. // Only files with a ready cached thumbnail are included. // --------------------------------------------------------------------------- router.get('/folder-images', requireAuth, async (req, res) => { const dir = String(req.query.dir || '').trim(); if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } const files = await getFilesWithThumbnailsInDir(dir); // Filter out any that escaped to a different accessible root (safety check). const filtered = files.filter(({ filePath }) => isAccessiblePath(filePath, roots, req.user, config)); res.json({ images: filtered.map(({ filePath }) => ({ filePath })) }); }); // --------------------------------------------------------------------------- // GET /api/files/folder-icon?dir= // Returns the current icon source file for a folder (explicit or auto-first). // --------------------------------------------------------------------------- router.get('/folder-icon', requireAuth, async (req, res) => { const dir = String(req.query.dir || '').trim(); if (!dir) return res.status(400).json({ error: 'dir is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(dir, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } const sourceFile = await getFolderIconSourceFile(dir); if (!sourceFile) return res.json({ icon: null }); // Verify the source is still accessible within a configured root or user folder. if (!isAccessiblePath(sourceFile, roots, req.user, config)) return res.json({ icon: null }); res.json({ icon: { filePath: sourceFile } }); }); // --------------------------------------------------------------------------- // POST /api/files/folder-icon // Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment. // Requires write access; the image must already have a cached thumbnail. // --------------------------------------------------------------------------- router.post('/folder-icon', requireAuth, async (req, res) => { const folderPath = String((req.body && req.body.folderPath) || '').trim(); const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null; if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' }); const { config, roots } = loadConfigAndRoots(); const info = resolveRootForUser(folderPath, roots, req.user, config); if (!info || !canWriteInfo(req.user, info)) { return res.status(403).json({ error: 'Access denied.' }); } let stat; try { stat = fs.statSync(folderPath); } catch { return res.status(404).json({ error: 'Folder not found.' }); } if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' }); if (rawImage !== null) { // Verify the image is inside a readable root or user folder. if (!isAccessiblePath(rawImage, roots, req.user, config)) return res.status(403).json({ error: 'Image not accessible.' }); // Must already have a cached thumbnail — only thumbnailed images can be selected. const thumb = await getCachedThumbnailInfo(rawImage); if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' }); } await setFolderIconAssignment(folderPath, rawImage); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // GET /api/files/global-favicon-image // Serves the configured global favicon thumbnail file (cache-backed). // Public so can fetch it without auth headers. // --------------------------------------------------------------------------- router.get('/global-favicon-image', async (req, res) => { const config = loadConfig(); const filePath = config && typeof config.globalFaviconPath === 'string' ? config.globalFaviconPath.trim() : ''; if (!filePath) return res.status(404).end(); const thumb = await getCachedThumbnailInfo(filePath); if (!thumb || !thumb.thumbPath) return res.status(404).end(); if (!fs.existsSync(thumb.thumbPath)) return res.status(404).end(); res.type(thumb.contentType || 'image/webp'); res.sendFile(thumb.thumbPath); }); // --------------------------------------------------------------------------- // GET /api/files/global-favicon // Returns the configured global favicon source file path, if any. // --------------------------------------------------------------------------- router.get('/global-favicon', requireAuth, async (req, res) => { const config = loadConfig(); const filePath = config && typeof config.globalFaviconPath === 'string' ? config.globalFaviconPath.trim() : ''; if (!filePath) return res.json({ favicon: null }); const thumb = await getCachedThumbnailInfo(filePath); if (!thumb) return res.json({ favicon: null }); res.json({ favicon: { filePath } }); }); // --------------------------------------------------------------------------- // POST /api/files/global-favicon // Body: { imagePath } where imagePath may be null to clear. // Admin-only route for setting the global favicon source image. // --------------------------------------------------------------------------- router.post('/global-favicon', requireAuth, async (req, res) => { if (!req.user || !req.user.isAdmin) { return res.status(403).json({ error: 'Admin access required.' }); } const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null; const config = loadConfig(); const roots = getEffectivePaths(config.paths || []); if (rawImage !== null) { const info = resolveRootForUser(rawImage, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { return res.status(403).json({ error: 'Image not accessible.' }); } const thumb = await getCachedThumbnailInfo(rawImage); if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' }); } config.globalFaviconPath = rawImage; saveConfig(config); res.json({ ok: true }); }); // --------------------------------------------------------------------------- // POST /api/files/copy // Body: { from: , toDir: } // Copies a file (not a directory) to the destination folder. // Supports conflict: 'error' (default) | 'overwrite' | 'rename' // --------------------------------------------------------------------------- router.post('/copy', requireAuth, async (req, res) => { const { from, toDir } = req.body; const conflict = String(req.body && req.body.conflict || 'error').toLowerCase(); const targetName = req.body && req.body.targetName != null ? String(req.body.targetName).trim() : ''; if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' }); if (!['error', 'overwrite', 'rename'].includes(conflict)) { return res.status(400).json({ error: 'Invalid conflict strategy.' }); } if (targetName && (path.basename(targetName) !== targetName || targetName.includes('/') || targetName.includes('\\'))) { return res.status(400).json({ error: 'Invalid targetName.' }); } const { config, roots } = loadConfigAndRoots(); const fromInfo = resolveRootForUser(from, roots, req.user, config); const toInfo = resolveRootForUser(toDir, roots, req.user, config); if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' }); if (!canReadInfo(req.user, fromInfo) || !canWriteInfo(req.user, toInfo)) { return res.status(403).json({ error: 'Access denied.' }); } let sourceStat; try { sourceStat = fs.statSync(from); } catch { return res.status(404).json({ error: 'Source not found.' }); } if (sourceStat.isDirectory()) { return res.status(400).json({ error: 'Copying directories is not supported.' }); } if (!fs.existsSync(toDir) || !fs.statSync(toDir).isDirectory()) { return res.status(404).json({ error: 'Destination directory not found.' }); } const requestedName = targetName || path.basename(from); const requestedDest = path.join(toDir, requestedName); if (!isAccessiblePath(requestedDest, roots, req.user, config)) return res.status(403).json({ error: 'Access denied.' }); // Enforce per-user folder size limit when copying into a user folder. if (toInfo.isUserFolder) { const limitError = checkUserFolderSizeLimit(config, req.user.username, sourceStat.size); if (limitError) return res.status(413).json({ error: limitError }); } let dest = requestedDest; let resolvedConflict = 'none'; if (fs.existsSync(requestedDest)) { if (conflict === 'error') { return res.status(409).json({ error: 'Destination already exists.' }); } if (conflict === 'rename') { dest = pickNumberedPath(toDir, requestedName); resolvedConflict = 'rename'; } if (conflict === 'overwrite') { resolvedConflict = 'overwrite'; } } try { fs.copyFileSync(from, dest); } catch (err) { return res.status(500).json({ error: err.message }); } try { await reindexDirectoryTree(toDir); } catch { // Non-fatal search index refresh. } enqueueFileHash(dest); res.json({ ok: true, path: dest, conflictResolution: resolvedConflict }); }); // Shared with the sync API (server/api) so both use the same permission rules. router.helpers = { loadConfigAndRoots, resolveRootForUser, canRead, canReadInfo, canWriteInfo, getUserFolderPath, checkUserFolderSizeLimit, rewriteMetaPaths, movePathWithFallback, }; module.exports = router;