| 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 mockRootAliases = {}; |
| 12 | let mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 13 | let mockThumbPath = null; |
| 14 | let mockFolderImages = []; |
| 15 | let mockFolderIconFile = null; |
| 16 | let lastFolderIconAssignment = undefined; |
| 17 | let mockVideoStreamSession = null; |
| 18 | let mockVideoStreamAsset = null; |
| 19 | |
| 20 | jest.mock('../server/db', () => |
| 21 | { |
| 22 | const { Database } = require('node-sqlite3-wasm'); |
| 23 | let db; |
| 24 | function getDb () |
| 25 | { |
| 26 | if (!db) |
| 27 | { |
| 28 | db = new Database(':memory:'); |
| 29 | db.exec(` |
| 30 | CREATE TABLE IF NOT EXISTS users ( |
| 31 | id INTEGER PRIMARY KEY AUTOINCREMENT, |
| 32 | username TEXT UNIQUE NOT NULL, |
| 33 | password_hash TEXT NOT NULL, |
| 34 | is_admin INTEGER NOT NULL DEFAULT 0, |
| 35 | permissions TEXT NOT NULL DEFAULT '{}' |
| 36 | ); |
| 37 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 38 | file_path TEXT PRIMARY KEY, |
| 39 | uploader TEXT NOT NULL DEFAULT '', |
| 40 | downloaders TEXT NOT NULL DEFAULT '[]' |
| 41 | ); |
| 42 | `); |
| 43 | } |
| 44 | return db; |
| 45 | } |
| 46 | return { getDb, initDb: getDb }; |
| 47 | }); |
| 48 | |
| 49 | jest.mock('../server/config', () => ({ |
| 50 | loadConfig: () => ({ port: 3000, paths: [...mockPaths], rootAliases: { ...mockRootAliases } }), |
| 51 | saveConfig: (config) => |
| 52 | { |
| 53 | mockPaths = [...(config.paths || [])]; |
| 54 | mockRootAliases = { ...(config.rootAliases || {}) }; |
| 55 | }, |
| 56 | getEffectivePaths: (paths) => paths, |
| 57 | getAllowedRoot: (targetPath, roots) => |
| 58 | { |
| 59 | const path = require('path'); |
| 60 | const absTarget = path.resolve(String(targetPath || '')); |
| 61 | return roots.find((root) => |
| 62 | { |
| 63 | const absRoot = path.resolve(root); |
| 64 | return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); |
| 65 | }) || null; |
| 66 | }, |
| 67 | })); |
| 68 | |
| 69 | jest.mock('../server/auth', () => ({ |
| 70 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 71 | })); |
| 72 | |
| 73 | jest.mock('../server/thumbnail-cache', () => ({ |
| 74 | getCachedThumbnailInfo: async () => |
| 75 | { |
| 76 | if (!mockThumbPath) return null; |
| 77 | return { thumbPath: mockThumbPath, contentType: 'image/webp' }; |
| 78 | }, |
| 79 | getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(), |
| 80 | getFolderIconSourceFile: async () => mockFolderIconFile, |
| 81 | setFolderIconAssignment: async (folderPath, imagePath) => |
| 82 | { |
| 83 | lastFolderIconAssignment = { folderPath, imagePath }; |
| 84 | }, |
| 85 | })); |
| 86 | |
| 87 | jest.mock('../server/video-stream', () => ({ |
| 88 | createVideoStreamSession: jest.fn(async () => |
| 89 | { |
| 90 | if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; |
| 91 | return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] }; |
| 92 | }), |
| 93 | sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, res) => |
| 94 | { |
| 95 | if (typeof mockVideoStreamAsset === 'function') |
| 96 | { |
| 97 | await mockVideoStreamAsset(sessionId, assetPath, res); |
| 98 | return; |
| 99 | } |
| 100 | res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); |
| 101 | }), |
| 102 | })); |
| 103 | |
| 104 | const filesRoutes = require('../server/routes/files'); |
| 105 | const { getDb } = require('../server/db'); |
| 106 | |
| 107 | let server; |
| 108 | let baseUrl; |
| 109 | let rootDir; |
| 110 | |
| 111 | beforeAll(async () => |
| 112 | { |
| 113 | rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); |
| 114 | mockPaths = [rootDir]; |
| 115 | |
| 116 | const app = express(); |
| 117 | app.use(express.json()); |
| 118 | app.use('/api/files', filesRoutes); |
| 119 | app.use((err, req, res, next) => |
| 120 | { |
| 121 | res.status(err.status || 500).json({ error: err.message || 'Internal error' }); |
| 122 | }); |
| 123 | |
| 124 | server = http.createServer(app); |
| 125 | server.listen(0); |
| 126 | await once(server, 'listening'); |
| 127 | baseUrl = `http://127.0.0.1:${server.address().port}`; |
| 128 | }); |
| 129 | |
| 130 | afterAll(() => |
| 131 | { |
| 132 | server.close(); |
| 133 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 134 | }); |
| 135 | |
| 136 | beforeEach(() => |
| 137 | { |
| 138 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 139 | fs.mkdirSync(rootDir, { recursive: true }); |
| 140 | mockRootAliases = {}; |
| 141 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 142 | mockThumbPath = null; |
| 143 | mockFolderImages = []; |
| 144 | mockFolderIconFile = null; |
| 145 | lastFolderIconAssignment = undefined; |
| 146 | mockVideoStreamSession = null; |
| 147 | mockVideoStreamAsset = null; |
| 148 | const db = getDb(); |
| 149 | db.prepare('DELETE FROM file_meta').run([]); |
| 150 | db.prepare('DELETE FROM users').run([]); |
| 151 | }); |
| 152 | |
| 153 | function req (method, routePath, body) |
| 154 | { |
| 155 | const payload = body ? JSON.stringify(body) : undefined; |
| 156 | return new Promise((resolve, reject) => |
| 157 | { |
| 158 | const request = http.request(baseUrl + routePath, { |
| 159 | method, |
| 160 | headers: { |
| 161 | 'Content-Type': 'application/json', |
| 162 | ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), |
| 163 | }, |
| 164 | }, res => |
| 165 | { |
| 166 | let data = ''; |
| 167 | res.on('data', chunk => data += chunk); |
| 168 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 169 | }); |
| 170 | request.on('error', reject); |
| 171 | if (payload) request.write(payload); |
| 172 | request.end(); |
| 173 | }); |
| 174 | } |
| 175 | |
| 176 | function reqRaw (method, routePath) |
| 177 | { |
| 178 | return new Promise((resolve, reject) => |
| 179 | { |
| 180 | const request = http.request(baseUrl + routePath, { method }, res => |
| 181 | { |
| 182 | const chunks = []; |
| 183 | res.on('data', chunk => chunks.push(Buffer.from(chunk))); |
| 184 | res.on('end', () => resolve({ |
| 185 | status: res.statusCode, |
| 186 | headers: res.headers, |
| 187 | body: Buffer.concat(chunks), |
| 188 | })); |
| 189 | }); |
| 190 | request.on('error', reject); |
| 191 | request.end(); |
| 192 | }); |
| 193 | } |
| 194 | |
| 195 | function reqMultipart (routePath, files, extraHeaders = {}) |
| 196 | { |
| 197 | const boundary = '----filemanager-test-boundary'; |
| 198 | const buffers = []; |
| 199 | |
| 200 | for (const file of files) |
| 201 | { |
| 202 | buffers.push(Buffer.from( |
| 203 | `--${boundary}\r\n` |
| 204 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 205 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 206 | )); |
| 207 | buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content))); |
| 208 | buffers.push(Buffer.from('\r\n')); |
| 209 | } |
| 210 | |
| 211 | buffers.push(Buffer.from(`--${boundary}--\r\n`)); |
| 212 | const payload = Buffer.concat(buffers); |
| 213 | |
| 214 | return new Promise((resolve, reject) => |
| 215 | { |
| 216 | const request = http.request(baseUrl + routePath, { |
| 217 | method: 'POST', |
| 218 | headers: { |
| 219 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 220 | 'Content-Length': payload.length, |
| 221 | ...extraHeaders, |
| 222 | }, |
| 223 | }, res => |
| 224 | { |
| 225 | let data = ''; |
| 226 | res.on('data', chunk => data += chunk); |
| 227 | res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); |
| 228 | }); |
| 229 | request.on('error', reject); |
| 230 | request.write(payload); |
| 231 | request.end(); |
| 232 | }); |
| 233 | } |
| 234 | |
| 235 | function abortMultipartUpload (routePath, file) |
| 236 | { |
| 237 | const boundary = '----filemanager-test-boundary-abort'; |
| 238 | const header = Buffer.from( |
| 239 | `--${boundary}\r\n` |
| 240 | + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` |
| 241 | + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` |
| 242 | ); |
| 243 | const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)); |
| 244 | |
| 245 | return new Promise((resolve) => |
| 246 | { |
| 247 | const request = http.request(baseUrl + routePath, { |
| 248 | method: 'POST', |
| 249 | headers: { |
| 250 | 'Content-Type': `multipart/form-data; boundary=${boundary}`, |
| 251 | }, |
| 252 | }); |
| 253 | |
| 254 | let settled = false; |
| 255 | const finish = () => |
| 256 | { |
| 257 | if (settled) return; |
| 258 | settled = true; |
| 259 | resolve(); |
| 260 | }; |
| 261 | |
| 262 | request.on('error', finish); |
| 263 | request.on('close', finish); |
| 264 | request.write(header); |
| 265 | request.write(chunk); |
| 266 | setTimeout(() => request.destroy(), 20); |
| 267 | }); |
| 268 | } |
| 269 | |
| 270 | async function waitFor(predicate, timeoutMs = 500) |
| 271 | { |
| 272 | const start = Date.now(); |
| 273 | while (Date.now() - start < timeoutMs) |
| 274 | { |
| 275 | if (predicate()) return; |
| 276 | await new Promise(resolve => setTimeout(resolve, 10)); |
| 277 | } |
| 278 | throw new Error('Timed out waiting for condition.'); |
| 279 | } |
| 280 | |
| 281 | describe('POST /api/files/upload', () => |
| 282 | { |
| 283 | test('stores a completed upload under its final name', async () => |
| 284 | { |
| 285 | const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 286 | { name: 'hello.txt', content: 'hello world', type: 'text/plain' }, |
| 287 | ]); |
| 288 | |
| 289 | expect(status).toBe(200); |
| 290 | expect(body.uploaded).toEqual(['hello.txt']); |
| 291 | expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world'); |
| 292 | |
| 293 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 294 | .get([path.join(rootDir, 'hello.txt')]); |
| 295 | expect(meta).toMatchObject({ uploader: 'admin' }); |
| 296 | }); |
| 297 | |
| 298 | test('removes partial files when the upload connection aborts', async () => |
| 299 | { |
| 300 | await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, { |
| 301 | name: 'partial.txt', |
| 302 | content: Buffer.alloc(256 * 1024, 'a'), |
| 303 | type: 'text/plain', |
| 304 | }); |
| 305 | |
| 306 | await waitFor(() => fs.readdirSync(rootDir).length === 0); |
| 307 | |
| 308 | expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false); |
| 309 | expect(fs.readdirSync(rootDir)).toEqual([]); |
| 310 | |
| 311 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 312 | .get([path.join(rootDir, 'partial.txt')]); |
| 313 | expect(meta).toBeFalsy(); |
| 314 | }); |
| 315 | }); |
| 316 | |
| 317 | describe('POST /api/files/move', () => |
| 318 | { |
| 319 | test('moves a file into another folder and rewrites metadata', async () => |
| 320 | { |
| 321 | const from = path.join(rootDir, 'alpha.txt'); |
| 322 | const toDir = path.join(rootDir, 'folder'); |
| 323 | fs.writeFileSync(from, 'hello'); |
| 324 | fs.mkdirSync(toDir); |
| 325 | |
| 326 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 327 | .run([from, 'admin', '["alice"]']); |
| 328 | |
| 329 | const { status, body } = await req('POST', '/api/files/move', { from, toDir }); |
| 330 | |
| 331 | expect(status).toBe(200); |
| 332 | expect(body.ok).toBe(true); |
| 333 | expect(fs.existsSync(from)).toBe(false); |
| 334 | expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); |
| 335 | |
| 336 | const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); |
| 337 | expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); |
| 338 | }); |
| 339 | |
| 340 | test('moves a folder into another folder and rewrites descendant metadata', async () => |
| 341 | { |
| 342 | const fromDir = path.join(rootDir, 'src-folder'); |
| 343 | const nestedFile = path.join(fromDir, 'child.txt'); |
| 344 | const toDir = path.join(rootDir, 'dest-folder'); |
| 345 | fs.mkdirSync(fromDir); |
| 346 | fs.mkdirSync(toDir); |
| 347 | fs.writeFileSync(nestedFile, 'hello'); |
| 348 | |
| 349 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 350 | .run([nestedFile, 'admin', '[]']); |
| 351 | |
| 352 | const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); |
| 353 | |
| 354 | expect(status).toBe(200); |
| 355 | expect(fs.existsSync(fromDir)).toBe(false); |
| 356 | expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); |
| 357 | |
| 358 | const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') |
| 359 | .get([path.join(toDir, 'src-folder', 'child.txt')]); |
| 360 | expect(movedMeta).toBeTruthy(); |
| 361 | }); |
| 362 | |
| 363 | test('rejects moving a folder into itself', async () => |
| 364 | { |
| 365 | const fromDir = path.join(rootDir, 'src-folder'); |
| 366 | const childDir = path.join(fromDir, 'child'); |
| 367 | fs.mkdirSync(childDir, { recursive: true }); |
| 368 | |
| 369 | const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); |
| 370 | |
| 371 | expect(status).toBe(400); |
| 372 | expect(body.error).toMatch(/folder into itself/i); |
| 373 | }); |
| 374 | |
| 375 | test('overwrites an existing destination when conflict strategy is overwrite', async () => |
| 376 | { |
| 377 | const sourceFile = path.join(rootDir, 'source.txt'); |
| 378 | const destinationDir = path.join(rootDir, 'dest'); |
| 379 | fs.mkdirSync(destinationDir); |
| 380 | fs.writeFileSync(sourceFile, 'new-content'); |
| 381 | fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content'); |
| 382 | |
| 383 | const { status, body } = await req('POST', '/api/files/move', { |
| 384 | from: sourceFile, |
| 385 | toDir: destinationDir, |
| 386 | conflict: 'overwrite', |
| 387 | }); |
| 388 | |
| 389 | expect(status).toBe(200); |
| 390 | expect(body.conflictResolution).toBe('overwrite'); |
| 391 | expect(fs.existsSync(sourceFile)).toBe(false); |
| 392 | expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content'); |
| 393 | }); |
| 394 | |
| 395 | test('renames destination when conflict strategy is rename', async () => |
| 396 | { |
| 397 | const sourceFile = path.join(rootDir, 'report.txt'); |
| 398 | const destinationDir = path.join(rootDir, 'dest'); |
| 399 | fs.mkdirSync(destinationDir); |
| 400 | fs.writeFileSync(sourceFile, 'latest'); |
| 401 | fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing'); |
| 402 | |
| 403 | const { status, body } = await req('POST', '/api/files/move', { |
| 404 | from: sourceFile, |
| 405 | toDir: destinationDir, |
| 406 | conflict: 'rename', |
| 407 | }); |
| 408 | |
| 409 | expect(status).toBe(200); |
| 410 | expect(body.conflictResolution).toBe('rename'); |
| 411 | expect(path.basename(body.path)).toBe('report (1).txt'); |
| 412 | expect(fs.readFileSync(body.path, 'utf8')).toBe('latest'); |
| 413 | expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing'); |
| 414 | }); |
| 415 | }); |
| 416 | |
| 417 | describe('root alias endpoints', () => |
| 418 | { |
| 419 | test('GET /api/files/roots returns alias label and original name', async () => |
| 420 | { |
| 421 | mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; |
| 422 | |
| 423 | const { status, body } = await req('GET', '/api/files/roots'); |
| 424 | |
| 425 | expect(status).toBe(200); |
| 426 | expect(body.roots).toHaveLength(1); |
| 427 | expect(body.roots[0]).toMatchObject({ |
| 428 | path: rootDir, |
| 429 | label: 'Workspace', |
| 430 | alias: 'Workspace', |
| 431 | originalName: path.basename(rootDir), |
| 432 | }); |
| 433 | }); |
| 434 | |
| 435 | test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => |
| 436 | { |
| 437 | const originalBase = path.basename(rootDir); |
| 438 | const { status, body } = await req('POST', '/api/files/root-alias', { |
| 439 | rootPath: rootDir, |
| 440 | alias: 'Shared Files', |
| 441 | }); |
| 442 | |
| 443 | expect(status).toBe(200); |
| 444 | expect(body.ok).toBe(true); |
| 445 | expect(body.root).toMatchObject({ |
| 446 | path: rootDir, |
| 447 | label: 'Shared Files', |
| 448 | alias: 'Shared Files', |
| 449 | originalName: originalBase, |
| 450 | }); |
| 451 | expect(fs.existsSync(rootDir)).toBe(true); |
| 452 | |
| 453 | const afterRoots = await req('GET', '/api/files/roots'); |
| 454 | expect(afterRoots.status).toBe(200); |
| 455 | expect(afterRoots.body.roots[0].label).toBe('Shared Files'); |
| 456 | expect(afterRoots.body.roots[0].originalName).toBe(originalBase); |
| 457 | }); |
| 458 | |
| 459 | test('POST /api/files/root-alias rejects non-root paths', async () => |
| 460 | { |
| 461 | const nested = path.join(rootDir, 'sub'); |
| 462 | fs.mkdirSync(nested, { recursive: true }); |
| 463 | |
| 464 | const { status } = await req('POST', '/api/files/root-alias', { |
| 465 | rootPath: nested, |
| 466 | alias: 'Nested', |
| 467 | }); |
| 468 | |
| 469 | expect(status).toBe(400); |
| 470 | }); |
| 471 | }); |
| 472 | |
| 473 | describe('GET /api/files/thumbnail', () => |
| 474 | { |
| 475 | test('returns 404 while cached thumbnail is not ready', async () => |
| 476 | { |
| 477 | const source = path.join(rootDir, 'photo.jpg'); |
| 478 | fs.writeFileSync(source, 'not-an-image'); |
| 479 | |
| 480 | const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 481 | expect(status).toBe(404); |
| 482 | expect(body.error).toMatch(/not ready/i); |
| 483 | }); |
| 484 | |
| 485 | test('serves cached thumbnail file when available', async () => |
| 486 | { |
| 487 | const source = path.join(rootDir, 'photo.jpg'); |
| 488 | const thumb = path.join(rootDir, 'photo-thumb.webp'); |
| 489 | fs.writeFileSync(source, 'not-an-image'); |
| 490 | fs.writeFileSync(thumb, 'webp-bytes'); |
| 491 | mockThumbPath = thumb; |
| 492 | |
| 493 | const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); |
| 494 | expect(response.status).toBe(200); |
| 495 | expect(String(response.headers['content-type'] || '')).toContain('image/webp'); |
| 496 | expect(response.body.toString('utf8')).toBe('webp-bytes'); |
| 497 | }); |
| 498 | }); |
| 499 | |
| 500 | describe('GET /api/files/root-access', () => |
| 501 | { |
| 502 | test('returns users with R/R+W modes for an exact root path', async () => |
| 503 | { |
| 504 | const label = path.basename(rootDir); |
| 505 | const db = getDb(); |
| 506 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 507 | .run(['admin', 'x', 1, '{}']); |
| 508 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 509 | .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]); |
| 510 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 511 | .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]); |
| 512 | db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') |
| 513 | .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]); |
| 514 | |
| 515 | const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`); |
| 516 | expect(status).toBe(200); |
| 517 | expect(body.root).toMatchObject({ path: rootDir, originalName: label }); |
| 518 | expect(body.users).toEqual([ |
| 519 | { username: 'admin', mode: 'R+W' }, |
| 520 | { username: 'bob', mode: 'R+W' }, |
| 521 | { username: 'alice', mode: 'R' }, |
| 522 | ]); |
| 523 | }); |
| 524 | |
| 525 | test('rejects non-exact nested root paths', async () => |
| 526 | { |
| 527 | const nested = path.join(rootDir, 'sub'); |
| 528 | fs.mkdirSync(nested, { recursive: true }); |
| 529 | |
| 530 | const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`); |
| 531 | expect(status).toBe(400); |
| 532 | }); |
| 533 | }); |
| 534 | |
| 535 | describe('folder icon endpoints', () => |
| 536 | { |
| 537 | test('GET /api/files/folder-images returns images that have cached thumbnails', async () => |
| 538 | { |
| 539 | const subDir = path.join(rootDir, 'photos'); |
| 540 | fs.mkdirSync(subDir); |
| 541 | const imgPath = path.join(subDir, 'a.jpg'); |
| 542 | fs.writeFileSync(imgPath, 'img'); |
| 543 | |
| 544 | mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }]; |
| 545 | |
| 546 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 547 | expect(status).toBe(200); |
| 548 | expect(body.images).toHaveLength(1); |
| 549 | expect(body.images[0].filePath).toBe(imgPath); |
| 550 | }); |
| 551 | |
| 552 | test('GET /api/files/folder-images returns empty list when no thumbnails available', async () => |
| 553 | { |
| 554 | mockFolderImages = []; |
| 555 | |
| 556 | const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); |
| 557 | expect(status).toBe(200); |
| 558 | expect(body.images).toEqual([]); |
| 559 | }); |
| 560 | |
| 561 | test('GET /api/files/folder-icon returns null when no icon available', async () => |
| 562 | { |
| 563 | mockFolderIconFile = null; |
| 564 | |
| 565 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 566 | expect(status).toBe(200); |
| 567 | expect(body.icon).toBeNull(); |
| 568 | }); |
| 569 | |
| 570 | test('GET /api/files/folder-icon returns source file path when icon is available', async () => |
| 571 | { |
| 572 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 573 | fs.writeFileSync(imgPath, 'img'); |
| 574 | mockFolderIconFile = imgPath; |
| 575 | |
| 576 | const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); |
| 577 | expect(status).toBe(200); |
| 578 | expect(body.icon).toMatchObject({ filePath: imgPath }); |
| 579 | }); |
| 580 | |
| 581 | test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () => |
| 582 | { |
| 583 | const imgPath = path.join(rootDir, 'cover.jpg'); |
| 584 | const thumbFile = path.join(rootDir, 'cover.webp'); |
| 585 | fs.writeFileSync(imgPath, 'img'); |
| 586 | fs.writeFileSync(thumbFile, 'webp'); |
| 587 | mockThumbPath = thumbFile; |
| 588 | |
| 589 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 590 | folderPath: rootDir, |
| 591 | imagePath: imgPath, |
| 592 | }); |
| 593 | expect(status).toBe(200); |
| 594 | expect(body.ok).toBe(true); |
| 595 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath }); |
| 596 | }); |
| 597 | |
| 598 | test('POST /api/files/folder-icon rejects image without cached thumbnail', async () => |
| 599 | { |
| 600 | const imgPath = path.join(rootDir, 'missing.jpg'); |
| 601 | fs.writeFileSync(imgPath, 'img'); |
| 602 | mockThumbPath = null; |
| 603 | |
| 604 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 605 | folderPath: rootDir, |
| 606 | imagePath: imgPath, |
| 607 | }); |
| 608 | expect(status).toBe(404); |
| 609 | expect(body.error).toMatch(/thumbnail not ready/i); |
| 610 | }); |
| 611 | |
| 612 | test('POST /api/files/folder-icon clears assignment when imagePath is null', async () => |
| 613 | { |
| 614 | const { status, body } = await req('POST', '/api/files/folder-icon', { |
| 615 | folderPath: rootDir, |
| 616 | imagePath: null, |
| 617 | }); |
| 618 | expect(status).toBe(200); |
| 619 | expect(body.ok).toBe(true); |
| 620 | expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null }); |
| 621 | }); |
| 622 | |
| 623 | test('POST /api/files/folder-icon returns 403 for read-only user', async () => |
| 624 | { |
| 625 | const label = path.basename(rootDir); |
| 626 | mockUser = { |
| 627 | username: 'reader', |
| 628 | isAdmin: false, |
| 629 | permissions: { [label]: { read: true, write: false } }, |
| 630 | }; |
| 631 | |
| 632 | const imgPath = path.join(rootDir, 'photo.jpg'); |
| 633 | fs.writeFileSync(imgPath, 'img'); |
| 634 | |
| 635 | const { status } = await req('POST', '/api/files/folder-icon', { |
| 636 | folderPath: rootDir, |
| 637 | imagePath: imgPath, |
| 638 | }); |
| 639 | expect(status).toBe(403); |
| 640 | }); |
| 641 | }); |
| 642 | |
| 643 | // --------------------------------------------------------------------------- |
| 644 | // GET /api/files/download-zip |
| 645 | // --------------------------------------------------------------------------- |
| 646 | describe('GET /api/files/download-zip', () => |
| 647 | { |
| 648 | beforeEach(() => |
| 649 | { |
| 650 | mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 651 | }); |
| 652 | |
| 653 | test('streams a valid zip for an accessible directory', async () => |
| 654 | { |
| 655 | const subDir = path.join(rootDir, 'zipme'); |
| 656 | fs.mkdirSync(subDir); |
| 657 | fs.writeFileSync(path.join(subDir, 'file.txt'), 'content'); |
| 658 | |
| 659 | const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`); |
| 660 | expect(status).toBe(200); |
| 661 | |
| 662 | const ct = headers['content-type'] || ''; |
| 663 | expect(ct.includes('zip') || ct.includes('octet')).toBe(true); |
| 664 | |
| 665 | // ZIP magic bytes PK\x03\x04 |
| 666 | expect(buf[0]).toBe(0x50); |
| 667 | expect(buf[1]).toBe(0x4b); |
| 668 | }, 20000); |
| 669 | |
| 670 | test('returns 400 when dir param is missing', async () => |
| 671 | { |
| 672 | const { status } = await req('GET', '/api/files/download-zip'); |
| 673 | expect(status).toBe(400); |
| 674 | }); |
| 675 | |
| 676 | test('returns 404 for a non-existent directory', async () => |
| 677 | { |
| 678 | const missing = path.join(rootDir, 'ghost'); |
| 679 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`); |
| 680 | expect(status).toBe(404); |
| 681 | }); |
| 682 | |
| 683 | test('returns 403 for path outside configured roots', async () => |
| 684 | { |
| 685 | const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`); |
| 686 | expect(status).toBe(403); |
| 687 | }); |
| 688 | }); |
| 689 | |
| 690 | describe('video streaming routes', () => |
| 691 | { |
| 692 | test('POST /api/files/video-stream creates a short-lived playlist session', async () => |
| 693 | { |
| 694 | const filePath = path.join(rootDir, 'clip.mkv'); |
| 695 | fs.writeFileSync(filePath, 'video'); |
| 696 | mockVideoStreamSession = { |
| 697 | sessionId: 'sess-123', |
| 698 | subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], |
| 699 | }; |
| 700 | |
| 701 | const { status, body } = await req('POST', '/api/files/video-stream', { filePath }); |
| 702 | |
| 703 | expect(status).toBe(200); |
| 704 | expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8'); |
| 705 | expect(body.subtitleTracks).toEqual([ |
| 706 | { |
| 707 | label: 'English', |
| 708 | language: 'eng', |
| 709 | default: true, |
| 710 | src: '/api/files/video-stream/sess-123/subtitle-0.vtt', |
| 711 | }, |
| 712 | ]); |
| 713 | }); |
| 714 | |
| 715 | test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () => |
| 716 | { |
| 717 | mockVideoStreamAsset = async (_sessionId, _assetPath, res) => |
| 718 | { |
| 719 | res.type('text/vtt').send('WEBVTT\n'); |
| 720 | }; |
| 721 | |
| 722 | const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt'); |
| 723 | |
| 724 | expect(status).toBe(200); |
| 725 | expect(headers['content-type']).toMatch(/text\/vtt/); |
| 726 | expect(body.toString()).toBe('WEBVTT\n'); |
| 727 | }); |
| 728 | }); |