BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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