'use strict'; const express = require('express'); const path = require('path'); const fs = require('fs'); const crypto = require('crypto'); const archiver = require('archiver'); const router = express.Router(); const { getDb } = require('../db'); const { requireAuth } = require('../auth'); const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config'); const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream'); const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache'); const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function effectivePaths () { return getEffectivePaths(loadConfig().paths || []); } /** Returns the configured root that contains absPath, or null. */ function resolveRoot (absPath) { return getAllowedRoot(absPath, effectivePaths()); } /** Generate a cryptographically random token. */ function generateToken () { return crypto.randomBytes(32).toString('hex'); } /** Ensure the zip cache directory exists. */ function ensureZipCacheDir () { if (!fs.existsSync(ZIP_CACHE_DIR)) { fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true }); } } /** * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS. * Also delete zip files whose corresponding share token has expired. */ function pruneZipCache () { ensureZipCacheDir(); const now = Date.now(); let entries; try { entries = fs.readdirSync(ZIP_CACHE_DIR); } catch { return; } for (const name of entries) { if (!name.endsWith('.zip')) continue; const fullPath = path.join(ZIP_CACHE_DIR, name); try { const stat = fs.statSync(fullPath); const age = now - stat.mtimeMs; if (age > ZIP_MAX_AGE_MS) { fs.unlinkSync(fullPath); } } catch { // Ignore files that disappeared. } } } /** * Create (or return cached) zip for the given directory. * cacheKey is used as the filename stem. * Returns the full path to the zip file. */ function buildZip (dirPath, cacheKey) { return new Promise((resolve, reject) => { ensureZipCacheDir(); pruneZipCache(); const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`); // Serve cached version if it exists and is not too old. if (fs.existsSync(zipPath)) { try { const stat = fs.statSync(zipPath); if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS) { return resolve(zipPath); } fs.unlinkSync(zipPath); } catch { /* fall through to rebuild */ } } const tmpPath = zipPath + '.tmp'; const output = fs.createWriteStream(tmpPath); const archive = archiver('zip', { zlib: { level: 6 } }); output.on('close', () => { try { fs.renameSync(tmpPath, zipPath); resolve(zipPath); } catch (err) { reject(err); } }); archive.on('error', (err) => { try { fs.unlinkSync(tmpPath); } catch { /* ignore */ } reject(err); }); archive.pipe(output); archive.directory(dirPath, path.basename(dirPath)); archive.finalize(); }); } // --------------------------------------------------------------------------- // POST /api/share/create // Body: { filePath: } // Authenticated. Creates a 24-hour share token for a file or directory. // --------------------------------------------------------------------------- router.post('/create', requireAuth, (req, res) => { const filePath = String((req.body && req.body.filePath) || '').trim(); if (!filePath) { return res.status(400).json({ error: 'filePath is required.' }); } const root = resolveRoot(filePath); if (!root) { return res.status(403).json({ error: 'Access denied.' }); } // Verify the user can read that root. const rootLabel = path.basename(root); const user = req.user; const canRead = user.isAdmin || !!(user.permissions[rootLabel] && user.permissions[rootLabel].read); if (!canRead) { return res.status(403).json({ error: 'Access denied.' }); } let stat; try { stat = fs.statSync(filePath); } catch { return res.status(404).json({ error: 'File or folder not found.' }); } const isDir = stat.isDirectory() ? 1 : 0; const now = Date.now(); const expiresAt = now + SHARE_TTL_MS; const token = generateToken(); const db = getDb(); db.prepare(` INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?) `).run([token, filePath, isDir, user.username, now, expiresAt]); res.json({ token, expiresAt }); }); // --------------------------------------------------------------------------- // GET /api/share/info/:token // Public (no auth). Returns metadata about the shared item. // --------------------------------------------------------------------------- router.get('/info/:token', (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) { return res.status(410).json({ error: 'Share link has expired.' }); } const name = path.basename(row.file_path); res.json({ name, isDir: !!row.is_dir, expiresAt: row.expires_at, }); }); // --------------------------------------------------------------------------- // GET /api/share/preview/:token // Public (no auth). Streams a file for inline preview (non-directory only). // --------------------------------------------------------------------------- router.get('/preview/:token', (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path)) { return res.status(404).json({ error: 'File not found.' }); } // Limit preview size to 50 MB to prevent accidental large file streaming. const MAX_PREVIEW_BYTES = 50 * 1024 * 1024; let stat; try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); } if (stat.size > MAX_PREVIEW_BYTES) { return res.status(413).json({ error: 'File too large for inline preview.' }); } res.set('Cache-Control', 'private, no-store'); res.sendFile(row.file_path); }); // --------------------------------------------------------------------------- // GET /api/share/video-stream/:token // Public (no auth). Creates a short-lived ffmpeg-backed HLS session. // --------------------------------------------------------------------------- router.get('/video-stream/:token', async (req, res, next) => { try { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'File not found.' }); } const session = await createVideoStreamSession(row.file_path); res.json({ sessionId: session.sessionId, playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`, subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 }, subtitleTracks: session.subtitleTracks.map((track) => ({ label: track.label, language: track.language, default: !!track.isDefault, src: `/api/share/video-stream/session/${session.sessionId}/${track.fileName}`, })), }); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // GET /api/share/video-stream/session/:sessionId/:assetPath(*) // Public. Serves HLS assets from an already-created share video session. // --------------------------------------------------------------------------- router.get('/video-stream/session/:sessionId/:assetPath(*)', async (req, res, next) => { try { await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res); } catch (err) { next(err); } }); // --------------------------------------------------------------------------- // GET /api/share/download/:token // Public (no auth). Streams the file or a zip of the directory. // --------------------------------------------------------------------------- router.get('/download/:token', async (req, res) => { const token = String(req.params.token || '').trim(); if (!token) return res.status(400).json({ error: 'Token is required.' }); const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); if (!row) return res.status(404).json({ error: 'Share link not found.' }); if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); if (row.is_dir) { if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory()) { return res.status(404).json({ error: 'Directory not found.' }); } try { const zipPath = await buildZip(row.file_path, token); const zipName = `${path.basename(row.file_path)}.zip`; res.download(zipPath, zipName); } catch (err) { res.status(500).json({ error: 'Failed to create zip archive.' }); } } else { if (!fs.existsSync(row.file_path)) { return res.status(404).json({ error: 'File not found.' }); } res.download(row.file_path, path.basename(row.file_path)); } }); module.exports = router; module.exports.buildZip = buildZip; module.exports.pruneZipCache = pruneZipCache; module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR;