'use strict'; const express = require('express'); const fs = require('fs'); const http = require('http'); const os = require('os'); const path = require('path'); const { once } = require('events'); let mockPaths = []; let mockUserPath = null; let mockRootAliases = {}; let mockUser = { username: 'admin', isAdmin: true, permissions: {} }; let mockThumbPath = null; let mockFolderImages = []; let mockFolderIconFile = null; let lastFolderIconAssignment = undefined; let mockVideoStreamSession = null; let mockVideoStreamAsset = null; let releasedVideoStreamSessionId = null; jest.mock('../server/db', () => { const { Database } = require('node-sqlite3-wasm'); let db; function getDb () { if (!db) { db = new Database(':memory:'); db.exec(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password_hash TEXT NOT NULL, is_admin INTEGER NOT NULL DEFAULT 0, permissions TEXT NOT NULL DEFAULT '{}' ); CREATE TABLE IF NOT EXISTS file_meta ( file_path TEXT PRIMARY KEY, uploader TEXT NOT NULL DEFAULT '', downloaders TEXT NOT NULL DEFAULT '[]', watched_by TEXT NOT NULL DEFAULT '{}', sha256 TEXT ); CREATE INDEX IF NOT EXISTS idx_file_meta_sha256 ON file_meta(sha256); `); } return db; } return { getDb, initDb: getDb }; }); jest.mock('../server/config', () => ({ loadConfig: () => ({ port: 3000, paths: [...mockPaths], userPath: mockUserPath, rootAliases: { ...mockRootAliases } }), saveConfig: (config) => { mockPaths = [...(config.paths || [])]; mockRootAliases = { ...(config.rootAliases || {}) }; }, getEffectivePaths: (paths) => paths, getAllowedRoot: (targetPath, roots) => { const path = require('path'); const absTarget = path.resolve(String(targetPath || '')); return roots.find((root) => { const absRoot = path.resolve(root); return absTarget === absRoot || absTarget.startsWith(absRoot + path.sep); }) || null; }, })); jest.mock('../server/auth', () => ({ requireAuth: (req, res, next) => { req.user = mockUser; next(); }, })); jest.mock('../server/thumbnail-cache', () => ({ getCachedThumbnailInfo: async () => { if (!mockThumbPath) return null; return { thumbPath: mockThumbPath, contentType: 'image/webp' }; }, getImagesWithThumbnailsInDir: async () => mockFolderImages.slice(), getFolderIconSourceFile: async () => mockFolderIconFile, setFolderIconAssignment: async (folderPath, imagePath) => { lastFolderIconAssignment = { folderPath, imagePath }; }, })); jest.mock('../server/video-stream', () => ({ createVideoStreamSession: jest.fn(async () => { if (mockVideoStreamSession instanceof Error) throw mockVideoStreamSession; return mockVideoStreamSession || { sessionId: 'video-session', subtitleTracks: [] }; }), sendVideoStreamAsset: jest.fn(async (sessionId, assetPath, req, res) => { if (typeof mockVideoStreamAsset === 'function') { await mockVideoStreamAsset(sessionId, assetPath, req, res); return; } res.type('application/vnd.apple.mpegurl').send('#EXTM3U\n'); }), releaseVideoStreamSession: jest.fn((sessionId) => { releasedVideoStreamSessionId = String(sessionId || ''); return true; }), })); const filesRoutes = require('../server/routes/files'); const { getDb } = require('../server/db'); let server; let baseUrl; let rootDir; beforeAll(async () => { rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-files-routes-')); mockPaths = [rootDir]; const app = express(); app.use(express.json()); app.use('/api/files', filesRoutes); app.use((err, req, res, next) => { res.status(err.status || 500).json({ error: err.message || 'Internal error' }); }); server = http.createServer(app); server.listen(0); await once(server, 'listening'); baseUrl = `http://127.0.0.1:${server.address().port}`; }); afterAll(() => { server.close(); fs.rmSync(rootDir, { recursive: true, force: true }); }); beforeEach(() => { fs.rmSync(rootDir, { recursive: true, force: true }); fs.mkdirSync(rootDir, { recursive: true }); if (mockUserPath) { fs.rmSync(mockUserPath, { recursive: true, force: true }); fs.mkdirSync(mockUserPath, { recursive: true }); } mockRootAliases = {}; mockUserPath = null; mockUser = { username: 'admin', isAdmin: true, permissions: {} }; mockThumbPath = null; mockFolderImages = []; mockFolderIconFile = null; lastFolderIconAssignment = undefined; mockVideoStreamSession = null; mockVideoStreamAsset = null; releasedVideoStreamSessionId = null; const db = getDb(); db.prepare('DELETE FROM file_meta').run([]); db.prepare('DELETE FROM users').run([]); }); function req (method, routePath, body) { const payload = body ? JSON.stringify(body) : undefined; return new Promise((resolve, reject) => { const request = http.request(baseUrl + routePath, { method, headers: { 'Content-Type': 'application/json', ...(payload ? { 'Content-Length': Buffer.byteLength(payload) } : {}), }, }, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); }); request.on('error', reject); if (payload) request.write(payload); request.end(); }); } function reqRaw (method, routePath) { return new Promise((resolve, reject) => { const request = http.request(baseUrl + routePath, { method }, res => { const chunks = []; res.on('data', chunk => chunks.push(Buffer.from(chunk))); res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: Buffer.concat(chunks), })); }); request.on('error', reject); request.end(); }); } function reqMultipart (routePath, files, extraHeaders = {}) { const boundary = '----filemanager-test-boundary'; const buffers = []; for (const file of files) { buffers.push(Buffer.from( `--${boundary}\r\n` + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` )); buffers.push(Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content))); buffers.push(Buffer.from('\r\n')); } buffers.push(Buffer.from(`--${boundary}--\r\n`)); const payload = Buffer.concat(buffers); return new Promise((resolve, reject) => { const request = http.request(baseUrl + routePath, { method: 'POST', headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}`, 'Content-Length': payload.length, ...extraHeaders, }, }, res => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); }); request.on('error', reject); request.write(payload); request.end(); }); } function abortMultipartUpload (routePath, file) { const boundary = '----filemanager-test-boundary-abort'; const header = Buffer.from( `--${boundary}\r\n` + `Content-Disposition: form-data; name="files"; filename="${file.name}"\r\n` + `Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n` ); const chunk = Buffer.isBuffer(file.content) ? file.content : Buffer.from(String(file.content)); return new Promise((resolve) => { const request = http.request(baseUrl + routePath, { method: 'POST', headers: { 'Content-Type': `multipart/form-data; boundary=${boundary}`, }, }); let settled = false; const finish = () => { if (settled) return; settled = true; resolve(); }; request.on('error', finish); request.on('close', finish); request.write(header); request.write(chunk); setTimeout(() => request.destroy(), 20); }); } async function waitFor (predicate, timeoutMs = 500) { const start = Date.now(); while (Date.now() - start < timeoutMs) { if (predicate()) return; await new Promise(resolve => setTimeout(resolve, 10)); } throw new Error('Timed out waiting for condition.'); } describe('POST /api/files/upload', () => { test('stores a completed upload under its final name', async () => { const { status, body } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ { name: 'hello.txt', content: 'hello world', type: 'text/plain' }, ]); expect(status).toBe(200); expect(body.uploaded).toEqual(['hello.txt']); expect(fs.readFileSync(path.join(rootDir, 'hello.txt'), 'utf8')).toBe('hello world'); const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') .get([path.join(rootDir, 'hello.txt')]); expect(meta).toMatchObject({ uploader: 'admin' }); }); test('removes partial files when the upload connection aborts', async () => { await abortMultipartUpload(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, { name: 'partial.txt', content: Buffer.alloc(256 * 1024, 'a'), type: 'text/plain', }); await waitFor(() => fs.readdirSync(rootDir).length === 0); expect(fs.existsSync(path.join(rootDir, 'partial.txt'))).toBe(false); expect(fs.readdirSync(rootDir)).toEqual([]); const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') .get([path.join(rootDir, 'partial.txt')]); expect(meta).toBeFalsy(); }); }); describe('POST /api/files/move', () => { test('moves a file into another folder and rewrites metadata', async () => { const from = path.join(rootDir, 'alpha.txt'); const toDir = path.join(rootDir, 'folder'); fs.writeFileSync(from, 'hello'); fs.mkdirSync(toDir); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([from, 'admin', '["alice"]']); const { status, body } = await req('POST', '/api/files/move', { from, toDir }); expect(status).toBe(200); expect(body.ok).toBe(true); expect(fs.existsSync(from)).toBe(false); expect(fs.existsSync(path.join(toDir, 'alpha.txt'))).toBe(true); const meta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?').get([path.join(toDir, 'alpha.txt')]); expect(meta).toMatchObject({ uploader: 'admin', downloaders: '["alice"]' }); }); test('moves a folder into another folder and rewrites descendant metadata', async () => { const fromDir = path.join(rootDir, 'src-folder'); const nestedFile = path.join(fromDir, 'child.txt'); const toDir = path.join(rootDir, 'dest-folder'); fs.mkdirSync(fromDir); fs.mkdirSync(toDir); fs.writeFileSync(nestedFile, 'hello'); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([nestedFile, 'admin', '[]']); const { status } = await req('POST', '/api/files/move', { from: fromDir, toDir }); expect(status).toBe(200); expect(fs.existsSync(fromDir)).toBe(false); expect(fs.existsSync(path.join(toDir, 'src-folder', 'child.txt'))).toBe(true); const movedMeta = getDb().prepare('SELECT * FROM file_meta WHERE file_path = ?') .get([path.join(toDir, 'src-folder', 'child.txt')]); expect(movedMeta).toBeTruthy(); }); test('rejects moving a folder into itself', async () => { const fromDir = path.join(rootDir, 'src-folder'); const childDir = path.join(fromDir, 'child'); fs.mkdirSync(childDir, { recursive: true }); const { status, body } = await req('POST', '/api/files/move', { from: fromDir, toDir: childDir }); expect(status).toBe(400); expect(body.error).toMatch(/folder into itself/i); }); test('overwrites an existing destination when conflict strategy is overwrite', async () => { const sourceFile = path.join(rootDir, 'source.txt'); const destinationDir = path.join(rootDir, 'dest'); fs.mkdirSync(destinationDir); fs.writeFileSync(sourceFile, 'new-content'); fs.writeFileSync(path.join(destinationDir, 'source.txt'), 'old-content'); const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: destinationDir, conflict: 'overwrite', }); expect(status).toBe(200); expect(body.conflictResolution).toBe('overwrite'); expect(fs.existsSync(sourceFile)).toBe(false); expect(fs.readFileSync(path.join(destinationDir, 'source.txt'), 'utf8')).toBe('new-content'); }); test('renames destination when conflict strategy is rename', async () => { const sourceFile = path.join(rootDir, 'report.txt'); const destinationDir = path.join(rootDir, 'dest'); fs.mkdirSync(destinationDir); fs.writeFileSync(sourceFile, 'latest'); fs.writeFileSync(path.join(destinationDir, 'report.txt'), 'existing'); const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: destinationDir, conflict: 'rename', }); expect(status).toBe(200); expect(body.conflictResolution).toBe('rename'); expect(path.basename(body.path)).toBe('report (1).txt'); expect(fs.readFileSync(body.path, 'utf8')).toBe('latest'); expect(fs.readFileSync(path.join(destinationDir, 'report.txt'), 'utf8')).toBe('existing'); }); test('moves a file into My Folder when rename falls back across filesystems', async () => { const sourceFile = path.join(rootDir, 'cross-root.txt'); const userFolderBase = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-userfolders-')); const userFolder = path.join(userFolderBase, 'alice'); mockPaths = [rootDir]; mockUserPath = userFolderBase; mockUser = { username: 'alice', isAdmin: false, permissions: { [path.basename(rootDir)]: { read: true, write: true }, }, }; fs.writeFileSync(sourceFile, 'hello'); fs.mkdirSync(userFolder, { recursive: true }); const originalRenameSync = fs.renameSync; fs.renameSync = (from, to) => { const err = new Error('cross-device move'); err.code = 'EXDEV'; throw err; }; try { const { status, body } = await req('POST', '/api/files/move', { from: sourceFile, toDir: userFolder }); expect(status).toBe(200); expect(body.path).toBe(path.join(userFolder, 'cross-root.txt')); expect(fs.existsSync(sourceFile)).toBe(false); expect(fs.readFileSync(path.join(userFolder, 'cross-root.txt'), 'utf8')).toBe('hello'); } finally { fs.renameSync = originalRenameSync; fs.rmSync(userFolderBase, { recursive: true, force: true }); } }); }); describe('root alias endpoints', () => { test('GET /api/files/roots returns alias label and original name', async () => { mockRootAliases = { [path.resolve(rootDir)]: 'Workspace' }; const { status, body } = await req('GET', '/api/files/roots'); expect(status).toBe(200); expect(body.roots).toHaveLength(1); expect(body.roots[0]).toMatchObject({ path: rootDir, label: 'Workspace', alias: 'Workspace', originalName: path.basename(rootDir), }); }); test('POST /api/files/root-alias stores alias without renaming filesystem path', async () => { const originalBase = path.basename(rootDir); const { status, body } = await req('POST', '/api/files/root-alias', { rootPath: rootDir, alias: 'Shared Files', }); expect(status).toBe(200); expect(body.ok).toBe(true); expect(body.root).toMatchObject({ path: rootDir, label: 'Shared Files', alias: 'Shared Files', originalName: originalBase, }); expect(fs.existsSync(rootDir)).toBe(true); const afterRoots = await req('GET', '/api/files/roots'); expect(afterRoots.status).toBe(200); expect(afterRoots.body.roots[0].label).toBe('Shared Files'); expect(afterRoots.body.roots[0].originalName).toBe(originalBase); }); test('POST /api/files/root-alias rejects non-root paths', async () => { const nested = path.join(rootDir, 'sub'); fs.mkdirSync(nested, { recursive: true }); const { status } = await req('POST', '/api/files/root-alias', { rootPath: nested, alias: 'Nested', }); expect(status).toBe(400); }); }); describe('GET /api/files/thumbnail', () => { test('returns 404 while cached thumbnail is not ready', async () => { const source = path.join(rootDir, 'photo.jpg'); fs.writeFileSync(source, 'not-an-image'); const { status, body } = await req('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); expect(status).toBe(404); expect(body.error).toMatch(/not ready/i); }); test('serves cached thumbnail file when available', async () => { const source = path.join(rootDir, 'photo.jpg'); const thumb = path.join(rootDir, 'photo-thumb.webp'); fs.writeFileSync(source, 'not-an-image'); fs.writeFileSync(thumb, 'webp-bytes'); mockThumbPath = thumb; const response = await reqRaw('GET', `/api/files/thumbnail?file=${encodeURIComponent(source)}`); expect(response.status).toBe(200); expect(String(response.headers['content-type'] || '')).toContain('image/webp'); expect(response.body.toString('utf8')).toBe('webp-bytes'); }); }); describe('GET /api/files/root-access', () => { test('returns users with R/R+W modes for an exact root path', async () => { const label = path.basename(rootDir); const db = getDb(); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['admin', 'x', 1, '{}']); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['alice', 'x', 0, JSON.stringify({ [label]: { read: true, write: false } })]); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['bob', 'x', 0, JSON.stringify({ [label]: { read: true, write: true } })]); db.prepare('INSERT INTO users (username, password_hash, is_admin, permissions) VALUES (?, ?, ?, ?)') .run(['charlie', 'x', 0, JSON.stringify({ other: { read: true, write: false } })]); const { status, body } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(rootDir)}`); expect(status).toBe(200); expect(body.root).toMatchObject({ path: rootDir, originalName: label }); expect(body.users).toEqual([ { username: 'admin', mode: 'R+W' }, { username: 'bob', mode: 'R+W' }, { username: 'alice', mode: 'R' }, ]); }); test('rejects non-exact nested root paths', async () => { const nested = path.join(rootDir, 'sub'); fs.mkdirSync(nested, { recursive: true }); const { status } = await req('GET', `/api/files/root-access?rootPath=${encodeURIComponent(nested)}`); expect(status).toBe(400); }); }); describe('folder icon endpoints', () => { test('GET /api/files/folder-images returns images that have cached thumbnails', async () => { const subDir = path.join(rootDir, 'photos'); fs.mkdirSync(subDir); const imgPath = path.join(subDir, 'a.jpg'); fs.writeFileSync(imgPath, 'img'); mockFolderImages = [{ filePath: imgPath, thumbRelPath: 'thumbs/a.jpg.webp' }]; const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); expect(status).toBe(200); expect(body.images).toHaveLength(1); expect(body.images[0].filePath).toBe(imgPath); }); test('GET /api/files/folder-images returns empty list when no thumbnails available', async () => { mockFolderImages = []; const { status, body } = await req('GET', `/api/files/folder-images?dir=${encodeURIComponent(rootDir)}`); expect(status).toBe(200); expect(body.images).toEqual([]); }); test('GET /api/files/folder-icon returns null when no icon available', async () => { mockFolderIconFile = null; const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); expect(status).toBe(200); expect(body.icon).toBeNull(); }); test('GET /api/files/folder-icon returns source file path when icon is available', async () => { const imgPath = path.join(rootDir, 'cover.jpg'); fs.writeFileSync(imgPath, 'img'); mockFolderIconFile = imgPath; const { status, body } = await req('GET', `/api/files/folder-icon?dir=${encodeURIComponent(rootDir)}`); expect(status).toBe(200); expect(body.icon).toMatchObject({ filePath: imgPath }); }); test('POST /api/files/folder-icon sets explicit assignment when thumbnail is ready', async () => { const imgPath = path.join(rootDir, 'cover.jpg'); const thumbFile = path.join(rootDir, 'cover.webp'); fs.writeFileSync(imgPath, 'img'); fs.writeFileSync(thumbFile, 'webp'); mockThumbPath = thumbFile; const { status, body } = await req('POST', '/api/files/folder-icon', { folderPath: rootDir, imagePath: imgPath, }); expect(status).toBe(200); expect(body.ok).toBe(true); expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: imgPath }); }); test('POST /api/files/folder-icon rejects image without cached thumbnail', async () => { const imgPath = path.join(rootDir, 'missing.jpg'); fs.writeFileSync(imgPath, 'img'); mockThumbPath = null; const { status, body } = await req('POST', '/api/files/folder-icon', { folderPath: rootDir, imagePath: imgPath, }); expect(status).toBe(404); expect(body.error).toMatch(/thumbnail not ready/i); }); test('POST /api/files/folder-icon clears assignment when imagePath is null', async () => { const { status, body } = await req('POST', '/api/files/folder-icon', { folderPath: rootDir, imagePath: null, }); expect(status).toBe(200); expect(body.ok).toBe(true); expect(lastFolderIconAssignment).toEqual({ folderPath: rootDir, imagePath: null }); }); test('POST /api/files/folder-icon returns 403 for read-only user', async () => { const label = path.basename(rootDir); mockUser = { username: 'reader', isAdmin: false, permissions: { [label]: { read: true, write: false } }, }; const imgPath = path.join(rootDir, 'photo.jpg'); fs.writeFileSync(imgPath, 'img'); const { status } = await req('POST', '/api/files/folder-icon', { folderPath: rootDir, imagePath: imgPath, }); expect(status).toBe(403); }); }); // --------------------------------------------------------------------------- // GET /api/files/download-zip // --------------------------------------------------------------------------- describe('GET /api/files/download-zip', () => { beforeEach(() => { mockUser = { username: 'admin', isAdmin: true, permissions: {} }; }); test('streams a valid zip for an accessible directory', async () => { const subDir = path.join(rootDir, 'zipme'); fs.mkdirSync(subDir); fs.writeFileSync(path.join(subDir, 'file.txt'), 'content'); const { status, headers, body: buf } = await reqRaw('GET', `/api/files/download-zip?dir=${encodeURIComponent(subDir)}`); expect(status).toBe(200); const ct = headers['content-type'] || ''; expect(ct.includes('zip') || ct.includes('octet')).toBe(true); // ZIP magic bytes PK\x03\x04 expect(buf[0]).toBe(0x50); expect(buf[1]).toBe(0x4b); }, 20000); test('returns 400 when dir param is missing', async () => { const { status } = await req('GET', '/api/files/download-zip'); expect(status).toBe(400); }); test('returns 404 for a non-existent directory', async () => { const missing = path.join(rootDir, 'ghost'); const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(missing)}`); expect(status).toBe(404); }); test('returns 403 for path outside configured roots', async () => { const { status } = await req('GET', `/api/files/download-zip?dir=${encodeURIComponent(os.tmpdir())}`); expect(status).toBe(403); }); }); describe('video streaming routes', () => { test('POST /api/files/video-stream creates a short-lived playlist session', async () => { const filePath = path.join(rootDir, 'clip.mkv'); fs.writeFileSync(filePath, 'video'); mockVideoStreamSession = { sessionId: 'sess-123', durationSeconds: 42.25, subtitleTracks: [{ fileName: 'subtitle-0.vtt', label: 'English', language: 'eng', isDefault: true }], }; const { status, body } = await req('POST', '/api/files/video-stream', { filePath }); expect(status).toBe(200); expect(body.playlistUrl).toBe('/api/files/video-stream/sess-123/master.m3u8'); expect(body.durationSeconds).toBe(42.25); expect(body.subtitleSummary).toEqual({ total: 0, converted: 0, skipped: 0 }); expect(body.subtitleTracks).toEqual([ { label: 'English', language: 'eng', default: true, src: '/api/files/video-stream/sess-123/subtitle-0.vtt', }, ]); }); test('GET /api/files/video-stream/:sessionId/:assetPath serves HLS assets', async () => { mockVideoStreamAsset = async (_sessionId, _assetPath, _req, res) => { res.type('text/vtt').send('WEBVTT\n'); }; const { status, headers, body } = await reqRaw('GET', '/api/files/video-stream/sess-123/subtitle-0.vtt'); expect(status).toBe(200); expect(headers['content-type']).toMatch(/text\/vtt/); expect(body.toString()).toBe('WEBVTT\n'); }); test('DELETE /api/files/video-stream/:sessionId releases an active stream session', async () => { const { status, body } = await req('DELETE', '/api/files/video-stream/sess-123'); expect(status).toBe(200); expect(body).toEqual({ ok: true }); expect(releasedVideoStreamSessionId).toBe('sess-123'); }); test('POST /api/files/watch-progress stores per-user watched status by thresholds', async () => { const filePath = path.join(rootDir, 'clip.mkv'); fs.writeFileSync(filePath, 'video'); let result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.15 }); expect(result.status).toBe(200); expect(result.body).toMatchObject({ ok: true, updated: true, status: 'partway' }); // A lower progress update should not downgrade the status. result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.2 }); expect(result.status).toBe(200); expect(result.body).toMatchObject({ ok: true, updated: false, status: 'partway' }); result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); expect(result.status).toBe(200); expect(result.body.watchedBy).toEqual({ admin: 'partway' }); result = await req('POST', '/api/files/watch-progress', { filePath, progress: 0.75 }); expect(result.status).toBe(200); expect(result.body).toMatchObject({ ok: true, updated: true, status: 'fully' }); result = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); expect(result.status).toBe(200); expect(result.body.watchedBy).toEqual({ admin: 'fully' }); }); test('POST /api/files/watched-statuses returns bulk watched statuses for accessible files', async () => { const clipA = path.join(rootDir, 'clip-a.mkv'); const clipB = path.join(rootDir, 'clip-b.mkv'); const clipC = path.join(rootDir, 'clip-c.mkv'); fs.writeFileSync(clipA, 'a'); fs.writeFileSync(clipB, 'b'); fs.writeFileSync(clipC, 'c'); const db = getDb(); db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') .run([clipA, '', '[]', JSON.stringify({ admin: 'fully' })]); db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') .run([clipB, '', '[]', JSON.stringify({ admin: 'partway' })]); db.prepare('INSERT INTO file_meta (file_path, uploader, downloaders, watched_by) VALUES (?, ?, ?, ?)') .run([clipC, '', '[]', JSON.stringify({ admin: 'none' })]); const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: [clipA, clipB, clipC], }); expect(status).toBe(200); expect(body.statuses).toEqual({ [clipA]: 'fully', [clipB]: 'partway', }); }); test('POST /api/files/watched-statuses validates filePaths input', async () => { const { status, body } = await req('POST', '/api/files/watched-statuses', { filePaths: 'nope' }); expect(status).toBe(400); expect(body.error).toMatch(/filePaths array is required/i); }); }); describe('SHA-256 hashing and duplicate detection', () => { test('POST /api/files/upload stores sha256 hash for uploaded files', async () => { const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' }, ]); expect(status).toBe(200); const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') .get([path.join(rootDir, 'hashme.txt')]); expect(meta).toBeTruthy(); // SHA-256 is a 64-char hex string. expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/); }); test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () => { const filePath = path.join(rootDir, 'lazy.txt'); fs.writeFileSync(filePath, 'lazy content'); // Insert a row without a hash to simulate a pre-existing file. getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([filePath, 'admin', '[]']); const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); expect(status).toBe(200); expect(body.sha256).toMatch(/^[0-9a-f]{64}$/); // Verify it was persisted. const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]); expect(row.sha256).toBe(body.sha256); }); test('GET /api/files/duplicates returns other files with the same hash', async () => { const content = 'duplicate content'; const fileA = path.join(rootDir, 'dup-a.txt'); const fileB = path.join(rootDir, 'dup-b.txt'); fs.writeFileSync(fileA, content); fs.writeFileSync(fileB, content); // Compute the expected hash. const crypto = require('crypto'); const expectedHash = crypto.createHash('sha256').update(content).digest('hex'); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') .run([fileA, 'admin', '[]', expectedHash]); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') .run([fileB, 'admin', '[]', expectedHash]); const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`); expect(status).toBe(200); expect(body.duplicates).toHaveLength(1); expect(body.duplicates[0].path).toBe(fileB); expect(body.duplicates[0].name).toBe('dup-b.txt'); }); test('GET /api/files/duplicates returns empty list when no hash is stored', async () => { const filePath = path.join(rootDir, 'nohash.txt'); fs.writeFileSync(filePath, 'no hash yet'); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') .run([filePath, 'admin', '[]']); const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`); expect(status).toBe(200); expect(body.duplicates).toEqual([]); }); test('GET /api/files/duplicates excludes files outside accessible roots', async () => { const content = 'secret dupe'; const accessible = path.join(rootDir, 'visible.txt'); const outsideRoot = path.join(os.tmpdir(), 'outside.txt'); fs.writeFileSync(accessible, content); const crypto = require('crypto'); const hash = crypto.createHash('sha256').update(content).digest('hex'); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') .run([accessible, 'admin', '[]', hash]); // Insert a row for a path that is NOT inside any configured root. getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') .run([outsideRoot, 'admin', '[]', hash]); const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`); expect(status).toBe(200); expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true); }); test('POST /api/files/move preserves sha256 after rename', async () => { const from = path.join(rootDir, 'withHash.txt'); const toDir = path.join(rootDir, 'subfolder'); fs.writeFileSync(from, 'content'); fs.mkdirSync(toDir); const hash = 'a'.repeat(64); getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') .run([from, 'admin', '[]', hash]); const { status } = await req('POST', '/api/files/move', { from, toDir }); expect(status).toBe(200); const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') .get([path.join(toDir, 'withHash.txt')]); expect(meta.sha256).toBe(hash); }); });