BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

Cursor Optimisation pass
timfa Tim Falken · pushed by timfa · 5 months ago
7e6dfc52 History
files.routes.test.js 59.3 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 mockThumbnailManifestPaths = null;
17let mockFolderImages = [];
18let mockFolderIconFile = null;
19let lastFolderIconAssignment = undefined;
20let mockVideoStreamSession = null;
21let mockVideoStreamAsset = null;
22let releasedVideoStreamSessionId = null;
23let mockSubtitleFrameResult = null;
24let mockSubtitleFrameError = null;
25let mockSubtitleRangeResult = null;
26let mockSubtitleRangeError = null;
27const mockSubtitleDebugLogDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
28
29jest.mock('../server/db', () =>
30{
31 const { Database } = require('node-sqlite3-wasm');
32 let db;
33 function getDb ()
34 {
35 if (!db)
36 {
37 db = new Database(':memory:');
38 db.exec(`
39 CREATE TABLE IF NOT EXISTS users (
40 id INTEGER PRIMARY KEY AUTOINCREMENT,
41 username TEXT UNIQUE NOT NULL,
42 password_hash TEXT NOT NULL,
43 is_admin INTEGER NOT NULL DEFAULT 0,
44 permissions TEXT NOT NULL DEFAULT '{}'
45 );
46 CREATE TABLE IF NOT EXISTS file_meta (
47 file_path TEXT PRIMARY KEY,
48 uploader TEXT NOT NULL DEFAULT '',
49 downloaders TEXT NOT NULL DEFAULT '[]',
50 watched_by TEXT NOT NULL DEFAULT '{}',
51 uploaded_at TEXT,
52 sha256 TEXT
53 );
54 CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);
55 CREATE TABLE IF NOT EXISTS user_last_navigation (
56 username TEXT PRIMARY KEY,
57 last_dir TEXT,
58 updated_at INTEGER NOT NULL
59 );
60 CREATE TABLE IF NOT EXISTS file_search_index (
61 file_path TEXT PRIMARY KEY,
62 root_path TEXT NOT NULL,
63 name TEXT NOT NULL,
64 name_lower TEXT NOT NULL,
65 relative_path TEXT NOT NULL,
66 relative_lower TEXT NOT NULL,
67 size INTEGER,
68 mtime_ms INTEGER,
69 indexed_at INTEGER NOT NULL
70 );
71 CREATE INDEX IF NOT EXISTS idx_file_search_root ON file_search_index(root_path);
72 `);
73 }
74 return db;
75 }
76 return { getDb, initDb: getDb };
77});
78
79jest.mock('../server/config', () => ({
80 loadConfig: () => ({
81 port: 3000,
82 paths: [...mockPaths],
83 userPath: mockUserPath,
84 rootAliases: { ...mockRootAliases },
85 globalFaviconPath: mockGlobalFaviconPath,
86 }),
87 saveConfig: (config) =>
88 {
89 mockPaths = [...(config.paths || [])];
90 mockRootAliases = { ...(config.rootAliases || {}) };
91 mockGlobalFaviconPath = config.globalFaviconPath || null;
92 },
93 getEffectivePaths: (paths) => paths,
94 getAllowedRoot: (targetPath, roots) =>
95 {
96 const path = require('path');
97 const absTarget = path.resolve(String(targetPath || ''));
98 return roots.find((root) =>
99 {
100 const absRoot = path.resolve(root);
101 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
102 }) || null;
103 },
104}));
105
106jest.mock('../server/auth', () => ({
107 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
108}));
109
110jest.mock('../server/thumbnail-cache', () => ({
111 getCachedThumbnailInfo: async () =>
112 {
113 if (!mockThumbPath) return null;
114 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
115 },
116 getThumbnailManifestSourcePathSet: async () =>
117 {
118 if (mockThumbnailManifestPaths) return new Set(mockThumbnailManifestPaths);
119 return new Set();
120 },
121 getFilesWithThumbnailsInDir: async () => mockFolderImages.slice(),
122 getFolderIconSourceFile: async () => mockFolderIconFile,
123 setFolderIconAssignment: async (folderPath, imagePath) =>
124 {
125 lastFolderIconAssignment = { folderPath, imagePath };
126 },
127 THUMB_HTTP_MAX_AGE_SEC: 3600,
128}));
129
130jest.mock('../server/video-stream', () => ({
131 createVideoStreamSession: jest.fn(async () =>
132 {
133 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
134 return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
135 }),
136 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
137 {
138 if (typeof mockVideoStreamAsset === 'function')
139 {
140 await mockVideoStreamAsset(sessionId, assetPath, req, res);
141 return;
142 }
143 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
144 }),
145 releaseVideoStreamSession: jest.fn((sessionId) =>
146 {
147 releasedVideoStreamSessionId = String(sessionId || '');
148 return true;
149 }),
150}));
151
152jest.mock('../server/image-subtitles', () => ({
153 renderImageSubtitleFrame: jest.fn(async () =>
154 {
155 if (mockSubtitleFrameError) throw mockSubtitleFrameError;
156 return mockSubtitleFrameResult;
157 }),
158 renderImageSubtitleFramesInRange: jest.fn(async () =>
159 {
160 if (mockSubtitleRangeError) throw mockSubtitleRangeError;
161 return mockSubtitleRangeResult;
162 }),
163}));
164
165jest.mock('../server/subtitle-debug-log', () => ({
166 SUBTITLE_DEBUG_LOG_DIR: mockSubtitleDebugLogDir,
167 appendSubtitleDebugEntries: jest.fn(),
168}));
169
170const filesRoutes = require('../server/routes/files');
171const { getDb } = require('../server/db');
172const { drainFileHashQueue, stopFileHashQueue } = require('../server/file-hash-queue');
173
174let server;
175let baseUrl;
176let rootDir;
177
178beforeAll(async () =>
179{
180 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
181 mockPaths = [rootDir];
182
183 const app = express();
184 app.use(express.json());
185 app.use('/api/files', filesRoutes);
186 app.use((err, req, res, next) =>
187 {
188 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
189 });
190
191 server = http.createServer(app);
192 server.listen(0);
193 await once(server, 'listening');
194 baseUrl = `http://127.0.0.1:${server.address().port}`;
195});
196
197afterAll(() =>
198{
199 server.close();
200 fs.rmSync(rootDir, { recursive: true, force: true });
201});
202
203beforeEach(() =>
204{
205 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD;
206 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD_DIR_MODE;
207 delete process.env.FILEMANAGER_LIST_ACCESS_CHMOD_FILE_MODE;
208
209 fs.rmSync(rootDir, { recursive: true, force: true });
210 fs.mkdirSync(rootDir, { recursive: true });
211 if (mockUserPath)
212 {
213 fs.rmSync(mockUserPath, { recursive: true, force: true });
214 fs.mkdirSync(mockUserPath, { recursive: true });
215 }
216 mockRootAliases = {};
217 mockGlobalFaviconPath = null;
218 mockUserPath = null;
219 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
220 mockThumbPath = null;
221 mockThumbnailManifestPaths = null;
222 mockFolderImages = [];
223 mockFolderIconFile = null;
224 lastFolderIconAssignment = undefined;
225 mockVideoStreamSession = null;
226 mockVideoStreamAsset = null;
227 releasedVideoStreamSessionId = null;
228 mockSubtitleFrameResult = null;
229 mockSubtitleFrameError = null;
230 mockSubtitleRangeResult = null;
231 mockSubtitleRangeError = null;
232 const db = getDb();
233 db.prepare('DELETE FROM file_meta').run([]);
234 db.prepare('DELETE FROM users').run([]);
235 db.exec('DELETE FROM file_search_index');
236 stopFileHashQueue();
237});
238
239function req (method, routePath, body)
240{
241 const payload = body ? JSON.stringify(body) : undefined;
242 return new Promise((resolve, reject) =>
243 {
244 const request = http.request(baseUrl + routePath, {
245 method,
246 headers: {
247 'Content-Type': 'application/json',
248 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
249 },
250 }, res =>
251 {
252 let data = '';
253 res.on('data', chunk => data += chunk);
254 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
255 });
256 request.on('error', reject);
257 if (payload) request.write(payload);
258 request.end();
259 });
260}
261
262function reqRaw (method, routePath)
263{
264 return new Promise((resolve, reject) =>
265 {
266 const request = http.request(baseUrl + routePath, { method }, res =>
267 {
268 const chunks = [];
269 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
270 res.on('end', () => resolve({
271 status: res.statusCode,
272 headers: res.headers,
273 body: Buffer.concat(chunks),
274 }));
275 });
276 request.on('error', reject);
277 request.end();
278 });
279}
280
281function reqMultipart (routePath, files, extraHeaders = {})
282{
283 const boundary = '----filemanager-test-boundary';
284 const buffers = [];
285
286 for (const file of files)
287 {
288 buffers.push(Buffer.from(
289 `--${boundary}\r\n`
290 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
291 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
292 ));
293 buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)));
294 buffers.push(Buffer.from('\r\n'));
295 }
296
297 buffers.push(Buffer.from(`--${boundary}--\r\n`));
298 const payload = Buffer.concat(buffers);
299
300 return new Promise((resolve, reject) =>
301 {
302 const request = http.request(baseUrl + routePath, {
303 method: 'POST',
304 headers: {
305 'Content-Type': `multipart/form-data; boundary=${boundary}`,
306 'Content-Length': payload.length,
307 ...extraHeaders,
308 },
309 }, res =>
310 {
311 let data = '';
312 res.on('data', chunk => data += chunk);
313 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
314 });
315 request.on('error', reject);
316 request.write(payload);
317 request.end();
318 });
319}
320
321function abortMultipartUpload (routePath, file)
322{
323 const boundary = '----filemanager-test-boundary-abort';
324 const header = Buffer.from(
325 `--${boundary}\r\n`
326 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
327 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
328 );
329 const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content));
330
331 return new Promise((resolve) =>
332 {
333 const request = http.request(baseUrl + routePath, {
334 method: 'POST',
335 headers: {
336 'Content-Type': `multipart/form-data; boundary=${boundary}`,
337 },
338 });
339
340 let settled = false;
341 const finish = () =>
342 {
343 if (settled) return;
344 settled = true;
345 resolve();
346 };
347
348 request.on('error', finish);
349 request.on('close', finish);
350 request.write(header);
351 request.write(chunk);
352 setTimeout(() => request.destroy(), 20);
353 });
354}
355
356async function waitFor (predicate, timeoutMs = 500)
357{
358 const start = Date.now();
359 while (Date.now() - start < timeoutMs)
360 {
361 if (predicate()) return;
362 await new Promise(resolve => setTimeout(resolve, 10));
363 }
364 throw new Error('Timed out waiting for condition.');
365}
366
367describe('POST /api/files/upload', () =>
368{
369 test('stores a completed upload under its final name', async () =>
370 {
371 const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
372 { name: 'hello.txt', content: 'hello world', type: 'text/plain' },
373 ]);
374
375 expect(status).toBe(200);
376 expect(body.uploaded).toEqual(['hello.txt']);
377 expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world');
378
379 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
380 .get([path.join(rootDir, 'hello.txt')]);
381 expect(meta).toMatchObject({ uploader: 'admin' });
382 });
383
384 test('removes partial files when the upload connection aborts', async () =>
385 {
386 await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, {
387 name: 'partial.txt',
388 content: Buffer.alloc(256 * 1024, 'a'),
389 type: 'text/plain',
390 });
391
392 await waitFor(() => fs.readdirSync(rootDir).length === 0);
393
394 expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false);
395 expect(fs.readdirSync(rootDir)).toEqual([]);
396
397 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
398 .get([path.join(rootDir, 'partial.txt')]);
399 expect(meta).toBeFalsy();
400 });
401});
402
403describe('POST /api/files/move', () =>
404{
405 test('moves a file into another folder and rewrites metadata', async () =>
406 {
407 const from = path.join(rootDir, 'alpha.txt');
408 const toDir = path.join(rootDir, 'folder');
409 fs.writeFileSync(from, 'hello');
410 fs.mkdirSync(toDir);
411 const uploadedAt = '2026-05-18T12:00:00.000Z';
412
413 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by, uploaded_at, sha256) VALUES (?, ?, ?, ?, ?, ?)')
414 .run([from, 'admin', '["alice"]', '{"admin":"partway"}', uploadedAt, 'abc123']);
415
416 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
417
418 expect(status).toBe(200);
419 expect(body.ok).toBe(true);
420 expect(fs.existsSync(from)).toBe(false);
421 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
422
423 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
424 expect(meta).toMatchObject({
425 uploader: 'admin',
426 downloaders: '["alice"]',
427 watched_by: '{"admin":"partway"}',
428 uploaded_at: uploadedAt,
429 sha256: 'abc123',
430 });
431 });
432
433 test('moves a folder into another folder and rewrites descendant metadata', async () =>
434 {
435 const fromDir = path.join(rootDir, 'src-folder');
436 const nestedFile = path.join(fromDir, 'child.txt');
437 const toDir = path.join(rootDir, 'dest-folder');
438 fs.mkdirSync(fromDir);
439 fs.mkdirSync(toDir);
440 fs.writeFileSync(nestedFile, 'hello');
441
442 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
443 .run([nestedFile, 'admin', '[]']);
444
445 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
446
447 expect(status).toBe(200);
448 expect(fs.existsSync(fromDir)).toBe(false);
449 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
450
451 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
452 .get([path.join(toDir, 'src-folder', 'child.txt')]);
453 expect(movedMeta).toBeTruthy();
454 });
455
456 test('rejects moving a folder into itself', async () =>
457 {
458 const fromDir = path.join(rootDir, 'src-folder');
459 const childDir = path.join(fromDir, 'child');
460 fs.mkdirSync(childDir, { recursive: true });
461
462 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
463
464 expect(status).toBe(400);
465 expect(body.error).toMatch(/folder into itself/i);
466 });
467
468 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
469 {
470 const sourceFile = path.join(rootDir, 'source.txt');
471 const destinationDir = path.join(rootDir, 'dest');
472 fs.mkdirSync(destinationDir);
473 fs.writeFileSync(sourceFile, 'new-content');
474 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
475
476 const { status, body } = await req('POST', '/api/files/move', {
477 from: sourceFile,
478 toDir: destinationDir,
479 conflict: 'overwrite',
480 });
481
482 expect(status).toBe(200);
483 expect(body.conflictResolution).toBe('overwrite');
484 expect(fs.existsSync(sourceFile)).toBe(false);
485 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
486 });
487
488 test('renames destination when conflict strategy is rename', async () =>
489 {
490 const sourceFile = path.join(rootDir, 'report.txt');
491 const destinationDir = path.join(rootDir, 'dest');
492 fs.mkdirSync(destinationDir);
493 fs.writeFileSync(sourceFile, 'latest');
494 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
495
496 const { status, body } = await req('POST', '/api/files/move', {
497 from: sourceFile,
498 toDir: destinationDir,
499 conflict: 'rename',
500 });
501
502 expect(status).toBe(200);
503 expect(body.conflictResolution).toBe('rename');
504 expect(path.basename(body.path)).toBe('report (1).txt');
505 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
506 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
507 });
508
509 test('moves a file into My Folder when rename falls back across filesystems', async () =>
510 {
511 const sourceFile = path.join(rootDir, 'cross-root.txt');
512 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
513 const userFolder = path.join(userFolderBase, 'alice');
514
515 mockPaths = [rootDir];
516 mockUserPath = userFolderBase;
517 mockUser = {
518 username: 'alice',
519 isAdmin: false,
520 permissions: {
521 [path.basename(rootDir)]: { read: true, write: true },
522 },
523 };
524
525 fs.writeFileSync(sourceFile, 'hello');
526 fs.mkdirSync(userFolder, { recursive: true });
527
528 const originalRenameSync = fs.renameSync;
529 fs.renameSync = (from, to) =>
530 {
531 const err = new Error('cross-device move');
532 err.code = 'EXDEV';
533 throw err;
534 };
535
536 try
537 {
538 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
539
540 expect(status).toBe(200);
541 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
542 expect(fs.existsSync(sourceFile)).toBe(false);
543 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
544 } finally
545 {
546 fs.renameSync = originalRenameSync;
547 fs.rmSync(userFolderBase, { recursive: true, force: true });
548 }
549 });
550});
551
552describe('root alias endpoints', () =>
553{
554 test('GET /api/files/roots returns alias label and original name', async () =>
555 {
556 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
557
558 const { status, body } = await req('GET', '/api/files/roots');
559
560 expect(status).toBe(200);
561 expect(body.roots).toHaveLength(1);
562 expect(body.roots[0]).toMatchObject({
563 path: rootDir,
564 label: 'Workspace',
565 alias: 'Workspace',
566 originalName: path.basename(rootDir),
567 });
568 });
569
570 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
571 {
572 const originalBase = path.basename(rootDir);
573 const { status, body } = await req('POST', '/api/files/root-alias', {
574 rootPath: rootDir,
575 alias: 'Shared Files',
576 });
577
578 expect(status).toBe(200);
579 expect(body.ok).toBe(true);
580 expect(body.root).toMatchObject({
581 path: rootDir,
582 label: 'Shared Files',
583 alias: 'Shared Files',
584 originalName: originalBase,
585 });
586 expect(fs.existsSync(rootDir)).toBe(true);
587
588 const afterRoots = await req('GET', '/api/files/roots');
589 expect(afterRoots.status).toBe(200);
590 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
591 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
592 });
593
594 test('POST /api/files/root-alias rejects non-root paths', async () =>
595 {
596 const nested = path.join(rootDir, 'sub');
597 fs.mkdirSync(nested, { recursive: true });
598
599 const { status } = await req('POST', '/api/files/root-alias', {
600 rootPath: nested,
601 alias: 'Nested',
602 });
603
604 expect(status).toBe(400);
605 });
606
607 test('GET /api/files/roots returns lastDir when user still has access', async () =>
608 {
609 const nestedDir = path.join(rootDir, 'series');
610 fs.mkdirSync(nestedDir, { recursive: true });
611
612 const db = getDb();
613 db.exec(`
614 CREATE TABLE IF NOT EXISTS user_last_navigation (
615 username TEXT PRIMARY KEY,
616 last_dir TEXT,
617 updated_at INTEGER NOT NULL
618 );
619 `);
620 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
621 .run(['admin', nestedDir, Date.now()]);
622
623 const { status, body } = await req('GET', '/api/files/roots');
624 expect(status).toBe(200);
625 expect(body.lastDir).toBe(nestedDir);
626 });
627
628 test('GET /api/files/roots returns null lastDir when saved folder is no longer accessible', async () =>
629 {
630 const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-outside-'));
631 mockUser = {
632 username: 'reader',
633 isAdmin: false,
634 permissions: {},
635 };
636
637 const db = getDb();
638 db.exec(`
639 CREATE TABLE IF NOT EXISTS user_last_navigation (
640 username TEXT PRIMARY KEY,
641 last_dir TEXT,
642 updated_at INTEGER NOT NULL
643 );
644 `);
645 db.prepare('INSERT INTO user_last_navigation (username, last_dir, updated_at) VALUES (?, ?, ?)')
646 .run(['reader', outsideDir, Date.now()]);
647
648 try
649 {
650 const { status, body } = await req('GET', '/api/files/roots');
651 expect(status).toBe(200);
652 expect(body.lastDir).toBeNull();
653 } finally
654 {
655 fs.rmSync(outsideDir, { recursive: true, force: true });
656 }
657 });
658});
659
660describe('last visited folder persistence', () =>
661{
662 test('GET /api/files/list stores the visited folder for the authenticated user', async () =>
663 {
664 const visited = path.join(rootDir, 'visited-folder');
665 fs.mkdirSync(visited, { recursive: true });
666
667 const { status } = await req('GET', `/api/files/list?dir=${encodeURIComponent(visited)}`);
668 expect(status).toBe(200);
669
670 const row = getDb().prepare('SELECT last_dir FROM user_last_navigation WHERE username = ?').get(['admin']);
671 expect(row).toBeTruthy();
672 expect(row.last_dir).toBe(visited);
673 });
674});
675
676describe('GET /api/files/thumbnail', () =>
677{
678 test('returns 404 while cached thumbnail is not ready', async () =>
679 {
680 const source = path.join(rootDir, 'photo.jpg');
681 fs.writeFileSync(source, 'not-an-image');
682
683 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
684 expect(status).toBe(404);
685 expect(body.error).toMatch(/not ready/i);
686 });
687
688 test('serves cached thumbnail file when available', async () =>
689 {
690 const source = path.join(rootDir, 'photo.jpg');
691 const thumb = path.join(rootDir, 'photo-thumb.webp');
692 fs.writeFileSync(source, 'not-an-image');
693 fs.writeFileSync(thumb, 'webp-bytes');
694 mockThumbPath = thumb;
695
696 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
697 expect(response.status).toBe(200);
698 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
699 expect(response.body.toString('utf8')).toBe('webp-bytes');
700 });
701});
702
703describe('GET /api/files/root-access', () =>
704{
705 test('returns users with R/R+W modes for an exact root path', async () =>
706 {
707 const label = path.basename(rootDir);
708 const db = getDb();
709 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
710 .run(['admin', 'x', 1, '{}']);
711 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
712 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
713 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
714 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
715 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
716 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
717
718 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
719 expect(status).toBe(200);
720 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
721 expect(body.users).toEqual([
722 { username: 'admin', mode: 'R+W' },
723 { username: 'bob', mode: 'R+W' },
724 { username: 'alice', mode: 'R' },
725 ]);
726 });
727
728 test('rejects non-exact nested root paths', async () =>
729 {
730 const nested = path.join(rootDir, 'sub');
731 fs.mkdirSync(nested, { recursive: true });
732
733 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
734 expect(status).toBe(400);
735 });
736});
737
738describe('orphaned user folder access', () =>
739{
740 test('admins can read and write in orphaned user folders', async () =>
741 {
742 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
743 const orphanFolder = path.join(userFolderBase, 'ghost-user');
744 fs.mkdirSync(orphanFolder, { recursive: true });
745 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
746
747 mockUserPath = userFolderBase;
748 mockUser = {
749 username: 'admin',
750 isAdmin: true,
751 permissions: {},
752 };
753
754 try
755 {
756 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
757 expect(listRes.status).toBe(200);
758 expect(Array.isArray(listRes.body.items)).toBe(true);
759 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
760
761 const mkdirRes = await req('POST', '/api/files/mkdir', {
762 dir: orphanFolder,
763 name: 'created-by-admin',
764 });
765 expect(mkdirRes.status).toBe(200);
766 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
767 } finally
768 {
769 fs.rmSync(userFolderBase, { recursive: true, force: true });
770 }
771 });
772
773 test('non-admin users cannot access orphaned user folders', async () =>
774 {
775 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
776 const orphanFolder = path.join(userFolderBase, 'ghost-user');
777 fs.mkdirSync(orphanFolder, { recursive: true });
778
779 mockUserPath = userFolderBase;
780 mockUser = {
781 username: 'alice',
782 isAdmin: false,
783 permissions: {},
784 };
785
786 try
787 {
788 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
789 expect(listRes.status).toBe(403);
790 } finally
791 {
792 fs.rmSync(userFolderBase, { recursive: true, force: true });
793 }
794 });
795});
796
797describe('list access chmod', () =>
798{
799 test('GET /api/files/list applies chmod to opened folder and direct children when enabled', async () =>
800 {
801 const nestedDir = path.join(rootDir, 'locked');
802 const nestedFile = path.join(nestedDir, 'data.txt');
803 const deepDir = path.join(nestedDir, 'deep');
804 const deepFile = path.join(deepDir, 'deep.txt');
805 fs.mkdirSync(nestedDir, { recursive: true });
806 fs.mkdirSync(deepDir, { recursive: true });
807 fs.writeFileSync(nestedFile, 'hello');
808 fs.writeFileSync(deepFile, 'deep');
809
810 fs.chmodSync(rootDir, 0o700);
811 fs.chmodSync(nestedDir, 0o700);
812 fs.chmodSync(nestedFile, 0o600);
813 fs.chmodSync(deepDir, 0o700);
814 fs.chmodSync(deepFile, 0o600);
815
816 process.env.FILEMANAGER_LIST_ACCESS_CHMOD = '1';
817
818 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
819 expect(listRes.status).toBe(200);
820
821 const rootMode = fs.statSync(rootDir).mode & 0o777;
822 const dirMode = fs.statSync(nestedDir).mode & 0o777;
823 const fileMode = fs.statSync(nestedFile).mode & 0o777;
824 const deepDirMode = fs.statSync(deepDir).mode & 0o777;
825 const deepFileMode = fs.statSync(deepFile).mode & 0o777;
826
827 expect(rootMode).toBe(0o777);
828 expect(dirMode).toBe(0o777);
829 expect(fileMode).toBe(0o600);
830 expect(deepDirMode).toBe(0o700);
831 expect(deepFileMode).toBe(0o600);
832 });
833
834 test('GET /api/files/list leaves permissions unchanged when disabled', async () =>
835 {
836 const nestedDir = path.join(rootDir, 'locked');
837 const nestedFile = path.join(nestedDir, 'data.txt');
838 fs.mkdirSync(nestedDir, { recursive: true });
839 fs.writeFileSync(nestedFile, 'hello');
840
841 fs.chmodSync(rootDir, 0o700);
842 fs.chmodSync(nestedDir, 0o700);
843 fs.chmodSync(nestedFile, 0o600);
844
845 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
846 expect(listRes.status).toBe(200);
847
848 const rootMode = fs.statSync(rootDir).mode & 0o777;
849 const dirMode = fs.statSync(nestedDir).mode & 0o777;
850 const fileMode = fs.statSync(nestedFile).mode & 0o777;
851
852 expect(rootMode).toBe(0o700);
853 expect(dirMode).toBe(0o700);
854 expect(fileMode).toBe(0o600);
855 });
856});
857
858describe('subtitle debug cache access', () =>
859{
860 test('admins can browse the subtitle debug cache folder', async () =>
861 {
862 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
863 fs.rmSync(logDir, { recursive: true, force: true });
864 fs.mkdirSync(logDir, { recursive: true });
865 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
866
867 mockUser = {
868 username: 'admin',
869 isAdmin: true,
870 permissions: {},
871 };
872
873 try
874 {
875 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
876 expect(listRes.status).toBe(200);
877 expect(Array.isArray(listRes.body.items)).toBe(true);
878 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
879 } finally
880 {
881 fs.rmSync(logDir, { recursive: true, force: true });
882 }
883 });
884
885 test('admins can delete files in the subtitle debug cache folder', async () =>
886 {
887 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
888 const logFile = path.join(logDir, '2026-05-25-delete-me-subtitlelog.txt');
889 fs.rmSync(logDir, { recursive: true, force: true });
890 fs.mkdirSync(logDir, { recursive: true });
891 fs.writeFileSync(logFile, 'delete me');
892
893 mockUser = {
894 username: 'admin',
895 isAdmin: true,
896 permissions: {},
897 };
898
899 try
900 {
901 const deleteRes = await req('POST', '/api/files/delete', { path: logFile });
902 expect(deleteRes.status).toBe(200);
903 expect(deleteRes.body).toEqual({ ok: true });
904 expect(fs.existsSync(logFile)).toBe(false);
905 } finally
906 {
907 fs.rmSync(logDir, { recursive: true, force: true });
908 }
909 });
910
911 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
912 {
913 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
914 fs.rmSync(logDir, { recursive: true, force: true });
915 fs.mkdirSync(logDir, { recursive: true });
916
917 mockUser = {
918 username: 'alice',
919 isAdmin: false,
920 permissions: {},
921 };
922
923 try
924 {
925 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
926 expect(listRes.status).toBe(403);
927 } finally
928 {
929 fs.rmSync(logDir, { recursive: true, force: true });
930 }
931 });
932});
933
934describe('folder icon endpoints', () =>
935{
936 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
937 {
938 const subDir = path.join(rootDir, 'photos');
939 fs.mkdirSync(subDir);
940 const imgPath = path.join(subDir, 'a.jpg');
941 fs.writeFileSync(imgPath, 'img');
942
943 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
944
945 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
946 expect(status).toBe(200);
947 expect(body.images).toHaveLength(1);
948 expect(body.images[0].filePath).toBe(imgPath);
949 });
950
951 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
952 {
953 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
954 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
955 fs.writeFileSync(videoPath, 'video');
956
957 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
958
959 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
960 expect(status).toBe(200);
961 expect(body.images).toEqual([{ filePath: videoPath }]);
962 });
963
964 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
965 {
966 mockFolderImages = [];
967
968 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
969 expect(status).toBe(200);
970 expect(body.images).toEqual([]);
971 });
972
973 test('GET /api/files/folder-icon returns null when no icon available', async () =>
974 {
975 mockFolderIconFile = null;
976
977 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
978 expect(status).toBe(200);
979 expect(body.icon).toBeNull();
980 });
981
982 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
983 {
984 const imgPath = path.join(rootDir, 'cover.jpg');
985 fs.writeFileSync(imgPath, 'img');
986 mockFolderIconFile = imgPath;
987
988 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
989 expect(status).toBe(200);
990 expect(body.icon).toMatchObject({ filePath: imgPath });
991 });
992
993 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
994 {
995 const imgPath = path.join(rootDir, 'cover.jpg');
996 const thumbFile = path.join(rootDir, 'cover.webp');
997 fs.writeFileSync(imgPath, 'img');
998 fs.writeFileSync(thumbFile, 'webp');
999 mockThumbPath = thumbFile;
1000
1001 const { status, body } = await req('POST', '/api/files/folder-icon', {
1002 folderPath: rootDir,
1003 imagePath: imgPath,
1004 });
1005 expect(status).toBe(200);
1006 expect(body.ok).toBe(true);
1007 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
1008 });
1009
1010 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
1011 {
1012 const imgPath = path.join(rootDir, 'missing.jpg');
1013 fs.writeFileSync(imgPath, 'img');
1014 mockThumbPath = null;
1015
1016 const { status, body } = await req('POST', '/api/files/folder-icon', {
1017 folderPath: rootDir,
1018 imagePath: imgPath,
1019 });
1020 expect(status).toBe(404);
1021 expect(body.error).toMatch(/thumbnail not ready/i);
1022 });
1023
1024 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
1025 {
1026 const { status, body } = await req('POST', '/api/files/folder-icon', {
1027 folderPath: rootDir,
1028 imagePath: null,
1029 });
1030 expect(status).toBe(200);
1031 expect(body.ok).toBe(true);
1032 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
1033 });
1034
1035 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
1036 {
1037 const label = path.basename(rootDir);
1038 mockUser = {
1039 username: 'reader',
1040 isAdmin: false,
1041 permissions: { [label]: { read: true, write: false } },
1042 };
1043
1044 const imgPath = path.join(rootDir, 'photo.jpg');
1045 fs.writeFileSync(imgPath, 'img');
1046
1047 const { status } = await req('POST', '/api/files/folder-icon', {
1048 folderPath: rootDir,
1049 imagePath: imgPath,
1050 });
1051 expect(status).toBe(403);
1052 });
1053});
1054
1055describe('file search endpoint', () =>
1056{
1057 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
1058 {
1059 const movieDir = path.join(rootDir, 'Movies');
1060 const docsDir = path.join(rootDir, 'Docs');
1061 fs.mkdirSync(movieDir, { recursive: true });
1062 fs.mkdirSync(docsDir, { recursive: true });
1063 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
1064 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
1065
1066 const { status, body } = await req('GET', '/api/files/search?query=dbs');
1067 expect(status).toBe(200);
1068 expect(body.query).toBe('dbs');
1069 expect(body.results.length).toBeGreaterThan(0);
1070 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
1071 });
1072
1073 test('GET /api/files/search returns 400 when query is missing', async () =>
1074 {
1075 const { status } = await req('GET', '/api/files/search');
1076 expect(status).toBe(400);
1077 });
1078});
1079
1080describe('image search endpoint', () =>
1081{
1082 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
1083 {
1084 const picsDir = path.join(rootDir, 'Pictures');
1085 fs.mkdirSync(picsDir, { recursive: true });
1086 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
1087 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
1088
1089 const imgPath = path.join(picsDir, 'dragon-cover.jpg');
1090 const thumbPath = path.join(rootDir, 'thumb.webp');
1091 fs.writeFileSync(thumbPath, 'thumb');
1092 mockThumbPath = thumbPath;
1093 mockThumbnailManifestPaths = [imgPath];
1094
1095 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
1096 expect(status).toBe(200);
1097 expect(body.results.length).toBe(1);
1098 expect(body.results[0].name).toBe('dragon-cover.jpg');
1099 });
1100
1101 test('GET /api/files/search-images returns 400 for short queries', async () =>
1102 {
1103 const { status } = await req('GET', '/api/files/search-images?query=a');
1104 expect(status).toBe(400);
1105 });
1106});
1107
1108describe('global favicon endpoints', () =>
1109{
1110 test('GET /api/files/global-favicon returns null when unset', async () =>
1111 {
1112 const { status, body } = await req('GET', '/api/files/global-favicon');
1113 expect(status).toBe(200);
1114 expect(body.favicon).toBeNull();
1115 });
1116
1117 test('POST /api/files/global-favicon stores selected image path', async () =>
1118 {
1119 const imgPath = path.join(rootDir, 'cover.jpg');
1120 const thumbPath = path.join(rootDir, 'cover.webp');
1121 fs.writeFileSync(imgPath, 'img');
1122 fs.writeFileSync(thumbPath, 'thumb');
1123 mockThumbPath = thumbPath;
1124
1125 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1126 expect(status).toBe(200);
1127 expect(body.ok).toBe(true);
1128 expect(mockGlobalFaviconPath).toBe(imgPath);
1129
1130 const fetched = await req('GET', '/api/files/global-favicon');
1131 expect(fetched.status).toBe(200);
1132 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
1133 });
1134
1135 test('POST /api/files/global-favicon clears the configured favicon', async () =>
1136 {
1137 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
1138
1139 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
1140 expect(status).toBe(200);
1141 expect(body.ok).toBe(true);
1142 expect(mockGlobalFaviconPath).toBeNull();
1143 });
1144
1145 test('POST /api/files/global-favicon is admin-only', async () =>
1146 {
1147 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
1148 const imgPath = path.join(rootDir, 'cover.jpg');
1149 fs.writeFileSync(imgPath, 'img');
1150
1151 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1152 expect(status).toBe(403);
1153 });
1154});
1155
1156// ---------------------------------------------------------------------------
1157// GET /api/files/download-zip
1158// ---------------------------------------------------------------------------
1159describe('GET /api/files/download-zip', () =>
1160{
1161 beforeEach(() =>
1162 {
1163 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
1164 });
1165
1166 test('streams a valid zip for an accessible directory', async () =>
1167 {
1168 const subDir = path.join(rootDir, 'zipme');
1169 fs.mkdirSync(subDir);
1170 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
1171
1172 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
1173 expect(status).toBe(200);
1174
1175 const ct = headers['content-type'] || '';
1176 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
1177
1178 // ZIP magic bytes PK\x03\x04
1179 expect(buf[0]).toBe(0x50);
1180 expect(buf[1]).toBe(0x4b);
1181 }, 20000);
1182
1183 test('returns 400 when dir param is missing', async () =>
1184 {
1185 const { status } = await req('GET', '/api/files/download-zip');
1186 expect(status).toBe(400);
1187 });
1188
1189 test('returns 404 for a non-existent directory', async () =>
1190 {
1191 const missing = path.join(rootDir, 'ghost');
1192 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
1193 expect(status).toBe(404);
1194 });
1195
1196 test('returns 403 for path outside configured roots', async () =>
1197 {
1198 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
1199 expect(status).toBe(403);
1200 });
1201});
1202
1203describe('video streaming routes', () =>
1204{
1205 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
1206 {
1207 const filePath = path.join(rootDir, 'clip.mkv');
1208 fs.writeFileSync(filePath, 'video');
1209 mockVideoStreamSession = {
1210 sessionId: 'sess-123',
1211 durationSeconds: 42.25,
1212 videoWidth: 1920,
1213 videoHeight: 1080,
1214 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
1215 };
1216
1217 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
1218
1219 expect(status).toBe(200);
1220 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
1221 expect(body.durationSeconds).toBe(42.25);
1222 expect(body.videoWidth).toBe(1920);
1223 expect(body.videoHeight).toBe(1080);
1224 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
1225 expect(body.subtitleTracks).toEqual([
1226 {
1227 label: 'English',
1228 language: 'eng',
1229 default: true,
1230 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
1231 },
1232 ]);
1233 });
1234
1235 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
1236 {
1237 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
1238 {
1239 res.type('text/vtt').send('WEBVTT\n');
1240 };
1241
1242 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
1243
1244 expect(status).toBe(200);
1245 expect(headers['content-type']).toMatch(/text\/vtt/);
1246 expect(body.toString()).toBe('WEBVTT\n');
1247 });
1248
1249 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
1250 {
1251 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
1252
1253 expect(status).toBe(200);
1254 expect(body).toEqual({ ok: true });
1255 expect(releasedVideoStreamSessionId).toBe('sess-123');
1256 });
1257
1258 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
1259 {
1260 const filePath = path.join(rootDir, 'clip.mkv');
1261 fs.writeFileSync(filePath, 'video');
1262 mockSubtitleFrameResult = {
1263 frame: Buffer.from('png-data'),
1264 left: 100,
1265 top: 50,
1266 width: 320,
1267 height: 180,
1268 canvasWidth: 640,
1269 canvasHeight: 360,
1270 startTimeSeconds: 1.5,
1271 endTimeSeconds: 3.2,
1272 };
1273
1274 const { status, headers, body } = await reqRaw(
1275 'GET',
1276 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
1277 );
1278
1279 expect(status).toBe(200);
1280 expect(headers['content-type']).toMatch(/image\/png/);
1281 expect(headers['x-subtitle-frame-status']).toBe('ok');
1282 expect(headers['x-subtitle-frame-left']).toBe('100');
1283 expect(headers['x-subtitle-frame-top']).toBe('50');
1284 expect(headers['x-subtitle-frame-width']).toBe('320');
1285 expect(headers['x-subtitle-frame-height']).toBe('180');
1286 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1287 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1288 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1289 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1290 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1291 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1292 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1293 });
1294
1295 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1296 {
1297 const filePath = path.join(rootDir, 'movie.mkv');
1298 fs.writeFileSync(filePath, 'video');
1299 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1300
1301 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1302 filePath,
1303 sessionId: 'sess-123',
1304 entries: [
1305 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1306 ],
1307 });
1308
1309 expect(status).toBe(200);
1310 expect(body).toEqual({ ok: true });
1311 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1312 videoName: 'movie.mkv',
1313 context: expect.objectContaining({
1314 filePath,
1315 sessionId: 'sess-123',
1316 source: 'app',
1317 }),
1318 }));
1319 });
1320
1321 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1322 {
1323 const filePath = path.join(rootDir, 'clip.mkv');
1324 fs.writeFileSync(filePath, 'video');
1325 mockSubtitleFrameResult = null;
1326
1327 const { status, headers, body } = await reqRaw(
1328 'GET',
1329 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1330 );
1331
1332 expect(status).toBe(204);
1333 expect(headers['x-subtitle-frame-status']).toBe('none');
1334 expect(body.length).toBe(0);
1335 });
1336
1337 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
1338 {
1339 const filePath = path.join(rootDir, 'clip.mkv');
1340 fs.writeFileSync(filePath, 'video');
1341 mockSubtitleFrameError = new Error('decode failed');
1342
1343 const { status, headers, body } = await reqRaw(
1344 'GET',
1345 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1346 );
1347
1348 expect(status).toBe(204);
1349 expect(headers['x-subtitle-frame-status']).toBe('error');
1350 expect(body.length).toBe(0);
1351 });
1352
1353 test('GET /api/files/video-stream-subtitle-range returns rendered subtitle frames in JSON', async () =>
1354 {
1355 const filePath = path.join(rootDir, 'clip.mkv');
1356 fs.writeFileSync(filePath, 'video');
1357 mockSubtitleRangeResult = {
1358 frames: [
1359 {
1360 frame: Buffer.from('png-a'),
1361 left: 10,
1362 top: 20,
1363 width: 300,
1364 height: 90,
1365 canvasWidth: 640,
1366 canvasHeight: 360,
1367 startTimeSeconds: 2,
1368 endTimeSeconds: 4,
1369 },
1370 {
1371 frame: Buffer.from('png-b'),
1372 left: 12,
1373 top: 24,
1374 width: 320,
1375 height: 96,
1376 canvasWidth: 640,
1377 canvasHeight: 360,
1378 startTimeSeconds: 5,
1379 endTimeSeconds: 7,
1380 },
1381 ],
1382 };
1383
1384 const result = await req('GET', `/api/files/video-stream-subtitle-range?filePath=${encodeURIComponent(filePath)}&streamIndex=0&startTimeSeconds=2&endTimeSeconds=8&videoWidth=1920&videoHeight=1080`);
1385
1386 expect(result.status).toBe(200);
1387 expect(result.body.status).toBe('ok');
1388 expect(result.body.frames).toHaveLength(2);
1389 expect(result.body.frames[0]).toEqual(expect.objectContaining({
1390 left: 10,
1391 top: 20,
1392 width: 300,
1393 height: 90,
1394 canvasWidth: 640,
1395 canvasHeight: 360,
1396 startTimeSeconds: 2,
1397 endTimeSeconds: 4,
1398 contentType: 'image/png',
1399 frameBase64: Buffer.from('png-a').toString('base64'),
1400 }));
1401 expect(result.body.frames[1].frameBase64).toBe(Buffer.from('png-b').toString('base64'));
1402 });
1403
1404 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
1405 {
1406 const filePath = path.join(rootDir, 'clip.mkv');
1407 fs.writeFileSync(filePath, 'video');
1408
1409 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
1410 expect(result.status).toBe(200);
1411 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
1412
1413 // A lower progress update should not downgrade the status.
1414 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
1415 expect(result.status).toBe(200);
1416 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
1417
1418 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1419 expect(result.status).toBe(200);
1420 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
1421
1422 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
1423 expect(result.status).toBe(200);
1424 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
1425
1426 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1427 expect(result.status).toBe(200);
1428 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
1429 });
1430
1431 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
1432 {
1433 const clipA = path.join(rootDir, 'clip-a.mkv');
1434 const clipB = path.join(rootDir, 'clip-b.mkv');
1435 const clipC = path.join(rootDir, 'clip-c.mkv');
1436 fs.writeFileSync(clipA, 'a');
1437 fs.writeFileSync(clipB, 'b');
1438 fs.writeFileSync(clipC, 'c');
1439
1440 const db = getDb();
1441 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1442 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
1443 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1444 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
1445 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1446 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
1447
1448 const { status, body } = await req('POST', '/api/files/watched-statuses', {
1449 filePaths: [clipA, clipB, clipC],
1450 });
1451
1452 expect(status).toBe(200);
1453 expect(body.statuses).toEqual({
1454 [clipA]: 'fully',
1455 [clipB]: 'partway',
1456 });
1457 });
1458
1459 test('POST /api/files/watched-statuses validates filePaths input', async () =>
1460 {
1461 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
1462 expect(status).toBe(400);
1463 expect(body.error).toMatch(/filePaths array is required/i);
1464 });
1465});
1466
1467describe('SHA-256 hashing and duplicate detection', () =>
1468{
1469 test('POST /api/files/upload queues sha256 hash for uploaded files', async () =>
1470 {
1471 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1472 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
1473 ]);
1474 expect(status).toBe(200);
1475
1476 await drainFileHashQueue();
1477
1478 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1479 .get([path.join(rootDir, 'hashme.txt')]);
1480 expect(meta).toBeTruthy();
1481 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
1482 });
1483
1484 test('POST /api/files/upload stores uploaded_at for uploaded files', async () =>
1485 {
1486 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1487 { name: 'uploaded-at.txt', content: 'hello', type: 'text/plain' },
1488 ]);
1489 expect(status).toBe(200);
1490
1491 const meta = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?')
1492 .get([path.join(rootDir, 'uploaded-at.txt')]);
1493 expect(meta).toBeTruthy();
1494 expect(String(meta.uploaded_at || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1495 });
1496
1497 test('GET /api/files/meta enqueues sha256 and background worker persists it', async () =>
1498 {
1499 const filePath = path.join(rootDir, 'lazy.txt');
1500 fs.writeFileSync(filePath, 'lazy content');
1501
1502 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1503 .run([filePath, 'admin', '[]']);
1504
1505 const first = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1506 expect(first.status).toBe(200);
1507 expect(first.body.sha256).toBeNull();
1508
1509 await drainFileHashQueue();
1510
1511 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
1512 expect(row.sha256).toMatch(/^[0-9a-f]{64}$/);
1513
1514 const second = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1515 expect(second.status).toBe(200);
1516 expect(second.body.sha256).toBe(row.sha256);
1517 });
1518
1519 test('GET /api/files/meta backfills uploaded_at when missing', async () =>
1520 {
1521 const filePath = path.join(rootDir, 'legacy.txt');
1522 fs.writeFileSync(filePath, 'legacy');
1523
1524 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1525 .run([filePath, 'admin', '[]']);
1526
1527 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1528 expect(status).toBe(200);
1529 expect(String(body.uploadedAt || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1530
1531 const row = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([filePath]);
1532 expect(String(row.uploaded_at || '')).toBe(String(body.uploadedAt || ''));
1533 });
1534
1535 test('GET /api/files/duplicates returns other files with the same hash', async () =>
1536 {
1537 const content = 'duplicate content';
1538 const fileA = path.join(rootDir, 'dup-a.txt');
1539 const fileB = path.join(rootDir, 'dup-b.txt');
1540 fs.writeFileSync(fileA, content);
1541 fs.writeFileSync(fileB, content);
1542
1543 // Compute the expected hash.
1544 const crypto = require('crypto');
1545 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
1546
1547 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1548 .run([fileA, 'admin', '[]', expectedHash]);
1549 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1550 .run([fileB, 'admin', '[]', expectedHash]);
1551
1552 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
1553 expect(status).toBe(200);
1554 expect(body.duplicates).toHaveLength(1);
1555 expect(body.duplicates[0].path).toBe(fileB);
1556 expect(body.duplicates[0].name).toBe('dup-b.txt');
1557 });
1558
1559 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
1560 {
1561 const filePath = path.join(rootDir, 'nohash.txt');
1562 fs.writeFileSync(filePath, 'no hash yet');
1563
1564 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1565 .run([filePath, 'admin', '[]']);
1566
1567 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
1568 expect(status).toBe(200);
1569 expect(body.duplicates).toEqual([]);
1570 });
1571
1572 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
1573 {
1574 const content = 'secret dupe';
1575 const accessible = path.join(rootDir, 'visible.txt');
1576 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
1577 fs.writeFileSync(accessible, content);
1578
1579 const crypto = require('crypto');
1580 const hash = crypto.createHash('sha256').update(content).digest('hex');
1581
1582 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1583 .run([accessible, 'admin', '[]', hash]);
1584 // Insert a row for a path that is NOT inside any configured root.
1585 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1586 .run([outsideRoot, 'admin', '[]', hash]);
1587
1588 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1589 expect(status).toBe(200);
1590 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1591 });
1592
1593 test('POST /api/files/move preserves sha256 after rename', async () =>
1594 {
1595 const from = path.join(rootDir, 'withHash.txt');
1596 const toDir = path.join(rootDir, 'subfolder');
1597 fs.writeFileSync(from, 'content');
1598 fs.mkdirSync(toDir);
1599
1600 const hash = 'a'.repeat(64);
1601 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1602 .run([from, 'admin', '[]', hash]);
1603
1604 const { status } = await req('POST', '/api/files/move', { from, toDir });
1605 expect(status).toBe(200);
1606
1607 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1608 .get([path.join(toDir, 'withHash.txt')]);
1609 expect(meta.sha256).toBe(hash);
1610 });
1611});