BlueGit

timfa filemanager

Files

filemanager / tests / files.routes.test.js

files.routes.test.js

70917e69 History
files.routes.test.js 35.6 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const fs = require('fs');
5const http = require('http');
6const os = require('os');
7const path = require('path');
8const { once } = require('events');
9
10let mockPaths = [];
11let mockUserPath = null;
12let mockRootAliases = {};
13let 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 getImagesWithThumbnailsInDir: 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 images 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 returns empty list when no thumbnails available', async () =>
612 {
613 mockFolderImages = [];
614
615 const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`);
616 expect(status).toBe(200);
617 expect(body.images).toEqual([]);
618 });
619
620 test('GET /api/files/folder-icon returns null when no icon available', async () =>
621 {
622 mockFolderIconFile = null;
623
624 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
625 expect(status).toBe(200);
626 expect(body.icon).toBeNull();
627 });
628
629 test('GET /api/files/folder-icon returns source file path when icon is available', async () =>
630 {
631 const imgPath = path.join(rootDir, 'cover.jpg');
632 fs.writeFileSync(imgPath, 'img');
633 mockFolderIconFile = imgPath;
634
635 const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`);
636 expect(status).toBe(200);
637 expect(body.icon).toMatchObject({ filePath: imgPath });
638 });
639
640 test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () =>
641 {
642 const imgPath = path.join(rootDir, 'cover.jpg');
643 const thumbFile = path.join(rootDir, 'cover.webp');
644 fs.writeFileSync(imgPath, 'img');
645 fs.writeFileSync(thumbFile, 'webp');
646 mockThumbPath = thumbFile;
647
648 const { status, body } = await req('POST', '/api/files/folder-icon', {
649 folderPath: rootDir,
650 imagePath: imgPath,
651 });
652 expect(status).toBe(200);
653 expect(body.ok).toBe(true);
654 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath });
655 });
656
657 test('POST /api/files/folder-icon rejects image without cached thumbnail', async () =>
658 {
659 const imgPath = path.join(rootDir, 'missing.jpg');
660 fs.writeFileSync(imgPath, 'img');
661 mockThumbPath = null;
662
663 const { status, body } = await req('POST', '/api/files/folder-icon', {
664 folderPath: rootDir,
665 imagePath: imgPath,
666 });
667 expect(status).toBe(404);
668 expect(body.error).toMatch(/thumbnail not ready/i);
669 });
670
671 test('POST /api/files/folder-icon clears assignment when imagePath is null', async () =>
672 {
673 const { status, body } = await req('POST', '/api/files/folder-icon', {
674 folderPath: rootDir,
675 imagePath: null,
676 });
677 expect(status).toBe(200);
678 expect(body.ok).toBe(true);
679 expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null });
680 });
681
682 test('POST /api/files/folder-icon returns 403 for read-only user', async () =>
683 {
684 const label = path.basename(rootDir);
685 mockUser = {
686 username: 'reader',
687 isAdmin: false,
688 permissions: { [label]: { read: true, write: false } },
689 };
690
691 const imgPath = path.join(rootDir, 'photo.jpg');
692 fs.writeFileSync(imgPath, 'img');
693
694 const { status } = await req('POST', '/api/files/folder-icon', {
695 folderPath: rootDir,
696 imagePath: imgPath,
697 });
698 expect(status).toBe(403);
699 });
700});
701
702// ---------------------------------------------------------------------------
703// GET /api/files/download-zip
704// ---------------------------------------------------------------------------
705describe('GET /api/files/download-zip', () =>
706{
707 beforeEach(() =>
708 {
709 mockUser = { username: 'admin', isAdmin: true, permissions: {} };
710 });
711
712 test('streams a valid zip for an accessible directory', async () =>
713 {
714 const subDir = path.join(rootDir, 'zipme');
715 fs.mkdirSync(subDir);
716 fs.writeFileSync(path.join(subDir, 'file.txt'), 'content');
717
718 const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`);
719 expect(status).toBe(200);
720
721 const ct = headers['content-type'] || '';
722 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
723
724 // ZIP magic bytes PK\x03\x04
725 expect(buf[0]).toBe(0x50);
726 expect(buf[1]).toBe(0x4b);
727 }, 20000);
728
729 test('returns 400 when dir param is missing', async () =>
730 {
731 const { status } = await req('GET', '/api/files/download-zip');
732 expect(status).toBe(400);
733 });
734
735 test('returns 404 for a non-existent directory', async () =>
736 {
737 const missing = path.join(rootDir, 'ghost');
738 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`);
739 expect(status).toBe(404);
740 });
741
742 test('returns 403 for path outside configured roots', async () =>
743 {
744 const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`);
745 expect(status).toBe(403);
746 });
747});
748
749describe('video streaming routes', () =>
750{
751 test('POST /api/files/video-stream creates a short-lived playlist session', async () =>
752 {
753 const filePath = path.join(rootDir, 'clip.mkv');
754 fs.writeFileSync(filePath, 'video');
755 mockVideoStreamSession = {
756 sessionId: 'sess-123',
757 durationSeconds: 42.25,
758 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
759 };
760
761 const { status, body } = await req('POST', '/api/files/video-stream', { filePath });
762
763 expect(status).toBe(200);
764 expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8');
765 expect(body.durationSeconds).toBe(42.25);
766 expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 });
767 expect(body.subtitleTracks).toEqual([
768 {
769 label: 'English',
770 language: 'eng',
771 default: true,
772 src: '/api/files/video-stream/sess-123/subtitle-0.vtt',
773 },
774 ]);
775 });
776
777 test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () =>
778 {
779 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
780 {
781 res.type('text/vtt').send('WEBVTT\n');
782 };
783
784 const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt');
785
786 expect(status).toBe(200);
787 expect(headers['content-type']).toMatch(/text\/vtt/);
788 expect(body.toString()).toBe('WEBVTT\n');
789 });
790
791 test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () =>
792 {
793 const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123');
794
795 expect(status).toBe(200);
796 expect(body).toEqual({ ok: true });
797 expect(releasedVideoStreamSessionId).toBe('sess-123');
798 });
799
800 test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () =>
801 {
802 const filePath = path.join(rootDir, 'clip.mkv');
803 fs.writeFileSync(filePath, 'video');
804
805 let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 });
806 expect(result.status).toBe(200);
807 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' });
808
809 // A lower progress update should not downgrade the status.
810 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 });
811 expect(result.status).toBe(200);
812 expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' });
813
814 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
815 expect(result.status).toBe(200);
816 expect(result.body.watchedBy).toEqual({ admin: 'partway' });
817
818 result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 });
819 expect(result.status).toBe(200);
820 expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' });
821
822 result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
823 expect(result.status).toBe(200);
824 expect(result.body.watchedBy).toEqual({ admin: 'fully' });
825 });
826
827 test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () =>
828 {
829 const clipA = path.join(rootDir, 'clip-a.mkv');
830 const clipB = path.join(rootDir, 'clip-b.mkv');
831 const clipC = path.join(rootDir, 'clip-c.mkv');
832 fs.writeFileSync(clipA, 'a');
833 fs.writeFileSync(clipB, 'b');
834 fs.writeFileSync(clipC, 'c');
835
836 const db = getDb();
837 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
838 .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]);
839 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
840 .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]);
841 db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)')
842 .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]);
843
844 const { status, body } = await req('POST', '/api/files/watched-statuses', {
845 filePaths: [clipA, clipB, clipC],
846 });
847
848 expect(status).toBe(200);
849 expect(body.statuses).toEqual({
850 [clipA]: 'fully',
851 [clipB]: 'partway',
852 });
853 });
854
855 test('POST /api/files/watched-statuses validates filePaths input', async () =>
856 {
857 const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' });
858 expect(status).toBe(400);
859 expect(body.error).toMatch(/filePaths array is required/i);
860 });
861});
862
863describe('SHA-256 hashing and duplicate detection', () =>
864{
865 test('POST /api/files/upload stores sha256 hash for uploaded files', async () =>
866 {
867 const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [
868 { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' },
869 ]);
870 expect(status).toBe(200);
871
872 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
873 .get([path.join(rootDir, 'hashme.txt')]);
874 expect(meta).toBeTruthy();
875 // SHA-256 is a 64-char hex string.
876 expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/);
877 });
878
879 test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () =>
880 {
881 const filePath = path.join(rootDir, 'lazy.txt');
882 fs.writeFileSync(filePath, 'lazy content');
883
884 // Insert a row without a hash to simulate a pre-existing file.
885 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
886 .run([filePath, 'admin', '[]']);
887
888 const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`);
889 expect(status).toBe(200);
890 expect(body.sha256).toMatch(/^[0-9a-f]{64}$/);
891
892 // Verify it was persisted.
893 const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]);
894 expect(row.sha256).toBe(body.sha256);
895 });
896
897 test('GET /api/files/duplicates returns other files with the same hash', async () =>
898 {
899 const content = 'duplicate content';
900 const fileA = path.join(rootDir, 'dup-a.txt');
901 const fileB = path.join(rootDir, 'dup-b.txt');
902 fs.writeFileSync(fileA, content);
903 fs.writeFileSync(fileB, content);
904
905 // Compute the expected hash.
906 const crypto = require('crypto');
907 const expectedHash = crypto.createHash('sha256').update(content).digest('hex');
908
909 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
910 .run([fileA, 'admin', '[]', expectedHash]);
911 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
912 .run([fileB, 'admin', '[]', expectedHash]);
913
914 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`);
915 expect(status).toBe(200);
916 expect(body.duplicates).toHaveLength(1);
917 expect(body.duplicates[0].path).toBe(fileB);
918 expect(body.duplicates[0].name).toBe('dup-b.txt');
919 });
920
921 test('GET /api/files/duplicates returns empty list when no hash is stored', async () =>
922 {
923 const filePath = path.join(rootDir, 'nohash.txt');
924 fs.writeFileSync(filePath, 'no hash yet');
925
926 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)')
927 .run([filePath, 'admin', '[]']);
928
929 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`);
930 expect(status).toBe(200);
931 expect(body.duplicates).toEqual([]);
932 });
933
934 test('GET /api/files/duplicates excludes files outside accessible roots', async () =>
935 {
936 const content = 'secret dupe';
937 const accessible = path.join(rootDir, 'visible.txt');
938 const outsideRoot = path.join(os.tmpdir(), 'outside.txt');
939 fs.writeFileSync(accessible, content);
940
941 const crypto = require('crypto');
942 const hash = crypto.createHash('sha256').update(content).digest('hex');
943
944 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
945 .run([accessible, 'admin', '[]', hash]);
946 // Insert a row for a path that is NOT inside any configured root.
947 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
948 .run([outsideRoot, 'admin', '[]', hash]);
949
950 const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`);
951 expect(status).toBe(200);
952 expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true);
953 });
954
955 test('POST /api/files/move preserves sha256 after rename', async () =>
956 {
957 const from = path.join(rootDir, 'withHash.txt');
958 const toDir = path.join(rootDir, 'subfolder');
959 fs.writeFileSync(from, 'content');
960 fs.mkdirSync(toDir);
961
962 const hash = 'a'.repeat(64);
963 getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)')
964 .run([from, 'admin', '[]', hash]);
965
966 const { status } = await req('POST', '/api/files/move', { from, toDir });
967 expect(status).toBe(200);
968
969 const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?')
970 .get([path.join(toDir, 'withHash.txt')]);
971 expect(meta.sha256).toBe(hash);
972 });
973});