BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

Add scheduled restart backend
timfa Tim Falken · pushed by timfa · 5 months ago
9e526bef History
index.js 4.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 { startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop } = require('./auth');
11const { loadConfig } = require('./config');
12const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache');
13const { startRestartScheduler, stopRestartScheduler } = require('./restart-scheduler');
14const { logError } = require('./logger');
15const authRoutes = require('./routes/auth');
16const filesRoutes = require('./routes/files');
17const adminRoutes = require('./routes/admin');
18const shareRoutes = require('./routes/share');
19const { startShareMaintenanceLoop, stopShareMaintenanceLoop } = require('./routes/share');
20
21const app = express();
22
23app.use(express.json({ limit: '50mb' }));
24app.use('/vendor/video.js', express.static(path.join(__dirname, '../node_modules/video.js/dist')));
25app.use(express.static(path.join(__dirname, '../public')));
26
27app.use('/api/auth', authRoutes);
28app.use('/api/files', filesRoutes);
29app.use('/api/admin', adminRoutes);
30app.use('/api/share', shareRoutes);
31
32app.use((err, req, res, next) =>
33{
34 logError(`${req.method} ${req.originalUrl || req.url} failed`, err, {
35 statusCode: res.statusCode,
36 user: req.user && req.user.username ? req.user.username : null,
37 });
38
39 if (res.headersSent) return next(err);
40 res.status(500).json({ error: 'Internal Server Error' });
41});
42
43// Share page — served without authentication. OG meta tags are injected
44// server-side so social media crawlers (Discord, WhatsApp, Telegram, etc.)
45// can display rich previews.
46app.get('/share/:token', (req, res) =>
47{
48 const token = String(req.params.token || '').trim();
49 const page = shareRoutes.buildShareOpenGraphPage(token, req);
50 res.type('html').send(page);
51});
52
53// SPA catch-all (only for non-API routes)
54app.get('*', (req, res) =>
55{
56 res.sendFile(path.join(__dirname, '../public/index.html'));
57});
58
59// Exposed so the shutdown route can trigger a graceful stop.
60function shutdown (opts = {}, ...servers)
61{
62 const exitCode = Number.isInteger(opts.exitCode) ? opts.exitCode : 0;
63 const active = servers.filter(Boolean);
64 if (active.length === 0 || active[0].__isShuttingDown) return;
65 active.forEach(s => { s.__isShuttingDown = true; });
66
67 stopThumbnailCacheLoop();
68 stopAuthSessionCleanupLoop();
69 stopShareMaintenanceLoop();
70 stopRestartScheduler();
71
72 // Close DB first so file locks are released as early as possible.
73 closeDb();
74
75 let closed = 0;
76 function onClose ()
77 {
78 if (++closed === active.length) process.exit(exitCode);
79 }
80
81 active.forEach(s => s.close(onClose));
82
83 // Force-exit after 5 s if connections don't drain in time.
84 setTimeout(() =>
85 {
86 process.exit(exitCode);
87 }, 5000).unref();
88}
89
90function start ()
91{
92 initDb();
93 ensureServerKeys();
94
95 const config = loadConfig();
96 const port = config.port || 3000;
97
98 const httpServer = http.createServer(app);
99 httpServer.listen(port, '0.0.0.0', () =>
100 {
101 console.log(`File manager running at http://localhost:${port}`);
102 });
103
104 let httpsServer = null;
105 if (config.httpsPort && config.tlsCert && config.tlsKey)
106 {
107 let tlsOptions;
108 try
109 {
110 tlsOptions = {
111 cert: fs.readFileSync(config.tlsCert),
112 key: fs.readFileSync(config.tlsKey),
113 };
114 } catch (err)
115 {
116 console.error('Failed to read TLS certificate/key:', err.message);
117 process.exit(1);
118 }
119 httpsServer = https.createServer(tlsOptions, app);
120 httpsServer.listen(config.httpsPort, '0.0.0.0', () =>
121 {
122 console.log(`File manager running at https://localhost:${config.httpsPort}`);
123 });
124 }
125
126 const shutdownAll = () => shutdown({}, httpServer, httpsServer);
127 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
128
129 startThumbnailCacheLoop();
130 startAuthSessionCleanupLoop();
131 startShareMaintenanceLoop();
132 startRestartScheduler({ shutdownForRestart });
133
134 // Give the admin route access to the server handle for graceful shutdown.
135 app.set('server', httpServer);
136 app.set('shutdown', shutdownAll);
137 app.set('shutdownForRestart', shutdownForRestart);
138
139 process.on('SIGINT', shutdownAll);
140 process.on('SIGTERM', shutdownAll);
141 process.on('uncaughtException', (err) =>
142 {
143 logError('Uncaught exception', err);
144 process.exit(1);
145 });
146 process.on('unhandledRejection', (reason) =>
147 {
148 logError('Unhandled rejection', reason instanceof Error ? reason : new Error(String(reason)));
149 });
150}
151
152try
153{
154 start();
155} catch (err)
156{
157 console.error('Failed to start server:', err);
158 process.exit(1);
159}