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