| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const fs = require('fs'); |
| 5 | const http = require('http'); |
| 6 | const os = require('os'); |
| 7 | const path = require('path'); |
| 8 | const { once } = require('events'); |
| 9 | |
| 10 | let mockPaths = []; |
| 11 | let mockUserPath = null; |
| 12 | let mockRootAliases = {}; |
| 13 | let mockGlobalFaviconPath = null; |
| 14 | let mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 15 | let mockThumbPath = null; |
| 16 | let mockFolderImages = []; |
| 17 | let mockFolderIconFile = null; |
| 18 | let lastFolderIconAssignment = undefined; |
| 19 | let mockVideoStreamSession = null; |
| 20 | let mockVideoStreamAsset = null; |
| 21 | let releasedVideoStreamSessionId = null; |
| 22 | let mockSubtitleFrameResult = null; |
| 23 | let mockSubtitleFrameError = null; |
| 24 | const mockSubtitleDebugLogDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); |
| 25 | |
| 26 | jest.mock('../server/db', () => |
| 27 | { |
| 28 | const { Database } = require('node-sqlite3-wasm'); |
| 29 | let db; |
| 30 | function getDb () |
| 31 | { |
| 32 | if (!db) |
| 33 | { |
| 34 | db = new Database(':memory:'); |
| 35 | db.exec(` |
| 36 | CREATE TABLE IF NOT EXISTS users ( |
| 37 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 38 | username TEXT UNIQUE NOT NULL, |
| 39 | password_hash TEXT NOT NULL, |
| 40 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 41 | permissions TEXT NOT NULL DEFAULT '{}' |
| 42 | ); |
| 43 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 44 | file_path TEXT PRIMARY KEY, |
| 45 | uploader TEXT NOT NULL DEFAULT '', |
| 46 | downloaders TEXT NOT NULL DEFAULT '[]', |
| 47 | watched_by TEXT NOT NULL DEFAULT '{}', |
| 48 | uploaded_at TEXT, |
| 49 | sha256 TEXT |
| 50 | ); |
| 51 | CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256); |
| 52 | `); |
| 53 | } |
| 54 | return db; |
| 55 | } |
| 56 | return { getDb, initDb: getDb }; |
| 57 | }); |
| 58 | |
| 59 | jest.mock('../server/config', () => ({ |
| 60 | loadConfig: () => ({ |
| 61 | port: 3000, |
| 62 | paths: [...mockPaths], |
| 63 | userPath: mockUserPath, |
| 64 | rootAliases: { ...mockRootAliases }, |
| 65 | globalFaviconPath: mockGlobalFaviconPath, |
| 66 | }), |
| 67 | saveConfig: (config) => |
| 68 | { |
| 69 | mockPaths = [...(config.paths || [])]; |
| 70 | mockRootAliases = { ...(config.rootAliases || {}) }; |
| 71 | mockGlobalFaviconPath = config.globalFaviconPath || null; |
| 72 | }, |
| 73 | getEffectivePaths: (paths) => paths, |
| 74 | getAllowedRoot: (targetPath, roots) => |
| 75 | { |
| 76 | const path = require('path'); |
| 77 | const absTarget = path.resolve(String(targetPath || '')); |
| 78 | return roots.find((root) => |
| 79 | { |
| 80 | const absRoot = path.resolve(root); |
| 81 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 82 | }) || null; |
| 83 | }, |
| 84 | })); |
| 85 | |
| 86 | jest.mock('../server/auth', () => ({ |
| 87 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 88 | })); |
| 89 | |
| 90 | jest.mock('../server/thumbnail-cache', () => ({ |
| 91 | getCachedThumbnailInfo: async () => |
| 92 | { |
| 93 | if (!mockThumbPath) return null; |
| 94 | return { thumbPath: mockThumbPath, contentType: 'image/webp' }; |
| 95 | }, |
| 96 | getFilesWithThumbnailsInDir: async () => mockFolderImages.slice(), |
| 97 | getFolderIconSourceFile: async () => mockFolderIconFile, |
| 98 | setFolderIconAssignment: async (folderPath, imagePath) => |
| 99 | { |
| 100 | lastFolderIconAssignment = { folderPath, imagePath }; |
| 101 | }, |
| 102 | })); |
| 103 | |
| 104 | jest.mock('../server/video-stream', () => ({ |
| 105 | createVideoStreamSession: jest.fn(async () => |
| 106 | { |
| 107 | if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; |
| 108 | return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] }; |
| 109 | }), |
| 110 | sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) => |
| 111 | { |
| 112 | if (typeof mockVideoStreamAsset === 'function') |
| 113 | { |
| 114 | await mockVideoStreamAsset(sessionId, assetPath, req, res); |
| 115 | return; |
| 116 | } |
| 117 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 118 | }), |
| 119 | releaseVideoStreamSession: jest.fn((sessionId) => |
| 120 | { |
| 121 | releasedVideoStreamSessionId = String(sessionId || ''); |
| 122 | return true; |
| 123 | }), |
| 124 | })); |
| 125 | |
| 126 | jest.mock('../server/image-subtitles', () => ({ |
| 127 | renderImageSubtitleFrame: jest.fn(async () => |
| 128 | { |
| 129 | if (mockSubtitleFrameError) throw mockSubtitleFrameError; |
| 130 | return mockSubtitleFrameResult; |
| 131 | }), |
| 132 | })); |
| 133 | |
| 134 | jest.mock('../server/subtitle-debug-log', () => ({ |
| 135 | SUBTITLE_DEBUG_LOG_DIR: mockSubtitleDebugLogDir, |
| 136 | appendSubtitleDebugEntries: jest.fn(), |
| 137 | })); |
| 138 | |
| 139 | const filesRoutes = require('../server/routes/files'); |
| 140 | const { getDb } = require('../server/db'); |
| 141 | |
| 142 | let server; |
| 143 | let baseUrl; |
| 144 | let rootDir; |
| 145 | |
| 146 | beforeAll(async () => |
| 147 | { |
| 148 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 149 | mockPaths = [rootDir]; |
| 150 | |
| 151 | const app = express(); |
| 152 | app.use(express.json()); |
| 153 | app.use('/api/files', filesRoutes); |
| 154 | app.use((err, req, res, next) => |
| 155 | { |
| 156 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 157 | }); |
| 158 | |
| 159 | server = http.createServer(app); |
| 160 | server.listen(0); |
| 161 | await once(server, 'listening'); |
| 162 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 163 | }); |
| 164 | |
| 165 | afterAll(() => |
| 166 | { |
| 167 | server.close(); |
| 168 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 169 | }); |
| 170 | |
| 171 | beforeEach(() => |
| 172 | { |
| 173 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 174 | fs.mkdirSync(rootDir, { recursive: true }); |
| 175 | if (mockUserPath) |
| 176 | { |
| 177 | fs.rmSync(mockUserPath, { recursive: true, force: true }); |
| 178 | fs.mkdirSync(mockUserPath, { recursive: true }); |
| 179 | } |
| 180 | mockRootAliases = {}; |
| 181 | mockGlobalFaviconPath = null; |
| 182 | mockUserPath = null; |
| 183 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 184 | mockThumbPath = null; |
| 185 | mockFolderImages = []; |
| 186 | mockFolderIconFile = null; |
| 187 | lastFolderIconAssignment = undefined; |
| 188 | mockVideoStreamSession = null; |
| 189 | mockVideoStreamAsset = null; |
| 190 | releasedVideoStreamSessionId = null; |
| 191 | mockSubtitleFrameResult = null; |
| 192 | mockSubtitleFrameError = null; |
| 193 | const db = getDb(); |
| 194 | db.prepare('DELETE FROM file_meta').run([]); |
| 195 | db.prepare('DELETE FROM users').run([]); |
| 196 | }); |
| 197 | |
| 198 | function req (method, routePath, body) |
| 199 | { |
| 200 | const payload = body ? JSON.stringify(body) : undefined; |
| 201 | return new Promise((resolve, reject) => |
| 202 | { |
| 203 | const request = http.request(baseUrl + routePath, { |
| 204 | method, |
| 205 | headers: { |
| 206 | 'Content-Type': 'application/json', |
| 207 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 208 | }, |
| 209 | }, res => |
| 210 | { |
| 211 | let data = ''; |
| 212 | res.on('data', chunk => data += chunk); |
| 213 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 214 | }); |
| 215 | request.on('error', reject); |
| 216 | if (payload) request.write(payload); |
| 217 | request.end(); |
| 218 | }); |
| 219 | } |
| 220 | |
| 221 | function reqRaw (method, routePath) |
| 222 | { |
| 223 | return new Promise((resolve, reject) => |
| 224 | { |
| 225 | const request = http.request(baseUrl + routePath, { method }, res => |
| 226 | { |
| 227 | const chunks = []; |
| 228 | res.on('data', chunk => chunks.push(Buffer.from(chunk))); |
| 229 | res.on('end', () => resolve({ |
| 230 | status: res.statusCode, |
| 231 | headers: res.headers, |
| 232 | body: Buffer.concat(chunks), |
| 233 | })); |
| 234 | }); |
| 235 | request.on('error', reject); |
| 236 | request.end(); |
| 237 | }); |
| 238 | } |
| 239 | |
| 240 | function reqMultipart (routePath, files, extraHeaders = {}) |
| 241 | { |
| 242 | const boundary = '----filemanager-test-boundary'; |
| 243 | const buffers = []; |
| 244 | |
| 245 | for (const file of files) |
| 246 | { |
| 247 | buffers.push(Buffer.from( |
| 248 | `--${boundary}\r\n` |
| 249 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 250 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 251 | )); |
| 252 | buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content))); |
| 253 | buffers.push(Buffer.from('\r\n')); |
| 254 | } |
| 255 | |
| 256 | buffers.push(Buffer.from(`--${boundary}--\r\n`)); |
| 257 | const payload = Buffer.concat(buffers); |
| 258 | |
| 259 | return new Promise((resolve, reject) => |
| 260 | { |
| 261 | const request = http.request(baseUrl + routePath, { |
| 262 | method: 'POST', |
| 263 | headers: { |
| 264 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 265 | 'Content-Length': payload.length, |
| 266 | ...extraHeaders, |
| 267 | }, |
| 268 | }, res => |
| 269 | { |
| 270 | let data = ''; |
| 271 | res.on('data', chunk => data += chunk); |
| 272 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 273 | }); |
| 274 | request.on('error', reject); |
| 275 | request.write(payload); |
| 276 | request.end(); |
| 277 | }); |
| 278 | } |
| 279 | |
| 280 | function abortMultipartUpload (routePath, file) |
| 281 | { |
| 282 | const boundary = '----filemanager-test-boundary-abort'; |
| 283 | const header = Buffer.from( |
| 284 | `--${boundary}\r\n` |
| 285 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 286 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 287 | ); |
| 288 | const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)); |
| 289 | |
| 290 | return new Promise((resolve) => |
| 291 | { |
| 292 | const request = http.request(baseUrl + routePath, { |
| 293 | method: 'POST', |
| 294 | headers: { |
| 295 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 296 | }, |
| 297 | }); |
| 298 | |
| 299 | let settled = false; |
| 300 | const finish = () => |
| 301 | { |
| 302 | if (settled) return; |
| 303 | settled = true; |
| 304 | resolve(); |
| 305 | }; |
| 306 | |
| 307 | request.on('error', finish); |
| 308 | request.on('close', finish); |
| 309 | request.write(header); |
| 310 | request.write(chunk); |
| 311 | setTimeout(() => request.destroy(), 20); |
| 312 | }); |
| 313 | } |
| 314 | |
| 315 | async function waitFor (predicate, timeoutMs = 500) |
| 316 | { |
| 317 | const start = Date.now(); |
| 318 | while (Date.now() - start < timeoutMs) |
| 319 | { |
| 320 | if (predicate()) return; |
| 321 | await new Promise(resolve => setTimeout(resolve, 10)); |
| 322 | } |
| 323 | throw new Error('Timed out waiting for condition.'); |
| 324 | } |
| 325 | |
| 326 | describe('POST /api/files/upload', () => |
| 327 | { |
| 328 | test('stores a completed upload under its final name', async () => |
| 329 | { |
| 330 | const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 331 | { name: 'hello.txt', content: 'hello world', type: 'text/plain' }, |
| 332 | ]); |
| 333 | |
| 334 | expect(status).toBe(200); |
| 335 | expect(body.uploaded).toEqual(['hello.txt']); |
| 336 | expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world'); |
| 337 | |
| 338 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 339 | .get([path.join(rootDir, 'hello.txt')]); |
| 340 | expect(meta).toMatchObject({ uploader: 'admin' }); |
| 341 | }); |
| 342 | |
| 343 | test('removes partial files when the upload connection aborts', async () => |
| 344 | { |
| 345 | await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, { |
| 346 | name: 'partial.txt', |
| 347 | content: Buffer.alloc(256 * 1024, 'a'), |
| 348 | type: 'text/plain', |
| 349 | }); |
| 350 | |
| 351 | await waitFor(() => fs.readdirSync(rootDir).length === 0); |
| 352 | |
| 353 | expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false); |
| 354 | expect(fs.readdirSync(rootDir)).toEqual([]); |
| 355 | |
| 356 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 357 | .get([path.join(rootDir, 'partial.txt')]); |
| 358 | expect(meta).toBeFalsy(); |
| 359 | }); |
| 360 | }); |
| 361 | |
| 362 | describe('POST /api/files/move', () => |
| 363 | { |
| 364 | test('moves a file into another folder and rewrites metadata', async () => |
| 365 | { |
| 366 | const from = path.join(rootDir, 'alpha.txt'); |
| 367 | const toDir = path.join(rootDir, 'folder'); |
| 368 | fs.writeFileSync(from, 'hello'); |
| 369 | fs.mkdirSync(toDir); |
| 370 | const uploadedAt = '2026-05-18T12:00:00.000Z'; |
| 371 | |
| 372 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)') |
| 373 | .run([from, 'admin', '["alice"]', '{"admin":"partway"}', uploadedAt, 'abc123']); |
| 374 | |
| 375 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 376 | |
| 377 | expect(status).toBe(200); |
| 378 | expect(body.ok).toBe(true); |
| 379 | expect(fs.existsSync(from)).toBe(false); |
| 380 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 381 | |
| 382 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 383 | expect(meta).toMatchObject({ |
| 384 | uploader: 'admin', |
| 385 | downloaders: '["alice"]', |
| 386 | watched_by: '{"admin":"partway"}', |
| 387 | uploaded_at: uploadedAt, |
| 388 | sha256: 'abc123', |
| 389 | }); |
| 390 | }); |
| 391 | |
| 392 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 393 | { |
| 394 | const fromDir = path.join(rootDir, 'src-folder'); |
| 395 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 396 | const toDir = path.join(rootDir, 'dest-folder'); |
| 397 | fs.mkdirSync(fromDir); |
| 398 | fs.mkdirSync(toDir); |
| 399 | fs.writeFileSync(nestedFile, 'hello'); |
| 400 | |
| 401 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 402 | .run([nestedFile, 'admin', '[]']); |
| 403 | |
| 404 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 405 | |
| 406 | expect(status).toBe(200); |
| 407 | expect(fs.existsSync(fromDir)).toBe(false); |
| 408 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 409 | |
| 410 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 411 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 412 | expect(movedMeta).toBeTruthy(); |
| 413 | }); |
| 414 | |
| 415 | test('rejects moving a folder into itself', async () => |
| 416 | { |
| 417 | const fromDir = path.join(rootDir, 'src-folder'); |
| 418 | const childDir = path.join(fromDir, 'child'); |
| 419 | fs.mkdirSync(childDir, { recursive: true }); |
| 420 | |
| 421 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 422 | |
| 423 | expect(status).toBe(400); |
| 424 | expect(body.error).toMatch(/folder into itself/i); |
| 425 | }); |
| 426 | |
| 427 | test('overwrites an existing destination when conflict strategy is overwrite', async () => |
| 428 | { |
| 429 | const sourceFile = path.join(rootDir, 'source.txt'); |
| 430 | const destinationDir = path.join(rootDir, 'dest'); |
| 431 | fs.mkdirSync(destinationDir); |
| 432 | fs.writeFileSync(sourceFile, 'new-content'); |
| 433 | fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content'); |
| 434 | |
| 435 | const { status, body } = await req('POST', '/api/files/move', { |
| 436 | from: sourceFile, |
| 437 | toDir: destinationDir, |
| 438 | conflict: 'overwrite', |
| 439 | }); |
| 440 | |
| 441 | expect(status).toBe(200); |
| 442 | expect(body.conflictResolution).toBe('overwrite'); |
| 443 | expect(fs.existsSync(sourceFile)).toBe(false); |
| 444 | expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content'); |
| 445 | }); |
| 446 | |
| 447 | test('renames destination when conflict strategy is rename', async () => |
| 448 | { |
| 449 | const sourceFile = path.join(rootDir, 'report.txt'); |
| 450 | const destinationDir = path.join(rootDir, 'dest'); |
| 451 | fs.mkdirSync(destinationDir); |
| 452 | fs.writeFileSync(sourceFile, 'latest'); |
| 453 | fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing'); |
| 454 | |
| 455 | const { status, body } = await req('POST', '/api/files/move', { |
| 456 | from: sourceFile, |
| 457 | toDir: destinationDir, |
| 458 | conflict: 'rename', |
| 459 | }); |
| 460 | |
| 461 | expect(status).toBe(200); |
| 462 | expect(body.conflictResolution).toBe('rename'); |
| 463 | expect(path.basename(body.path)).toBe('report (1).txt'); |
| 464 | expect(fs.readFileSync(body.path, 'utf8')).toBe('latest'); |
| 465 | expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing'); |
| 466 | }); |
| 467 | |
| 468 | test('moves a file into My Folder when rename falls back across filesystems', async () => |
| 469 | { |
| 470 | const sourceFile = path.join(rootDir, 'cross-root.txt'); |
| 471 | const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-')); |
| 472 | const userFolder = path.join(userFolderBase, 'alice'); |
| 473 | |
| 474 | mockPaths = [rootDir]; |
| 475 | mockUserPath = userFolderBase; |
| 476 | mockUser = { |
| 477 | username: 'alice', |
| 478 | isAdmin: false, |
| 479 | permissions: { |
| 480 | [path.basename(rootDir)]: { read: true, write: true }, |
| 481 | }, |
| 482 | }; |
| 483 | |
| 484 | fs.writeFileSync(sourceFile, 'hello'); |
| 485 | fs.mkdirSync(userFolder, { recursive: true }); |
| 486 | |
| 487 | const originalRenameSync = fs.renameSync; |
| 488 | fs.renameSync = (from, to) => |
| 489 | { |
| 490 | const err = new Error('cross-device move'); |
| 491 | err.code = 'EXDEV'; |
| 492 | throw err; |
| 493 | }; |
| 494 | |
| 495 | try |
| 496 | { |
| 497 | const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder }); |
| 498 | |
| 499 | expect(status).toBe(200); |
| 500 | expect(body.path).toBe(path.join(userFolder, 'cross-root.txt')); |
| 501 | expect(fs.existsSync(sourceFile)).toBe(false); |
| 502 | expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello'); |
| 503 | } finally |
| 504 | { |
| 505 | fs.renameSync = originalRenameSync; |
| 506 | fs.rmSync(userFolderBase, { recursive: true, force: true }); |
| 507 | } |
| 508 | }); |
| 509 | }); |
| 510 | |
| 511 | describe('root alias endpoints', () => |
| 512 | { |
| 513 | test('GET /api/files/roots returns alias label and original name', async () => |
| 514 | { |
| 515 | mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; |
| 516 | |
| 517 | const { status, body } = await req('GET', '/api/files/roots'); |
| 518 | |
| 519 | expect(status).toBe(200); |
| 520 | expect(body.roots).toHaveLength(1); |
| 521 | expect(body.roots[0]).toMatchObject({ |
| 522 | path: rootDir, |
| 523 | label: 'Workspace', |
| 524 | alias: 'Workspace', |
| 525 | originalName: path.basename(rootDir), |
| 526 | }); |
| 527 | }); |
| 528 | |
| 529 | test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => |
| 530 | { |
| 531 | const originalBase = path.basename(rootDir); |
| 532 | const { status, body } = await req('POST', '/api/files/root-alias', { |
| 533 | rootPath: rootDir, |
| 534 | alias: 'Shared Files', |
| 535 | }); |
| 536 | |
| 537 | expect(status).toBe(200); |
| 538 | expect(body.ok).toBe(true); |
| 539 | expect(body.root).toMatchObject({ |
| 540 | path: rootDir, |
| 541 | label: 'Shared Files', |
| 542 | alias: 'Shared Files', |
| 543 | originalName: originalBase, |
| 544 | }); |
| 545 | expect(fs.existsSync(rootDir)).toBe(true); |
| 546 | |
| 547 | const afterRoots = await req('GET', '/api/files/roots'); |
| 548 | expect(afterRoots.status).toBe(200); |
| 549 | expect(afterRoots.body.roots[0].label).toBe('Shared Files'); |
| 550 | expect(afterRoots.body.roots[0].originalName).toBe(originalBase); |
| 551 | }); |
| 552 | |
| 553 | test('POST /api/files/root-alias rejects non-root paths', async () => |
| 554 | { |
| 555 | const nested = path.join(rootDir, 'sub'); |
| 556 | fs.mkdirSync(nested, { recursive: true }); |
| 557 | |
| 558 | const { status } = await req('POST', '/api/files/root-alias', { |
| 559 | rootPath: nested, |
| 560 | alias: 'Nested', |
| 561 | }); |
| 562 | |
| 563 | expect(status).toBe(400); |
| 564 | }); |
| 565 | }); |
| 566 | |
| 567 | describe('GET /api/files/thumbnail', () => |
| 568 | { |
| 569 | test('returns 404 while cached thumbnail is not ready', async () => |
| 570 | { |
| 571 | const source = path.join(rootDir, 'photo.jpg'); |
| 572 | fs.writeFileSync(source, 'not-an-image'); |
| 573 | |
| 574 | const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 575 | expect(status).toBe(404); |
| 576 | expect(body.error).toMatch(/not ready/i); |
| 577 | }); |
| 578 | |
| 579 | test('serves cached thumbnail file when available', async () => |
| 580 | { |
| 581 | const source = path.join(rootDir, 'photo.jpg'); |
| 582 | const thumb = path.join(rootDir, 'photo-thumb.webp'); |
| 583 | fs.writeFileSync(source, 'not-an-image'); |
| 584 | fs.writeFileSync(thumb, 'webp-bytes'); |
| 585 | mockThumbPath = thumb; |
| 586 | |
| 587 | const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 588 | expect(response.status).toBe(200); |
| 589 | expect(String(response.headers['content-type'] || '')).toContain('image/webp'); |
| 590 | expect(response.body.toString('utf8')).toBe('webp-bytes'); |
| 591 | }); |
| 592 | }); |
| 593 | |
| 594 | describe('GET /api/files/root-access', () => |
| 595 | { |
| 596 | test('returns users with R/R+W modes for an exact root path', async () => |
| 597 | { |
| 598 | const label = path.basename(rootDir); |
| 599 | const db = getDb(); |
| 600 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 601 | .run(['admin', 'x', 1, '{}']); |
| 602 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 603 | .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]); |
| 604 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 605 | .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]); |
| 606 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 607 | .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]); |
| 608 | |
| 609 | const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`); |
| 610 | expect(status).toBe(200); |
| 611 | expect(body.root).toMatchObject({ path: rootDir, originalName: label }); |
| 612 | expect(body.users).toEqual([ |
| 613 | { username: 'admin', mode: 'R+W' }, |
| 614 | { username: 'bob', mode: 'R+W' }, |
| 615 | { username: 'alice', mode: 'R' }, |
| 616 | ]); |
| 617 | }); |
| 618 | |
| 619 | test('rejects non-exact nested root paths', async () => |
| 620 | { |
| 621 | const nested = path.join(rootDir, 'sub'); |
| 622 | fs.mkdirSync(nested, { recursive: true }); |
| 623 | |
| 624 | const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`); |
| 625 | expect(status).toBe(400); |
| 626 | }); |
| 627 | }); |
| 628 | |
| 629 | describe('orphaned user folder access', () => |
| 630 | { |
| 631 | test('admins can read and write in orphaned user folders', async () => |
| 632 | { |
| 633 | const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-')); |
| 634 | const orphanFolder = path.join(userFolderBase, 'ghost-user'); |
| 635 | fs.mkdirSync(orphanFolder, { recursive: true }); |
| 636 | fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello'); |
| 637 | |
| 638 | mockUserPath = userFolderBase; |
| 639 | mockUser = { |
| 640 | username: 'admin', |
| 641 | isAdmin: true, |
| 642 | permissions: {}, |
| 643 | }; |
| 644 | |
| 645 | try |
| 646 | { |
| 647 | const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`); |
| 648 | expect(listRes.status).toBe(200); |
| 649 | expect(Array.isArray(listRes.body.items)).toBe(true); |
| 650 | expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true); |
| 651 | |
| 652 | const mkdirRes = await req('POST', '/api/files/mkdir', { |
| 653 | dir: orphanFolder, |
| 654 | name: 'created-by-admin', |
| 655 | }); |
| 656 | expect(mkdirRes.status).toBe(200); |
| 657 | expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true); |
| 658 | } finally |
| 659 | { |
| 660 | fs.rmSync(userFolderBase, { recursive: true, force: true }); |
| 661 | } |
| 662 | }); |
| 663 | |
| 664 | test('non-admin users cannot access orphaned user folders', async () => |
| 665 | { |
| 666 | const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-')); |
| 667 | const orphanFolder = path.join(userFolderBase, 'ghost-user'); |
| 668 | fs.mkdirSync(orphanFolder, { recursive: true }); |
| 669 | |
| 670 | mockUserPath = userFolderBase; |
| 671 | mockUser = { |
| 672 | username: 'alice', |
| 673 | isAdmin: false, |
| 674 | permissions: {}, |
| 675 | }; |
| 676 | |
| 677 | try |
| 678 | { |
| 679 | const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`); |
| 680 | expect(listRes.status).toBe(403); |
| 681 | } finally |
| 682 | { |
| 683 | fs.rmSync(userFolderBase, { recursive: true, force: true }); |
| 684 | } |
| 685 | }); |
| 686 | }); |
| 687 | |
| 688 | describe('subtitle debug cache access', () => |
| 689 | { |
| 690 | test('admins can browse the subtitle debug cache folder', async () => |
| 691 | { |
| 692 | const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); |
| 693 | fs.rmSync(logDir, { recursive: true, force: true }); |
| 694 | fs.mkdirSync(logDir, { recursive: true }); |
| 695 | fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello'); |
| 696 | |
| 697 | mockUser = { |
| 698 | username: 'admin', |
| 699 | isAdmin: true, |
| 700 | permissions: {}, |
| 701 | }; |
| 702 | |
| 703 | try |
| 704 | { |
| 705 | const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`); |
| 706 | expect(listRes.status).toBe(200); |
| 707 | expect(Array.isArray(listRes.body.items)).toBe(true); |
| 708 | expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true); |
| 709 | } finally |
| 710 | { |
| 711 | fs.rmSync(logDir, { recursive: true, force: true }); |
| 712 | } |
| 713 | }); |
| 714 | |
| 715 | test('non-admin users cannot browse the subtitle debug cache folder', async () => |
| 716 | { |
| 717 | const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs'); |
| 718 | fs.rmSync(logDir, { recursive: true, force: true }); |
| 719 | fs.mkdirSync(logDir, { recursive: true }); |
| 720 | |
| 721 | mockUser = { |
| 722 | username: 'alice', |
| 723 | isAdmin: false, |
| 724 | permissions: {}, |
| 725 | }; |
| 726 | |
| 727 | try |
| 728 | { |
| 729 | const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`); |
| 730 | expect(listRes.status).toBe(403); |
| 731 | } finally |
| 732 | { |
| 733 | fs.rmSync(logDir, { recursive: true, force: true }); |
| 734 | } |
| 735 | }); |
| 736 | }); |
| 737 | |
| 738 | describe('folder icon endpoints', () => |
| 739 | { |
| 740 | test('GET /api/files/folder-images returns files that have cached thumbnails', async () => |
| 741 | { |
| 742 | const subDir = path.join(rootDir, 'photos'); |
| 743 | fs.mkdirSync(subDir); |
| 744 | const imgPath = path.join(subDir, 'a.jpg'); |
| 745 | fs.writeFileSync(imgPath, 'img'); |
| 746 | |
| 747 | mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }]; |
| 748 | |
| 749 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 750 | expect(status).toBe(200); |
| 751 | expect(body.images).toHaveLength(1); |
| 752 | expect(body.images[0].filePath).toBe(imgPath); |
| 753 | }); |
| 754 | |
| 755 | test('GET /api/files/folder-images includes video files with cached thumbnails', async () => |
| 756 | { |
| 757 | const videoPath = path.join(rootDir, 'photos', 'clip.mp4'); |
| 758 | fs.mkdirSync(path.dirname(videoPath), { recursive: true }); |
| 759 | fs.writeFileSync(videoPath, 'video'); |
| 760 | |
| 761 | mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }]; |
| 762 | |
| 763 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 764 | expect(status).toBe(200); |
| 765 | expect(body.images).toEqual([{ filePath: videoPath }]); |
| 766 | }); |
| 767 | |
| 768 | test('GET /api/files/folder-images returns empty list when no thumbnails available', async () => |
| 769 | { |
| 770 | mockFolderImages = []; |
| 771 | |
| 772 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 773 | expect(status).toBe(200); |
| 774 | expect(body.images).toEqual([]); |
| 775 | }); |
| 776 | |
| 777 | test('GET /api/files/folder-icon returns null when no icon available', async () => |
| 778 | { |
| 779 | mockFolderIconFile = null; |
| 780 | |
| 781 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 782 | expect(status).toBe(200); |
| 783 | expect(body.icon).toBeNull(); |
| 784 | }); |
| 785 | |
| 786 | test('GET /api/files/folder-icon returns source file path when icon is available', async () => |
| 787 | { |
| 788 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 789 | fs.writeFileSync(imgPath, 'img'); |
| 790 | mockFolderIconFile = imgPath; |
| 791 | |
| 792 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 793 | expect(status).toBe(200); |
| 794 | expect(body.icon).toMatchObject({ filePath: imgPath }); |
| 795 | }); |
| 796 | |
| 797 | test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () => |
| 798 | { |
| 799 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 800 | const thumbFile = path.join(rootDir, 'cover.webp'); |
| 801 | fs.writeFileSync(imgPath, 'img'); |
| 802 | fs.writeFileSync(thumbFile, 'webp'); |
| 803 | mockThumbPath = thumbFile; |
| 804 | |
| 805 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 806 | folderPath: rootDir, |
| 807 | imagePath: imgPath, |
| 808 | }); |
| 809 | expect(status).toBe(200); |
| 810 | expect(body.ok).toBe(true); |
| 811 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath }); |
| 812 | }); |
| 813 | |
| 814 | test('POST /api/files/folder-icon rejects image without cached thumbnail', async () => |
| 815 | { |
| 816 | const imgPath = path.join(rootDir, 'missing.jpg'); |
| 817 | fs.writeFileSync(imgPath, 'img'); |
| 818 | mockThumbPath = null; |
| 819 | |
| 820 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 821 | folderPath: rootDir, |
| 822 | imagePath: imgPath, |
| 823 | }); |
| 824 | expect(status).toBe(404); |
| 825 | expect(body.error).toMatch(/thumbnail not ready/i); |
| 826 | }); |
| 827 | |
| 828 | test('POST /api/files/folder-icon clears assignment when imagePath is null', async () => |
| 829 | { |
| 830 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 831 | folderPath: rootDir, |
| 832 | imagePath: null, |
| 833 | }); |
| 834 | expect(status).toBe(200); |
| 835 | expect(body.ok).toBe(true); |
| 836 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null }); |
| 837 | }); |
| 838 | |
| 839 | test('POST /api/files/folder-icon returns 403 for read-only user', async () => |
| 840 | { |
| 841 | const label = path.basename(rootDir); |
| 842 | mockUser = { |
| 843 | username: 'reader', |
| 844 | isAdmin: false, |
| 845 | permissions: { [label]: { read: true, write: false } }, |
| 846 | }; |
| 847 | |
| 848 | const imgPath = path.join(rootDir, 'photo.jpg'); |
| 849 | fs.writeFileSync(imgPath, 'img'); |
| 850 | |
| 851 | const { status } = await req('POST', '/api/files/folder-icon', { |
| 852 | folderPath: rootDir, |
| 853 | imagePath: imgPath, |
| 854 | }); |
| 855 | expect(status).toBe(403); |
| 856 | }); |
| 857 | }); |
| 858 | |
| 859 | describe('file search endpoint', () => |
| 860 | { |
| 861 | test('GET /api/files/search returns fuzzy-matched files across folders', async () => |
| 862 | { |
| 863 | const movieDir = path.join(rootDir, 'Movies'); |
| 864 | const docsDir = path.join(rootDir, 'Docs'); |
| 865 | fs.mkdirSync(movieDir, { recursive: true }); |
| 866 | fs.mkdirSync(docsDir, { recursive: true }); |
| 867 | fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid'); |
| 868 | fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt'); |
| 869 | |
| 870 | const { status, body } = await req('GET', '/api/files/search?query=dbs'); |
| 871 | expect(status).toBe(200); |
| 872 | expect(body.query).toBe('dbs'); |
| 873 | expect(body.results.length).toBeGreaterThan(0); |
| 874 | expect(body.results[0].name).toBe('Dragon Ball Super.mkv'); |
| 875 | }); |
| 876 | |
| 877 | test('GET /api/files/search returns 400 when query is missing', async () => |
| 878 | { |
| 879 | const { status } = await req('GET', '/api/files/search'); |
| 880 | expect(status).toBe(400); |
| 881 | }); |
| 882 | }); |
| 883 | |
| 884 | describe('image search endpoint', () => |
| 885 | { |
| 886 | test('GET /api/files/search-images returns thumbnailed image matches only', async () => |
| 887 | { |
| 888 | const picsDir = path.join(rootDir, 'Pictures'); |
| 889 | fs.mkdirSync(picsDir, { recursive: true }); |
| 890 | fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img'); |
| 891 | fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt'); |
| 892 | |
| 893 | const thumbPath = path.join(rootDir, 'thumb.webp'); |
| 894 | fs.writeFileSync(thumbPath, 'thumb'); |
| 895 | mockThumbPath = thumbPath; |
| 896 | |
| 897 | const { status, body } = await req('GET', '/api/files/search-images?query=dragon'); |
| 898 | expect(status).toBe(200); |
| 899 | expect(body.results.length).toBe(1); |
| 900 | expect(body.results[0].name).toBe('dragon-cover.jpg'); |
| 901 | }); |
| 902 | |
| 903 | test('GET /api/files/search-images returns 400 for short queries', async () => |
| 904 | { |
| 905 | const { status } = await req('GET', '/api/files/search-images?query=a'); |
| 906 | expect(status).toBe(400); |
| 907 | }); |
| 908 | }); |
| 909 | |
| 910 | describe('global favicon endpoints', () => |
| 911 | { |
| 912 | test('GET /api/files/global-favicon returns null when unset', async () => |
| 913 | { |
| 914 | const { status, body } = await req('GET', '/api/files/global-favicon'); |
| 915 | expect(status).toBe(200); |
| 916 | expect(body.favicon).toBeNull(); |
| 917 | }); |
| 918 | |
| 919 | test('POST /api/files/global-favicon stores selected image path', async () => |
| 920 | { |
| 921 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 922 | const thumbPath = path.join(rootDir, 'cover.webp'); |
| 923 | fs.writeFileSync(imgPath, 'img'); |
| 924 | fs.writeFileSync(thumbPath, 'thumb'); |
| 925 | mockThumbPath = thumbPath; |
| 926 | |
| 927 | const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath }); |
| 928 | expect(status).toBe(200); |
| 929 | expect(body.ok).toBe(true); |
| 930 | expect(mockGlobalFaviconPath).toBe(imgPath); |
| 931 | |
| 932 | const fetched = await req('GET', '/api/files/global-favicon'); |
| 933 | expect(fetched.status).toBe(200); |
| 934 | expect(fetched.body.favicon).toEqual({ filePath: imgPath }); |
| 935 | }); |
| 936 | |
| 937 | test('POST /api/files/global-favicon clears the configured favicon', async () => |
| 938 | { |
| 939 | mockGlobalFaviconPath = path.join(rootDir, 'old.jpg'); |
| 940 | |
| 941 | const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null }); |
| 942 | expect(status).toBe(200); |
| 943 | expect(body.ok).toBe(true); |
| 944 | expect(mockGlobalFaviconPath).toBeNull(); |
| 945 | }); |
| 946 | |
| 947 | test('POST /api/files/global-favicon is admin-only', async () => |
| 948 | { |
| 949 | mockUser = { username: 'reader', isAdmin: false, permissions: {} }; |
| 950 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 951 | fs.writeFileSync(imgPath, 'img'); |
| 952 | |
| 953 | const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath }); |
| 954 | expect(status).toBe(403); |
| 955 | }); |
| 956 | }); |
| 957 | |
| 958 | // --------------------------------------------------------------------------- |
| 959 | // GET /api/files/download-zip |
| 960 | // --------------------------------------------------------------------------- |
| 961 | describe('GET /api/files/download-zip', () => |
| 962 | { |
| 963 | beforeEach(() => |
| 964 | { |
| 965 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 966 | }); |
| 967 | |
| 968 | test('streams a valid zip for an accessible directory', async () => |
| 969 | { |
| 970 | const subDir = path.join(rootDir, 'zipme'); |
| 971 | fs.mkdirSync(subDir); |
| 972 | fs.writeFileSync(path.join(subDir, 'file.txt'), 'content'); |
| 973 | |
| 974 | const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`); |
| 975 | expect(status).toBe(200); |
| 976 | |
| 977 | const ct = headers['content-type'] || ''; |
| 978 | expect(ct.includes('zip') || ct.includes('octet')).toBe(true); |
| 979 | |
| 980 | // ZIP magic bytes PK\x03\x04 |
| 981 | expect(buf[0]).toBe(0x50); |
| 982 | expect(buf[1]).toBe(0x4b); |
| 983 | }, 20000); |
| 984 | |
| 985 | test('returns 400 when dir param is missing', async () => |
| 986 | { |
| 987 | const { status } = await req('GET', '/api/files/download-zip'); |
| 988 | expect(status).toBe(400); |
| 989 | }); |
| 990 | |
| 991 | test('returns 404 for a non-existent directory', async () => |
| 992 | { |
| 993 | const missing = path.join(rootDir, 'ghost'); |
| 994 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`); |
| 995 | expect(status).toBe(404); |
| 996 | }); |
| 997 | |
| 998 | test('returns 403 for path outside configured roots', async () => |
| 999 | { |
| 1000 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`); |
| 1001 | expect(status).toBe(403); |
| 1002 | }); |
| 1003 | }); |
| 1004 | |
| 1005 | describe('video streaming routes', () => |
| 1006 | { |
| 1007 | test('POST /api/files/video-stream creates a short-lived playlist session', async () => |
| 1008 | { |
| 1009 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 1010 | fs.writeFileSync(filePath, 'video'); |
| 1011 | mockVideoStreamSession = { |
| 1012 | sessionId: 'sess-123', |
| 1013 | durationSeconds: 42.25, |
| 1014 | videoWidth: 1920, |
| 1015 | videoHeight: 1080, |
| 1016 | subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], |
| 1017 | }; |
| 1018 | |
| 1019 | const { status, body } = await req('POST', '/api/files/video-stream', { filePath }); |
| 1020 | |
| 1021 | expect(status).toBe(200); |
| 1022 | expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8'); |
| 1023 | expect(body.durationSeconds).toBe(42.25); |
| 1024 | expect(body.videoWidth).toBe(1920); |
| 1025 | expect(body.videoHeight).toBe(1080); |
| 1026 | expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 }); |
| 1027 | expect(body.subtitleTracks).toEqual([ |
| 1028 | { |
| 1029 | label: 'English', |
| 1030 | language: 'eng', |
| 1031 | default: true, |
| 1032 | src: '/api/files/video-stream/sess-123/subtitle-0.vtt', |
| 1033 | }, |
| 1034 | ]); |
| 1035 | }); |
| 1036 | |
| 1037 | test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () => |
| 1038 | { |
| 1039 | mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) => |
| 1040 | { |
| 1041 | res.type('text/vtt').send('WEBVTT\n'); |
| 1042 | }; |
| 1043 | |
| 1044 | const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt'); |
| 1045 | |
| 1046 | expect(status).toBe(200); |
| 1047 | expect(headers['content-type']).toMatch(/text\/vtt/); |
| 1048 | expect(body.toString()).toBe('WEBVTT\n'); |
| 1049 | }); |
| 1050 | |
| 1051 | test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () => |
| 1052 | { |
| 1053 | const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123'); |
| 1054 | |
| 1055 | expect(status).toBe(200); |
| 1056 | expect(body).toEqual({ ok: true }); |
| 1057 | expect(releasedVideoStreamSessionId).toBe('sess-123'); |
| 1058 | }); |
| 1059 | |
| 1060 | test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () => |
| 1061 | { |
| 1062 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 1063 | fs.writeFileSync(filePath, 'video'); |
| 1064 | mockSubtitleFrameResult = { |
| 1065 | frame: Buffer.from('png-data'), |
| 1066 | left: 100, |
| 1067 | top: 50, |
| 1068 | width: 320, |
| 1069 | height: 180, |
| 1070 | canvasWidth: 640, |
| 1071 | canvasHeight: 360, |
| 1072 | startTimeSeconds: 1.5, |
| 1073 | endTimeSeconds: 3.2, |
| 1074 | }; |
| 1075 | |
| 1076 | const { status, headers, body } = await reqRaw( |
| 1077 | 'GET', |
| 1078 | `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080` |
| 1079 | ); |
| 1080 | |
| 1081 | expect(status).toBe(200); |
| 1082 | expect(headers['content-type']).toMatch(/image\/png/); |
| 1083 | expect(headers['x-subtitle-frame-status']).toBe('ok'); |
| 1084 | expect(headers['x-subtitle-frame-left']).toBe('100'); |
| 1085 | expect(headers['x-subtitle-frame-top']).toBe('50'); |
| 1086 | expect(headers['x-subtitle-frame-width']).toBe('320'); |
| 1087 | expect(headers['x-subtitle-frame-height']).toBe('180'); |
| 1088 | expect(headers['x-subtitle-frame-canvas-width']).toBe('640'); |
| 1089 | expect(headers['x-subtitle-frame-canvas-height']).toBe('360'); |
| 1090 | expect(headers['x-subtitle-frame-start-time']).toBe('1.5'); |
| 1091 | expect(headers['x-subtitle-frame-end-time']).toBe('3.2'); |
| 1092 | expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0); |
| 1093 | expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0); |
| 1094 | expect(body.equals(Buffer.from('png-data'))).toBe(true); |
| 1095 | }); |
| 1096 | |
| 1097 | test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () => |
| 1098 | { |
| 1099 | const filePath = path.join(rootDir, 'movie.mkv'); |
| 1100 | fs.writeFileSync(filePath, 'video'); |
| 1101 | const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log'); |
| 1102 | |
| 1103 | const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', { |
| 1104 | filePath, |
| 1105 | sessionId: 'sess-123', |
| 1106 | entries: [ |
| 1107 | { loggedAtMs: 1000, eventType: 'subtitle_png_requested' }, |
| 1108 | ], |
| 1109 | }); |
| 1110 | |
| 1111 | expect(status).toBe(200); |
| 1112 | expect(body).toEqual({ ok: true }); |
| 1113 | expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({ |
| 1114 | videoName: 'movie.mkv', |
| 1115 | context: expect.objectContaining({ |
| 1116 | filePath, |
| 1117 | sessionId: 'sess-123', |
| 1118 | source: 'app', |
| 1119 | }), |
| 1120 | })); |
| 1121 | }); |
| 1122 | |
| 1123 | test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () => |
| 1124 | { |
| 1125 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 1126 | fs.writeFileSync(filePath, 'video'); |
| 1127 | mockSubtitleFrameResult = null; |
| 1128 | |
| 1129 | const { status, headers, body } = await reqRaw( |
| 1130 | 'GET', |
| 1131 | `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5` |
| 1132 | ); |
| 1133 | |
| 1134 | expect(status).toBe(204); |
| 1135 | expect(headers['x-subtitle-frame-status']).toBe('none'); |
| 1136 | expect(body.length).toBe(0); |
| 1137 | }); |
| 1138 | |
| 1139 | test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () => |
| 1140 | { |
| 1141 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 1142 | fs.writeFileSync(filePath, 'video'); |
| 1143 | mockSubtitleFrameError = new Error('decode failed'); |
| 1144 | |
| 1145 | const { status, headers, body } = await reqRaw( |
| 1146 | 'GET', |
| 1147 | `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5` |
| 1148 | ); |
| 1149 | |
| 1150 | expect(status).toBe(204); |
| 1151 | expect(headers['x-subtitle-frame-status']).toBe('error'); |
| 1152 | expect(body.length).toBe(0); |
| 1153 | }); |
| 1154 | |
| 1155 | test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () => |
| 1156 | { |
| 1157 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 1158 | fs.writeFileSync(filePath, 'video'); |
| 1159 | |
| 1160 | let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 }); |
| 1161 | expect(result.status).toBe(200); |
| 1162 | expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' }); |
| 1163 | |
| 1164 | // A lower progress update should not downgrade the status. |
| 1165 | result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 }); |
| 1166 | expect(result.status).toBe(200); |
| 1167 | expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' }); |
| 1168 | |
| 1169 | result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 1170 | expect(result.status).toBe(200); |
| 1171 | expect(result.body.watchedBy).toEqual({ admin: 'partway' }); |
| 1172 | |
| 1173 | result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 }); |
| 1174 | expect(result.status).toBe(200); |
| 1175 | expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' }); |
| 1176 | |
| 1177 | result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 1178 | expect(result.status).toBe(200); |
| 1179 | expect(result.body.watchedBy).toEqual({ admin: 'fully' }); |
| 1180 | }); |
| 1181 | |
| 1182 | test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () => |
| 1183 | { |
| 1184 | const clipA = path.join(rootDir, 'clip-a.mkv'); |
| 1185 | const clipB = path.join(rootDir, 'clip-b.mkv'); |
| 1186 | const clipC = path.join(rootDir, 'clip-c.mkv'); |
| 1187 | fs.writeFileSync(clipA, 'a'); |
| 1188 | fs.writeFileSync(clipB, 'b'); |
| 1189 | fs.writeFileSync(clipC, 'c'); |
| 1190 | |
| 1191 | const db = getDb(); |
| 1192 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') |
| 1193 | .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]); |
| 1194 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') |
| 1195 | .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]); |
| 1196 | db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') |
| 1197 | .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]); |
| 1198 | |
| 1199 | const { status, body } = await req('POST', '/api/files/watched-statuses', { |
| 1200 | filePaths: [clipA, clipB, clipC], |
| 1201 | }); |
| 1202 | |
| 1203 | expect(status).toBe(200); |
| 1204 | expect(body.statuses).toEqual({ |
| 1205 | [clipA]: 'fully', |
| 1206 | [clipB]: 'partway', |
| 1207 | }); |
| 1208 | }); |
| 1209 | |
| 1210 | test('POST /api/files/watched-statuses validates filePaths input', async () => |
| 1211 | { |
| 1212 | const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' }); |
| 1213 | expect(status).toBe(400); |
| 1214 | expect(body.error).toMatch(/filePaths array is required/i); |
| 1215 | }); |
| 1216 | }); |
| 1217 | |
| 1218 | describe('SHA-256 hashing and duplicate detection', () => |
| 1219 | { |
| 1220 | test('POST /api/files/upload stores sha256 hash for uploaded files', async () => |
| 1221 | { |
| 1222 | const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 1223 | { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' }, |
| 1224 | ]); |
| 1225 | expect(status).toBe(200); |
| 1226 | |
| 1227 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 1228 | .get([path.join(rootDir, 'hashme.txt')]); |
| 1229 | expect(meta).toBeTruthy(); |
| 1230 | // SHA-256 is a 64-char hex string. |
| 1231 | expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 1232 | }); |
| 1233 | |
| 1234 | test('POST /api/files/upload stores uploaded_at for uploaded files', async () => |
| 1235 | { |
| 1236 | const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 1237 | { name: 'uploaded-at.txt', content: 'hello', type: 'text/plain' }, |
| 1238 | ]); |
| 1239 | expect(status).toBe(200); |
| 1240 | |
| 1241 | const meta = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?') |
| 1242 | .get([path.join(rootDir, 'uploaded-at.txt')]); |
| 1243 | expect(meta).toBeTruthy(); |
| 1244 | expect(String(meta.uploaded_at || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/); |
| 1245 | }); |
| 1246 | |
| 1247 | test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () => |
| 1248 | { |
| 1249 | const filePath = path.join(rootDir, 'lazy.txt'); |
| 1250 | fs.writeFileSync(filePath, 'lazy content'); |
| 1251 | |
| 1252 | // Insert a row without a hash to simulate a pre-existing file. |
| 1253 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 1254 | .run([filePath, 'admin', '[]']); |
| 1255 | |
| 1256 | const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 1257 | expect(status).toBe(200); |
| 1258 | expect(body.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 1259 | |
| 1260 | // Verify it was persisted. |
| 1261 | const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]); |
| 1262 | expect(row.sha256).toBe(body.sha256); |
| 1263 | }); |
| 1264 | |
| 1265 | test('GET /api/files/meta backfills uploaded_at when missing', async () => |
| 1266 | { |
| 1267 | const filePath = path.join(rootDir, 'legacy.txt'); |
| 1268 | fs.writeFileSync(filePath, 'legacy'); |
| 1269 | |
| 1270 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 1271 | .run([filePath, 'admin', '[]']); |
| 1272 | |
| 1273 | const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 1274 | expect(status).toBe(200); |
| 1275 | expect(String(body.uploadedAt || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/); |
| 1276 | |
| 1277 | const row = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([filePath]); |
| 1278 | expect(String(row.uploaded_at || '')).toBe(String(body.uploadedAt || '')); |
| 1279 | }); |
| 1280 | |
| 1281 | test('GET /api/files/duplicates returns other files with the same hash', async () => |
| 1282 | { |
| 1283 | const content = 'duplicate content'; |
| 1284 | const fileA = path.join(rootDir, 'dup-a.txt'); |
| 1285 | const fileB = path.join(rootDir, 'dup-b.txt'); |
| 1286 | fs.writeFileSync(fileA, content); |
| 1287 | fs.writeFileSync(fileB, content); |
| 1288 | |
| 1289 | // Compute the expected hash. |
| 1290 | const crypto = require('crypto'); |
| 1291 | const expectedHash = crypto.createHash('sha256').update(content).digest('hex'); |
| 1292 | |
| 1293 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 1294 | .run([fileA, 'admin', '[]', expectedHash]); |
| 1295 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 1296 | .run([fileB, 'admin', '[]', expectedHash]); |
| 1297 | |
| 1298 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`); |
| 1299 | expect(status).toBe(200); |
| 1300 | expect(body.duplicates).toHaveLength(1); |
| 1301 | expect(body.duplicates[0].path).toBe(fileB); |
| 1302 | expect(body.duplicates[0].name).toBe('dup-b.txt'); |
| 1303 | }); |
| 1304 | |
| 1305 | test('GET /api/files/duplicates returns empty list when no hash is stored', async () => |
| 1306 | { |
| 1307 | const filePath = path.join(rootDir, 'nohash.txt'); |
| 1308 | fs.writeFileSync(filePath, 'no hash yet'); |
| 1309 | |
| 1310 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 1311 | .run([filePath, 'admin', '[]']); |
| 1312 | |
| 1313 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`); |
| 1314 | expect(status).toBe(200); |
| 1315 | expect(body.duplicates).toEqual([]); |
| 1316 | }); |
| 1317 | |
| 1318 | test('GET /api/files/duplicates excludes files outside accessible roots', async () => |
| 1319 | { |
| 1320 | const content = 'secret dupe'; |
| 1321 | const accessible = path.join(rootDir, 'visible.txt'); |
| 1322 | const outsideRoot = path.join(os.tmpdir(), 'outside.txt'); |
| 1323 | fs.writeFileSync(accessible, content); |
| 1324 | |
| 1325 | const crypto = require('crypto'); |
| 1326 | const hash = crypto.createHash('sha256').update(content).digest('hex'); |
| 1327 | |
| 1328 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 1329 | .run([accessible, 'admin', '[]', hash]); |
| 1330 | // Insert a row for a path that is NOT inside any configured root. |
| 1331 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 1332 | .run([outsideRoot, 'admin', '[]', hash]); |
| 1333 | |
| 1334 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`); |
| 1335 | expect(status).toBe(200); |
| 1336 | expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true); |
| 1337 | }); |
| 1338 | |
| 1339 | test('POST /api/files/move preserves sha256 after rename', async () => |
| 1340 | { |
| 1341 | const from = path.join(rootDir, 'withHash.txt'); |
| 1342 | const toDir = path.join(rootDir, 'subfolder'); |
| 1343 | fs.writeFileSync(from, 'content'); |
| 1344 | fs.mkdirSync(toDir); |
| 1345 | |
| 1346 | const hash = 'a'.repeat(64); |
| 1347 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 1348 | .run([from, 'admin', '[]', hash]); |
| 1349 | |
| 1350 | const { status } = await req('POST', '/api/files/move', { from, toDir }); |
| 1351 | expect(status).toBe(200); |
| 1352 | |
| 1353 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 1354 | .get([path.join(toDir, 'withHash.txt')]); |
| 1355 | expect(meta.sha256).toBe(hash); |
| 1356 | }); |
| 1357 | }); |