| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const path = require('path'); |
| 5 | const { initDb, closeDb } = require('./db'); |
| 6 | const { ensureServerKeys } = require('./crypto'); |
| 7 | const { loadConfig } = require('./config'); |
| 8 | const authRoutes = require('./routes/auth'); |
| 9 | const filesRoutes = require('./routes/files'); |
| 10 | const adminRoutes = require('./routes/admin'); |
| 11 | |
| 12 | const app = express(); |
| 13 | |
| 14 | app.use(express.json({ limit: '50mb' })); |
| 15 | app.use(express.static(path.join(__dirname, '../public'))); |
| 16 | |
| 17 | app.use('/api/auth', authRoutes); |
| 18 | app.use('/api/files', filesRoutes); |
| 19 | app.use('/api/admin', adminRoutes); |
| 20 | |
| 21 | // SPA catch-all (only for non-API routes) |
| 22 | app.get('*', (req, res) => { |
| 23 | res.sendFile(path.join(__dirname, '../public/index.html')); |
| 24 | }); |
| 25 | |
| 26 | // Exposed so the shutdown route can trigger a graceful stop. |
| 27 | function shutdown(server) { |
| 28 | server.close(() => { |
| 29 | closeDb(); |
| 30 | process.exit(0); |
| 31 | }); |
| 32 | // Force-exit after 5 s if connections don't drain in time. |
| 33 | setTimeout(() => { |
| 34 | closeDb(); |
| 35 | process.exit(0); |
| 36 | }, 5000).unref(); |
| 37 | } |
| 38 | |
| 39 | function start() { |
| 40 | initDb(); |
| 41 | ensureServerKeys(); |
| 42 | |
| 43 | const config = loadConfig(); |
| 44 | const port = config.port || 3000; |
| 45 | |
| 46 | const server = app.listen(port, '0.0.0.0', () => { |
| 47 | console.log(`File manager running at http://localhost:${port}`); |
| 48 | }); |
| 49 | |
| 50 | // Give the admin route access to the server handle for graceful shutdown. |
| 51 | app.set('server', server); |
| 52 | app.set('shutdown', () => shutdown(server)); |
| 53 | } |
| 54 | |
| 55 | try { |
| 56 | start(); |
| 57 | } catch (err) { |
| 58 | console.error('Failed to start server:', err); |
| 59 | process.exit(1); |
| 60 | } |