BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

6d2b5978 History
files.routes.test.js 37.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 mockUserPath = null;
12let mockRootAliases = {};
13let mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockThumbPath = null;
15let mockFolderImages = [];
16let mockFolderIconFile = null;
17let lastFolderIconAssignment = undefined;
18let mockVideoStreamSession = null;
19let mockVideoStreamAsset = null;
20let releasedVideoStreamSessionId = null;
21let mockSubtitleFrameResult = null;
22let mockSubtitleFrameError = null;
23
24jest.mock('../server/db', () =>
25{
26 const { Database } = require('node-sqlite3-wasm');
27 let db;
28 function getDb ()
29 {
30 if (!db)
31 {
32 db = new Database(':memory:');
33 db.exec(`
34 CREATE TABLE IF NOT EXISTS users (
35 id INTEGER PRIMARY KEY AUTOINCREMENT,
36 username TEXT UNIQUE NOT NULL,
37 password_hash TEXT NOT NULL,
38 is_admin INTEGER NOT NULL DEFAULT 0,
39 permissions TEXT NOT NULL DEFAULT '{}'
40 );
41 CREATE TABLE IF NOT EXISTS file_meta (
42 file_path TEXT PRIMARY KEY,
43 uploader TEXT NOT NULL DEFAULT '',
44 downloaders TEXT NOT NULL DEFAULT '[]',
45 watched_by TEXT NOT NULL DEFAULT '{}',
46 sha256 TEXT
47 );
48 CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);
49 `);
50 }
51 return db;
52 }
53 return { getDb, initDb: getDb };
54});
55
56jest.mock('../server/config', () => ({
57 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
58 saveConfig: (config) =>
59 {
60 mockPaths = [...(config.paths || [])];
61 mockRootAliases = { ...(config.rootAliases || {}) };
62 },
63 getEffectivePaths: (paths) => paths,
64 getAllowedRoot: (targetPath, roots) =>
65 {
66 const path = require('path');
67 const absTarget = path.resolve(String(targetPath || ''));
68 return roots.find((root) =>
69 {
70 const absRoot = path.resolve(root);
71 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
72 }) || null;
73 },
74}));
75
76jest.mock('../server/auth', () => ({
77 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
78}));
79
80jest.mock('../server/thumbnail-cache', () => ({
81 getCachedThumbnailInfo: async () =>
82 {
83 if (!mockThumbPath) return null;
84 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
85 },
86 getFilesWithThumbnailsInDir: async () => mockFolderImages.slice(),
87 getFolderIconSourceFile: async () => mockFolderIconFile,
88 setFolderIconAssignment: async (folderPath, imagePath) =>
89 {
90 lastFolderIconAssignment = { folderPath, imagePath };
91 },
92}));
93
94jest.mock('../server/video-stream', () => ({
95 createVideoStreamSession: jest.fn(async () =>
96 {
97 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
98 return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
99 }),
100 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
101 {
102 if (typeof mockVideoStreamAsset === 'function')
103 {
104 await mockVideoStreamAsset(sessionId, assetPath, req, res);
105 return;
106 }
107 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
108 }),
109 releaseVideoStreamSession: jest.fn((sessionId) =>
110 {
111 releasedVideoStreamSessionId = String(sessionId || '');
112 return true;
113 }),
114}));
115
116jest.mock('../server/image-subtitles', () => ({
117 renderImageSubtitleFrame: jest.fn(async () =>
118 {
119 if (mockSubtitleFrameError) throw mockSubtitleFrameError;
120 return mockSubtitleFrameResult;
121 }),
122}));
123
124const filesRoutes = require('../server/routes/files');
125const { getDb } = require('../server/db');
126
127let server;
128let baseUrl;
129let rootDir;
130
131beforeAll(async () =>
132{
133 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
134 mockPaths = [rootDir];
135
136 const app = express();
137 app.use(express.json());
138 app.use('/api/files', filesRoutes);
139 app.use((err, req, res, next) =>
140 {
141 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
142 });
143
144 server = http.createServer(app);
145 server.listen(0);
146 await once(server, 'listening');
147 baseUrl = `http://127.0.0.1:${server.address().port}`;
148});
149
150afterAll(() =>
151{
152 server.close();
153 fs.rmSync(rootDir, { recursive: true, force: true });
154});
155
156beforeEach(() =>
157{
158 fs.rmSync(rootDir, { recursive: true, force: true });
159 fs.mkdirSync(rootDir, { recursive: true });
160 if (mockUserPath)
161 {
162 fs.rmSync(mockUserPath, { recursive: true, force: true });
163 fs.mkdirSync(mockUserPath, { recursive: true });
164 }
165 mockRootAliases = {};
166 mockUserPath = null;
167 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
168 mockThumbPath = null;
169 mockFolderImages = [];
170 mockFolderIconFile = null;
171 lastFolderIconAssignment = undefined;
172 mockVideoStreamSession = null;
173 mockVideoStreamAsset = null;
174 releasedVideoStreamSessionId = null;
175 mockSubtitleFrameResult = null;
176 mockSubtitleFrameError = null;
177 const db = getDb();
178 db.prepare('DELETE FROM file_meta').run([]);
179 db.prepare('DELETE FROM users').run([]);
180});
181
182function req (method, routePath, body)
183{
184 const payload = body ? JSON.stringify(body) : undefined;
185 return new Promise((resolve, reject) =>
186 {
187 const request = http.request(baseUrl + routePath, {
188 method,
189 headers: {
190 'Content-Type': 'application/json',
191 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
192 },
193 }, res =>
194 {
195 let data = '';
196 res.on('data', chunk => data += chunk);
197 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
198 });
199 request.on('error', reject);
200 if (payload) request.write(payload);
201 request.end();
202 });
203}
204
205function reqRaw (method, routePath)
206{
207 return new Promise((resolve, reject) =>
208 {
209 const request = http.request(baseUrl + routePath, { method }, res =>
210 {
211 const chunks = [];
212 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
213 res.on('end', () => resolve({
214 status: res.statusCode,
215 headers: res.headers,
216 body: Buffer.concat(chunks),
217 }));
218 });
219 request.on('error', reject);
220 request.end();
221 });
222}
223
224function reqMultipart (routePath, files, extraHeaders = {})
225{
226 const boundary = '----filemanager-test-boundary';
227 const buffers = [];
228
229 for (const file of files)
230 {
231 buffers.push(Buffer.from(
232 `--${boundary}\r\n`
233 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
234 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
235 ));
236 buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)));
237 buffers.push(Buffer.from('\r\n'));
238 }
239
240 buffers.push(Buffer.from(`--${boundary}--\r\n`));
241 const payload = Buffer.concat(buffers);
242
243 return new Promise((resolve, reject) =>
244 {
245 const request = http.request(baseUrl + routePath, {
246 method: 'POST',
247 headers: {
248 'Content-Type': `multipart/form-data; boundary=${boundary}`,
249 'Content-Length': payload.length,
250 ...extraHeaders,
251 },
252 }, res =>
253 {
254 let data = '';
255 res.on('data', chunk => data += chunk);
256 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
257 });
258 request.on('error', reject);
259 request.write(payload);
260 request.end();
261 });
262}
263
264function abortMultipartUpload (routePath, file)
265{
266 const boundary = '----filemanager-test-boundary-abort';
267 const header = Buffer.from(
268 `--${boundary}\r\n`
269 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
270 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
271 );
272 const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content));
273
274 return new Promise((resolve) =>
275 {
276 const request = http.request(baseUrl + routePath, {
277 method: 'POST',
278 headers: {
279 'Content-Type': `multipart/form-data; boundary=${boundary}`,
280 },
281 });
282
283 let settled = false;
284 const finish = () =>
285 {
286 if (settled) return;
287 settled = true;
288 resolve();
289 };
290
291 request.on('error', finish);
292 request.on('close', finish);
293 request.write(header);
294 request.write(chunk);
295 setTimeout(() => request.destroy(), 20);
296 });
297}
298
299async function waitFor (predicate, timeoutMs = 500)
300{
301 const start = Date.now();
302 while (Date.now() - start < timeoutMs)
303 {
304 if (predicate()) return;
305 await new Promise(resolve => setTimeout(resolve, 10));
306 }
307 throw new Error('Timed out waiting for condition.');
308}
309
310describe('POST /api/files/upload', () =>
311{
312 test('stores a completed upload under its final name', async () =>
313 {
314 const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
315 { name: 'hello.txt', content: 'hello world', type: 'text/plain' },
316 ]);
317
318 expect(status).toBe(200);
319 expect(body.uploaded).toEqual(['hello.txt']);
320 expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world');
321
322 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
323 .get([path.join(rootDir, 'hello.txt')]);
324 expect(meta).toMatchObject({ uploader: 'admin' });
325 });
326
327 test('removes partial files when the upload connection aborts', async () =>
328 {
329 await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, {
330 name: 'partial.txt',
331 content: Buffer.alloc(256 * 1024, 'a'),
332 type: 'text/plain',
333 });
334
335 await waitFor(() => fs.readdirSync(rootDir).length === 0);
336
337 expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false);
338 expect(fs.readdirSync(rootDir)).toEqual([]);
339
340 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
341 .get([path.join(rootDir, 'partial.txt')]);
342 expect(meta).toBeFalsy();
343 });
344});
345
346describe('POST /api/files/move', () =>
347{
348 test('moves a file into another folder and rewrites metadata', async () =>
349 {
350 const from = path.join(rootDir, 'alpha.txt');
351 const toDir = path.join(rootDir, 'folder');
352 fs.writeFileSync(from, 'hello');
353 fs.mkdirSync(toDir);
354
355 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
356 .run([from, 'admin', '["alice"]']);
357
358 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
359
360 expect(status).toBe(200);
361 expect(body.ok).toBe(true);
362 expect(fs.existsSync(from)).toBe(false);
363 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
364
365 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
366 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
367 });
368
369 test('moves a folder into another folder and rewrites descendant metadata', async () =>
370 {
371 const fromDir = path.join(rootDir, 'src-folder');
372 const nestedFile = path.join(fromDir, 'child.txt');
373 const toDir = path.join(rootDir, 'dest-folder');
374 fs.mkdirSync(fromDir);
375 fs.mkdirSync(toDir);
376 fs.writeFileSync(nestedFile, 'hello');
377
378 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
379 .run([nestedFile, 'admin', '[]']);
380
381 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
382
383 expect(status).toBe(200);
384 expect(fs.existsSync(fromDir)).toBe(false);
385 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
386
387 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
388 .get([path.join(toDir, 'src-folder', 'child.txt')]);
389 expect(movedMeta).toBeTruthy();
390 });
391
392 test('rejects moving a folder into itself', async () =>
393 {
394 const fromDir = path.join(rootDir, 'src-folder');
395 const childDir = path.join(fromDir, 'child');
396 fs.mkdirSync(childDir, { recursive: true });
397
398 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
399
400 expect(status).toBe(400);
401 expect(body.error).toMatch(/folder into itself/i);
402 });
403
404 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
405 {
406 const sourceFile = path.join(rootDir, 'source.txt');
407 const destinationDir = path.join(rootDir, 'dest');
408 fs.mkdirSync(destinationDir);
409 fs.writeFileSync(sourceFile, 'new-content');
410 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
411
412 const { status, body } = await req('POST', '/api/files/move', {
413 from: sourceFile,
414 toDir: destinationDir,
415 conflict: 'overwrite',
416 });
417
418 expect(status).toBe(200);
419 expect(body.conflictResolution).toBe('overwrite');
420 expect(fs.existsSync(sourceFile)).toBe(false);
421 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
422 });
423
424 test('renames destination when conflict strategy is rename', async () =>
425 {
426 const sourceFile = path.join(rootDir, 'report.txt');
427 const destinationDir = path.join(rootDir, 'dest');
428 fs.mkdirSync(destinationDir);
429 fs.writeFileSync(sourceFile, 'latest');
430 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
431
432 const { status, body } = await req('POST', '/api/files/move', {
433 from: sourceFile,
434 toDir: destinationDir,
435 conflict: 'rename',
436 });
437
438 expect(status).toBe(200);
439 expect(body.conflictResolution).toBe('rename');
440 expect(path.basename(body.path)).toBe('report (1).txt');
441 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
442 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
443 });
444
445 test('moves a file into My Folder when rename falls back across filesystems', async () =>
446 {
447 const sourceFile = path.join(rootDir, 'cross-root.txt');
448 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
449 const userFolder = path.join(userFolderBase, 'alice');
450
451 mockPaths = [rootDir];
452 mockUserPath = userFolderBase;
453 mockUser = {
454 username: 'alice',
455 isAdmin: false,
456 permissions: {
457 [path.basename(rootDir)]: { read: true, write: true },
458 },
459 };
460
461 fs.writeFileSync(sourceFile, 'hello');
462 fs.mkdirSync(userFolder, { recursive: true });
463
464 const originalRenameSync = fs.renameSync;
465 fs.renameSync = (from, to) =>
466 {
467 const err = new Error('cross-device move');
468 err.code = 'EXDEV';
469 throw err;
470 };
471
472 try
473 {
474 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
475
476 expect(status).toBe(200);
477 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
478 expect(fs.existsSync(sourceFile)).toBe(false);
479 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
480 } finally
481 {
482 fs.renameSync = originalRenameSync;
483 fs.rmSync(userFolderBase, { recursive: true, force: true });
484 }
485 });
486});
487
488describe('root alias endpoints', () =>
489{
490 test('GET /api/files/roots returns alias label and original name', async () =>
491 {
492 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
493
494 const { status, body } = await req('GET', '/api/files/roots');
495
496 expect(status).toBe(200);
497 expect(body.roots).toHaveLength(1);
498 expect(body.roots[0]).toMatchObject({
499 path: rootDir,
500 label: 'Workspace',
501 alias: 'Workspace',
502 originalName: path.basename(rootDir),
503 });
504 });
505
506 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
507 {
508 const originalBase = path.basename(rootDir);
509 const { status, body } = await req('POST', '/api/files/root-alias', {
510 rootPath: rootDir,
511 alias: 'Shared Files',
512 });
513
514 expect(status).toBe(200);
515 expect(body.ok).toBe(true);
516 expect(body.root).toMatchObject({
517 path: rootDir,
518 label: 'Shared Files',
519 alias: 'Shared Files',
520 originalName: originalBase,
521 });
522 expect(fs.existsSync(rootDir)).toBe(true);
523
524 const afterRoots = await req('GET', '/api/files/roots');
525 expect(afterRoots.status).toBe(200);
526 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
527 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
528 });
529
530 test('POST /api/files/root-alias rejects non-root paths', async () =>
531 {
532 const nested = path.join(rootDir, 'sub');
533 fs.mkdirSync(nested, { recursive: true });
534
535 const { status } = await req('POST', '/api/files/root-alias', {
536 rootPath: nested,
537 alias: 'Nested',
538 });
539
540 expect(status).toBe(400);
541 });
542});
543
544describe('GET /api/files/thumbnail', () =>
545{
546 test('returns 404 while cached thumbnail is not ready', async () =>
547 {
548 const source = path.join(rootDir, 'photo.jpg');
549 fs.writeFileSync(source, 'not-an-image');
550
551 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
552 expect(status).toBe(404);
553 expect(body.error).toMatch(/not ready/i);
554 });
555
556 test('serves cached thumbnail file when available', async () =>
557 {
558 const source = path.join(rootDir, 'photo.jpg');
559 const thumb = path.join(rootDir, 'photo-thumb.webp');
560 fs.writeFileSync(source, 'not-an-image');
561 fs.writeFileSync(thumb, 'webp-bytes');
562 mockThumbPath = thumb;
563
564 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
565 expect(response.status).toBe(200);
566 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
567 expect(response.body.toString('utf8')).toBe('webp-bytes');
568 });
569});
570
571describe('GET /api/files/root-access', () =>
572{
573 test('returns users with R/R+W modes for an exact root path', async () =>
574 {
575 const label = path.basename(rootDir);
576 const db = getDb();
577 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
578 .run(['admin', 'x', 1, '{}']);
579 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
580 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
581 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
582 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
583 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
584 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
585
586 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
587 expect(status).toBe(200);
588 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
589 expect(body.users).toEqual([
590 { username: 'admin', mode: 'R+W' },
591 { username: 'bob', mode: 'R+W' },
592 { username: 'alice', mode: 'R' },
593 ]);
594 });
595
596 test('rejects non-exact nested root paths', async () =>
597 {
598 const nested = path.join(rootDir, 'sub');
599 fs.mkdirSync(nested, { recursive: true });
600
601 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
602 expect(status).toBe(400);
603 });
604});
605
606describe('folder icon endpoints', () =>
607{
608 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
609 {
610 const subDir = path.join(rootDir, 'photos');
611 fs.mkdirSync(subDir);
612 const imgPath = path.join(subDir, 'a.jpg');
613 fs.writeFileSync(imgPath, 'img');
614
615 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
616
617 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
618 expect(status).toBe(200);
619 expect(body.images).toHaveLength(1);
620 expect(body.images[0].filePath).toBe(imgPath);
621 });
622
623 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
624 {
625 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
626 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
627 fs.writeFileSync(videoPath, 'video');
628
629 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
630
631 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
632 expect(status).toBe(200);
633 expect(body.images).toEqual([{ filePath: videoPath }]);
634 });
635
636 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
637 {
638 mockFolderImages = [];
639
640 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
641 expect(status).toBe(200);
642 expect(body.images).toEqual([]);
643 });
644
645 test('GET /api/files/folder-icon returns null when no icon available', async () =>
646 {
647 mockFolderIconFile = null;
648
649 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
650 expect(status).toBe(200);
651 expect(body.icon).toBeNull();
652 });
653
654 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
655 {
656 const imgPath = path.join(rootDir, 'cover.jpg');
657 fs.writeFileSync(imgPath, 'img');
658 mockFolderIconFile = imgPath;
659
660 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
661 expect(status).toBe(200);
662 expect(body.icon).toMatchObject({ filePath: imgPath });
663 });
664
665 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
666 {
667 const imgPath = path.join(rootDir, 'cover.jpg');
668 const thumbFile = path.join(rootDir, 'cover.webp');
669 fs.writeFileSync(imgPath, 'img');
670 fs.writeFileSync(thumbFile, 'webp');
671 mockThumbPath = thumbFile;
672
673 const { status, body } = await req('POST', '/api/files/folder-icon', {
674 folderPath: rootDir,
675 imagePath: imgPath,
676 });
677 expect(status).toBe(200);
678 expect(body.ok).toBe(true);
679 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
680 });
681
682 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
683 {
684 const imgPath = path.join(rootDir, 'missing.jpg');
685 fs.writeFileSync(imgPath, 'img');
686 mockThumbPath = null;
687
688 const { status, body } = await req('POST', '/api/files/folder-icon', {
689 folderPath: rootDir,
690 imagePath: imgPath,
691 });
692 expect(status).toBe(404);
693 expect(body.error).toMatch(/thumbnail not ready/i);
694 });
695
696 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
697 {
698 const { status, body } = await req('POST', '/api/files/folder-icon', {
699 folderPath: rootDir,
700 imagePath: null,
701 });
702 expect(status).toBe(200);
703 expect(body.ok).toBe(true);
704 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
705 });
706
707 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
708 {
709 const label = path.basename(rootDir);
710 mockUser = {
711 username: 'reader',
712 isAdmin: false,
713 permissions: { [label]: { read: true, write: false } },
714 };
715
716 const imgPath = path.join(rootDir, 'photo.jpg');
717 fs.writeFileSync(imgPath, 'img');
718
719 const { status } = await req('POST', '/api/files/folder-icon', {
720 folderPath: rootDir,
721 imagePath: imgPath,
722 });
723 expect(status).toBe(403);
724 });
725});
726
727// ---------------------------------------------------------------------------
728// GET /api/files/download-zip
729// ---------------------------------------------------------------------------
730describe('GET /api/files/download-zip', () =>
731{
732 beforeEach(() =>
733 {
734 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
735 });
736
737 test('streams a valid zip for an accessible directory', async () =>
738 {
739 const subDir = path.join(rootDir, 'zipme');
740 fs.mkdirSync(subDir);
741 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
742
743 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
744 expect(status).toBe(200);
745
746 const ct = headers['content-type'] || '';
747 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
748
749 // ZIP magic bytes PK\x03\x04
750 expect(buf[0]).toBe(0x50);
751 expect(buf[1]).toBe(0x4b);
752 }, 20000);
753
754 test('returns 400 when dir param is missing', async () =>
755 {
756 const { status } = await req('GET', '/api/files/download-zip');
757 expect(status).toBe(400);
758 });
759
760 test('returns 404 for a non-existent directory', async () =>
761 {
762 const missing = path.join(rootDir, 'ghost');
763 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
764 expect(status).toBe(404);
765 });
766
767 test('returns 403 for path outside configured roots', async () =>
768 {
769 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
770 expect(status).toBe(403);
771 });
772});
773
774describe('video streaming routes', () =>
775{
776 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
777 {
778 const filePath = path.join(rootDir, 'clip.mkv');
779 fs.writeFileSync(filePath, 'video');
780 mockVideoStreamSession = {
781 sessionId: 'sess-123',
782 durationSeconds: 42.25,
783 videoWidth: 1920,
784 videoHeight: 1080,
785 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
786 };
787
788 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
789
790 expect(status).toBe(200);
791 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
792 expect(body.durationSeconds).toBe(42.25);
793 expect(body.videoWidth).toBe(1920);
794 expect(body.videoHeight).toBe(1080);
795 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
796 expect(body.subtitleTracks).toEqual([
797 {
798 label: 'English',
799 language: 'eng',
800 default: true,
801 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
802 },
803 ]);
804 });
805
806 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
807 {
808 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
809 {
810 res.type('text/vtt').send('WEBVTT\n');
811 };
812
813 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
814
815 expect(status).toBe(200);
816 expect(headers['content-type']).toMatch(/text\/vtt/);
817 expect(body.toString()).toBe('WEBVTT\n');
818 });
819
820 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
821 {
822 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
823
824 expect(status).toBe(200);
825 expect(body).toEqual({ ok: true });
826 expect(releasedVideoStreamSessionId).toBe('sess-123');
827 });
828
829 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
830 {
831 const filePath = path.join(rootDir, 'clip.mkv');
832 fs.writeFileSync(filePath, 'video');
833 mockSubtitleFrameResult = Buffer.from('png-data');
834
835 const { status, headers, body } = await reqRaw(
836 'GET',
837 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
838 );
839
840 expect(status).toBe(200);
841 expect(headers['content-type']).toMatch(/image\/png/);
842 expect(body.equals(Buffer.from('png-data'))).toBe(true);
843 });
844
845 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
846 {
847 const filePath = path.join(rootDir, 'clip.mkv');
848 fs.writeFileSync(filePath, 'video');
849 mockSubtitleFrameError = new Error('decode failed');
850
851 const { status, body } = await reqRaw(
852 'GET',
853 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
854 );
855
856 expect(status).toBe(204);
857 expect(body.length).toBe(0);
858 });
859
860 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
861 {
862 const filePath = path.join(rootDir, 'clip.mkv');
863 fs.writeFileSync(filePath, 'video');
864
865 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
866 expect(result.status).toBe(200);
867 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
868
869 // A lower progress update should not downgrade the status.
870 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
871 expect(result.status).toBe(200);
872 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
873
874 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
875 expect(result.status).toBe(200);
876 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
877
878 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
879 expect(result.status).toBe(200);
880 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
881
882 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
883 expect(result.status).toBe(200);
884 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
885 });
886
887 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
888 {
889 const clipA = path.join(rootDir, 'clip-a.mkv');
890 const clipB = path.join(rootDir, 'clip-b.mkv');
891 const clipC = path.join(rootDir, 'clip-c.mkv');
892 fs.writeFileSync(clipA, 'a');
893 fs.writeFileSync(clipB, 'b');
894 fs.writeFileSync(clipC, 'c');
895
896 const db = getDb();
897 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
898 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
899 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
900 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
901 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
902 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
903
904 const { status, body } = await req('POST', '/api/files/watched-statuses', {
905 filePaths: [clipA, clipB, clipC],
906 });
907
908 expect(status).toBe(200);
909 expect(body.statuses).toEqual({
910 [clipA]: 'fully',
911 [clipB]: 'partway',
912 });
913 });
914
915 test('POST /api/files/watched-statuses validates filePaths input', async () =>
916 {
917 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
918 expect(status).toBe(400);
919 expect(body.error).toMatch(/filePaths array is required/i);
920 });
921});
922
923describe('SHA-256 hashing and duplicate detection', () =>
924{
925 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
926 {
927 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
928 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
929 ]);
930 expect(status).toBe(200);
931
932 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
933 .get([path.join(rootDir, 'hashme.txt')]);
934 expect(meta).toBeTruthy();
935 // SHA-256 is a 64-char hex string.
936 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
937 });
938
939 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
940 {
941 const filePath = path.join(rootDir, 'lazy.txt');
942 fs.writeFileSync(filePath, 'lazy content');
943
944 // Insert a row without a hash to simulate a pre-existing file.
945 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
946 .run([filePath, 'admin', '[]']);
947
948 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
949 expect(status).toBe(200);
950 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
951
952 // Verify it was persisted.
953 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
954 expect(row.sha256).toBe(body.sha256);
955 });
956
957 test('GET /api/files/duplicates returns other files with the same hash', async () =>
958 {
959 const content = 'duplicate content';
960 const fileA = path.join(rootDir, 'dup-a.txt');
961 const fileB = path.join(rootDir, 'dup-b.txt');
962 fs.writeFileSync(fileA, content);
963 fs.writeFileSync(fileB, content);
964
965 // Compute the expected hash.
966 const crypto = require('crypto');
967 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
968
969 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
970 .run([fileA, 'admin', '[]', expectedHash]);
971 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
972 .run([fileB, 'admin', '[]', expectedHash]);
973
974 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
975 expect(status).toBe(200);
976 expect(body.duplicates).toHaveLength(1);
977 expect(body.duplicates[0].path).toBe(fileB);
978 expect(body.duplicates[0].name).toBe('dup-b.txt');
979 });
980
981 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
982 {
983 const filePath = path.join(rootDir, 'nohash.txt');
984 fs.writeFileSync(filePath, 'no hash yet');
985
986 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
987 .run([filePath, 'admin', '[]']);
988
989 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
990 expect(status).toBe(200);
991 expect(body.duplicates).toEqual([]);
992 });
993
994 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
995 {
996 const content = 'secret dupe';
997 const accessible = path.join(rootDir, 'visible.txt');
998 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
999 fs.writeFileSync(accessible, content);
1000
1001 const crypto = require('crypto');
1002 const hash = crypto.createHash('sha256').update(content).digest('hex');
1003
1004 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1005 .run([accessible, 'admin', '[]', hash]);
1006 // Insert a row for a path that is NOT inside any configured root.
1007 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1008 .run([outsideRoot, 'admin', '[]', hash]);
1009
1010 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1011 expect(status).toBe(200);
1012 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1013 });
1014
1015 test('POST /api/files/move preserves sha256 after rename', async () =>
1016 {
1017 const from = path.join(rootDir, 'withHash.txt');
1018 const toDir = path.join(rootDir, 'subfolder');
1019 fs.writeFileSync(from, 'content');
1020 fs.mkdirSync(toDir);
1021
1022 const hash = 'a'.repeat(64);
1023 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1024 .run([from, 'admin', '[]', hash]);
1025
1026 const { status } = await req('POST', '/api/files/move', { from, toDir });
1027 expect(status).toBe(200);
1028
1029 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1030 .get([path.join(toDir, 'withHash.txt')]);
1031 expect(meta.sha256).toBe(hash);
1032 });
1033});