BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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