BlueGit

timfa filemanager

Files

filemanager / server / index.js

index.js

index.js 3.4 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.
29app.get('/share/:token', (req, res) =>
30{
31 res.sendFile(path.join(__dirname, '../public/share.html'));
32});
33
34// SPA catch-all (only for non-API routes)
35app.get('*', (req, res) =>
36{
37 res.sendFile(path.join(__dirname, '../public/index.html'));
38});
39
40// Exposed so the shutdown route can trigger a graceful stop.
41function shutdown (opts = {}, ...servers)
42{
43 const exitCode = Number.isInteger(opts.exitCode) ? opts.exitCode : 0;
44 const active = servers.filter(Boolean);
45 if (active.length === 0 || active[0].__isShuttingDown) return;
46 active.forEach(s => { s.__isShuttingDown = true; });
47
48 stopThumbnailCacheLoop();
49
50 // Close DB first so file locks are released as early as possible.
51 closeDb();
52
53 let closed = 0;
54 function onClose ()
55 {
56 if (++closed === active.length) process.exit(exitCode);
57 }
58
59 active.forEach(s => s.close(onClose));
60
61 // Force-exit after 5 s if connections don't drain in time.
62 setTimeout(() =>
63 {
64 process.exit(exitCode);
65 }, 5000).unref();
66}
67
68function start ()
69{
70 initDb();
71 ensureServerKeys();
72
73 const config = loadConfig();
74 const port = config.port || 3000;
75
76 const httpServer = http.createServer(app);
77 httpServer.listen(port, '0.0.0.0', () =>
78 {
79 console.log(`File manager running at http://localhost:${port}`);
80 });
81
82 let httpsServer = null;
83 if (config.httpsPort && config.tlsCert && config.tlsKey)
84 {
85 let tlsOptions;
86 try
87 {
88 tlsOptions = {
89 cert: fs.readFileSync(config.tlsCert),
90 key: fs.readFileSync(config.tlsKey),
91 };
92 } catch (err)
93 {
94 console.error('Failed to read TLS certificate/key:', err.message);
95 process.exit(1);
96 }
97 httpsServer = https.createServer(tlsOptions, app);
98 httpsServer.listen(config.httpsPort, '0.0.0.0', () =>
99 {
100 console.log(`File manager running at https://localhost:${config.httpsPort}`);
101 });
102 }
103
104 const shutdownAll = () => shutdown({}, httpServer, httpsServer);
105 const shutdownForRestart = () => shutdown({ exitCode: 1 }, httpServer, httpsServer);
106
107 startThumbnailCacheLoop();
108
109 // Give the admin route access to the server handle for graceful shutdown.
110 app.set('server', httpServer);
111 app.set('shutdown', shutdownAll);
112 app.set('shutdownForRestart', shutdownForRestart);
113
114 process.on('SIGINT', shutdownAll);
115 process.on('SIGTERM', shutdownAll);
116}
117
118try
119{
120 start();
121} catch (err)
122{
123 console.error('Failed to start server:', err);
124 process.exit(1);
125}