| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const fs = require('fs'); |
| 5 | const http = require('http'); |
| 6 | const os = require('os'); |
| 7 | const path = require('path'); |
| 8 | const { once } = require('events'); |
| 9 | |
| 10 | let mockPaths = []; |
| 11 | let mockUserPath = null; |
| 12 | let mockRootAliases = {}; |
| 13 | let mockUser = { username: 'admin', isAdmin: true, permissions: {} }; |
| 14 | let mockThumbPath = null; |
| 15 | let mockFolderImages = []; |
| 16 | let mockFolderIconFile = null; |
| 17 | let lastFolderIconAssignment = undefined; |
| 18 | let mockVideoStreamSession = null; |
| 19 | let mockVideoStreamAsset = null; |
| 20 | let releasedVideoStreamSessionId = null; |
| 21 | |
| 22 | jest.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 | |
| 54 | jest.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 | |
| 74 | jest.mock('../server/auth', () => ({ |
| 75 | requireAuth: (req, res, next) => { req.user = mockUser; next(); }, |
| 76 | })); |
| 77 | |
| 78 | jest.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 | |
| 92 | jest.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 | |
| 114 | const filesRoutes = require('../server/routes/files'); |
| 115 | const { getDb } = require('../server/db'); |
| 116 | |
| 117 | let server; |
| 118 | let baseUrl; |
| 119 | let rootDir; |
| 120 | |
| 121 | beforeAll(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 | |
| 140 | afterAll(() => |
| 141 | { |
| 142 | server.close(); |
| 143 | fs.rmSync(rootDir, { recursive: true, force: true }); |
| 144 | }); |
| 145 | |
| 146 | beforeEach(() => |
| 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 | |
| 170 | function 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 | |
| 193 | function 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 | |
| 212 | function 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 | |
| 252 | function 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 | |
| 287 | async 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 | |
| 298 | describe('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 | |
| 334 | describe('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 | |
| 476 | describe('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 | |
| 532 | describe('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 | |
| 559 | describe('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 | |
| 594 | describe('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 | // --------------------------------------------------------------------------- |
| 705 | describe('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 | |
| 749 | describe('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 | |
| 828 | describe('SHA-256 hashing and duplicate detection', () => |
| 829 | { |
| 830 | test('POST /api/files/upload stores sha256 hash for uploaded files', async () => |
| 831 | { |
| 832 | const { status } = await reqMultipart(`/api/files/upload?dir=${encodeURIComponent(rootDir)}`, [ |
| 833 | { name: 'hashme.txt', content: 'hello hash', type: 'text/plain' }, |
| 834 | ]); |
| 835 | expect(status).toBe(200); |
| 836 | |
| 837 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 838 | .get([path.join(rootDir, 'hashme.txt')]); |
| 839 | expect(meta).toBeTruthy(); |
| 840 | // SHA-256 is a 64-char hex string. |
| 841 | expect(meta.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 842 | }); |
| 843 | |
| 844 | test('GET /api/files/meta returns sha256 and computes it lazily when missing', async () => |
| 845 | { |
| 846 | const filePath = path.join(rootDir, 'lazy.txt'); |
| 847 | fs.writeFileSync(filePath, 'lazy content'); |
| 848 | |
| 849 | // Insert a row without a hash to simulate a pre-existing file. |
| 850 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 851 | .run([filePath, 'admin', '[]']); |
| 852 | |
| 853 | const { status, body } = await req('GET', `/api/files/meta?file=${encodeURIComponent(filePath)}`); |
| 854 | expect(status).toBe(200); |
| 855 | expect(body.sha256).toMatch(/^[0-9a-f]{64}$/); |
| 856 | |
| 857 | // Verify it was persisted. |
| 858 | const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]); |
| 859 | expect(row.sha256).toBe(body.sha256); |
| 860 | }); |
| 861 | |
| 862 | test('GET /api/files/duplicates returns other files with the same hash', async () => |
| 863 | { |
| 864 | const content = 'duplicate content'; |
| 865 | const fileA = path.join(rootDir, 'dup-a.txt'); |
| 866 | const fileB = path.join(rootDir, 'dup-b.txt'); |
| 867 | fs.writeFileSync(fileA, content); |
| 868 | fs.writeFileSync(fileB, content); |
| 869 | |
| 870 | // Compute the expected hash. |
| 871 | const crypto = require('crypto'); |
| 872 | const expectedHash = crypto.createHash('sha256').update(content).digest('hex'); |
| 873 | |
| 874 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 875 | .run([fileA, 'admin', '[]', expectedHash]); |
| 876 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 877 | .run([fileB, 'admin', '[]', expectedHash]); |
| 878 | |
| 879 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(fileA)}`); |
| 880 | expect(status).toBe(200); |
| 881 | expect(body.duplicates).toHaveLength(1); |
| 882 | expect(body.duplicates[0].path).toBe(fileB); |
| 883 | expect(body.duplicates[0].name).toBe('dup-b.txt'); |
| 884 | }); |
| 885 | |
| 886 | test('GET /api/files/duplicates returns empty list when no hash is stored', async () => |
| 887 | { |
| 888 | const filePath = path.join(rootDir, 'nohash.txt'); |
| 889 | fs.writeFileSync(filePath, 'no hash yet'); |
| 890 | |
| 891 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 892 | .run([filePath, 'admin', '[]']); |
| 893 | |
| 894 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(filePath)}`); |
| 895 | expect(status).toBe(200); |
| 896 | expect(body.duplicates).toEqual([]); |
| 897 | }); |
| 898 | |
| 899 | test('GET /api/files/duplicates excludes files outside accessible roots', async () => |
| 900 | { |
| 901 | const content = 'secret dupe'; |
| 902 | const accessible = path.join(rootDir, 'visible.txt'); |
| 903 | const outsideRoot = path.join(os.tmpdir(), 'outside.txt'); |
| 904 | fs.writeFileSync(accessible, content); |
| 905 | |
| 906 | const crypto = require('crypto'); |
| 907 | const hash = crypto.createHash('sha256').update(content).digest('hex'); |
| 908 | |
| 909 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 910 | .run([accessible, 'admin', '[]', hash]); |
| 911 | // Insert a row for a path that is NOT inside any configured root. |
| 912 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 913 | .run([outsideRoot, 'admin', '[]', hash]); |
| 914 | |
| 915 | const { status, body } = await req('GET', `/api/files/duplicates?file=${encodeURIComponent(accessible)}`); |
| 916 | expect(status).toBe(200); |
| 917 | expect(body.duplicates.every(d => d.path !== outsideRoot)).toBe(true); |
| 918 | }); |
| 919 | |
| 920 | test('POST /api/files/move preserves sha256 after rename', async () => |
| 921 | { |
| 922 | const from = path.join(rootDir, 'withHash.txt'); |
| 923 | const toDir = path.join(rootDir, 'subfolder'); |
| 924 | fs.writeFileSync(from, 'content'); |
| 925 | fs.mkdirSync(toDir); |
| 926 | |
| 927 | const hash = 'a'.repeat(64); |
| 928 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders, sha256) VALUES (?, ?, ?, ?)') |
| 929 | .run([from, 'admin', '[]', hash]); |
| 930 | |
| 931 | const { status } = await req('POST', '/api/files/move', { from, toDir }); |
| 932 | expect(status).toBe(200); |
| 933 | |
| 934 | const meta = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?') |
| 935 | .get([path.join(toDir, 'withHash.txt')]); |
| 936 | expect(meta.sha256).toBe(hash); |
| 937 | }); |
| 938 | }); |