BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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