'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()); } function getUserFolderPath (config, username) { const base = typeof config.userPath === 'string' ? config.userPath.trim() : ''; if (!base) return null; return path.join(base, String(username)); } function resolveRootForUser (absPath, roots, user, config) { const matched = getAllowedRoot(absPath, roots); if (matched) return { root: matched, label: path.basename(matched), isUserFolder: false }; if (!user || !user.username) return null; const userFolder = getUserFolderPath(config, user.username); if (!userFolder) return null; const resolved = path.resolve(absPath); const resolvedFolder = path.resolve(userFolder); if (resolved === resolvedFolder || resolved.startsWith(resolvedFolder + path.sep)) { return { root: userFolder, label: path.basename(userFolder), isUserFolder: true }; } return null; } function canReadInfo (user, info) { if (!info) return false; if (info.isUserFolder) return true; if (user.isAdmin) return true; return !!(user.permissions[info.label] && user.permissions[info.label].read); } /** 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 config = loadConfig(); const roots = effectivePaths(); const info = resolveRootForUser(filePath, roots, req.user, config); if (!info || !canReadInfo(req.user, info)) { 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 user = req.user; 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`, durationSeconds: session.durationSeconds || null, 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, req, 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)); } }); // --------------------------------------------------------------------------- // Open Graph helpers // --------------------------------------------------------------------------- const SHARE_HTML_PATH = path.join(__dirname, '../../public/share.html'); const OG_IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'avif', 'bmp']); function ogEsc (s) { return String(s || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function fileExtLower (name) { const i = String(name || '').lastIndexOf('.'); return i >= 0 ? name.slice(i + 1).toLowerCase() : ''; } function formatOgValidity (expiresAt) { const ms = expiresAt - Date.now(); if (ms <= 0) return null; const h = Math.floor(ms / 3600000); const m = Math.floor((ms % 3600000) / 60000); if (h > 0) return `${h} hour${h !== 1 ? 's' : ''} ${m} minute${m !== 1 ? 's' : ''}`; return `${m} minute${m !== 1 ? 's' : ''}`; } /** * Reads share.html, injects Open Graph meta tags for the given token, and * returns the resulting HTML string. Works for all visitors — crawlers get * the OG data they need; browsers get the same interactive page but with a * dynamic title and preview metadata already in the . */ function buildShareOpenGraphPage (token, req) { const db = getDb(); const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); const baseUrl = `${req.protocol}://${req.get('host')}`; const shareUrl = `${baseUrl}/share/${encodeURIComponent(token)}`; let pageTitle, ogTitle, ogDesc, ogImageUrl = null, twitterCard; if (!row) { pageTitle = 'Link Not Found'; ogTitle = 'Link Not Found'; ogDesc = 'This shared file link does not exist.'; twitterCard = 'summary'; } else { const name = path.basename(row.file_path); const expired = Date.now() > row.expires_at; if (expired) { pageTitle = `Link Expired \u2014 ${name}`; ogTitle = 'Link Expired'; ogDesc = `This shared link for \u201C${name}\u201D has expired.`; twitterCard = 'summary'; } else { pageTitle = name; ogTitle = name; const validity = formatOgValidity(row.expires_at); const typeLabel = row.is_dir ? 'folder' : 'file'; ogDesc = validity ? `Shared ${typeLabel} \u00B7 Valid for ${validity}` : `Shared ${typeLabel}`; if (!row.is_dir && OG_IMAGE_EXTS.has(fileExtLower(name))) { ogImageUrl = `${baseUrl}/api/share/preview/${encodeURIComponent(token)}`; twitterCard = 'summary_large_image'; } else { twitterCard = 'summary'; } } } const metaLines = [ ``, ``, ``, ``, ``, ``, ``, ]; if (ogImageUrl) { metaLines.push(``); metaLines.push(``); } const ogBlock = metaLines.join('\n '); let html; try { html = fs.readFileSync(SHARE_HTML_PATH, 'utf8'); } catch { html = ''; } html = html.replace( 'Shared file', `${ogEsc(pageTitle)}\n ${ogBlock}`, ); return html; } module.exports = router; module.exports.buildZip = buildZip; module.exports.pruneZipCache = pruneZipCache; module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR; module.exports.buildShareOpenGraphPage = buildShareOpenGraphPage;