| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const path = require('path'); |
| 5 | const fs = require('fs'); |
| 6 | const crypto = require('crypto'); |
| 7 | const archiver = require('archiver'); |
| 8 | const router = express.Router(); |
| 9 | |
| 10 | const { getDb } = require('../db'); |
| 11 | const { requireAuth } = require('../auth'); |
| 12 | const { loadConfig, getEffectivePaths, getAllowedRoot } = require('../config'); |
| 13 | const { createVideoStreamSession, sendVideoStreamAsset } = require('../video-stream'); |
| 14 | |
| 15 | const SHARE_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours |
| 16 | const ZIP_CACHE_DIR = path.join(__dirname, '../../zip-cache'); |
| 17 | const ZIP_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day |
| 18 | |
| 19 | // --------------------------------------------------------------------------- |
| 20 | // Helpers |
| 21 | // --------------------------------------------------------------------------- |
| 22 | |
| 23 | function effectivePaths () |
| 24 | { |
| 25 | return getEffectivePaths(loadConfig().paths || []); |
| 26 | } |
| 27 | |
| 28 | /** Returns the configured root that contains absPath, or null. */ |
| 29 | function resolveRoot (absPath) |
| 30 | { |
| 31 | return getAllowedRoot(absPath, effectivePaths()); |
| 32 | } |
| 33 | |
| 34 | /** Generate a cryptographically random token. */ |
| 35 | function generateToken () |
| 36 | { |
| 37 | return crypto.randomBytes(32).toString('hex'); |
| 38 | } |
| 39 | |
| 40 | /** Ensure the zip cache directory exists. */ |
| 41 | function ensureZipCacheDir () |
| 42 | { |
| 43 | if (!fs.existsSync(ZIP_CACHE_DIR)) |
| 44 | { |
| 45 | fs.mkdirSync(ZIP_CACHE_DIR, { recursive: true }); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /** |
| 50 | * Delete zip files in ZIP_CACHE_DIR that are older than ZIP_MAX_AGE_MS. |
| 51 | * Also delete zip files whose corresponding share token has expired. |
| 52 | */ |
| 53 | function pruneZipCache () |
| 54 | { |
| 55 | ensureZipCacheDir(); |
| 56 | const now = Date.now(); |
| 57 | let entries; |
| 58 | try |
| 59 | { |
| 60 | entries = fs.readdirSync(ZIP_CACHE_DIR); |
| 61 | } catch |
| 62 | { |
| 63 | return; |
| 64 | } |
| 65 | |
| 66 | for (const name of entries) |
| 67 | { |
| 68 | if (!name.endsWith('.zip')) continue; |
| 69 | const fullPath = path.join(ZIP_CACHE_DIR, name); |
| 70 | try |
| 71 | { |
| 72 | const stat = fs.statSync(fullPath); |
| 73 | const age = now - stat.mtimeMs; |
| 74 | if (age > ZIP_MAX_AGE_MS) |
| 75 | { |
| 76 | fs.unlinkSync(fullPath); |
| 77 | } |
| 78 | } catch |
| 79 | { |
| 80 | // Ignore files that disappeared. |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /** |
| 86 | * Create (or return cached) zip for the given directory. |
| 87 | * cacheKey is used as the filename stem. |
| 88 | * Returns the full path to the zip file. |
| 89 | */ |
| 90 | function buildZip (dirPath, cacheKey) |
| 91 | { |
| 92 | return new Promise((resolve, reject) => |
| 93 | { |
| 94 | ensureZipCacheDir(); |
| 95 | pruneZipCache(); |
| 96 | |
| 97 | const zipPath = path.join(ZIP_CACHE_DIR, `${cacheKey}.zip`); |
| 98 | |
| 99 | // Serve cached version if it exists and is not too old. |
| 100 | if (fs.existsSync(zipPath)) |
| 101 | { |
| 102 | try |
| 103 | { |
| 104 | const stat = fs.statSync(zipPath); |
| 105 | if (Date.now() - stat.mtimeMs < ZIP_MAX_AGE_MS) |
| 106 | { |
| 107 | return resolve(zipPath); |
| 108 | } |
| 109 | fs.unlinkSync(zipPath); |
| 110 | } catch { /* fall through to rebuild */ } |
| 111 | } |
| 112 | |
| 113 | const tmpPath = zipPath + '.tmp'; |
| 114 | const output = fs.createWriteStream(tmpPath); |
| 115 | const archive = archiver('zip', { zlib: { level: 6 } }); |
| 116 | |
| 117 | output.on('close', () => |
| 118 | { |
| 119 | try |
| 120 | { |
| 121 | fs.renameSync(tmpPath, zipPath); |
| 122 | resolve(zipPath); |
| 123 | } catch (err) |
| 124 | { |
| 125 | reject(err); |
| 126 | } |
| 127 | }); |
| 128 | |
| 129 | archive.on('error', (err) => |
| 130 | { |
| 131 | try { fs.unlinkSync(tmpPath); } catch { /* ignore */ } |
| 132 | reject(err); |
| 133 | }); |
| 134 | |
| 135 | archive.pipe(output); |
| 136 | archive.directory(dirPath, path.basename(dirPath)); |
| 137 | archive.finalize(); |
| 138 | }); |
| 139 | } |
| 140 | |
| 141 | // --------------------------------------------------------------------------- |
| 142 | // POST /api/share/create |
| 143 | // Body: { filePath: <absolute-path> } |
| 144 | // Authenticated. Creates a 24-hour share token for a file or directory. |
| 145 | // --------------------------------------------------------------------------- |
| 146 | router.post('/create', requireAuth, (req, res) => |
| 147 | { |
| 148 | const filePath = String((req.body && req.body.filePath) || '').trim(); |
| 149 | if (!filePath) |
| 150 | { |
| 151 | return res.status(400).json({ error: 'filePath is required.' }); |
| 152 | } |
| 153 | |
| 154 | const root = resolveRoot(filePath); |
| 155 | if (!root) |
| 156 | { |
| 157 | return res.status(403).json({ error: 'Access denied.' }); |
| 158 | } |
| 159 | |
| 160 | // Verify the user can read that root. |
| 161 | const rootLabel = path.basename(root); |
| 162 | const user = req.user; |
| 163 | const canRead = user.isAdmin |
| 164 | || !!(user.permissions[rootLabel] && user.permissions[rootLabel].read); |
| 165 | if (!canRead) |
| 166 | { |
| 167 | return res.status(403).json({ error: 'Access denied.' }); |
| 168 | } |
| 169 | |
| 170 | let stat; |
| 171 | try |
| 172 | { |
| 173 | stat = fs.statSync(filePath); |
| 174 | } catch |
| 175 | { |
| 176 | return res.status(404).json({ error: 'File or folder not found.' }); |
| 177 | } |
| 178 | |
| 179 | const isDir = stat.isDirectory() ? 1 : 0; |
| 180 | const now = Date.now(); |
| 181 | const expiresAt = now + SHARE_TTL_MS; |
| 182 | const token = generateToken(); |
| 183 | |
| 184 | const db = getDb(); |
| 185 | db.prepare(` |
| 186 | INSERT INTO share_tokens (token, file_path, is_dir, created_by, created_at, expires_at) |
| 187 | VALUES (?, ?, ?, ?, ?, ?) |
| 188 | `).run([token, filePath, isDir, user.username, now, expiresAt]); |
| 189 | |
| 190 | res.json({ token, expiresAt }); |
| 191 | }); |
| 192 | |
| 193 | // --------------------------------------------------------------------------- |
| 194 | // GET /api/share/info/:token |
| 195 | // Public (no auth). Returns metadata about the shared item. |
| 196 | // --------------------------------------------------------------------------- |
| 197 | router.get('/info/:token', (req, res) => |
| 198 | { |
| 199 | const token = String(req.params.token || '').trim(); |
| 200 | if (!token) return res.status(400).json({ error: 'Token is required.' }); |
| 201 | |
| 202 | const db = getDb(); |
| 203 | const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); |
| 204 | |
| 205 | if (!row) return res.status(404).json({ error: 'Share link not found.' }); |
| 206 | if (Date.now() > row.expires_at) |
| 207 | { |
| 208 | return res.status(410).json({ error: 'Share link has expired.' }); |
| 209 | } |
| 210 | |
| 211 | const name = path.basename(row.file_path); |
| 212 | res.json({ |
| 213 | name, |
| 214 | isDir: !!row.is_dir, |
| 215 | expiresAt: row.expires_at, |
| 216 | }); |
| 217 | }); |
| 218 | |
| 219 | // --------------------------------------------------------------------------- |
| 220 | // GET /api/share/preview/:token |
| 221 | // Public (no auth). Streams a file for inline preview (non-directory only). |
| 222 | // --------------------------------------------------------------------------- |
| 223 | router.get('/preview/:token', (req, res) => |
| 224 | { |
| 225 | const token = String(req.params.token || '').trim(); |
| 226 | if (!token) return res.status(400).json({ error: 'Token is required.' }); |
| 227 | |
| 228 | const db = getDb(); |
| 229 | const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); |
| 230 | |
| 231 | if (!row) return res.status(404).json({ error: 'Share link not found.' }); |
| 232 | if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); |
| 233 | if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); |
| 234 | |
| 235 | if (!fs.existsSync(row.file_path)) |
| 236 | { |
| 237 | return res.status(404).json({ error: 'File not found.' }); |
| 238 | } |
| 239 | |
| 240 | // Limit preview size to 50 MB to prevent accidental large file streaming. |
| 241 | const MAX_PREVIEW_BYTES = 50 * 1024 * 1024; |
| 242 | let stat; |
| 243 | try { stat = fs.statSync(row.file_path); } catch { return res.status(404).json({ error: 'File not found.' }); } |
| 244 | |
| 245 | if (stat.size > MAX_PREVIEW_BYTES) |
| 246 | { |
| 247 | return res.status(413).json({ error: 'File too large for inline preview.' }); |
| 248 | } |
| 249 | |
| 250 | res.set('Cache-Control', 'private, no-store'); |
| 251 | res.sendFile(row.file_path); |
| 252 | }); |
| 253 | |
| 254 | // --------------------------------------------------------------------------- |
| 255 | // GET /api/share/video-stream/:token |
| 256 | // Public (no auth). Creates a short-lived ffmpeg-backed HLS session. |
| 257 | // --------------------------------------------------------------------------- |
| 258 | router.get('/video-stream/:token', async (req, res, next) => |
| 259 | { |
| 260 | try |
| 261 | { |
| 262 | const token = String(req.params.token || '').trim(); |
| 263 | if (!token) return res.status(400).json({ error: 'Token is required.' }); |
| 264 | |
| 265 | const db = getDb(); |
| 266 | const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); |
| 267 | |
| 268 | if (!row) return res.status(404).json({ error: 'Share link not found.' }); |
| 269 | if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); |
| 270 | if (row.is_dir) return res.status(400).json({ error: 'Cannot preview a directory.' }); |
| 271 | |
| 272 | if (!fs.existsSync(row.file_path) || fs.statSync(row.file_path).isDirectory()) |
| 273 | { |
| 274 | return res.status(404).json({ error: 'File not found.' }); |
| 275 | } |
| 276 | |
| 277 | const session = await createVideoStreamSession(row.file_path); |
| 278 | res.json({ |
| 279 | sessionId: session.sessionId, |
| 280 | playlistUrl: `/api/share/video-stream/session/${session.sessionId}/master.m3u8`, |
| 281 | subtitleSummary: session.subtitleSummary || { total: 0, converted: 0, skipped: 0 }, |
| 282 | subtitleTracks: session.subtitleTracks.map((track) => ({ |
| 283 | label: track.label, |
| 284 | language: track.language, |
| 285 | default: !!track.isDefault, |
| 286 | src: `/api/share/video-stream/session/${session.sessionId}/${track.fileName}`, |
| 287 | })), |
| 288 | }); |
| 289 | } catch (err) |
| 290 | { |
| 291 | next(err); |
| 292 | } |
| 293 | }); |
| 294 | |
| 295 | // --------------------------------------------------------------------------- |
| 296 | // GET /api/share/video-stream/session/:sessionId/:assetPath(*) |
| 297 | // Public. Serves HLS assets from an already-created share video session. |
| 298 | // --------------------------------------------------------------------------- |
| 299 | router.get('/video-stream/session/:sessionId/:assetPath(*)', async (req, res, next) => |
| 300 | { |
| 301 | try |
| 302 | { |
| 303 | await sendVideoStreamAsset(String(req.params.sessionId || ''), req.params.assetPath, res); |
| 304 | } catch (err) |
| 305 | { |
| 306 | next(err); |
| 307 | } |
| 308 | }); |
| 309 | |
| 310 | // --------------------------------------------------------------------------- |
| 311 | // GET /api/share/download/:token |
| 312 | // Public (no auth). Streams the file or a zip of the directory. |
| 313 | // --------------------------------------------------------------------------- |
| 314 | router.get('/download/:token', async (req, res) => |
| 315 | { |
| 316 | const token = String(req.params.token || '').trim(); |
| 317 | if (!token) return res.status(400).json({ error: 'Token is required.' }); |
| 318 | |
| 319 | const db = getDb(); |
| 320 | const row = db.prepare('SELECT * FROM share_tokens WHERE token = ?').get([token]); |
| 321 | |
| 322 | if (!row) return res.status(404).json({ error: 'Share link not found.' }); |
| 323 | if (Date.now() > row.expires_at) return res.status(410).json({ error: 'Share link has expired.' }); |
| 324 | |
| 325 | if (row.is_dir) |
| 326 | { |
| 327 | if (!fs.existsSync(row.file_path) || !fs.statSync(row.file_path).isDirectory()) |
| 328 | { |
| 329 | return res.status(404).json({ error: 'Directory not found.' }); |
| 330 | } |
| 331 | |
| 332 | try |
| 333 | { |
| 334 | const zipPath = await buildZip(row.file_path, token); |
| 335 | const zipName = `${path.basename(row.file_path)}.zip`; |
| 336 | res.download(zipPath, zipName); |
| 337 | } catch (err) |
| 338 | { |
| 339 | res.status(500).json({ error: 'Failed to create zip archive.' }); |
| 340 | } |
| 341 | } else |
| 342 | { |
| 343 | if (!fs.existsSync(row.file_path)) |
| 344 | { |
| 345 | return res.status(404).json({ error: 'File not found.' }); |
| 346 | } |
| 347 | |
| 348 | res.download(row.file_path, path.basename(row.file_path)); |
| 349 | } |
| 350 | }); |
| 351 | |
| 352 | module.exports = router; |
| 353 | module.exports.buildZip = buildZip; |
| 354 | module.exports.pruneZipCache = pruneZipCache; |
| 355 | module.exports.ZIP_CACHE_DIR = ZIP_CACHE_DIR; |