'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 { loadConfig } = require('./config'); const authRoutes = require('./routes/auth'); const filesRoutes = require('./routes/files'); const adminRoutes = require('./routes/admin'); const app = express(); app.use(express.json({ limit: '50mb' })); app.use(express.static(path.join(__dirname, '../public'))); app.use('/api/auth', authRoutes); app.use('/api/files', filesRoutes); app.use('/api/admin', adminRoutes); // 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; }); // 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); // 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); } try { start(); } catch (err) { console.error('Failed to start server:', err); process.exit(1); }