BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

8fd0f82d History
files.routes.test.js 44.7 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('orphaned user folder access', () =>
616{
617 test('admins can read and write in orphaned user folders', async () =>
618 {
619 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
620 const orphanFolder = path.join(userFolderBase, 'ghost-user');
621 fs.mkdirSync(orphanFolder, { recursive: true });
622 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
623
624 mockUserPath = userFolderBase;
625 mockUser = {
626 username: 'admin',
627 isAdmin: true,
628 permissions: {},
629 };
630
631 try
632 {
633 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
634 expect(listRes.status).toBe(200);
635 expect(Array.isArray(listRes.body.items)).toBe(true);
636 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
637
638 const mkdirRes = await req('POST', '/api/files/mkdir', {
639 dir: orphanFolder,
640 name: 'created-by-admin',
641 });
642 expect(mkdirRes.status).toBe(200);
643 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
644 } finally
645 {
646 fs.rmSync(userFolderBase, { recursive: true, force: true });
647 }
648 });
649
650 test('non-admin users cannot access orphaned user folders', async () =>
651 {
652 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
653 const orphanFolder = path.join(userFolderBase, 'ghost-user');
654 fs.mkdirSync(orphanFolder, { recursive: true });
655
656 mockUserPath = userFolderBase;
657 mockUser = {
658 username: 'alice',
659 isAdmin: false,
660 permissions: {},
661 };
662
663 try
664 {
665 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
666 expect(listRes.status).toBe(403);
667 } finally
668 {
669 fs.rmSync(userFolderBase, { recursive: true, force: true });
670 }
671 });
672});
673
674describe('folder icon endpoints', () =>
675{
676 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
677 {
678 const subDir = path.join(rootDir, 'photos');
679 fs.mkdirSync(subDir);
680 const imgPath = path.join(subDir, 'a.jpg');
681 fs.writeFileSync(imgPath, 'img');
682
683 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
684
685 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
686 expect(status).toBe(200);
687 expect(body.images).toHaveLength(1);
688 expect(body.images[0].filePath).toBe(imgPath);
689 });
690
691 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
692 {
693 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
694 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
695 fs.writeFileSync(videoPath, 'video');
696
697 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
698
699 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
700 expect(status).toBe(200);
701 expect(body.images).toEqual([{ filePath: videoPath }]);
702 });
703
704 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
705 {
706 mockFolderImages = [];
707
708 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
709 expect(status).toBe(200);
710 expect(body.images).toEqual([]);
711 });
712
713 test('GET /api/files/folder-icon returns null when no icon available', async () =>
714 {
715 mockFolderIconFile = null;
716
717 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
718 expect(status).toBe(200);
719 expect(body.icon).toBeNull();
720 });
721
722 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
723 {
724 const imgPath = path.join(rootDir, 'cover.jpg');
725 fs.writeFileSync(imgPath, 'img');
726 mockFolderIconFile = imgPath;
727
728 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
729 expect(status).toBe(200);
730 expect(body.icon).toMatchObject({ filePath: imgPath });
731 });
732
733 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
734 {
735 const imgPath = path.join(rootDir, 'cover.jpg');
736 const thumbFile = path.join(rootDir, 'cover.webp');
737 fs.writeFileSync(imgPath, 'img');
738 fs.writeFileSync(thumbFile, 'webp');
739 mockThumbPath = thumbFile;
740
741 const { status, body } = await req('POST', '/api/files/folder-icon', {
742 folderPath: rootDir,
743 imagePath: imgPath,
744 });
745 expect(status).toBe(200);
746 expect(body.ok).toBe(true);
747 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
748 });
749
750 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
751 {
752 const imgPath = path.join(rootDir, 'missing.jpg');
753 fs.writeFileSync(imgPath, 'img');
754 mockThumbPath = null;
755
756 const { status, body } = await req('POST', '/api/files/folder-icon', {
757 folderPath: rootDir,
758 imagePath: imgPath,
759 });
760 expect(status).toBe(404);
761 expect(body.error).toMatch(/thumbnail not ready/i);
762 });
763
764 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
765 {
766 const { status, body } = await req('POST', '/api/files/folder-icon', {
767 folderPath: rootDir,
768 imagePath: null,
769 });
770 expect(status).toBe(200);
771 expect(body.ok).toBe(true);
772 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
773 });
774
775 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
776 {
777 const label = path.basename(rootDir);
778 mockUser = {
779 username: 'reader',
780 isAdmin: false,
781 permissions: { [label]: { read: true, write: false } },
782 };
783
784 const imgPath = path.join(rootDir, 'photo.jpg');
785 fs.writeFileSync(imgPath, 'img');
786
787 const { status } = await req('POST', '/api/files/folder-icon', {
788 folderPath: rootDir,
789 imagePath: imgPath,
790 });
791 expect(status).toBe(403);
792 });
793});
794
795describe('file search endpoint', () =>
796{
797 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
798 {
799 const movieDir = path.join(rootDir, 'Movies');
800 const docsDir = path.join(rootDir, 'Docs');
801 fs.mkdirSync(movieDir, { recursive: true });
802 fs.mkdirSync(docsDir, { recursive: true });
803 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
804 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
805
806 const { status, body } = await req('GET', '/api/files/search?query=dbs');
807 expect(status).toBe(200);
808 expect(body.query).toBe('dbs');
809 expect(body.results.length).toBeGreaterThan(0);
810 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
811 });
812
813 test('GET /api/files/search returns 400 when query is missing', async () =>
814 {
815 const { status } = await req('GET', '/api/files/search');
816 expect(status).toBe(400);
817 });
818});
819
820describe('image search endpoint', () =>
821{
822 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
823 {
824 const picsDir = path.join(rootDir, 'Pictures');
825 fs.mkdirSync(picsDir, { recursive: true });
826 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
827 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
828
829 const thumbPath = path.join(rootDir, 'thumb.webp');
830 fs.writeFileSync(thumbPath, 'thumb');
831 mockThumbPath = thumbPath;
832
833 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
834 expect(status).toBe(200);
835 expect(body.results.length).toBe(1);
836 expect(body.results[0].name).toBe('dragon-cover.jpg');
837 });
838
839 test('GET /api/files/search-images returns 400 for short queries', async () =>
840 {
841 const { status } = await req('GET', '/api/files/search-images?query=a');
842 expect(status).toBe(400);
843 });
844});
845
846describe('global favicon endpoints', () =>
847{
848 test('GET /api/files/global-favicon returns null when unset', async () =>
849 {
850 const { status, body } = await req('GET', '/api/files/global-favicon');
851 expect(status).toBe(200);
852 expect(body.favicon).toBeNull();
853 });
854
855 test('POST /api/files/global-favicon stores selected image path', async () =>
856 {
857 const imgPath = path.join(rootDir, 'cover.jpg');
858 const thumbPath = path.join(rootDir, 'cover.webp');
859 fs.writeFileSync(imgPath, 'img');
860 fs.writeFileSync(thumbPath, 'thumb');
861 mockThumbPath = thumbPath;
862
863 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
864 expect(status).toBe(200);
865 expect(body.ok).toBe(true);
866 expect(mockGlobalFaviconPath).toBe(imgPath);
867
868 const fetched = await req('GET', '/api/files/global-favicon');
869 expect(fetched.status).toBe(200);
870 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
871 });
872
873 test('POST /api/files/global-favicon clears the configured favicon', async () =>
874 {
875 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
876
877 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
878 expect(status).toBe(200);
879 expect(body.ok).toBe(true);
880 expect(mockGlobalFaviconPath).toBeNull();
881 });
882
883 test('POST /api/files/global-favicon is admin-only', async () =>
884 {
885 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
886 const imgPath = path.join(rootDir, 'cover.jpg');
887 fs.writeFileSync(imgPath, 'img');
888
889 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
890 expect(status).toBe(403);
891 });
892});
893
894// ---------------------------------------------------------------------------
895// GET /api/files/download-zip
896// ---------------------------------------------------------------------------
897describe('GET /api/files/download-zip', () =>
898{
899 beforeEach(() =>
900 {
901 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
902 });
903
904 test('streams a valid zip for an accessible directory', async () =>
905 {
906 const subDir = path.join(rootDir, 'zipme');
907 fs.mkdirSync(subDir);
908 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
909
910 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
911 expect(status).toBe(200);
912
913 const ct = headers['content-type'] || '';
914 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
915
916 // ZIP magic bytes PK\x03\x04
917 expect(buf[0]).toBe(0x50);
918 expect(buf[1]).toBe(0x4b);
919 }, 20000);
920
921 test('returns 400 when dir param is missing', async () =>
922 {
923 const { status } = await req('GET', '/api/files/download-zip');
924 expect(status).toBe(400);
925 });
926
927 test('returns 404 for a non-existent directory', async () =>
928 {
929 const missing = path.join(rootDir, 'ghost');
930 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
931 expect(status).toBe(404);
932 });
933
934 test('returns 403 for path outside configured roots', async () =>
935 {
936 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
937 expect(status).toBe(403);
938 });
939});
940
941describe('video streaming routes', () =>
942{
943 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
944 {
945 const filePath = path.join(rootDir, 'clip.mkv');
946 fs.writeFileSync(filePath, 'video');
947 mockVideoStreamSession = {
948 sessionId: 'sess-123',
949 durationSeconds: 42.25,
950 videoWidth: 1920,
951 videoHeight: 1080,
952 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
953 };
954
955 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
956
957 expect(status).toBe(200);
958 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
959 expect(body.durationSeconds).toBe(42.25);
960 expect(body.videoWidth).toBe(1920);
961 expect(body.videoHeight).toBe(1080);
962 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
963 expect(body.subtitleTracks).toEqual([
964 {
965 label: 'English',
966 language: 'eng',
967 default: true,
968 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
969 },
970 ]);
971 });
972
973 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
974 {
975 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
976 {
977 res.type('text/vtt').send('WEBVTT\n');
978 };
979
980 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
981
982 expect(status).toBe(200);
983 expect(headers['content-type']).toMatch(/text\/vtt/);
984 expect(body.toString()).toBe('WEBVTT\n');
985 });
986
987 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
988 {
989 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
990
991 expect(status).toBe(200);
992 expect(body).toEqual({ ok: true });
993 expect(releasedVideoStreamSessionId).toBe('sess-123');
994 });
995
996 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
997 {
998 const filePath = path.join(rootDir, 'clip.mkv');
999 fs.writeFileSync(filePath, 'video');
1000 mockSubtitleFrameResult = Buffer.from('png-data');
1001
1002 const { status, headers, body } = await reqRaw(
1003 'GET',
1004 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
1005 );
1006
1007 expect(status).toBe(200);
1008 expect(headers['content-type']).toMatch(/image\/png/);
1009 expect(headers['x-subtitle-frame-status']).toBe('ok');
1010 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1011 });
1012
1013 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1014 {
1015 const filePath = path.join(rootDir, 'clip.mkv');
1016 fs.writeFileSync(filePath, 'video');
1017 mockSubtitleFrameResult = null;
1018
1019 const { status, headers, body } = await reqRaw(
1020 'GET',
1021 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1022 );
1023
1024 expect(status).toBe(204);
1025 expect(headers['x-subtitle-frame-status']).toBe('none');
1026 expect(body.length).toBe(0);
1027 });
1028
1029 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
1030 {
1031 const filePath = path.join(rootDir, 'clip.mkv');
1032 fs.writeFileSync(filePath, 'video');
1033 mockSubtitleFrameError = new Error('decode failed');
1034
1035 const { status, headers, body } = await reqRaw(
1036 'GET',
1037 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1038 );
1039
1040 expect(status).toBe(204);
1041 expect(headers['x-subtitle-frame-status']).toBe('error');
1042 expect(body.length).toBe(0);
1043 });
1044
1045 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
1046 {
1047 const filePath = path.join(rootDir, 'clip.mkv');
1048 fs.writeFileSync(filePath, 'video');
1049
1050 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
1051 expect(result.status).toBe(200);
1052 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
1053
1054 // A lower progress update should not downgrade the status.
1055 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
1056 expect(result.status).toBe(200);
1057 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
1058
1059 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1060 expect(result.status).toBe(200);
1061 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
1062
1063 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
1064 expect(result.status).toBe(200);
1065 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
1066
1067 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1068 expect(result.status).toBe(200);
1069 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
1070 });
1071
1072 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
1073 {
1074 const clipA = path.join(rootDir, 'clip-a.mkv');
1075 const clipB = path.join(rootDir, 'clip-b.mkv');
1076 const clipC = path.join(rootDir, 'clip-c.mkv');
1077 fs.writeFileSync(clipA, 'a');
1078 fs.writeFileSync(clipB, 'b');
1079 fs.writeFileSync(clipC, 'c');
1080
1081 const db = getDb();
1082 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1083 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
1084 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1085 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
1086 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1087 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
1088
1089 const { status, body } = await req('POST', '/api/files/watched-statuses', {
1090 filePaths: [clipA, clipB, clipC],
1091 });
1092
1093 expect(status).toBe(200);
1094 expect(body.statuses).toEqual({
1095 [clipA]: 'fully',
1096 [clipB]: 'partway',
1097 });
1098 });
1099
1100 test('POST /api/files/watched-statuses validates filePaths input', async () =>
1101 {
1102 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
1103 expect(status).toBe(400);
1104 expect(body.error).toMatch(/filePaths array is required/i);
1105 });
1106});
1107
1108describe('SHA-256 hashing and duplicate detection', () =>
1109{
1110 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
1111 {
1112 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1113 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
1114 ]);
1115 expect(status).toBe(200);
1116
1117 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1118 .get([path.join(rootDir, 'hashme.txt')]);
1119 expect(meta).toBeTruthy();
1120 // SHA-256 is a 64-char hex string.
1121 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
1122 });
1123
1124 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
1125 {
1126 const filePath = path.join(rootDir, 'lazy.txt');
1127 fs.writeFileSync(filePath, 'lazy content');
1128
1129 // Insert a row without a hash to simulate a pre-existing file.
1130 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1131 .run([filePath, 'admin', '[]']);
1132
1133 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1134 expect(status).toBe(200);
1135 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
1136
1137 // Verify it was persisted.
1138 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
1139 expect(row.sha256).toBe(body.sha256);
1140 });
1141
1142 test('GET /api/files/duplicates returns other files with the same hash', async () =>
1143 {
1144 const content = 'duplicate content';
1145 const fileA = path.join(rootDir, 'dup-a.txt');
1146 const fileB = path.join(rootDir, 'dup-b.txt');
1147 fs.writeFileSync(fileA, content);
1148 fs.writeFileSync(fileB, content);
1149
1150 // Compute the expected hash.
1151 const crypto = require('crypto');
1152 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
1153
1154 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1155 .run([fileA, 'admin', '[]', expectedHash]);
1156 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1157 .run([fileB, 'admin', '[]', expectedHash]);
1158
1159 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
1160 expect(status).toBe(200);
1161 expect(body.duplicates).toHaveLength(1);
1162 expect(body.duplicates[0].path).toBe(fileB);
1163 expect(body.duplicates[0].name).toBe('dup-b.txt');
1164 });
1165
1166 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
1167 {
1168 const filePath = path.join(rootDir, 'nohash.txt');
1169 fs.writeFileSync(filePath, 'no hash yet');
1170
1171 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1172 .run([filePath, 'admin', '[]']);
1173
1174 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
1175 expect(status).toBe(200);
1176 expect(body.duplicates).toEqual([]);
1177 });
1178
1179 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
1180 {
1181 const content = 'secret dupe';
1182 const accessible = path.join(rootDir, 'visible.txt');
1183 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
1184 fs.writeFileSync(accessible, content);
1185
1186 const crypto = require('crypto');
1187 const hash = crypto.createHash('sha256').update(content).digest('hex');
1188
1189 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1190 .run([accessible, 'admin', '[]', hash]);
1191 // Insert a row for a path that is NOT inside any configured root.
1192 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1193 .run([outsideRoot, 'admin', '[]', hash]);
1194
1195 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1196 expect(status).toBe(200);
1197 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1198 });
1199
1200 test('POST /api/files/move preserves sha256 after rename', async () =>
1201 {
1202 const from = path.join(rootDir, 'withHash.txt');
1203 const toDir = path.join(rootDir, 'subfolder');
1204 fs.writeFileSync(from, 'content');
1205 fs.mkdirSync(toDir);
1206
1207 const hash = 'a'.repeat(64);
1208 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1209 .run([from, 'admin', '[]', hash]);
1210
1211 const { status } = await req('POST', '/api/files/move', { from, toDir });
1212 expect(status).toBe(200);
1213
1214 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1215 .get([path.join(toDir, 'withHash.txt')]);
1216 expect(meta.sha256).toBe(hash);
1217 });
1218});