BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

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