'use strict'; const express = require('express'); const path = require('path'); const fs = require('fs'); const http = require('http'); const https = require('https'); const { initDb, closeDb } = require('./db'); const { ensureServerKeys } = require('./crypto'); const { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth'); const { loadConfig } = require('./config'); const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache'); const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler'); const { logError } = require('./logger'); const authRoutes = require('./routes/auth'); const filesRoutes = require('./routes/files'); const adminRoutes = require('./routes/admin'); const shareRoutes = require('./routes/share'); const { startShareMaintenanceLoop, stopShareMaintenanceLoop } = require('./routes/share'); const app = express(); app.use(express.json({ limit: '50mb' })); app.use('/vendor/video.js', express.static(path.join(__dirname, '../node_modules/video.js/dist'))); app.use(express.static(path.join(__dirname, '../public'))); app.use('/api/auth', authRoutes); app.use('/api/files', filesRoutes); app.use('/api/admin', adminRoutes); app.use('/api/share', shareRoutes); app.use((err, req, res, next) => { logError(`${req.method} ${req.originalUrl || req.url} failed`, err, { statusCode: res.statusCode, user: req.user && req.user.username ? req.user.username : null, }); if (res.headersSent) return next(err); res.status(500).json({ error: 'Internal Server Error' }); }); // Share page — served without authentication. OG meta tags are injected // server-side so social media crawlers (Discord, WhatsApp, Telegram, etc.) // can display rich previews. app.get('/share/:token', (req, res) => { const token = String(req.params.token || '').trim(); const page = shareRoutes.buildShareOpenGraphPage(token, req); res.type('html').send(page); }); // SPA catch-all (only for non-API routes) app.get('*', (req, res) => { res.sendFile(path.join(__dirname, '../public/index.html')); }); // Exposed so the shutdown route can trigger a graceful stop. function shutdown (opts = {}, ...servers) { const exitCode = Number.isInteger(opts.exitCode) ? opts.exitCode : 0; const active = servers.filter(Boolean); if (active.length === 0 || active[0].__isShuttingDown) return; active.forEach(s => { s.__isShuttingDown = true; }); stopThumbnailCacheLoop(); stopAuthSessionCleanupLoop(); stopShareMaintenanceLoop(); stopRestartScheduler(); // Close DB first so file locks are released as early as possible. closeDb(); let closed = 0; function onClose () { if (++closed === active.length) process.exit(exitCode); } active.forEach(s => s.close(onClose)); // Force-exit after 5 s if connections don't drain in time. setTimeout(() => { process.exit(exitCode); }, 5000).unref(); } function start () { initDb(); ensureServerKeys(); const config = loadConfig(); const port = config.port || 3000; const httpServer = http.createServer(app); httpServer.listen(port, '0.0.0.0', () => { console.log(`File manager running at http://localhost:${port}`); }); let httpsServer = null; if (config.httpsPort && config.tlsCert && config.tlsKey) { let tlsOptions; try { tlsOptions = { cert: fs.readFileSync(config.tlsCert), key: fs.readFileSync(config.tlsKey), }; } catch (err) { console.error('Failed to read TLS certificate/key:', err.message); process.exit(1); } httpsServer = https.createServer(tlsOptions, app); httpsServer.listen(config.httpsPort, '0.0.0.0', () => { console.log(`File manager running at https://localhost:${config.httpsPort}`); }); } const shutdownAll = () => shutdown({}, httpServer, httpsServer); const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer); startThumbnailCacheLoop(); startAuthSessionCleanupLoop(); startShareMaintenanceLoop(); startRestartScheduler({ shutdownForRestart }); // Give the admin route access to the server handle for graceful shutdown. app.set('server', httpServer); app.set('shutdown', shutdownAll); app.set('shutdownForRestart', shutdownForRestart); process.on('SIGINT', shutdownAll); process.on('SIGTERM', shutdownAll); process.on('uncaughtException', (err) => { logError('Uncaught exception', err); process.exit(1); }); process.on('unhandledRejection', (reason) => { logError('Unhandled rejection', reason instanceof Error ? reason : new Error(String(reason))); }); } try { start(); } catch (err) { console.error('Failed to start server:', err); process.exit(1); }