BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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