BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

719ffd79 History
files.routes.test.js 53.5 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
571describe('GET /api/files/thumbnail', () =>
572{
573 test('returns 404 while cached thumbnail is not ready', async () =>
574 {
575 const source = path.join(rootDir, 'photo.jpg');
576 fs.writeFileSync(source, 'not-an-image');
577
578 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
579 expect(status).toBe(404);
580 expect(body.error).toMatch(/not ready/i);
581 });
582
583 test('serves cached thumbnail file when available', async () =>
584 {
585 const source = path.join(rootDir, 'photo.jpg');
586 const thumb = path.join(rootDir, 'photo-thumb.webp');
587 fs.writeFileSync(source, 'not-an-image');
588 fs.writeFileSync(thumb, 'webp-bytes');
589 mockThumbPath = thumb;
590
591 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
592 expect(response.status).toBe(200);
593 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
594 expect(response.body.toString('utf8')).toBe('webp-bytes');
595 });
596});
597
598describe('GET /api/files/root-access', () =>
599{
600 test('returns users with R/R+W modes for an exact root path', async () =>
601 {
602 const label = path.basename(rootDir);
603 const db = getDb();
604 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
605 .run(['admin', 'x', 1, '{}']);
606 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
607 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
608 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
609 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
610 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
611 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
612
613 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
614 expect(status).toBe(200);
615 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
616 expect(body.users).toEqual([
617 { username: 'admin', mode: 'R+W' },
618 { username: 'bob', mode: 'R+W' },
619 { username: 'alice', mode: 'R' },
620 ]);
621 });
622
623 test('rejects non-exact nested root paths', async () =>
624 {
625 const nested = path.join(rootDir, 'sub');
626 fs.mkdirSync(nested, { recursive: true });
627
628 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
629 expect(status).toBe(400);
630 });
631});
632
633describe('orphaned user folder access', () =>
634{
635 test('admins can read and write in orphaned user folders', async () =>
636 {
637 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
638 const orphanFolder = path.join(userFolderBase, 'ghost-user');
639 fs.mkdirSync(orphanFolder, { recursive: true });
640 fs.writeFileSync(path.join(orphanFolder, 'notes.txt'), 'hello');
641
642 mockUserPath = userFolderBase;
643 mockUser = {
644 username: 'admin',
645 isAdmin: true,
646 permissions: {},
647 };
648
649 try
650 {
651 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
652 expect(listRes.status).toBe(200);
653 expect(Array.isArray(listRes.body.items)).toBe(true);
654 expect(listRes.body.items.some((item) => item.name === 'notes.txt')).toBe(true);
655
656 const mkdirRes = await req('POST', '/api/files/mkdir', {
657 dir: orphanFolder,
658 name: 'created-by-admin',
659 });
660 expect(mkdirRes.status).toBe(200);
661 expect(fs.existsSync(path.join(orphanFolder, 'created-by-admin'))).toBe(true);
662 } finally
663 {
664 fs.rmSync(userFolderBase, { recursive: true, force: true });
665 }
666 });
667
668 test('non-admin users cannot access orphaned user folders', async () =>
669 {
670 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
671 const orphanFolder = path.join(userFolderBase, 'ghost-user');
672 fs.mkdirSync(orphanFolder, { recursive: true });
673
674 mockUserPath = userFolderBase;
675 mockUser = {
676 username: 'alice',
677 isAdmin: false,
678 permissions: {},
679 };
680
681 try
682 {
683 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(orphanFolder)}`);
684 expect(listRes.status).toBe(403);
685 } finally
686 {
687 fs.rmSync(userFolderBase, { recursive: true, force: true });
688 }
689 });
690});
691
692describe('list access chmod', () =>
693{
694 test('GET /api/files/list applies chmod to opened folder and direct children when enabled', async () =>
695 {
696 const nestedDir = path.join(rootDir, 'locked');
697 const nestedFile = path.join(nestedDir, 'data.txt');
698 const deepDir = path.join(nestedDir, 'deep');
699 const deepFile = path.join(deepDir, 'deep.txt');
700 fs.mkdirSync(nestedDir, { recursive: true });
701 fs.mkdirSync(deepDir, { recursive: true });
702 fs.writeFileSync(nestedFile, 'hello');
703 fs.writeFileSync(deepFile, 'deep');
704
705 fs.chmodSync(rootDir, 0o700);
706 fs.chmodSync(nestedDir, 0o700);
707 fs.chmodSync(nestedFile, 0o600);
708 fs.chmodSync(deepDir, 0o700);
709 fs.chmodSync(deepFile, 0o600);
710
711 process.env.FILEMANAGER_LIST_ACCESS_CHMOD = '1';
712
713 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
714 expect(listRes.status).toBe(200);
715
716 const rootMode = fs.statSync(rootDir).mode & 0o777;
717 const dirMode = fs.statSync(nestedDir).mode & 0o777;
718 const fileMode = fs.statSync(nestedFile).mode & 0o777;
719 const deepDirMode = fs.statSync(deepDir).mode & 0o777;
720 const deepFileMode = fs.statSync(deepFile).mode & 0o777;
721
722 expect(rootMode).toBe(0o777);
723 expect(dirMode).toBe(0o777);
724 expect(fileMode).toBe(0o600);
725 expect(deepDirMode).toBe(0o700);
726 expect(deepFileMode).toBe(0o600);
727 });
728
729 test('GET /api/files/list leaves permissions unchanged when disabled', async () =>
730 {
731 const nestedDir = path.join(rootDir, 'locked');
732 const nestedFile = path.join(nestedDir, 'data.txt');
733 fs.mkdirSync(nestedDir, { recursive: true });
734 fs.writeFileSync(nestedFile, 'hello');
735
736 fs.chmodSync(rootDir, 0o700);
737 fs.chmodSync(nestedDir, 0o700);
738 fs.chmodSync(nestedFile, 0o600);
739
740 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(rootDir)}`);
741 expect(listRes.status).toBe(200);
742
743 const rootMode = fs.statSync(rootDir).mode & 0o777;
744 const dirMode = fs.statSync(nestedDir).mode & 0o777;
745 const fileMode = fs.statSync(nestedFile).mode & 0o777;
746
747 expect(rootMode).toBe(0o700);
748 expect(dirMode).toBe(0o700);
749 expect(fileMode).toBe(0o600);
750 });
751});
752
753describe('subtitle debug cache access', () =>
754{
755 test('admins can browse the subtitle debug cache folder', async () =>
756 {
757 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
758 fs.rmSync(logDir, { recursive: true, force: true });
759 fs.mkdirSync(logDir, { recursive: true });
760 fs.writeFileSync(path.join(logDir, '2026-05-25-sample-subtitlelog.txt'), 'hello');
761
762 mockUser = {
763 username: 'admin',
764 isAdmin: true,
765 permissions: {},
766 };
767
768 try
769 {
770 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
771 expect(listRes.status).toBe(200);
772 expect(Array.isArray(listRes.body.items)).toBe(true);
773 expect(listRes.body.items.some((item) => item.name === '2026-05-25-sample-subtitlelog.txt')).toBe(true);
774 } finally
775 {
776 fs.rmSync(logDir, { recursive: true, force: true });
777 }
778 });
779
780 test('admins can delete files in the subtitle debug cache folder', async () =>
781 {
782 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
783 const logFile = path.join(logDir, '2026-05-25-delete-me-subtitlelog.txt');
784 fs.rmSync(logDir, { recursive: true, force: true });
785 fs.mkdirSync(logDir, { recursive: true });
786 fs.writeFileSync(logFile, 'delete me');
787
788 mockUser = {
789 username: 'admin',
790 isAdmin: true,
791 permissions: {},
792 };
793
794 try
795 {
796 const deleteRes = await req('POST', '/api/files/delete', { path: logFile });
797 expect(deleteRes.status).toBe(200);
798 expect(deleteRes.body).toEqual({ ok: true });
799 expect(fs.existsSync(logFile)).toBe(false);
800 } finally
801 {
802 fs.rmSync(logDir, { recursive: true, force: true });
803 }
804 });
805
806 test('non-admin users cannot browse the subtitle debug cache folder', async () =>
807 {
808 const logDir = path.join(os.tmpdir(), 'filemanager-subtitle-debug-logs');
809 fs.rmSync(logDir, { recursive: true, force: true });
810 fs.mkdirSync(logDir, { recursive: true });
811
812 mockUser = {
813 username: 'alice',
814 isAdmin: false,
815 permissions: {},
816 };
817
818 try
819 {
820 const listRes = await req('GET', `/api/files/list?dir=${encodeURIComponent(logDir)}`);
821 expect(listRes.status).toBe(403);
822 } finally
823 {
824 fs.rmSync(logDir, { recursive: true, force: true });
825 }
826 });
827});
828
829describe('folder icon endpoints', () =>
830{
831 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
832 {
833 const subDir = path.join(rootDir, 'photos');
834 fs.mkdirSync(subDir);
835 const imgPath = path.join(subDir, 'a.jpg');
836 fs.writeFileSync(imgPath, 'img');
837
838 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
839
840 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
841 expect(status).toBe(200);
842 expect(body.images).toHaveLength(1);
843 expect(body.images[0].filePath).toBe(imgPath);
844 });
845
846 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
847 {
848 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
849 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
850 fs.writeFileSync(videoPath, 'video');
851
852 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
853
854 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
855 expect(status).toBe(200);
856 expect(body.images).toEqual([{ filePath: videoPath }]);
857 });
858
859 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
860 {
861 mockFolderImages = [];
862
863 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
864 expect(status).toBe(200);
865 expect(body.images).toEqual([]);
866 });
867
868 test('GET /api/files/folder-icon returns null when no icon available', async () =>
869 {
870 mockFolderIconFile = null;
871
872 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
873 expect(status).toBe(200);
874 expect(body.icon).toBeNull();
875 });
876
877 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
878 {
879 const imgPath = path.join(rootDir, 'cover.jpg');
880 fs.writeFileSync(imgPath, 'img');
881 mockFolderIconFile = imgPath;
882
883 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
884 expect(status).toBe(200);
885 expect(body.icon).toMatchObject({ filePath: imgPath });
886 });
887
888 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
889 {
890 const imgPath = path.join(rootDir, 'cover.jpg');
891 const thumbFile = path.join(rootDir, 'cover.webp');
892 fs.writeFileSync(imgPath, 'img');
893 fs.writeFileSync(thumbFile, 'webp');
894 mockThumbPath = thumbFile;
895
896 const { status, body } = await req('POST', '/api/files/folder-icon', {
897 folderPath: rootDir,
898 imagePath: imgPath,
899 });
900 expect(status).toBe(200);
901 expect(body.ok).toBe(true);
902 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
903 });
904
905 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
906 {
907 const imgPath = path.join(rootDir, 'missing.jpg');
908 fs.writeFileSync(imgPath, 'img');
909 mockThumbPath = null;
910
911 const { status, body } = await req('POST', '/api/files/folder-icon', {
912 folderPath: rootDir,
913 imagePath: imgPath,
914 });
915 expect(status).toBe(404);
916 expect(body.error).toMatch(/thumbnail not ready/i);
917 });
918
919 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
920 {
921 const { status, body } = await req('POST', '/api/files/folder-icon', {
922 folderPath: rootDir,
923 imagePath: null,
924 });
925 expect(status).toBe(200);
926 expect(body.ok).toBe(true);
927 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
928 });
929
930 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
931 {
932 const label = path.basename(rootDir);
933 mockUser = {
934 username: 'reader',
935 isAdmin: false,
936 permissions: { [label]: { read: true, write: false } },
937 };
938
939 const imgPath = path.join(rootDir, 'photo.jpg');
940 fs.writeFileSync(imgPath, 'img');
941
942 const { status } = await req('POST', '/api/files/folder-icon', {
943 folderPath: rootDir,
944 imagePath: imgPath,
945 });
946 expect(status).toBe(403);
947 });
948});
949
950describe('file search endpoint', () =>
951{
952 test('GET /api/files/search returns fuzzy-matched files across folders', async () =>
953 {
954 const movieDir = path.join(rootDir, 'Movies');
955 const docsDir = path.join(rootDir, 'Docs');
956 fs.mkdirSync(movieDir, { recursive: true });
957 fs.mkdirSync(docsDir, { recursive: true });
958 fs.writeFileSync(path.join(movieDir, 'Dragon Ball Super.mkv'), 'vid');
959 fs.writeFileSync(path.join(docsDir, 'notes.txt'), 'txt');
960
961 const { status, body } = await req('GET', '/api/files/search?query=dbs');
962 expect(status).toBe(200);
963 expect(body.query).toBe('dbs');
964 expect(body.results.length).toBeGreaterThan(0);
965 expect(body.results[0].name).toBe('Dragon Ball Super.mkv');
966 });
967
968 test('GET /api/files/search returns 400 when query is missing', async () =>
969 {
970 const { status } = await req('GET', '/api/files/search');
971 expect(status).toBe(400);
972 });
973});
974
975describe('image search endpoint', () =>
976{
977 test('GET /api/files/search-images returns thumbnailed image matches only', async () =>
978 {
979 const picsDir = path.join(rootDir, 'Pictures');
980 fs.mkdirSync(picsDir, { recursive: true });
981 fs.writeFileSync(path.join(picsDir, 'dragon-cover.jpg'), 'img');
982 fs.writeFileSync(path.join(picsDir, 'dragon-notes.txt'), 'txt');
983
984 const thumbPath = path.join(rootDir, 'thumb.webp');
985 fs.writeFileSync(thumbPath, 'thumb');
986 mockThumbPath = thumbPath;
987
988 const { status, body } = await req('GET', '/api/files/search-images?query=dragon');
989 expect(status).toBe(200);
990 expect(body.results.length).toBe(1);
991 expect(body.results[0].name).toBe('dragon-cover.jpg');
992 });
993
994 test('GET /api/files/search-images returns 400 for short queries', async () =>
995 {
996 const { status } = await req('GET', '/api/files/search-images?query=a');
997 expect(status).toBe(400);
998 });
999});
1000
1001describe('global favicon endpoints', () =>
1002{
1003 test('GET /api/files/global-favicon returns null when unset', async () =>
1004 {
1005 const { status, body } = await req('GET', '/api/files/global-favicon');
1006 expect(status).toBe(200);
1007 expect(body.favicon).toBeNull();
1008 });
1009
1010 test('POST /api/files/global-favicon stores selected image path', async () =>
1011 {
1012 const imgPath = path.join(rootDir, 'cover.jpg');
1013 const thumbPath = path.join(rootDir, 'cover.webp');
1014 fs.writeFileSync(imgPath, 'img');
1015 fs.writeFileSync(thumbPath, 'thumb');
1016 mockThumbPath = thumbPath;
1017
1018 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1019 expect(status).toBe(200);
1020 expect(body.ok).toBe(true);
1021 expect(mockGlobalFaviconPath).toBe(imgPath);
1022
1023 const fetched = await req('GET', '/api/files/global-favicon');
1024 expect(fetched.status).toBe(200);
1025 expect(fetched.body.favicon).toEqual({ filePath: imgPath });
1026 });
1027
1028 test('POST /api/files/global-favicon clears the configured favicon', async () =>
1029 {
1030 mockGlobalFaviconPath = path.join(rootDir, 'old.jpg');
1031
1032 const { status, body } = await req('POST', '/api/files/global-favicon', { imagePath: null });
1033 expect(status).toBe(200);
1034 expect(body.ok).toBe(true);
1035 expect(mockGlobalFaviconPath).toBeNull();
1036 });
1037
1038 test('POST /api/files/global-favicon is admin-only', async () =>
1039 {
1040 mockUser = { username: 'reader', isAdmin: false, permissions: {} };
1041 const imgPath = path.join(rootDir, 'cover.jpg');
1042 fs.writeFileSync(imgPath, 'img');
1043
1044 const { status } = await req('POST', '/api/files/global-favicon', { imagePath: imgPath });
1045 expect(status).toBe(403);
1046 });
1047});
1048
1049// ---------------------------------------------------------------------------
1050// GET /api/files/download-zip
1051// ---------------------------------------------------------------------------
1052describe('GET /api/files/download-zip', () =>
1053{
1054 beforeEach(() =>
1055 {
1056 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
1057 });
1058
1059 test('streams a valid zip for an accessible directory', async () =>
1060 {
1061 const subDir = path.join(rootDir, 'zipme');
1062 fs.mkdirSync(subDir);
1063 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
1064
1065 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
1066 expect(status).toBe(200);
1067
1068 const ct = headers['content-type'] || '';
1069 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
1070
1071 // ZIP magic bytes PK\x03\x04
1072 expect(buf[0]).toBe(0x50);
1073 expect(buf[1]).toBe(0x4b);
1074 }, 20000);
1075
1076 test('returns 400 when dir param is missing', async () =>
1077 {
1078 const { status } = await req('GET', '/api/files/download-zip');
1079 expect(status).toBe(400);
1080 });
1081
1082 test('returns 404 for a non-existent directory', async () =>
1083 {
1084 const missing = path.join(rootDir, 'ghost');
1085 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
1086 expect(status).toBe(404);
1087 });
1088
1089 test('returns 403 for path outside configured roots', async () =>
1090 {
1091 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
1092 expect(status).toBe(403);
1093 });
1094});
1095
1096describe('video streaming routes', () =>
1097{
1098 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
1099 {
1100 const filePath = path.join(rootDir, 'clip.mkv');
1101 fs.writeFileSync(filePath, 'video');
1102 mockVideoStreamSession = {
1103 sessionId: 'sess-123',
1104 durationSeconds: 42.25,
1105 videoWidth: 1920,
1106 videoHeight: 1080,
1107 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
1108 };
1109
1110 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
1111
1112 expect(status).toBe(200);
1113 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
1114 expect(body.durationSeconds).toBe(42.25);
1115 expect(body.videoWidth).toBe(1920);
1116 expect(body.videoHeight).toBe(1080);
1117 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
1118 expect(body.subtitleTracks).toEqual([
1119 {
1120 label: 'English',
1121 language: 'eng',
1122 default: true,
1123 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
1124 },
1125 ]);
1126 });
1127
1128 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
1129 {
1130 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
1131 {
1132 res.type('text/vtt').send('WEBVTT\n');
1133 };
1134
1135 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
1136
1137 expect(status).toBe(200);
1138 expect(headers['content-type']).toMatch(/text\/vtt/);
1139 expect(body.toString()).toBe('WEBVTT\n');
1140 });
1141
1142 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
1143 {
1144 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
1145
1146 expect(status).toBe(200);
1147 expect(body).toEqual({ ok: true });
1148 expect(releasedVideoStreamSessionId).toBe('sess-123');
1149 });
1150
1151 test('GET /api/files/video-stream-subtitle-frame returns rendered PNG frames', async () =>
1152 {
1153 const filePath = path.join(rootDir, 'clip.mkv');
1154 fs.writeFileSync(filePath, 'video');
1155 mockSubtitleFrameResult = {
1156 frame: Buffer.from('png-data'),
1157 left: 100,
1158 top: 50,
1159 width: 320,
1160 height: 180,
1161 canvasWidth: 640,
1162 canvasHeight: 360,
1163 startTimeSeconds: 1.5,
1164 endTimeSeconds: 3.2,
1165 };
1166
1167 const { status, headers, body } = await reqRaw(
1168 'GET',
1169 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080`
1170 );
1171
1172 expect(status).toBe(200);
1173 expect(headers['content-type']).toMatch(/image\/png/);
1174 expect(headers['x-subtitle-frame-status']).toBe('ok');
1175 expect(headers['x-subtitle-frame-left']).toBe('100');
1176 expect(headers['x-subtitle-frame-top']).toBe('50');
1177 expect(headers['x-subtitle-frame-width']).toBe('320');
1178 expect(headers['x-subtitle-frame-height']).toBe('180');
1179 expect(headers['x-subtitle-frame-canvas-width']).toBe('640');
1180 expect(headers['x-subtitle-frame-canvas-height']).toBe('360');
1181 expect(headers['x-subtitle-frame-start-time']).toBe('1.5');
1182 expect(headers['x-subtitle-frame-end-time']).toBe('3.2');
1183 expect(Number(headers['x-subtitle-request-received-at-ms'])).toBeGreaterThan(0);
1184 expect(Number(headers['x-subtitle-response-sent-at-ms'])).toBeGreaterThan(0);
1185 expect(body.equals(Buffer.from('png-data'))).toBe(true);
1186 });
1187
1188 test('POST /api/files/video-stream-subtitle-log persists subtitle debug batches', async () =>
1189 {
1190 const filePath = path.join(rootDir, 'movie.mkv');
1191 fs.writeFileSync(filePath, 'video');
1192 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
1193
1194 const { status, body } = await req('POST', '/api/files/video-stream-subtitle-log', {
1195 filePath,
1196 sessionId: 'sess-123',
1197 entries: [
1198 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
1199 ],
1200 });
1201
1202 expect(status).toBe(200);
1203 expect(body).toEqual({ ok: true });
1204 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
1205 videoName: 'movie.mkv',
1206 context: expect.objectContaining({
1207 filePath,
1208 sessionId: 'sess-123',
1209 source: 'app',
1210 }),
1211 }));
1212 });
1213
1214 test('GET /api/files/video-stream-subtitle-frame returns 204 with none status when no subtitle is active', async () =>
1215 {
1216 const filePath = path.join(rootDir, 'clip.mkv');
1217 fs.writeFileSync(filePath, 'video');
1218 mockSubtitleFrameResult = null;
1219
1220 const { status, headers, body } = await reqRaw(
1221 'GET',
1222 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1223 );
1224
1225 expect(status).toBe(204);
1226 expect(headers['x-subtitle-frame-status']).toBe('none');
1227 expect(body.length).toBe(0);
1228 });
1229
1230 test('GET /api/files/video-stream-subtitle-frame returns 204 when rendering fails', async () =>
1231 {
1232 const filePath = path.join(rootDir, 'clip.mkv');
1233 fs.writeFileSync(filePath, 'video');
1234 mockSubtitleFrameError = new Error('decode failed');
1235
1236 const { status, headers, body } = await reqRaw(
1237 'GET',
1238 `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(filePath)}&streamIndex=0&timeSeconds=2.5`
1239 );
1240
1241 expect(status).toBe(204);
1242 expect(headers['x-subtitle-frame-status']).toBe('error');
1243 expect(body.length).toBe(0);
1244 });
1245
1246 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
1247 {
1248 const filePath = path.join(rootDir, 'clip.mkv');
1249 fs.writeFileSync(filePath, 'video');
1250
1251 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
1252 expect(result.status).toBe(200);
1253 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
1254
1255 // A lower progress update should not downgrade the status.
1256 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
1257 expect(result.status).toBe(200);
1258 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
1259
1260 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1261 expect(result.status).toBe(200);
1262 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
1263
1264 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
1265 expect(result.status).toBe(200);
1266 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
1267
1268 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1269 expect(result.status).toBe(200);
1270 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
1271 });
1272
1273 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
1274 {
1275 const clipA = path.join(rootDir, 'clip-a.mkv');
1276 const clipB = path.join(rootDir, 'clip-b.mkv');
1277 const clipC = path.join(rootDir, 'clip-c.mkv');
1278 fs.writeFileSync(clipA, 'a');
1279 fs.writeFileSync(clipB, 'b');
1280 fs.writeFileSync(clipC, 'c');
1281
1282 const db = getDb();
1283 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1284 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
1285 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1286 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
1287 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
1288 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
1289
1290 const { status, body } = await req('POST', '/api/files/watched-statuses', {
1291 filePaths: [clipA, clipB, clipC],
1292 });
1293
1294 expect(status).toBe(200);
1295 expect(body.statuses).toEqual({
1296 [clipA]: 'fully',
1297 [clipB]: 'partway',
1298 });
1299 });
1300
1301 test('POST /api/files/watched-statuses validates filePaths input', async () =>
1302 {
1303 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
1304 expect(status).toBe(400);
1305 expect(body.error).toMatch(/filePaths array is required/i);
1306 });
1307});
1308
1309describe('SHA-256 hashing and duplicate detection', () =>
1310{
1311 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
1312 {
1313 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1314 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
1315 ]);
1316 expect(status).toBe(200);
1317
1318 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1319 .get([path.join(rootDir, 'hashme.txt')]);
1320 expect(meta).toBeTruthy();
1321 // SHA-256 is a 64-char hex string.
1322 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
1323 });
1324
1325 test('POST /api/files/upload stores uploaded_at for uploaded files', async () =>
1326 {
1327 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
1328 { name: 'uploaded-at.txt', content: 'hello', type: 'text/plain' },
1329 ]);
1330 expect(status).toBe(200);
1331
1332 const meta = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?')
1333 .get([path.join(rootDir, 'uploaded-at.txt')]);
1334 expect(meta).toBeTruthy();
1335 expect(String(meta.uploaded_at || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1336 });
1337
1338 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
1339 {
1340 const filePath = path.join(rootDir, 'lazy.txt');
1341 fs.writeFileSync(filePath, 'lazy content');
1342
1343 // Insert a row without a hash to simulate a pre-existing file.
1344 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1345 .run([filePath, 'admin', '[]']);
1346
1347 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1348 expect(status).toBe(200);
1349 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
1350
1351 // Verify it was persisted.
1352 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
1353 expect(row.sha256).toBe(body.sha256);
1354 });
1355
1356 test('GET /api/files/meta backfills uploaded_at when missing', async () =>
1357 {
1358 const filePath = path.join(rootDir, 'legacy.txt');
1359 fs.writeFileSync(filePath, 'legacy');
1360
1361 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1362 .run([filePath, 'admin', '[]']);
1363
1364 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
1365 expect(status).toBe(200);
1366 expect(String(body.uploadedAt || '')).toMatch(/^\d{4}-\d{2}-\d{2}T/);
1367
1368 const row = getDb().prepare('SELECT uploaded_at FROM file_meta WHERE file_path = ?').get([filePath]);
1369 expect(String(row.uploaded_at || '')).toBe(String(body.uploadedAt || ''));
1370 });
1371
1372 test('GET /api/files/duplicates returns other files with the same hash', async () =>
1373 {
1374 const content = 'duplicate content';
1375 const fileA = path.join(rootDir, 'dup-a.txt');
1376 const fileB = path.join(rootDir, 'dup-b.txt');
1377 fs.writeFileSync(fileA, content);
1378 fs.writeFileSync(fileB, content);
1379
1380 // Compute the expected hash.
1381 const crypto = require('crypto');
1382 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
1383
1384 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1385 .run([fileA, 'admin', '[]', expectedHash]);
1386 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1387 .run([fileB, 'admin', '[]', expectedHash]);
1388
1389 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
1390 expect(status).toBe(200);
1391 expect(body.duplicates).toHaveLength(1);
1392 expect(body.duplicates[0].path).toBe(fileB);
1393 expect(body.duplicates[0].name).toBe('dup-b.txt');
1394 });
1395
1396 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
1397 {
1398 const filePath = path.join(rootDir, 'nohash.txt');
1399 fs.writeFileSync(filePath, 'no hash yet');
1400
1401 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
1402 .run([filePath, 'admin', '[]']);
1403
1404 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
1405 expect(status).toBe(200);
1406 expect(body.duplicates).toEqual([]);
1407 });
1408
1409 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
1410 {
1411 const content = 'secret dupe';
1412 const accessible = path.join(rootDir, 'visible.txt');
1413 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
1414 fs.writeFileSync(accessible, content);
1415
1416 const crypto = require('crypto');
1417 const hash = crypto.createHash('sha256').update(content).digest('hex');
1418
1419 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1420 .run([accessible, 'admin', '[]', hash]);
1421 // Insert a row for a path that is NOT inside any configured root.
1422 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1423 .run([outsideRoot, 'admin', '[]', hash]);
1424
1425 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
1426 expect(status).toBe(200);
1427 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
1428 });
1429
1430 test('POST /api/files/move preserves sha256 after rename', async () =>
1431 {
1432 const from = path.join(rootDir, 'withHash.txt');
1433 const toDir = path.join(rootDir, 'subfolder');
1434 fs.writeFileSync(from, 'content');
1435 fs.mkdirSync(toDir);
1436
1437 const hash = 'a'.repeat(64);
1438 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
1439 .run([from, 'admin', '[]', hash]);
1440
1441 const { status } = await req('POST', '/api/files/move', { from, toDir });
1442 expect(status).toBe(200);
1443
1444 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
1445 .get([path.join(toDir, 'withHash.txt')]);
1446 expect(meta.sha256).toBe(hash);
1447 });
1448});