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