| 1 | 'use strict'; |
| 2 | |
| 3 | const express = require('express'); |
| 4 | const path = require('path'); |
| 5 | const fs = require('fs'); |
| 6 | const http = require('http'); |
| 7 | const https = require('https'); |
| 8 | const { initDb, closeDb } = require('./db'); |
| 9 | const { ensureServerKeys } = require('./crypto'); |
| 10 | const { loadConfig } = require('./config'); |
| 11 | const { startThumbnailCacheLoop, stopThumbnailCacheLoop } = require('./thumbnail-cache'); |
| 12 | const { logError } = require('./logger'); |
| 13 | const authRoutes = require('./routes/auth'); |
| 14 | const filesRoutes = require('./routes/files'); |
| 15 | const adminRoutes = require('./routes/admin'); |
| 16 | const shareRoutes = require('./routes/share'); |
| 17 | |
| 18 | const app = express(); |
| 19 | |
| 20 | app.use(express.json({ limit: '50mb' })); |
| 21 | app.use('/vendor/video.js', express.static(path.join(__dirname, '../node_modules/video.js/dist'))); |
| 22 | app.use(express.static(path.join(__dirname, '../public'))); |
| 23 | |
| 24 | app.use('/api/auth', authRoutes); |
| 25 | app.use('/api/files', filesRoutes); |
| 26 | app.use('/api/admin', adminRoutes); |
| 27 | app.use('/api/share', shareRoutes); |
| 28 | |
| 29 | app.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. |
| 43 | app.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) |
| 51 | app.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. |
| 57 | function 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 | |
| 84 | function 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 | |
| 143 | try |
| 144 | { |
| 145 | start(); |
| 146 | } catch (err) |
| 147 | { |
| 148 | console.error('Failed to start server:', err); |
| 149 | process.exit(1); |
| 150 | } |