BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

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