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