| 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 | { |
| 24 | res.sendFile(path.join(__dirname, '../public/index.html')); |
| 25 | }); |
| 26 | |
| 27 | // Exposed so the shutdown route can trigger a graceful stop. |
| 28 | function shutdown (server) |
| 29 | { |
| 30 | if (!server || server.__isShuttingDown) return; |
| 31 | server.__isShuttingDown = true; |
| 32 | |
| 33 | // Close DB first so file locks are released as early as possible. |
| 34 | closeDb(); |
| 35 | |
| 36 | server.close(() => |
| 37 | { |
| 38 | process.exit(0); |
| 39 | }); |
| 40 | |
| 41 | // Force-exit after 5 s if connections don't drain in time. |
| 42 | setTimeout(() => |
| 43 | { |
| 44 | process.exit(0); |
| 45 | }, 5000).unref(); |
| 46 | } |
| 47 | |
| 48 | function start () |
| 49 | { |
| 50 | initDb(); |
| 51 | ensureServerKeys(); |
| 52 | |
| 53 | const config = loadConfig(); |
| 54 | const port = config.port || 3000; |
| 55 | |
| 56 | const server = app.listen(port, '0.0.0.0', () => |
| 57 | { |
| 58 | console.log(`File manager running at http://localhost:${port}`); |
| 59 | }); |
| 60 | |
| 61 | // Give the admin route access to the server handle for graceful shutdown. |
| 62 | app.set('server', server); |
| 63 | app.set('shutdown', () => shutdown(server)); |
| 64 | |
| 65 | process.on('SIGINT', () => shutdown(server)); |
| 66 | process.on('SIGTERM', () => shutdown(server)); |
| 67 | } |
| 68 | |
| 69 | try |
| 70 | { |
| 71 | start(); |
| 72 | } catch (err) |
| 73 | { |
| 74 | console.error('Failed to start server:', err); |
| 75 | process.exit(1); |
| 76 | } |