BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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