BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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