BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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