BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

index.js 2.6 KiB Download Raw
1'use strict';
2
3const express = require('express');
4const path = require('path');
5const fs = require('fs');
6const http = require('http');
7const https = require('https');
8const { initDb, closeDb } = require('./db');
9const { ensureServerKeys } = require('./crypto');
10const { loadConfig } = require('./config');
11const authRoutes = require('./routes/auth');
12const filesRoutes = require('./routes/files');
13const adminRoutes = require('./routes/admin');
14
15const app = express();
16
17app.use(express.json({ limit: '50mb' }));
18app.use(express.static(path.join(__dirname, '../public')));
19
20app.use('/api/auth', authRoutes);
21app.use('/api/files', filesRoutes);
22app.use('/api/admin', adminRoutes);
23
24// SPA catch-all (only for non-API routes)
25app.get('*', (req, res) =>
26{
27 res.sendFile(path.join(__dirname, '../public/index.html'));
28});
29
30// Exposed so the shutdown route can trigger a graceful stop.
31function shutdown (...servers)
32{
33 const active = servers.filter(Boolean);
34 if (active.length === 0 || active[0].__isShuttingDown) return;
35 active.forEach(s => { s.__isShuttingDown = true; });
36
37 // Close DB first so file locks are released as early as possible.
38 closeDb();
39
40 let closed = 0;
41 function onClose ()
42 {
43 if (++closed === active.length) process.exit(0);
44 }
45
46 active.forEach(s => s.close(onClose));
47
48 // Force-exit after 5 s if connections don't drain in time.
49 setTimeout(() =>
50 {
51 process.exit(0);
52 }, 5000).unref();
53}
54
55function start ()
56{
57 initDb();
58 ensureServerKeys();
59
60 const config = loadConfig();
61 const port = config.port || 3000;
62
63 const httpServer = http.createServer(app);
64 httpServer.listen(port, '0.0.0.0', () =>
65 {
66 console.log(`File manager running at http://localhost:${port}`);
67 });
68
69 let httpsServer = null;
70 if (config.httpsPort && config.tlsCert && config.tlsKey)
71 {
72 let tlsOptions;
73 try
74 {
75 tlsOptions = {
76 cert: fs.readFileSync(config.tlsCert),
77 key: fs.readFileSync(config.tlsKey),
78 };
79 } catch (err)
80 {
81 console.error('Failed to read TLS certificate/key:', err.message);
82 process.exit(1);
83 }
84 httpsServer = https.createServer(tlsOptions, app);
85 httpsServer.listen(config.httpsPort, '0.0.0.0', () =>
86 {
87 console.log(`File manager running at https://localhost:${config.httpsPort}`);
88 });
89 }
90
91 const shutdownAll = () => shutdown(httpServer, httpsServer);
92
93 // Give the admin route access to the server handle for graceful shutdown.
94 app.set('server', httpServer);
95 app.set('shutdown', shutdownAll);
96
97 process.on('SIGINT', shutdownAll);
98 process.on('SIGTERM', shutdownAll);
99}
100
101try
102{
103 start();
104} catch (err)
105{
106 console.error('Failed to start server:', err);
107 process.exit(1);
108}