BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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