BlueGit

timfa filemanager

Files

filemanager / tests / share.routes.test.js

share.routes.test.js

Add subtitle runtime logging
timfa Tim Falken · pushed by timfa · 5 months ago
b5c1f94d History
share.routes.test.js 21.4 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 mockUser = { username: 'testuser', isAdmin: true, permissions: {} };
13let mockVideoStreamSession = null;
14let mockVideoStreamAsset = null;
15let releasedVideoStreamSessionId = null;
16let mockSubtitleFrameResult = null;
17let mockSubtitleFrameError = null;
18
19jest.mock('../server/db', () =>
20{
21 const { Database } = require('node-sqlite3-wasm');
22 let db;
23 function getDb ()
24 {
25 if (!db)
26 {
27 db = new Database(':memory:');
28 db.exec(`
29 CREATE TABLE IF NOT EXISTS share_tokens (
30 token TEXT PRIMARY KEY,
31 file_path TEXT NOT NULL,
32 is_dir INTEGER NOT NULL DEFAULT 0,
33 created_by TEXT NOT NULL,
34 created_at INTEGER NOT NULL,
35 expires_at INTEGER NOT NULL
36 );
37 `);
38 }
39 return db;
40 }
41 return { getDb, initDb: getDb };
42});
43
44jest.mock('../server/config', () => ({
45 loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: {} }),
46 saveConfig: jest.fn(),
47 getEffectivePaths: (paths) => paths,
48 getAllowedRoot: (targetPath, roots) =>
49 {
50 const pathMod = require('path');
51 const absTarget = pathMod.resolve(String(targetPath || ''));
52 return roots.find((root) =>
53 {
54 const absRoot = pathMod.resolve(root);
55 return absTarget === absRoot || absTarget.startsWith(absRoot + pathMod.sep);
56 }) || null;
57 },
58}));
59
60jest.mock('../server/auth', () => ({
61 requireAuth: (req, res, next) => { req.user = mockUser; next(); },
62}));
63
64jest.mock('../server/video-stream', () => ({
65 createVideoStreamSession: jest.fn(async () =>
66 {
67 if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession;
68 return mockVideoStreamSession || { sessionId: 'share-video-session', subtitleTracks: [] };
69 }),
70 sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) =>
71 {
72 if (typeof mockVideoStreamAsset === 'function')
73 {
74 await mockVideoStreamAsset(sessionId, assetPath, req, res);
75 return;
76 }
77 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
78 }),
79 releaseVideoStreamSession: jest.fn((sessionId) =>
80 {
81 releasedVideoStreamSessionId = sessionId;
82 }),
83}));
84
85jest.mock('../server/image-subtitles', () => ({
86 renderImageSubtitleFrame: jest.fn(async () =>
87 {
88 if (mockSubtitleFrameError) throw mockSubtitleFrameError;
89 return mockSubtitleFrameResult;
90 }),
91}));
92
93jest.mock('../server/logger', () => ({
94 logError: jest.fn(),
95}));
96
97jest.mock('../server/subtitle-debug-log', () => ({
98 appendSubtitleDebugEntries: jest.fn(),
99}));
100
101const shareRoutes = require('../server/routes/share');
102const { getDb } = require('../server/db');
103
104let server;
105let baseUrl;
106let rootDir;
107
108function get (p) { return fetch(baseUrl + p); }
109function post (p, body)
110{
111 return fetch(baseUrl + p, {
112 method: 'POST',
113 headers: { 'Content-Type': 'application/json' },
114 body: JSON.stringify(body),
115 });
116}
117
118beforeAll(async () =>
119{
120 rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-test-'));
121 mockPaths = [rootDir];
122
123 const app = express();
124 app.use(express.json());
125 app.use('/api/share', shareRoutes);
126 app.use((err, req, res, _next) =>
127 {
128 res.status(err.status || 500).json({ error: err.message || 'Internal error' });
129 });
130
131 server = http.createServer(app);
132 server.listen(0);
133 await once(server, 'listening');
134 baseUrl = `http://127.0.0.1:${server.address().port}`;
135});
136
137afterAll(() =>
138{
139 server.close();
140 fs.rmSync(rootDir, { recursive: true, force: true });
141});
142
143beforeEach(() =>
144{
145 fs.rmSync(rootDir, { recursive: true, force: true });
146 fs.mkdirSync(rootDir, { recursive: true });
147 if (mockUserPath)
148 {
149 fs.rmSync(mockUserPath, { recursive: true, force: true });
150 fs.mkdirSync(mockUserPath, { recursive: true });
151 }
152 mockUserPath = null;
153 mockVideoStreamSession = null;
154 mockVideoStreamAsset = null;
155 releasedVideoStreamSessionId = null;
156 mockSubtitleFrameResult = null;
157 mockSubtitleFrameError = null;
158 // Reset DB between tests
159 const db = getDb();
160 db.exec('DELETE FROM share_tokens');
161});
162
163// ---------------------------------------------------------------------------
164// POST /api/share/create
165// ---------------------------------------------------------------------------
166describe('POST /api/share/create', () =>
167{
168 test('creates a token for a file', async () =>
169 {
170 const filePath = path.join(rootDir, 'hello.txt');
171 fs.writeFileSync(filePath, 'hello');
172
173 const res = await post('/api/share/create', { filePath });
174 expect(res.status).toBe(200);
175 const body = await res.json();
176 expect(typeof body.token).toBe('string');
177 expect(body.token).toHaveLength(64); // 32 bytes hex
178 expect(typeof body.expiresAt).toBe('number');
179 expect(body.expiresAt).toBeGreaterThan(Date.now());
180 });
181
182 test('creates a token for a directory', async () =>
183 {
184 const dirPath = path.join(rootDir, 'subdir');
185 fs.mkdirSync(dirPath);
186
187 const res = await post('/api/share/create', { filePath: dirPath });
188 expect(res.status).toBe(200);
189 const body = await res.json();
190 expect(typeof body.token).toBe('string');
191 });
192
193 test('returns 400 when filePath is missing', async () =>
194 {
195 const res = await post('/api/share/create', {});
196 expect(res.status).toBe(400);
197 });
198
199 test('returns 403 when path is outside configured roots', async () =>
200 {
201 const res = await post('/api/share/create', { filePath: os.tmpdir() });
202 expect(res.status).toBe(403);
203 });
204
205 test('returns 404 when file does not exist', async () =>
206 {
207 const res = await post('/api/share/create', { filePath: path.join(rootDir, 'missing.txt') });
208 expect(res.status).toBe(404);
209 });
210
211 test('creates a token for a file inside My Folder', async () =>
212 {
213 const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-share-userfolders-'));
214 const userFolder = path.join(userFolderBase, 'testuser');
215 const filePath = path.join(userFolder, 'private.txt');
216
217 mockUserPath = userFolderBase;
218 mockUser = { username: 'testuser', isAdmin: false, permissions: {} };
219 fs.mkdirSync(userFolder, { recursive: true });
220 fs.writeFileSync(filePath, 'private');
221
222 try
223 {
224 const res = await post('/api/share/create', { filePath });
225 expect(res.status).toBe(200);
226 const body = await res.json();
227 expect(typeof body.token).toBe('string');
228 } finally
229 {
230 fs.rmSync(userFolderBase, { recursive: true, force: true });
231 }
232 });
233});
234
235// ---------------------------------------------------------------------------
236// GET /api/share/info/:token
237// ---------------------------------------------------------------------------
238describe('GET /api/share/info/:token', () =>
239{
240 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
241 {
242 getDb().prepare(
243 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
244 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
245 }
246
247 test('returns file info for a valid token', async () =>
248 {
249 const filePath = path.join(rootDir, 'info.txt');
250 fs.writeFileSync(filePath, 'data');
251 insertToken({ token: 'aaaa', filePath });
252
253 const res = await get('/api/share/info/aaaa');
254 expect(res.status).toBe(200);
255 const body = await res.json();
256 expect(body.name).toBe('info.txt');
257 expect(body.isDir).toBe(false);
258 expect(typeof body.expiresAt).toBe('number');
259 });
260
261 test('returns isDir=true for directory tokens', async () =>
262 {
263 const dirPath = path.join(rootDir, 'mydir');
264 fs.mkdirSync(dirPath);
265 insertToken({ token: 'bbbb', filePath: dirPath, isDir: 1 });
266
267 const res = await get('/api/share/info/bbbb');
268 expect(res.status).toBe(200);
269 const body = await res.json();
270 expect(body.isDir).toBe(true);
271 });
272
273 test('returns 404 for unknown token', async () =>
274 {
275 const res = await get('/api/share/info/unknowntoken');
276 expect(res.status).toBe(404);
277 });
278
279 test('returns 410 for expired token', async () =>
280 {
281 const filePath = path.join(rootDir, 'exp.txt');
282 fs.writeFileSync(filePath, 'x');
283 insertToken({ token: 'cccc', filePath, expiresAt: Date.now() - 1000 });
284
285 const res = await get('/api/share/info/cccc');
286 expect(res.status).toBe(410);
287 });
288});
289
290// ---------------------------------------------------------------------------
291// GET /api/share/preview/:token
292// ---------------------------------------------------------------------------
293describe('GET /api/share/preview/:token', () =>
294{
295 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
296 {
297 getDb().prepare(
298 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
299 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
300 }
301
302 test('streams file content for a valid file token', async () =>
303 {
304 const filePath = path.join(rootDir, 'preview.txt');
305 fs.writeFileSync(filePath, 'preview content');
306 insertToken({ token: 'prev1', filePath });
307
308 const res = await get('/api/share/preview/prev1');
309 expect(res.status).toBe(200);
310 const text = await res.text();
311 expect(text).toBe('preview content');
312 });
313
314 test('returns 400 when token points to a directory', async () =>
315 {
316 const dirPath = path.join(rootDir, 'previewdir');
317 fs.mkdirSync(dirPath);
318 insertToken({ token: 'prev2', filePath: dirPath, isDir: 1 });
319
320 const res = await get('/api/share/preview/prev2');
321 expect(res.status).toBe(400);
322 });
323
324 test('returns 410 for expired token', async () =>
325 {
326 const filePath = path.join(rootDir, 'ep.txt');
327 fs.writeFileSync(filePath, 'x');
328 insertToken({ token: 'prev3', filePath, expiresAt: Date.now() - 1 });
329
330 const res = await get('/api/share/preview/prev3');
331 expect(res.status).toBe(410);
332 });
333});
334
335describe('GET /api/share/video-stream/:token', () =>
336{
337 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
338 {
339 getDb().prepare(
340 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
341 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
342 }
343
344 test('creates a stream session for a shared video', async () =>
345 {
346 const filePath = path.join(rootDir, 'movie.mkv');
347 fs.writeFileSync(filePath, 'video');
348 insertToken({ token: 'stream1', filePath });
349 mockVideoStreamSession = {
350 sessionId: 'share-sess-1',
351 durationSeconds: 42.25,
352 subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }],
353 };
354
355 const res = await get('/api/share/video-stream/stream1');
356 expect(res.status).toBe(200);
357 const body = await res.json();
358 expect(body.playlistUrl).toBe('/api/share/video-stream/session/share-sess-1/master.m3u8');
359 expect(body.durationSeconds).toBe(42.25);
360 expect(body.subtitleTracks).toEqual([
361 {
362 label: 'English',
363 language: 'eng',
364 default: true,
365 src: '/api/share/video-stream/session/share-sess-1/subtitle-0.vtt',
366 },
367 ]);
368 });
369
370 test('serves stream assets from an existing share session', async () =>
371 {
372 mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) =>
373 {
374 res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n');
375 };
376
377 const res = await get('/api/share/video-stream/session/share-sess-1/master.m3u8');
378 expect(res.status).toBe(200);
379 expect(await res.text()).toBe('#EXTM3U\n');
380 });
381
382 test('releases an existing share stream session', async () =>
383 {
384 const res = await fetch(baseUrl + '/api/share/video-stream/session/share-sess-1', {
385 method: 'DELETE',
386 });
387
388 expect(res.status).toBe(200);
389 expect(await res.json()).toEqual({ ok: true });
390 expect(releasedVideoStreamSessionId).toBe('share-sess-1');
391 });
392
393 test('renders image subtitle frames for a shared video', async () =>
394 {
395 const filePath = path.join(rootDir, 'movie-subs.mkv');
396 fs.writeFileSync(filePath, 'video');
397 insertToken({ token: 'stream-subs', filePath });
398 mockSubtitleFrameResult = {
399 frame: Buffer.from('png-data'),
400 left: 100,
401 top: 50,
402 width: 320,
403 height: 180,
404 canvasWidth: 640,
405 canvasHeight: 360,
406 startTimeSeconds: 1.5,
407 endTimeSeconds: 3.2,
408 };
409
410 const res = await get('/api/share/video-stream-subtitle-frame/stream-subs?streamIndex=0&timeSeconds=2.5&videoWidth=1920&videoHeight=1080');
411
412 expect(res.status).toBe(200);
413 expect(res.headers.get('content-type')).toMatch(/image\/png/);
414 expect(res.headers.get('x-subtitle-frame-status')).toBe('ok');
415 expect(res.headers.get('x-subtitle-frame-left')).toBe('100');
416 expect(res.headers.get('x-subtitle-frame-top')).toBe('50');
417 expect(res.headers.get('x-subtitle-frame-width')).toBe('320');
418 expect(res.headers.get('x-subtitle-frame-height')).toBe('180');
419 expect(res.headers.get('x-subtitle-frame-canvas-width')).toBe('640');
420 expect(res.headers.get('x-subtitle-frame-canvas-height')).toBe('360');
421 expect(res.headers.get('x-subtitle-frame-start-time')).toBe('1.5');
422 expect(res.headers.get('x-subtitle-frame-end-time')).toBe('3.2');
423 expect(Number(res.headers.get('x-subtitle-request-received-at-ms'))).toBeGreaterThan(0);
424 expect(Number(res.headers.get('x-subtitle-response-sent-at-ms'))).toBeGreaterThan(0);
425 expect(Buffer.from(await res.arrayBuffer()).equals(Buffer.from('png-data'))).toBe(true);
426 });
427
428 test('persists subtitle debug batches for shared video playback', async () =>
429 {
430 const filePath = path.join(rootDir, 'movie-subs.mkv');
431 fs.writeFileSync(filePath, 'video');
432 insertToken({ token: 'stream-subs-log', filePath });
433 const { appendSubtitleDebugEntries } = require('../server/subtitle-debug-log');
434
435 const res = await post('/api/share/video-stream-subtitle-log/stream-subs-log', {
436 sessionId: 'share-sess-1',
437 entries: [
438 { loggedAtMs: 1000, eventType: 'subtitle_png_requested' },
439 ],
440 });
441
442 expect(res.status).toBe(200);
443 expect(await res.json()).toEqual({ ok: true });
444 expect(appendSubtitleDebugEntries).toHaveBeenCalledWith(expect.objectContaining({
445 videoName: 'movie-subs.mkv',
446 context: expect.objectContaining({
447 filePath,
448 sessionId: 'share-sess-1',
449 source: 'share',
450 shareToken: 'stream-subs-log',
451 }),
452 }));
453 });
454});
455
456// ---------------------------------------------------------------------------
457// GET /api/share/download/:token
458// ---------------------------------------------------------------------------
459describe('GET /api/share/download/:token', () =>
460{
461 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
462 {
463 getDb().prepare(
464 'INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)',
465 ).run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
466 }
467
468 test('downloads a file', async () =>
469 {
470 const filePath = path.join(rootDir, 'dl.txt');
471 fs.writeFileSync(filePath, 'download me');
472 insertToken({ token: 'dl01', filePath });
473
474 const res = await get('/api/share/download/dl01');
475 expect(res.status).toBe(200);
476 const text = await res.text();
477 expect(text).toBe('download me');
478 });
479
480 test('downloads a directory as zip', async () =>
481 {
482 const dirPath = path.join(rootDir, 'zipit');
483 fs.mkdirSync(dirPath);
484 fs.writeFileSync(path.join(dirPath, 'a.txt'), 'aaa');
485 insertToken({ token: 'dl02', filePath: dirPath, isDir: 1 });
486
487 const res = await get('/api/share/download/dl02');
488 expect(res.status).toBe(200);
489 const ct = res.headers.get('content-type') || '';
490 // Express sends application/zip or application/octet-stream for .zip downloads
491 expect(ct.includes('zip') || ct.includes('octet')).toBe(true);
492 const buf = await res.arrayBuffer();
493 // ZIP magic bytes: PK\x03\x04
494 expect(new Uint8Array(buf.slice(0, 4))).toEqual(new Uint8Array([0x50, 0x4b, 0x03, 0x04]));
495 });
496
497 test('returns 410 for expired token', async () =>
498 {
499 const filePath = path.join(rootDir, 'edl.txt');
500 fs.writeFileSync(filePath, 'x');
501 insertToken({ token: 'dl03', filePath, expiresAt: Date.now() - 1 });
502
503 const res = await get('/api/share/download/dl03');
504 expect(res.status).toBe(410);
505 });
506
507 test('returns 404 for unknown token', async () =>
508 {
509 const res = await get('/api/share/download/nosuchtoken');
510 expect(res.status).toBe(404);
511 });
512});
513
514// ---------------------------------------------------------------------------
515// pruneZipCache
516// ---------------------------------------------------------------------------
517describe('pruneZipCache', () =>
518{
519 test('deletes zip files older than 1 day', () =>
520 {
521 const { pruneZipCache, ZIP_CACHE_DIR } = require('../server/routes/share');
522 fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true });
523
524 const oldZip = path.join(ZIP_CACHE_DIR, 'old.zip');
525 fs.writeFileSync(oldZip, 'fake zip');
526 // Back-date the mtime by 25 hours
527 const pastTime = new Date(Date.now() - 25 * 60 * 60 * 1000);
528 fs.utimesSync(oldZip, pastTime, pastTime);
529
530 const freshZip = path.join(ZIP_CACHE_DIR, 'fresh.zip');
531 fs.writeFileSync(freshZip, 'fake fresh zip');
532
533 pruneZipCache();
534
535 expect(fs.existsSync(oldZip)).toBe(false);
536 expect(fs.existsSync(freshZip)).toBe(true);
537
538 // Cleanup
539 try { fs.unlinkSync(freshZip); } catch { /* ignore */ }
540 });
541});
542
543// ---------------------------------------------------------------------------
544// buildShareOpenGraphPage
545// ---------------------------------------------------------------------------
546describe('buildShareOpenGraphPage', () =>
547{
548 const { buildShareOpenGraphPage } = require('../server/routes/share');
549
550 const mockReq = {
551 protocol: 'https',
552 get: (header) =>
553 {
554 if (header === 'host') return 'example.com';
555 return null;
556 },
557 };
558
559 function insertToken ({ token, filePath, isDir = 0, expiresAt = Date.now() + 86400000 })
560 {
561 getDb()
562 .prepare('INSERT OR REPLACE INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?,?,?,?,?,?)')
563 .run([token, filePath, isDir, 'testuser', Date.now(), expiresAt]);
564 }
565
566 test('returns HTML page containing correct og:title for a valid file token', () =>
567 {
568 insertToken({ token: 'og-valid', filePath: '/data/report.pdf' });
569 const html = buildShareOpenGraphPage('og-valid', mockReq);
570 expect(html).toContain('<meta property="og:title" content="report.pdf"');
571 expect(html).toContain('<title>report.pdf</title>');
572 });
573
574 test('includes og:image and summary_large_image twitter:card for image files', () =>
575 {
576 insertToken({ token: 'og-img', filePath: '/data/photo.jpg' });
577 const html = buildShareOpenGraphPage('og-img', mockReq);
578 expect(html).toContain('property="og:image"');
579 expect(html).toContain('/api/share/preview/og-img');
580 expect(html).toContain('summary_large_image');
581 });
582
583 test('includes og:image for png files', () =>
584 {
585 insertToken({ token: 'og-png', filePath: '/data/banner.png' });
586 const html = buildShareOpenGraphPage('og-png', mockReq);
587 expect(html).toContain('property="og:image"');
588 });
589
590 test('includes og:image for webp files', () =>
591 {
592 insertToken({ token: 'og-webp', filePath: '/data/thumb.webp' });
593 const html = buildShareOpenGraphPage('og-webp', mockReq);
594 expect(html).toContain('property="og:image"');
595 });
596
597 test('does not include og:image for non-image files and uses summary twitter:card', () =>
598 {
599 insertToken({ token: 'og-video', filePath: '/data/movie.mkv' });
600 const html = buildShareOpenGraphPage('og-video', mockReq);
601 expect(html).not.toContain('property="og:image"');
602 expect(html).toContain('content="summary"');
603 });
604
605 test('does not include og:image for directory tokens', () =>
606 {
607 insertToken({ token: 'og-dir', filePath: '/data/photos', isDir: 1 });
608 const html = buildShareOpenGraphPage('og-dir', mockReq);
609 expect(html).not.toContain('property="og:image"');
610 });
611
612 test('returns "Link Expired" in og:title for an expired token', () =>
613 {
614 insertToken({ token: 'og-exp', filePath: '/data/old.jpg', expiresAt: Date.now() - 1000 });
615 const html = buildShareOpenGraphPage('og-exp', mockReq);
616 expect(html).toContain('content="Link Expired"');
617 expect(html).not.toContain('property="og:image"');
618 });
619
620 test('returns "Link Not Found" in og:title for an unknown token', () =>
621 {
622 const html = buildShareOpenGraphPage('does-not-exist', mockReq);
623 expect(html).toContain('content="Link Not Found"');
624 });
625
626 test('includes og:url pointing to the share page', () =>
627 {
628 insertToken({ token: 'og-url', filePath: '/data/file.txt' });
629 const html = buildShareOpenGraphPage('og-url', mockReq);
630 expect(html).toContain('https://example.com/share/og-url');
631 });
632
633 test('og:description mentions validity for a valid token', () =>
634 {
635 insertToken({ token: 'og-desc', filePath: '/data/doc.pdf', expiresAt: Date.now() + 7200000 });
636 const html = buildShareOpenGraphPage('og-desc', mockReq);
637 expect(html).toContain('Valid for');
638 });
639
640 test('retains the full share page client JS (not a bare meta-only response)', () =>
641 {
642 insertToken({ token: 'og-full', filePath: '/data/file.txt' });
643 const html = buildShareOpenGraphPage('og-full', mockReq);
644 // The interactive share page JS should still be present.
645 expect(html).toContain('api/share/info/');
646 });
647});