BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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