BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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