BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

test
timfa Tim Falken · pushed by timfa · 6 months ago
2c0e0fdd History
files.routes.test.js 36.2 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 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
14let mockThumbPath = null;
15let mockFolderImages = [];
16let mockFolderIconFile = null;
17let lastFolderIconAssignment = undefined;
18let mockVideoStreamSession = null;
19let mockVideoStreamAsset = null;
20let releasedVideoStreamSessionId = null;
21
22jest.mock('../server/db', () =>
23{
24 const { Database } = require('node-sqlite3-wasm');
25 let db;
26 function getDb ()
27 {
28 if (!db)
29 {
30 db = new Database(':memory:');
31 db.exec(`
32 CREATE TABLE IF NOT EXISTS users (
33 id INTEGER PRIMARY KEY AUTOINCREMENT,
34 username TEXT UNIQUE NOT NULL,
35 password_hash TEXT NOT NULL,
36 is_admin INTEGER NOT NULL DEFAULT 0,
37 permissions TEXT NOT NULL DEFAULT '{}'
38 );
39 CREATE TABLE IF NOT EXISTS file_meta (
40 file_path TEXT PRIMARY KEY,
41 uploader TEXT NOT NULL DEFAULT '',
42 downloaders TEXT NOT NULL DEFAULT '[]',
43 watched_by TEXT NOT NULL DEFAULT '{}',
44 sha256 TEXT
45 );
46 CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256);
47 `);
48 }
49 return db;
50 }
51 return { getDb, initDb: getDb };
52});
53
54jest.mock('../server/config', () => ({
55 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }),
56 saveConfig: (config) =>
57 {
58 mockPaths = [...(config.paths || [])];
59 mockRootAliases = { ...(config.rootAliases || {}) };
60 },
61 getEffectivePaths: (paths) => paths,
62 getAllowedRoot: (targetPath, roots) =>
63 {
64 const path = require('path');
65 const absTarget = path.resolve(String(targetPath || ''));
66 return roots.find((root) =>
67 {
68 const absRoot = path.resolve(root);
69 return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep);
70 }) || null;
71 },
72}));
73
74jest.mock('../server/auth', () => ({
75 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
76}));
77
78jest.mock('../server/thumbnail-cache', () => ({
79 getCachedThumbnailInfo: async () =>
80 {
81 if (!mockThumbPath) return null;
82 return { thumbPath: mockThumbPath, contentType: 'image/webp' };
83 },
84 getFilesWithThumbnailsInDir: async () => mockFolderImages.slice(),
85 getFolderIconSourceFile: async () => mockFolderIconFile,
86 setFolderIconAssignment: async (folderPath, imagePath) =>
87 {
88 lastFolderIconAssignment = { folderPath, imagePath };
89 },
90}));
91
92jest.mock('../server/video-stream', () => ({
93 createVideoStreamSession: jest.fn(async () =>
94 {
95 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
96 return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] };
97 }),
98 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
99 {
100 if (typeof mockVideoStreamAsset === 'function')
101 {
102 await mockVideoStreamAsset(sessionId, assetPath, req, res);
103 return;
104 }
105 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
106 }),
107 releaseVideoStreamSession: jest.fn((sessionId) =>
108 {
109 releasedVideoStreamSessionId = String(sessionId || '');
110 return true;
111 }),
112}));
113
114const filesRoutes = require('../server/routes/files');
115const { getDb } = require('../server/db');
116
117let server;
118let baseUrl;
119let rootDir;
120
121beforeAll(async () =>
122{
123 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-'));
124 mockPaths = [rootDir];
125
126 const app = express();
127 app.use(express.json());
128 app.use('/api/files', filesRoutes);
129 app.use((err, req, res, next) =>
130 {
131 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
132 });
133
134 server = http.createServer(app);
135 server.listen(0);
136 await once(server, 'listening');
137 baseUrl = `http://127.0.0.1:${server.address().port}`;
138});
139
140afterAll(() =>
141{
142 server.close();
143 fs.rmSync(rootDir, { recursive: true, force: true });
144});
145
146beforeEach(() =>
147{
148 fs.rmSync(rootDir, { recursive: true, force: true });
149 fs.mkdirSync(rootDir, { recursive: true });
150 if (mockUserPath)
151 {
152 fs.rmSync(mockUserPath, { recursive: true, force: true });
153 fs.mkdirSync(mockUserPath, { recursive: true });
154 }
155 mockRootAliases = {};
156 mockUserPath = null;
157 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
158 mockThumbPath = null;
159 mockFolderImages = [];
160 mockFolderIconFile = null;
161 lastFolderIconAssignment = undefined;
162 mockVideoStreamSession = null;
163 mockVideoStreamAsset = null;
164 releasedVideoStreamSessionId = null;
165 const db = getDb();
166 db.prepare('DELETE FROM file_meta').run([]);
167 db.prepare('DELETE FROM users').run([]);
168});
169
170function req (method, routePath, body)
171{
172 const payload = body ? JSON.stringify(body) : undefined;
173 return new Promise((resolve, reject) =>
174 {
175 const request = http.request(baseUrl + routePath, {
176 method,
177 headers: {
178 'Content-Type': 'application/json',
179 ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}),
180 },
181 }, res =>
182 {
183 let data = '';
184 res.on('data', chunk => data += chunk);
185 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
186 });
187 request.on('error', reject);
188 if (payload) request.write(payload);
189 request.end();
190 });
191}
192
193function reqRaw (method, routePath)
194{
195 return new Promise((resolve, reject) =>
196 {
197 const request = http.request(baseUrl + routePath, { method }, res =>
198 {
199 const chunks = [];
200 res.on('data', chunk => chunks.push(Buffer.from(chunk)));
201 res.on('end', () => resolve({
202 status: res.statusCode,
203 headers: res.headers,
204 body: Buffer.concat(chunks),
205 }));
206 });
207 request.on('error', reject);
208 request.end();
209 });
210}
211
212function reqMultipart (routePath, files, extraHeaders = {})
213{
214 const boundary = '----filemanager-test-boundary';
215 const buffers = [];
216
217 for (const file of files)
218 {
219 buffers.push(Buffer.from(
220 `--${boundary}\r\n`
221 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
222 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
223 ));
224 buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)));
225 buffers.push(Buffer.from('\r\n'));
226 }
227
228 buffers.push(Buffer.from(`--${boundary}--\r\n`));
229 const payload = Buffer.concat(buffers);
230
231 return new Promise((resolve, reject) =>
232 {
233 const request = http.request(baseUrl + routePath, {
234 method: 'POST',
235 headers: {
236 'Content-Type': `multipart/form-data; boundary=${boundary}`,
237 'Content-Length': payload.length,
238 ...extraHeaders,
239 },
240 }, res =>
241 {
242 let data = '';
243 res.on('data', chunk => data += chunk);
244 res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) }));
245 });
246 request.on('error', reject);
247 request.write(payload);
248 request.end();
249 });
250}
251
252function abortMultipartUpload (routePath, file)
253{
254 const boundary = '----filemanager-test-boundary-abort';
255 const header = Buffer.from(
256 `--${boundary}\r\n`
257 + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n`
258 + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`
259 );
260 const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content));
261
262 return new Promise((resolve) =>
263 {
264 const request = http.request(baseUrl + routePath, {
265 method: 'POST',
266 headers: {
267 'Content-Type': `multipart/form-data; boundary=${boundary}`,
268 },
269 });
270
271 let settled = false;
272 const finish = () =>
273 {
274 if (settled) return;
275 settled = true;
276 resolve();
277 };
278
279 request.on('error', finish);
280 request.on('close', finish);
281 request.write(header);
282 request.write(chunk);
283 setTimeout(() => request.destroy(), 20);
284 });
285}
286
287async function waitFor (predicate, timeoutMs = 500)
288{
289 const start = Date.now();
290 while (Date.now() - start < timeoutMs)
291 {
292 if (predicate()) return;
293 await new Promise(resolve => setTimeout(resolve, 10));
294 }
295 throw new Error('Timed out waiting for condition.');
296}
297
298describe('POST /api/files/upload', () =>
299{
300 test('stores a completed upload under its final name', async () =>
301 {
302 const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
303 { name: 'hello.txt', content: 'hello world', type: 'text/plain' },
304 ]);
305
306 expect(status).toBe(200);
307 expect(body.uploaded).toEqual(['hello.txt']);
308 expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world');
309
310 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
311 .get([path.join(rootDir, 'hello.txt')]);
312 expect(meta).toMatchObject({ uploader: 'admin' });
313 });
314
315 test('removes partial files when the upload connection aborts', async () =>
316 {
317 await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, {
318 name: 'partial.txt',
319 content: Buffer.alloc(256 * 1024, 'a'),
320 type: 'text/plain',
321 });
322
323 await waitFor(() => fs.readdirSync(rootDir).length === 0);
324
325 expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false);
326 expect(fs.readdirSync(rootDir)).toEqual([]);
327
328 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
329 .get([path.join(rootDir, 'partial.txt')]);
330 expect(meta).toBeFalsy();
331 });
332});
333
334describe('POST /api/files/move', () =>
335{
336 test('moves a file into another folder and rewrites metadata', async () =>
337 {
338 const from = path.join(rootDir, 'alpha.txt');
339 const toDir = path.join(rootDir, 'folder');
340 fs.writeFileSync(from, 'hello');
341 fs.mkdirSync(toDir);
342
343 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
344 .run([from, 'admin', '["alice"]']);
345
346 const { status, body } = await req('POST', '/api/files/move', { from, toDir });
347
348 expect(status).toBe(200);
349 expect(body.ok).toBe(true);
350 expect(fs.existsSync(from)).toBe(false);
351 expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true);
352
353 const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]);
354 expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' });
355 });
356
357 test('moves a folder into another folder and rewrites descendant metadata', async () =>
358 {
359 const fromDir = path.join(rootDir, 'src-folder');
360 const nestedFile = path.join(fromDir, 'child.txt');
361 const toDir = path.join(rootDir, 'dest-folder');
362 fs.mkdirSync(fromDir);
363 fs.mkdirSync(toDir);
364 fs.writeFileSync(nestedFile, 'hello');
365
366 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
367 .run([nestedFile, 'admin', '[]']);
368
369 const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir });
370
371 expect(status).toBe(200);
372 expect(fs.existsSync(fromDir)).toBe(false);
373 expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true);
374
375 const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?')
376 .get([path.join(toDir, 'src-folder', 'child.txt')]);
377 expect(movedMeta).toBeTruthy();
378 });
379
380 test('rejects moving a folder into itself', async () =>
381 {
382 const fromDir = path.join(rootDir, 'src-folder');
383 const childDir = path.join(fromDir, 'child');
384 fs.mkdirSync(childDir, { recursive: true });
385
386 const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir });
387
388 expect(status).toBe(400);
389 expect(body.error).toMatch(/folder into itself/i);
390 });
391
392 test('overwrites an existing destination when conflict strategy is overwrite', async () =>
393 {
394 const sourceFile = path.join(rootDir, 'source.txt');
395 const destinationDir = path.join(rootDir, 'dest');
396 fs.mkdirSync(destinationDir);
397 fs.writeFileSync(sourceFile, 'new-content');
398 fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content');
399
400 const { status, body } = await req('POST', '/api/files/move', {
401 from: sourceFile,
402 toDir: destinationDir,
403 conflict: 'overwrite',
404 });
405
406 expect(status).toBe(200);
407 expect(body.conflictResolution).toBe('overwrite');
408 expect(fs.existsSync(sourceFile)).toBe(false);
409 expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content');
410 });
411
412 test('renames destination when conflict strategy is rename', async () =>
413 {
414 const sourceFile = path.join(rootDir, 'report.txt');
415 const destinationDir = path.join(rootDir, 'dest');
416 fs.mkdirSync(destinationDir);
417 fs.writeFileSync(sourceFile, 'latest');
418 fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing');
419
420 const { status, body } = await req('POST', '/api/files/move', {
421 from: sourceFile,
422 toDir: destinationDir,
423 conflict: 'rename',
424 });
425
426 expect(status).toBe(200);
427 expect(body.conflictResolution).toBe('rename');
428 expect(path.basename(body.path)).toBe('report (1).txt');
429 expect(fs.readFileSync(body.path, 'utf8')).toBe('latest');
430 expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing');
431 });
432
433 test('moves a file into My Folder when rename falls back across filesystems', async () =>
434 {
435 const sourceFile = path.join(rootDir, 'cross-root.txt');
436 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-'));
437 const userFolder = path.join(userFolderBase, 'alice');
438
439 mockPaths = [rootDir];
440 mockUserPath = userFolderBase;
441 mockUser = {
442 username: 'alice',
443 isAdmin: false,
444 permissions: {
445 [path.basename(rootDir)]: { read: true, write: true },
446 },
447 };
448
449 fs.writeFileSync(sourceFile, 'hello');
450 fs.mkdirSync(userFolder, { recursive: true });
451
452 const originalRenameSync = fs.renameSync;
453 fs.renameSync = (from, to) =>
454 {
455 const err = new Error('cross-device move');
456 err.code = 'EXDEV';
457 throw err;
458 };
459
460 try
461 {
462 const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder });
463
464 expect(status).toBe(200);
465 expect(body.path).toBe(path.join(userFolder, 'cross-root.txt'));
466 expect(fs.existsSync(sourceFile)).toBe(false);
467 expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello');
468 } finally
469 {
470 fs.renameSync = originalRenameSync;
471 fs.rmSync(userFolderBase, { recursive: true, force: true });
472 }
473 });
474});
475
476describe('root alias endpoints', () =>
477{
478 test('GET /api/files/roots returns alias label and original name', async () =>
479 {
480 mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' };
481
482 const { status, body } = await req('GET', '/api/files/roots');
483
484 expect(status).toBe(200);
485 expect(body.roots).toHaveLength(1);
486 expect(body.roots[0]).toMatchObject({
487 path: rootDir,
488 label: 'Workspace',
489 alias: 'Workspace',
490 originalName: path.basename(rootDir),
491 });
492 });
493
494 test('POST /api/files/root-alias stores alias without renaming filesystem path', async () =>
495 {
496 const originalBase = path.basename(rootDir);
497 const { status, body } = await req('POST', '/api/files/root-alias', {
498 rootPath: rootDir,
499 alias: 'Shared Files',
500 });
501
502 expect(status).toBe(200);
503 expect(body.ok).toBe(true);
504 expect(body.root).toMatchObject({
505 path: rootDir,
506 label: 'Shared Files',
507 alias: 'Shared Files',
508 originalName: originalBase,
509 });
510 expect(fs.existsSync(rootDir)).toBe(true);
511
512 const afterRoots = await req('GET', '/api/files/roots');
513 expect(afterRoots.status).toBe(200);
514 expect(afterRoots.body.roots[0].label).toBe('Shared Files');
515 expect(afterRoots.body.roots[0].originalName).toBe(originalBase);
516 });
517
518 test('POST /api/files/root-alias rejects non-root paths', async () =>
519 {
520 const nested = path.join(rootDir, 'sub');
521 fs.mkdirSync(nested, { recursive: true });
522
523 const { status } = await req('POST', '/api/files/root-alias', {
524 rootPath: nested,
525 alias: 'Nested',
526 });
527
528 expect(status).toBe(400);
529 });
530});
531
532describe('GET /api/files/thumbnail', () =>
533{
534 test('returns 404 while cached thumbnail is not ready', async () =>
535 {
536 const source = path.join(rootDir, 'photo.jpg');
537 fs.writeFileSync(source, 'not-an-image');
538
539 const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
540 expect(status).toBe(404);
541 expect(body.error).toMatch(/not ready/i);
542 });
543
544 test('serves cached thumbnail file when available', async () =>
545 {
546 const source = path.join(rootDir, 'photo.jpg');
547 const thumb = path.join(rootDir, 'photo-thumb.webp');
548 fs.writeFileSync(source, 'not-an-image');
549 fs.writeFileSync(thumb, 'webp-bytes');
550 mockThumbPath = thumb;
551
552 const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`);
553 expect(response.status).toBe(200);
554 expect(String(response.headers['content-type'] || '')).toContain('image/webp');
555 expect(response.body.toString('utf8')).toBe('webp-bytes');
556 });
557});
558
559describe('GET /api/files/root-access', () =>
560{
561 test('returns users with R/R+W modes for an exact root path', async () =>
562 {
563 const label = path.basename(rootDir);
564 const db = getDb();
565 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
566 .run(['admin', 'x', 1, '{}']);
567 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
568 .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]);
569 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
570 .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]);
571 db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)')
572 .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]);
573
574 const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`);
575 expect(status).toBe(200);
576 expect(body.root).toMatchObject({ path: rootDir, originalName: label });
577 expect(body.users).toEqual([
578 { username: 'admin', mode: 'R+W' },
579 { username: 'bob', mode: 'R+W' },
580 { username: 'alice', mode: 'R' },
581 ]);
582 });
583
584 test('rejects non-exact nested root paths', async () =>
585 {
586 const nested = path.join(rootDir, 'sub');
587 fs.mkdirSync(nested, { recursive: true });
588
589 const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`);
590 expect(status).toBe(400);
591 });
592});
593
594describe('folder icon endpoints', () =>
595{
596 test('GET /api/files/folder-images returns files that have cached thumbnails', async () =>
597 {
598 const subDir = path.join(rootDir, 'photos');
599 fs.mkdirSync(subDir);
600 const imgPath = path.join(subDir, 'a.jpg');
601 fs.writeFileSync(imgPath, 'img');
602
603 mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }];
604
605 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
606 expect(status).toBe(200);
607 expect(body.images).toHaveLength(1);
608 expect(body.images[0].filePath).toBe(imgPath);
609 });
610
611 test('GET /api/files/folder-images includes video files with cached thumbnails', async () =>
612 {
613 const videoPath = path.join(rootDir, 'photos', 'clip.mp4');
614 fs.mkdirSync(path.dirname(videoPath), { recursive: true });
615 fs.writeFileSync(videoPath, 'video');
616
617 mockFolderImages = [{ filePath: videoPath, thumbRelPath: 'thumbs/clip.mp4.webp' }];
618
619 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
620 expect(status).toBe(200);
621 expect(body.images).toEqual([{ filePath: videoPath }]);
622 });
623
624 test('GET /api/files/folder-images returns empty list when no thumbnails available', async () =>
625 {
626 mockFolderImages = [];
627
628 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
629 expect(status).toBe(200);
630 expect(body.images).toEqual([]);
631 });
632
633 test('GET /api/files/folder-icon returns null when no icon available', async () =>
634 {
635 mockFolderIconFile = null;
636
637 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
638 expect(status).toBe(200);
639 expect(body.icon).toBeNull();
640 });
641
642 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
643 {
644 const imgPath = path.join(rootDir, 'cover.jpg');
645 fs.writeFileSync(imgPath, 'img');
646 mockFolderIconFile = imgPath;
647
648 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
649 expect(status).toBe(200);
650 expect(body.icon).toMatchObject({ filePath: imgPath });
651 });
652
653 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
654 {
655 const imgPath = path.join(rootDir, 'cover.jpg');
656 const thumbFile = path.join(rootDir, 'cover.webp');
657 fs.writeFileSync(imgPath, 'img');
658 fs.writeFileSync(thumbFile, 'webp');
659 mockThumbPath = thumbFile;
660
661 const { status, body } = await req('POST', '/api/files/folder-icon', {
662 folderPath: rootDir,
663 imagePath: imgPath,
664 });
665 expect(status).toBe(200);
666 expect(body.ok).toBe(true);
667 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
668 });
669
670 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
671 {
672 const imgPath = path.join(rootDir, 'missing.jpg');
673 fs.writeFileSync(imgPath, 'img');
674 mockThumbPath = null;
675
676 const { status, body } = await req('POST', '/api/files/folder-icon', {
677 folderPath: rootDir,
678 imagePath: imgPath,
679 });
680 expect(status).toBe(404);
681 expect(body.error).toMatch(/thumbnail not ready/i);
682 });
683
684 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
685 {
686 const { status, body } = await req('POST', '/api/files/folder-icon', {
687 folderPath: rootDir,
688 imagePath: null,
689 });
690 expect(status).toBe(200);
691 expect(body.ok).toBe(true);
692 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
693 });
694
695 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
696 {
697 const label = path.basename(rootDir);
698 mockUser = {
699 username: 'reader',
700 isAdmin: false,
701 permissions: { [label]: { read: true, write: false } },
702 };
703
704 const imgPath = path.join(rootDir, 'photo.jpg');
705 fs.writeFileSync(imgPath, 'img');
706
707 const { status } = await req('POST', '/api/files/folder-icon', {
708 folderPath: rootDir,
709 imagePath: imgPath,
710 });
711 expect(status).toBe(403);
712 });
713});
714
715// ---------------------------------------------------------------------------
716// GET /api/files/download-zip
717// ---------------------------------------------------------------------------
718describe('GET /api/files/download-zip', () =>
719{
720 beforeEach(() =>
721 {
722 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
723 });
724
725 test('streams a valid zip for an accessible directory', async () =>
726 {
727 const subDir = path.join(rootDir, 'zipme');
728 fs.mkdirSync(subDir);
729 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
730
731 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
732 expect(status).toBe(200);
733
734 const ct = headers['content-type'] || '';
735 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
736
737 // ZIP magic bytes PK\x03\x04
738 expect(buf[0]).toBe(0x50);
739 expect(buf[1]).toBe(0x4b);
740 }, 20000);
741
742 test('returns 400 when dir param is missing', async () =>
743 {
744 const { status } = await req('GET', '/api/files/download-zip');
745 expect(status).toBe(400);
746 });
747
748 test('returns 404 for a non-existent directory', async () =>
749 {
750 const missing = path.join(rootDir, 'ghost');
751 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
752 expect(status).toBe(404);
753 });
754
755 test('returns 403 for path outside configured roots', async () =>
756 {
757 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
758 expect(status).toBe(403);
759 });
760});
761
762describe('video streaming routes', () =>
763{
764 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
765 {
766 const filePath = path.join(rootDir, 'clip.mkv');
767 fs.writeFileSync(filePath, 'video');
768 mockVideoStreamSession = {
769 sessionId: 'sess-123',
770 durationSeconds: 42.25,
771 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
772 };
773
774 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
775
776 expect(status).toBe(200);
777 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
778 expect(body.durationSeconds).toBe(42.25);
779 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, imageBased: 0, skipped: 0 });
780 expect(body.subtitleTracks).toEqual([
781 {
782 label: 'English',
783 language: 'eng',
784 default: true,
785 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
786 },
787 ]);
788 });
789
790 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
791 {
792 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
793 {
794 res.type('text/vtt').send('WEBVTT\n');
795 };
796
797 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
798
799 expect(status).toBe(200);
800 expect(headers['content-type']).toMatch(/text\/vtt/);
801 expect(body.toString()).toBe('WEBVTT\n');
802 });
803
804 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
805 {
806 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
807
808 expect(status).toBe(200);
809 expect(body).toEqual({ ok: true });
810 expect(releasedVideoStreamSessionId).toBe('sess-123');
811 });
812
813 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
814 {
815 const filePath = path.join(rootDir, 'clip.mkv');
816 fs.writeFileSync(filePath, 'video');
817
818 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
819 expect(result.status).toBe(200);
820 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
821
822 // A lower progress update should not downgrade the status.
823 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
824 expect(result.status).toBe(200);
825 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
826
827 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
828 expect(result.status).toBe(200);
829 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
830
831 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
832 expect(result.status).toBe(200);
833 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
834
835 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
836 expect(result.status).toBe(200);
837 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
838 });
839
840 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
841 {
842 const clipA = path.join(rootDir, 'clip-a.mkv');
843 const clipB = path.join(rootDir, 'clip-b.mkv');
844 const clipC = path.join(rootDir, 'clip-c.mkv');
845 fs.writeFileSync(clipA, 'a');
846 fs.writeFileSync(clipB, 'b');
847 fs.writeFileSync(clipC, 'c');
848
849 const db = getDb();
850 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
851 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
852 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
853 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
854 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
855 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
856
857 const { status, body } = await req('POST', '/api/files/watched-statuses', {
858 filePaths: [clipA, clipB, clipC],
859 });
860
861 expect(status).toBe(200);
862 expect(body.statuses).toEqual({
863 [clipA]: 'fully',
864 [clipB]: 'partway',
865 });
866 });
867
868 test('POST /api/files/watched-statuses validates filePaths input', async () =>
869 {
870 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
871 expect(status).toBe(400);
872 expect(body.error).toMatch(/filePaths array is required/i);
873 });
874});
875
876describe('SHA-256 hashing and duplicate detection', () =>
877{
878 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
879 {
880 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
881 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
882 ]);
883 expect(status).toBe(200);
884
885 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
886 .get([path.join(rootDir, 'hashme.txt')]);
887 expect(meta).toBeTruthy();
888 // SHA-256 is a 64-char hex string.
889 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
890 });
891
892 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
893 {
894 const filePath = path.join(rootDir, 'lazy.txt');
895 fs.writeFileSync(filePath, 'lazy content');
896
897 // Insert a row without a hash to simulate a pre-existing file.
898 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
899 .run([filePath, 'admin', '[]']);
900
901 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
902 expect(status).toBe(200);
903 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
904
905 // Verify it was persisted.
906 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
907 expect(row.sha256).toBe(body.sha256);
908 });
909
910 test('GET /api/files/duplicates returns other files with the same hash', async () =>
911 {
912 const content = 'duplicate content';
913 const fileA = path.join(rootDir, 'dup-a.txt');
914 const fileB = path.join(rootDir, 'dup-b.txt');
915 fs.writeFileSync(fileA, content);
916 fs.writeFileSync(fileB, content);
917
918 // Compute the expected hash.
919 const crypto = require('crypto');
920 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
921
922 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
923 .run([fileA, 'admin', '[]', expectedHash]);
924 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
925 .run([fileB, 'admin', '[]', expectedHash]);
926
927 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
928 expect(status).toBe(200);
929 expect(body.duplicates).toHaveLength(1);
930 expect(body.duplicates[0].path).toBe(fileB);
931 expect(body.duplicates[0].name).toBe('dup-b.txt');
932 });
933
934 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
935 {
936 const filePath = path.join(rootDir, 'nohash.txt');
937 fs.writeFileSync(filePath, 'no hash yet');
938
939 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
940 .run([filePath, 'admin', '[]']);
941
942 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
943 expect(status).toBe(200);
944 expect(body.duplicates).toEqual([]);
945 });
946
947 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
948 {
949 const content = 'secret dupe';
950 const accessible = path.join(rootDir, 'visible.txt');
951 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
952 fs.writeFileSync(accessible, content);
953
954 const crypto = require('crypto');
955 const hash = crypto.createHash('sha256').update(content).digest('hex');
956
957 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
958 .run([accessible, 'admin', '[]', hash]);
959 // Insert a row for a path that is NOT inside any configured root.
960 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
961 .run([outsideRoot, 'admin', '[]', hash]);
962
963 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
964 expect(status).toBe(200);
965 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
966 });
967
968 test('POST /api/files/move preserves sha256 after rename', async () =>
969 {
970 const from = path.join(rootDir, 'withHash.txt');
971 const toDir = path.join(rootDir, 'subfolder');
972 fs.writeFileSync(from, 'content');
973 fs.mkdirSync(toDir);
974
975 const hash = 'a'.repeat(64);
976 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
977 .run([from, 'admin', '[]', hash]);
978
979 const { status } = await req('POST', '/api/files/move', { from, toDir });
980 expect(status).toBe(200);
981
982 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
983 .get([path.join(toDir, 'withHash.txt')]);
984 expect(meta.sha256).toBe(hash);
985 });
986});