| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const path = require('path'); |
| 5 | const fs = require('fs'); |
| 6 | const multer = require('multer'); |
| 7 | const router = express.Router(); |
| 8 | |
| 9 | const { getDb } = require('../db'); |
| 10 | const { loadConfig, saveConfig, getEffectivePaths, getAllowedRoot } = require('../config'); |
| 11 | const { requireAuth } = require('../auth'); |
| 12 | const { getCachedThumbnailInfo, getImagesWithThumbnailsInDir, getFolderIconSourceFile, setFolderIconAssignment } = require('../thumbnail-cache'); |
| 13 | |
| 14 | // --------------------------------------------------------------------------- |
| 15 | // Multer storage — files are written directly to the target directory |
| 16 | // --------------------------------------------------------------------------- |
| 17 | const storage = multer.diskStorage({ |
| 18 | destination (req, file, cb) |
| 19 | { |
| 20 | // The target directory is resolved in the route handler, so we stash it |
| 21 | // during the multer middleware call via req._uploadDir. |
| 22 | cb(null, req._uploadDir); |
| 23 | }, |
| 24 | filename (req, file, cb) |
| 25 | { |
| 26 | cb(null, file.originalname); |
| 27 | }, |
| 28 | }); |
| 29 | |
| 30 | const upload = multer({ |
| 31 | storage, |
| 32 | limits: { fileSize: 10 * 1024 * 1024 * 1024 }, // 10 GB |
| 33 | }); |
| 34 | |
| 35 | // --------------------------------------------------------------------------- |
| 36 | // Helpers |
| 37 | // --------------------------------------------------------------------------- |
| 38 | |
| 39 | function effectivePaths () |
| 40 | { |
| 41 | return getEffectivePaths(loadConfig().paths || []); |
| 42 | } |
| 43 | |
| 44 | function rootAliasesFromConfig (config) |
| 45 | { |
| 46 | if (!config || typeof config !== 'object') return {}; |
| 47 | if (!config.rootAliases || typeof config.rootAliases !== 'object') return {}; |
| 48 | return config.rootAliases; |
| 49 | } |
| 50 | |
| 51 | function getFreeBytes (targetPath) |
| 52 | { |
| 53 | if (typeof fs.statfsSync !== 'function') return null; |
| 54 | try |
| 55 | { |
| 56 | const stat = fs.statfsSync(targetPath); |
| 57 | if (typeof stat.bavail !== 'number' || typeof stat.bsize !== 'number') return null; |
| 58 | return stat.bavail * stat.bsize; |
| 59 | } catch |
| 60 | { |
| 61 | return null; |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | function getRecursiveSize (targetPath) |
| 66 | { |
| 67 | try |
| 68 | { |
| 69 | const stat = fs.statSync(targetPath); |
| 70 | if (!stat.isDirectory()) return stat.size; |
| 71 | } catch |
| 72 | { |
| 73 | return 0; |
| 74 | } |
| 75 | |
| 76 | let total = 0; |
| 77 | let entries = []; |
| 78 | try |
| 79 | { |
| 80 | entries = fs.readdirSync(targetPath, { withFileTypes: true }); |
| 81 | } catch |
| 82 | { |
| 83 | return 0; |
| 84 | } |
| 85 | |
| 86 | for (const entry of entries) |
| 87 | { |
| 88 | const child = path.join(targetPath, entry.name); |
| 89 | if (entry.isDirectory()) |
| 90 | { |
| 91 | total += getRecursiveSize(child); |
| 92 | continue; |
| 93 | } |
| 94 | try |
| 95 | { |
| 96 | total += fs.statSync(child).size; |
| 97 | } catch |
| 98 | { |
| 99 | // Ignore files that disappear during traversal. |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | return total; |
| 104 | } |
| 105 | |
| 106 | /** |
| 107 | * Verify that the user has read access to the given configured-path label. |
| 108 | * `pathLabel` is the base-name of the effective path (shown in the UI). |
| 109 | */ |
| 110 | function canRead (user, pathLabel) |
| 111 | { |
| 112 | if (user.isAdmin) return true; |
| 113 | return !!(user.permissions[pathLabel] && user.permissions[pathLabel].read); |
| 114 | } |
| 115 | |
| 116 | function canWrite (user, pathLabel) |
| 117 | { |
| 118 | if (user.isAdmin) return true; |
| 119 | return !!(user.permissions[pathLabel] && user.permissions[pathLabel].write); |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Given an absolute path and the effective-paths list, return |
| 124 | * { root, label } where label is the base-name of the root, or null. |
| 125 | */ |
| 126 | function resolveRoot (absPath, roots) |
| 127 | { |
| 128 | const matchedRoot = getAllowedRoot(absPath, roots); |
| 129 | if (!matchedRoot) return null; |
| 130 | return { root: matchedRoot, label: path.basename(matchedRoot) }; |
| 131 | } |
| 132 | |
| 133 | function sameResolvedPath (a, b) |
| 134 | { |
| 135 | return path.resolve(String(a || '')) === path.resolve(String(b || '')); |
| 136 | } |
| 137 | |
| 138 | function pathInsideResolved (child, root) |
| 139 | { |
| 140 | const relative = path.relative(path.resolve(root), path.resolve(child)); |
| 141 | return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative); |
| 142 | } |
| 143 | |
| 144 | function rewriteMetaPaths (fromPath, toPath) |
| 145 | { |
| 146 | const db = getDb(); |
| 147 | const rows = db.prepare('SELECT file_path, uploader, downloaders FROM file_meta WHERE file_path = ? OR file_path LIKE ?') |
| 148 | .all([fromPath, fromPath + path.sep + '%']); |
| 149 | |
| 150 | if (!rows.length) return; |
| 151 | |
| 152 | const del = db.prepare('DELETE FROM file_meta WHERE file_path = ?'); |
| 153 | const upsert = db.prepare(` |
| 154 | INSERT INTO file_meta (file_path, uploader, downloaders) |
| 155 | VALUES (?, ?, ?) |
| 156 | ON CONFLICT(file_path) DO UPDATE SET |
| 157 | uploader = excluded.uploader, |
| 158 | downloaders = excluded.downloaders |
| 159 | `); |
| 160 | |
| 161 | for (const row of rows) |
| 162 | { |
| 163 | const nextPath = row.file_path === fromPath |
| 164 | ? toPath |
| 165 | : toPath + row.file_path.slice(fromPath.length); |
| 166 | del.run([row.file_path]); |
| 167 | upsert.run([nextPath, row.uploader, row.downloaders]); |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | // --------------------------------------------------------------------------- |
| 172 | // GET /api/files/roots |
| 173 | // Returns the effective configured paths the user can read. |
| 174 | // --------------------------------------------------------------------------- |
| 175 | router.get('/roots', requireAuth, (req, res) => |
| 176 | { |
| 177 | const config = loadConfig(); |
| 178 | const roots = getEffectivePaths(config.paths || []); |
| 179 | const rootAliases = rootAliasesFromConfig(config); |
| 180 | |
| 181 | const readable = roots |
| 182 | .filter(r => canRead(req.user, path.basename(r))) |
| 183 | .map(r => |
| 184 | { |
| 185 | const originalName = path.basename(r); |
| 186 | const alias = String(rootAliases[path.resolve(r)] || '').trim(); |
| 187 | return { |
| 188 | label: alias || originalName, |
| 189 | path: r, |
| 190 | originalName, |
| 191 | alias: alias || null, |
| 192 | }; |
| 193 | }); |
| 194 | res.json({ roots: readable }); |
| 195 | }); |
| 196 | |
| 197 | // --------------------------------------------------------------------------- |
| 198 | // GET /api/files/root-access?rootPath=<absolute-root-path> |
| 199 | // Returns users that can access a configured root and their mode (R / R+W). |
| 200 | // --------------------------------------------------------------------------- |
| 201 | router.get('/root-access', requireAuth, (req, res) => |
| 202 | { |
| 203 | const rootPath = String(req.query.rootPath || '').trim(); |
| 204 | if (!rootPath) |
| 205 | { |
| 206 | return res.status(400).json({ error: 'rootPath is required.' }); |
| 207 | } |
| 208 | |
| 209 | const config = loadConfig(); |
| 210 | const roots = getEffectivePaths(config.paths || []); |
| 211 | const info = resolveRoot(rootPath, roots); |
| 212 | if (!info) return res.status(403).json({ error: 'Access denied.' }); |
| 213 | if (!sameResolvedPath(rootPath, info.root)) |
| 214 | { |
| 215 | return res.status(400).json({ error: 'rootPath must be an exact configured root.' }); |
| 216 | } |
| 217 | if (!canRead(req.user, info.label)) |
| 218 | { |
| 219 | return res.status(403).json({ error: 'Access denied.' }); |
| 220 | } |
| 221 | |
| 222 | const db = getDb(); |
| 223 | const rows = db.prepare('SELECT username, is_admin, permissions FROM users').all(); |
| 224 | const users = []; |
| 225 | |
| 226 | for (const row of rows) |
| 227 | { |
| 228 | if (row.is_admin === 1) |
| 229 | { |
| 230 | users.push({ username: row.username, mode: 'R+W' }); |
| 231 | continue; |
| 232 | } |
| 233 | |
| 234 | let permissions = {}; |
| 235 | try |
| 236 | { |
| 237 | permissions = JSON.parse(row.permissions || '{}'); |
| 238 | } catch |
| 239 | { |
| 240 | permissions = {}; |
| 241 | } |
| 242 | |
| 243 | const perm = permissions[info.label]; |
| 244 | if (!perm || typeof perm !== 'object') continue; |
| 245 | const canWriteRoot = !!perm.write; |
| 246 | const canReadRoot = !!perm.read || canWriteRoot; |
| 247 | if (!canReadRoot) continue; |
| 248 | users.push({ username: row.username, mode: canWriteRoot ? 'R+W' : 'R' }); |
| 249 | } |
| 250 | |
| 251 | users.sort((a, b) => |
| 252 | { |
| 253 | const modeRank = (mode) => mode === 'R+W' ? 0 : 1; |
| 254 | const byMode = modeRank(a.mode) - modeRank(b.mode); |
| 255 | if (byMode !== 0) return byMode; |
| 256 | return String(a.username).localeCompare(String(b.username)); |
| 257 | }); |
| 258 | |
| 259 | const rootAliases = rootAliasesFromConfig(config); |
| 260 | const alias = String(rootAliases[path.resolve(info.root)] || '').trim(); |
| 261 | res.json({ |
| 262 | root: { |
| 263 | path: info.root, |
| 264 | label: alias || info.label, |
| 265 | originalName: info.label, |
| 266 | alias: alias || null, |
| 267 | }, |
| 268 | users, |
| 269 | }); |
| 270 | }); |
| 271 | |
| 272 | // --------------------------------------------------------------------------- |
| 273 | // POST /api/files/root-alias |
| 274 | // Body: { rootPath: <absolute-root-path>, alias: <display-alias> } |
| 275 | // Sets a display-only alias for a configured root. |
| 276 | // --------------------------------------------------------------------------- |
| 277 | router.post('/root-alias', requireAuth, (req, res) => |
| 278 | { |
| 279 | const rootPath = String(req.body && req.body.rootPath || '').trim(); |
| 280 | const alias = String(req.body && req.body.alias || '').trim(); |
| 281 | if (!rootPath || !alias) |
| 282 | { |
| 283 | return res.status(400).json({ error: 'rootPath and alias are required.' }); |
| 284 | } |
| 285 | |
| 286 | const roots = effectivePaths(); |
| 287 | const info = resolveRoot(rootPath, roots); |
| 288 | if (!info) return res.status(403).json({ error: 'Access denied.' }); |
| 289 | if (!sameResolvedPath(rootPath, info.root)) |
| 290 | { |
| 291 | return res.status(400).json({ error: 'rootPath must be an exact configured root.' }); |
| 292 | } |
| 293 | if (!canWrite(req.user, info.label)) |
| 294 | { |
| 295 | return res.status(403).json({ error: 'Access denied.' }); |
| 296 | } |
| 297 | |
| 298 | const config = loadConfig(); |
| 299 | const rootAliases = rootAliasesFromConfig(config); |
| 300 | const key = path.resolve(info.root); |
| 301 | if (alias === info.label) |
| 302 | { |
| 303 | delete rootAliases[key]; |
| 304 | } else |
| 305 | { |
| 306 | rootAliases[key] = alias; |
| 307 | } |
| 308 | config.rootAliases = rootAliases; |
| 309 | saveConfig(config); |
| 310 | |
| 311 | res.json({ |
| 312 | ok: true, |
| 313 | root: { |
| 314 | path: info.root, |
| 315 | label: alias, |
| 316 | originalName: info.label, |
| 317 | alias, |
| 318 | }, |
| 319 | }); |
| 320 | }); |
| 321 | |
| 322 | // --------------------------------------------------------------------------- |
| 323 | // GET /api/files/list?dir=<absolute-path> |
| 324 | // Lists files and folders in the given directory. |
| 325 | // --------------------------------------------------------------------------- |
| 326 | router.get('/list', requireAuth, (req, res) => |
| 327 | { |
| 328 | const dir = req.query.dir; |
| 329 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 330 | |
| 331 | const roots = effectivePaths(); |
| 332 | const info = resolveRoot(dir, roots); |
| 333 | if (!info) return res.status(403).json({ error: 'Access denied.' }); |
| 334 | if (!canRead(req.user, info.label)) return res.status(403).json({ error: 'Access denied.' }); |
| 335 | |
| 336 | let entries; |
| 337 | try |
| 338 | { |
| 339 | entries = fs.readdirSync(dir, { withFileTypes: true }); |
| 340 | } catch |
| 341 | { |
| 342 | return res.status(404).json({ error: 'Directory not found.' }); |
| 343 | } |
| 344 | |
| 345 | const items = entries.map(e => |
| 346 | { |
| 347 | const fullPath = path.join(dir, e.name); |
| 348 | let size = null; |
| 349 | let mtime = null; |
| 350 | try |
| 351 | { |
| 352 | const stat = fs.statSync(fullPath); |
| 353 | size = stat.size; |
| 354 | mtime = stat.mtime.toISOString(); |
| 355 | } catch { /* ignore */ } |
| 356 | |
| 357 | return { |
| 358 | name: e.name, |
| 359 | isDir: e.isDirectory(), |
| 360 | size, |
| 361 | mtime, |
| 362 | path: fullPath, |
| 363 | }; |
| 364 | }); |
| 365 | |
| 366 | res.json({ items }); |
| 367 | }); |
| 368 | |
| 369 | // --------------------------------------------------------------------------- |
| 370 | // GET /api/files/meta?file=<absolute-path> |
| 371 | // Returns file metadata from the DB. |
| 372 | // --------------------------------------------------------------------------- |
| 373 | router.get('/meta', requireAuth, (req, res) => |
| 374 | { |
| 375 | const file = req.query.file; |
| 376 | if (!file) return res.status(400).json({ error: 'file is required.' }); |
| 377 | |
| 378 | const roots = effectivePaths(); |
| 379 | const info = resolveRoot(file, roots); |
| 380 | if (!info || !canRead(req.user, info.label)) |
| 381 | { |
| 382 | return res.status(403).json({ error: 'Access denied.' }); |
| 383 | } |
| 384 | |
| 385 | let stat; |
| 386 | try |
| 387 | { |
| 388 | stat = fs.statSync(file); |
| 389 | } catch |
| 390 | { |
| 391 | return res.status(404).json({ error: 'File not found.' }); |
| 392 | } |
| 393 | |
| 394 | const db = getDb(); |
| 395 | const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); |
| 396 | |
| 397 | res.json({ |
| 398 | name: path.basename(file), |
| 399 | size: stat.size, |
| 400 | mtime: stat.mtime.toISOString(), |
| 401 | uploader: meta ? meta.uploader : '', |
| 402 | downloaders: meta ? JSON.parse(meta.downloaders) : [], |
| 403 | }); |
| 404 | }); |
| 405 | |
| 406 | // --------------------------------------------------------------------------- |
| 407 | // GET /api/files/space?dir=<absolute-path> |
| 408 | // Returns recursive used bytes for dir and available bytes on its root fs. |
| 409 | // --------------------------------------------------------------------------- |
| 410 | router.get('/space', requireAuth, (req, res) => |
| 411 | { |
| 412 | const dir = req.query.dir; |
| 413 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 414 | |
| 415 | const roots = effectivePaths(); |
| 416 | const info = resolveRoot(dir, roots); |
| 417 | if (!info || !canRead(req.user, info.label)) |
| 418 | { |
| 419 | return res.status(403).json({ error: 'Access denied.' }); |
| 420 | } |
| 421 | |
| 422 | if (!fs.existsSync(dir)) |
| 423 | { |
| 424 | return res.status(404).json({ error: 'Path not found.' }); |
| 425 | } |
| 426 | |
| 427 | const usedBytes = getRecursiveSize(dir); |
| 428 | const freeBytes = getFreeBytes(info.root); |
| 429 | res.json({ |
| 430 | usedBytes, |
| 431 | freeBytes, |
| 432 | rootPath: info.root, |
| 433 | rootLabel: info.label, |
| 434 | }); |
| 435 | }); |
| 436 | |
| 437 | // --------------------------------------------------------------------------- |
| 438 | // GET /api/files/download?file=<absolute-path> |
| 439 | // Streams the file to the client; records the download. |
| 440 | // --------------------------------------------------------------------------- |
| 441 | router.get('/download', requireAuth, (req, res) => |
| 442 | { |
| 443 | const file = req.query.file; |
| 444 | if (!file) return res.status(400).json({ error: 'file is required.' }); |
| 445 | |
| 446 | const roots = effectivePaths(); |
| 447 | const info = resolveRoot(file, roots); |
| 448 | if (!info || !canRead(req.user, info.label)) |
| 449 | { |
| 450 | return res.status(403).json({ error: 'Access denied.' }); |
| 451 | } |
| 452 | |
| 453 | if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) |
| 454 | { |
| 455 | return res.status(404).json({ error: 'File not found.' }); |
| 456 | } |
| 457 | |
| 458 | // Record download |
| 459 | const db = getDb(); |
| 460 | const meta = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([file]); |
| 461 | if (meta) |
| 462 | { |
| 463 | const downloaders = JSON.parse(meta.downloaders); |
| 464 | if (!downloaders.includes(req.user.username)) |
| 465 | { |
| 466 | downloaders.push(req.user.username); |
| 467 | db.prepare('UPDATE file_meta SET downloaders = ? WHERE file_path = ?') |
| 468 | .run([JSON.stringify(downloaders), file]); |
| 469 | } |
| 470 | } else |
| 471 | { |
| 472 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 473 | .run([file, '', JSON.stringify([req.user.username])]); |
| 474 | } |
| 475 | |
| 476 | res.download(file, path.basename(file)); |
| 477 | }); |
| 478 | |
| 479 | // --------------------------------------------------------------------------- |
| 480 | // GET /api/files/thumbnail?file=<absolute-path> |
| 481 | // Returns a pre-generated cached thumbnail if present. |
| 482 | // --------------------------------------------------------------------------- |
| 483 | router.get('/thumbnail', requireAuth, async (req, res) => |
| 484 | { |
| 485 | const file = req.query.file; |
| 486 | if (!file) return res.status(400).json({ error: 'file is required.' }); |
| 487 | |
| 488 | const roots = effectivePaths(); |
| 489 | const info = resolveRoot(file, roots); |
| 490 | if (!info || !canRead(req.user, info.label)) |
| 491 | { |
| 492 | return res.status(403).json({ error: 'Access denied.' }); |
| 493 | } |
| 494 | |
| 495 | if (!fs.existsSync(file) || fs.statSync(file).isDirectory()) |
| 496 | { |
| 497 | return res.status(404).json({ error: 'File not found.' }); |
| 498 | } |
| 499 | |
| 500 | const thumb = await getCachedThumbnailInfo(file); |
| 501 | if (!thumb) |
| 502 | { |
| 503 | return res.status(404).json({ error: 'Thumbnail not ready.' }); |
| 504 | } |
| 505 | |
| 506 | res.type(thumb.contentType); |
| 507 | res.set('Cache-Control', 'private, max-age=10'); |
| 508 | res.sendFile(thumb.thumbPath); |
| 509 | }); |
| 510 | |
| 511 | // --------------------------------------------------------------------------- |
| 512 | // POST /api/files/upload?dir=<absolute-path> |
| 513 | // Accepts multipart file upload. |
| 514 | // --------------------------------------------------------------------------- |
| 515 | router.post('/upload', requireAuth, (req, res, next) => |
| 516 | { |
| 517 | const dir = req.query.dir; |
| 518 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 519 | |
| 520 | const roots = effectivePaths(); |
| 521 | const info = resolveRoot(dir, roots); |
| 522 | if (!info || !canWrite(req.user, info.label)) |
| 523 | { |
| 524 | return res.status(403).json({ error: 'Access denied.' }); |
| 525 | } |
| 526 | |
| 527 | if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) |
| 528 | { |
| 529 | return res.status(404).json({ error: 'Directory not found.' }); |
| 530 | } |
| 531 | |
| 532 | const announcedSize = Number(req.header('x-upload-size') || 0); |
| 533 | if (Number.isFinite(announcedSize) && announcedSize > 0) |
| 534 | { |
| 535 | const freeBytes = getFreeBytes(info.root); |
| 536 | if (typeof freeBytes === 'number' && announcedSize > freeBytes) |
| 537 | { |
| 538 | return res.status(413).json({ |
| 539 | error: 'Upload too large for remaining free space on selected root.', |
| 540 | freeBytes, |
| 541 | requiredBytes: announcedSize, |
| 542 | }); |
| 543 | } |
| 544 | } |
| 545 | |
| 546 | req._uploadDir = dir; |
| 547 | |
| 548 | upload.array('files')(req, res, (err) => |
| 549 | { |
| 550 | if (err) return res.status(500).json({ error: err.message }); |
| 551 | |
| 552 | const db = getDb(); |
| 553 | for (const f of (req.files || [])) |
| 554 | { |
| 555 | const filePath = path.join(dir, f.originalname); |
| 556 | const existing = db.prepare('SELECT * FROM file_meta WHERE file_path = ?').get([filePath]); |
| 557 | if (existing) |
| 558 | { |
| 559 | db.prepare('UPDATE file_meta SET uploader = ? WHERE file_path = ?') |
| 560 | .run([req.user.username, filePath]); |
| 561 | } else |
| 562 | { |
| 563 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 564 | .run([filePath, req.user.username, '[]']); |
| 565 | } |
| 566 | } |
| 567 | res.json({ uploaded: (req.files || []).map(f => f.originalname) }); |
| 568 | }); |
| 569 | }); |
| 570 | |
| 571 | // --------------------------------------------------------------------------- |
| 572 | // POST /api/files/rename |
| 573 | // Body: { from: <absolute-path>, to: <new-name> } (to = just the filename, not full path) |
| 574 | // --------------------------------------------------------------------------- |
| 575 | router.post('/rename', requireAuth, (req, res) => |
| 576 | { |
| 577 | const { from, to } = req.body; |
| 578 | if (!from || !to) return res.status(400).json({ error: 'from and to are required.' }); |
| 579 | |
| 580 | // Prevent path traversal in the new name |
| 581 | if (path.basename(to) !== to || to.includes('/') || to.includes('\\')) |
| 582 | { |
| 583 | return res.status(400).json({ error: 'Invalid name.' }); |
| 584 | } |
| 585 | |
| 586 | const roots = effectivePaths(); |
| 587 | const info = resolveRoot(from, roots); |
| 588 | if (!info || !canWrite(req.user, info.label)) |
| 589 | { |
| 590 | return res.status(403).json({ error: 'Access denied.' }); |
| 591 | } |
| 592 | |
| 593 | const dest = path.join(path.dirname(from), to); |
| 594 | |
| 595 | // Ensure dest is still inside the same root |
| 596 | if (!getAllowedRoot(dest, roots)) |
| 597 | { |
| 598 | return res.status(403).json({ error: 'Access denied.' }); |
| 599 | } |
| 600 | |
| 601 | try |
| 602 | { |
| 603 | fs.renameSync(from, dest); |
| 604 | } catch (err) |
| 605 | { |
| 606 | return res.status(500).json({ error: err.message }); |
| 607 | } |
| 608 | |
| 609 | rewriteMetaPaths(from, dest); |
| 610 | |
| 611 | res.json({ ok: true }); |
| 612 | }); |
| 613 | |
| 614 | // --------------------------------------------------------------------------- |
| 615 | // POST /api/files/move |
| 616 | // Body: { from: <absolute-path>, toDir: <absolute-destination-directory> } |
| 617 | // --------------------------------------------------------------------------- |
| 618 | router.post('/move', requireAuth, (req, res) => |
| 619 | { |
| 620 | const { from, toDir } = req.body; |
| 621 | if (!from || !toDir) return res.status(400).json({ error: 'from and toDir are required.' }); |
| 622 | |
| 623 | const roots = effectivePaths(); |
| 624 | const fromInfo = resolveRoot(from, roots); |
| 625 | const toInfo = resolveRoot(toDir, roots); |
| 626 | if (!fromInfo || !toInfo) return res.status(403).json({ error: 'Access denied.' }); |
| 627 | if (!canWrite(req.user, fromInfo.label) || !canWrite(req.user, toInfo.label)) |
| 628 | { |
| 629 | return res.status(403).json({ error: 'Access denied.' }); |
| 630 | } |
| 631 | |
| 632 | let sourceStat; |
| 633 | let destStat; |
| 634 | try |
| 635 | { |
| 636 | sourceStat = fs.statSync(from); |
| 637 | destStat = fs.statSync(toDir); |
| 638 | } catch |
| 639 | { |
| 640 | return res.status(404).json({ error: 'Source or destination not found.' }); |
| 641 | } |
| 642 | |
| 643 | if (!destStat.isDirectory()) return res.status(400).json({ error: 'Destination must be a directory.' }); |
| 644 | |
| 645 | const dest = path.join(toDir, path.basename(from)); |
| 646 | if (!getAllowedRoot(dest, roots)) return res.status(403).json({ error: 'Access denied.' }); |
| 647 | if (sameResolvedPath(from, toDir) || sameResolvedPath(from, dest)) |
| 648 | { |
| 649 | return res.status(400).json({ error: 'Cannot move onto itself.' }); |
| 650 | } |
| 651 | if (sourceStat.isDirectory() && pathInsideResolved(toDir, from)) |
| 652 | { |
| 653 | return res.status(400).json({ error: 'Cannot move a folder into itself.' }); |
| 654 | } |
| 655 | if (fs.existsSync(dest)) return res.status(409).json({ error: 'Destination already exists.' }); |
| 656 | |
| 657 | try |
| 658 | { |
| 659 | fs.renameSync(from, dest); |
| 660 | } catch (err) |
| 661 | { |
| 662 | return res.status(500).json({ error: err.message }); |
| 663 | } |
| 664 | |
| 665 | rewriteMetaPaths(from, dest); |
| 666 | res.json({ ok: true, path: dest }); |
| 667 | }); |
| 668 | |
| 669 | // --------------------------------------------------------------------------- |
| 670 | // POST /api/files/mkdir |
| 671 | // Body: { dir: <absolute-path>, name: <folder-name> } |
| 672 | // --------------------------------------------------------------------------- |
| 673 | router.post('/mkdir', requireAuth, (req, res) => |
| 674 | { |
| 675 | const { dir, name } = req.body; |
| 676 | if (!dir || !name) return res.status(400).json({ error: 'dir and name are required.' }); |
| 677 | |
| 678 | if (path.basename(name) !== name) |
| 679 | { |
| 680 | return res.status(400).json({ error: 'Invalid folder name.' }); |
| 681 | } |
| 682 | |
| 683 | const roots = effectivePaths(); |
| 684 | const info = resolveRoot(dir, roots); |
| 685 | if (!info || !canWrite(req.user, info.label)) |
| 686 | { |
| 687 | return res.status(403).json({ error: 'Access denied.' }); |
| 688 | } |
| 689 | |
| 690 | const newDir = path.join(dir, name); |
| 691 | if (!getAllowedRoot(newDir, roots)) |
| 692 | { |
| 693 | return res.status(403).json({ error: 'Access denied.' }); |
| 694 | } |
| 695 | |
| 696 | try |
| 697 | { |
| 698 | fs.mkdirSync(newDir, { recursive: false }); |
| 699 | } catch (err) |
| 700 | { |
| 701 | return res.status(500).json({ error: err.message }); |
| 702 | } |
| 703 | |
| 704 | res.json({ ok: true, path: newDir }); |
| 705 | }); |
| 706 | |
| 707 | // --------------------------------------------------------------------------- |
| 708 | // POST /api/files/delete |
| 709 | // Body: { path: <absolute-path> } |
| 710 | // --------------------------------------------------------------------------- |
| 711 | router.post('/delete', requireAuth, (req, res) => |
| 712 | { |
| 713 | const target = req.body.path; |
| 714 | if (!target) return res.status(400).json({ error: 'path is required.' }); |
| 715 | |
| 716 | const roots = effectivePaths(); |
| 717 | const info = resolveRoot(target, roots); |
| 718 | if (!info || !canWrite(req.user, info.label)) |
| 719 | { |
| 720 | return res.status(403).json({ error: 'Access denied.' }); |
| 721 | } |
| 722 | |
| 723 | // Do not allow deleting a configured root itself |
| 724 | if (roots.map(r => path.resolve(r)).includes(path.resolve(target))) |
| 725 | { |
| 726 | return res.status(403).json({ error: 'Cannot delete a configured root path.' }); |
| 727 | } |
| 728 | |
| 729 | try |
| 730 | { |
| 731 | const stat = fs.statSync(target); |
| 732 | if (stat.isDirectory()) |
| 733 | { |
| 734 | fs.rmSync(target, { recursive: true, force: true }); |
| 735 | } else |
| 736 | { |
| 737 | fs.unlinkSync(target); |
| 738 | } |
| 739 | } catch (err) |
| 740 | { |
| 741 | return res.status(500).json({ error: err.message }); |
| 742 | } |
| 743 | |
| 744 | // Clean up any DB meta entries under that path |
| 745 | const db = getDb(); |
| 746 | db.prepare("DELETE FROM file_meta WHERE file_path = ? OR file_path LIKE ?") |
| 747 | .run([target, target + path.sep + '%']); |
| 748 | |
| 749 | res.json({ ok: true }); |
| 750 | }); |
| 751 | |
| 752 | // --------------------------------------------------------------------------- |
| 753 | // GET /api/files/folder-images?dir=<absolute-path> |
| 754 | // Returns images inside dir (recursive) that already have a cached thumbnail. |
| 755 | // Only images with a ready thumbnail are included (user constraint). |
| 756 | // --------------------------------------------------------------------------- |
| 757 | router.get('/folder-images', requireAuth, async (req, res) => |
| 758 | { |
| 759 | const dir = String(req.query.dir || '').trim(); |
| 760 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 761 | |
| 762 | const roots = effectivePaths(); |
| 763 | const info = resolveRoot(dir, roots); |
| 764 | if (!info || !canRead(req.user, info.label)) |
| 765 | { |
| 766 | return res.status(403).json({ error: 'Access denied.' }); |
| 767 | } |
| 768 | |
| 769 | if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) |
| 770 | { |
| 771 | return res.status(404).json({ error: 'Directory not found.' }); |
| 772 | } |
| 773 | |
| 774 | const images = await getImagesWithThumbnailsInDir(dir); |
| 775 | // Filter out any that escaped to a different root (safety check). |
| 776 | const filtered = images.filter(({ filePath }) => !!getAllowedRoot(filePath, roots)); |
| 777 | |
| 778 | res.json({ images: filtered.map(({ filePath }) => ({ filePath })) }); |
| 779 | }); |
| 780 | |
| 781 | // --------------------------------------------------------------------------- |
| 782 | // GET /api/files/folder-icon?dir=<absolute-path> |
| 783 | // Returns the current icon source file for a folder (explicit or auto-first). |
| 784 | // --------------------------------------------------------------------------- |
| 785 | router.get('/folder-icon', requireAuth, async (req, res) => |
| 786 | { |
| 787 | const dir = String(req.query.dir || '').trim(); |
| 788 | if (!dir) return res.status(400).json({ error: 'dir is required.' }); |
| 789 | |
| 790 | const roots = effectivePaths(); |
| 791 | const info = resolveRoot(dir, roots); |
| 792 | if (!info || !canRead(req.user, info.label)) |
| 793 | { |
| 794 | return res.status(403).json({ error: 'Access denied.' }); |
| 795 | } |
| 796 | |
| 797 | const sourceFile = await getFolderIconSourceFile(dir); |
| 798 | if (!sourceFile) return res.json({ icon: null }); |
| 799 | |
| 800 | // Verify the source is still accessible within a configured root. |
| 801 | if (!getAllowedRoot(sourceFile, roots)) return res.json({ icon: null }); |
| 802 | |
| 803 | res.json({ icon: { filePath: sourceFile } }); |
| 804 | }); |
| 805 | |
| 806 | // --------------------------------------------------------------------------- |
| 807 | // POST /api/files/folder-icon |
| 808 | // Body: { folderPath, imagePath } — imagePath: null to clear explicit assignment. |
| 809 | // Requires write access; the image must already have a cached thumbnail. |
| 810 | // --------------------------------------------------------------------------- |
| 811 | router.post('/folder-icon', requireAuth, async (req, res) => |
| 812 | { |
| 813 | const folderPath = String((req.body && req.body.folderPath) || '').trim(); |
| 814 | const rawImage = req.body && req.body.imagePath != null ? String(req.body.imagePath).trim() : null; |
| 815 | |
| 816 | if (!folderPath) return res.status(400).json({ error: 'folderPath is required.' }); |
| 817 | |
| 818 | const roots = effectivePaths(); |
| 819 | const info = resolveRoot(folderPath, roots); |
| 820 | if (!info || !canWrite(req.user, info.label)) |
| 821 | { |
| 822 | return res.status(403).json({ error: 'Access denied.' }); |
| 823 | } |
| 824 | |
| 825 | let stat; |
| 826 | try { stat = fs.statSync(folderPath); } |
| 827 | catch { return res.status(404).json({ error: 'Folder not found.' }); } |
| 828 | if (!stat.isDirectory()) return res.status(400).json({ error: 'Path is not a directory.' }); |
| 829 | |
| 830 | if (rawImage !== null) |
| 831 | { |
| 832 | // Verify the image is inside a readable root. |
| 833 | const imageRoot = getAllowedRoot(rawImage, roots); |
| 834 | if (!imageRoot) return res.status(403).json({ error: 'Image not accessible.' }); |
| 835 | |
| 836 | // Must already have a cached thumbnail — only thumbnailed images can be selected. |
| 837 | const thumb = await getCachedThumbnailInfo(rawImage); |
| 838 | if (!thumb) return res.status(404).json({ error: 'Thumbnail not ready for that image.' }); |
| 839 | } |
| 840 | |
| 841 | await setFolderIconAssignment(folderPath, rawImage); |
| 842 | res.json({ ok: true }); |
| 843 | }); |
| 844 | |
| 845 | module.exports = router; |