BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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