]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
/!\ Use a dedicated config file for development
[github/Chocobozzz/PeerTube.git] / server.ts
1 // ----------- Node modules -----------
2 import { registerOpentelemetryTracing } from './server/lib/opentelemetry/tracing'
3 registerOpentelemetryTracing()
4
5 import express from 'express'
6 import morgan, { token } from 'morgan'
7 import cors from 'cors'
8 import cookieParser from 'cookie-parser'
9 import { frameguard } from 'helmet'
10 import { parse } from 'useragent'
11 import anonymize from 'ip-anonymize'
12 import { program as cli } from 'commander'
13
14 process.title = 'peertube'
15
16 // Create our main app
17 const app = express().disable('x-powered-by')
18
19 // ----------- Core checker -----------
20 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
21
22 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
23 import { CONFIG } from './server/initializers/config'
24 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
25 import { logger } from './server/helpers/logger'
26
27 const missed = checkMissedConfig()
28 if (missed.length !== 0) {
29 logger.error('Your configuration files miss keys: ' + missed)
30 process.exit(-1)
31 }
32
33 checkFFmpeg(CONFIG)
34 .catch(err => {
35 logger.error('Error in ffmpeg check.', { err })
36 process.exit(-1)
37 })
38
39 try {
40 checkNodeVersion()
41 } catch (err) {
42 logger.error('Error in NodeJS check.', { err })
43 process.exit(-1)
44 }
45
46 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
47
48 checkConfig()
49
50 // Trust our proxy (IP forwarding...)
51 app.set('trust proxy', CONFIG.TRUST_PROXY)
52
53 app.use((_req, res, next) => {
54 res.locals.requestStart = Date.now()
55
56 return next()
57 })
58
59 // Security middleware
60 import { baseCSP } from './server/middlewares/csp'
61
62 if (CONFIG.CSP.ENABLED) {
63 app.use(baseCSP)
64 }
65
66 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
67 app.use(frameguard({
68 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
69 }))
70 }
71
72 // ----------- Database -----------
73
74 // Initialize database and models
75 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
76 checkDatabaseConnectionOrDie()
77
78 import { migrate } from './server/initializers/migrator'
79 migrate()
80 .then(() => initDatabaseModels(false))
81 .then(() => startApplication())
82 .catch(err => {
83 logger.error('Cannot start application.', { err })
84 process.exit(-1)
85 })
86
87 // ----------- Initialize -----------
88 loadLanguages()
89
90 // ----------- PeerTube modules -----------
91 import { installApplication } from './server/initializers/installer'
92 import { Emailer } from './server/lib/emailer'
93 import { JobQueue } from './server/lib/job-queue'
94 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
95 import {
96 activityPubRouter,
97 apiRouter,
98 clientsRouter,
99 feedsRouter,
100 staticRouter,
101 lazyStaticRouter,
102 servicesRouter,
103 liveRouter,
104 pluginsRouter,
105 webfingerRouter,
106 trackerRouter,
107 createWebsocketTrackerServer,
108 botsRouter,
109 downloadRouter
110 } from './server/controllers'
111 import { advertiseDoNotTrack } from './server/middlewares/dnt'
112 import { apiFailMiddleware } from './server/middlewares/error'
113 import { Redis } from './server/lib/redis'
114 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
115 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
116 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
117 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
118 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
119 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
120 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
121 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
122 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
123 import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
124 import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
125 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
126 import { PeerTubeSocket } from './server/lib/peertube-socket'
127 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
128 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
129 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
130 import { Hooks } from './server/lib/plugins/hooks'
131 import { PluginManager } from './server/lib/plugins/plugin-manager'
132 import { LiveManager } from './server/lib/live'
133 import { HttpStatusCode } from './shared/models/http/http-error-codes'
134 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
135 import { ServerConfigManager } from '@server/lib/server-config-manager'
136 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
137 import { isTestOrDevInstance } from './server/helpers/core-utils'
138 import { OpenTelemetryMetrics } from '@server/lib/opentelemetry/metrics'
139
140 // ----------- Command line -----------
141
142 cli
143 .option('--no-client', 'Start PeerTube without client interface')
144 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
145 .option('--benchmark-startup', 'Automatically stop server when initialized')
146 .parse(process.argv)
147
148 // ----------- App -----------
149
150 // Enable CORS for develop
151 if (isTestOrDevInstance()) {
152 app.use(cors({
153 origin: '*',
154 exposedHeaders: 'Retry-After',
155 credentials: true
156 }))
157 }
158
159 // For the logger
160 token('remote-addr', (req: express.Request) => {
161 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
162 return anonymize(req.ip, 16, 16)
163 }
164
165 return req.ip
166 })
167 token('user-agent', (req: express.Request) => {
168 if (req.get('DNT') === '1') {
169 return parse(req.get('user-agent')).family
170 }
171
172 return req.get('user-agent')
173 })
174 app.use(morgan('combined', {
175 stream: {
176 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
177 },
178 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
179 }))
180
181 // Add .fail() helper to response
182 app.use(apiFailMiddleware)
183
184 // For body requests
185 app.use(express.urlencoded({ extended: false }))
186 app.use(express.json({
187 type: [ 'application/json', 'application/*+json' ],
188 limit: '500kb',
189 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
190 const valid = isHTTPSignatureDigestValid(buf, req)
191
192 if (valid !== true) {
193 res.fail({
194 status: HttpStatusCode.FORBIDDEN_403,
195 message: 'Invalid digest'
196 })
197 }
198 }
199 }))
200
201 // Cookies
202 app.use(cookieParser())
203
204 // W3C DNT Tracking Status
205 app.use(advertiseDoNotTrack)
206
207 // ----------- Open Telemetry -----------
208
209 OpenTelemetryMetrics.Instance.init(app)
210
211 // ----------- Views, routes and static files -----------
212
213 // API
214 const apiRoute = '/api/' + API_VERSION
215 app.use(apiRoute, apiRouter)
216
217 // Services (oembed...)
218 app.use('/services', servicesRouter)
219
220 // Live streaming
221 app.use('/live', liveRouter)
222
223 // Plugins & themes
224 app.use('/', pluginsRouter)
225
226 app.use('/', activityPubRouter)
227 app.use('/', feedsRouter)
228 app.use('/', webfingerRouter)
229 app.use('/', trackerRouter)
230 app.use('/', botsRouter)
231
232 // Static files
233 app.use('/', staticRouter)
234 app.use('/', downloadRouter)
235 app.use('/', lazyStaticRouter)
236
237 // Client files, last valid routes!
238 const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
239 if (cliOptions.client) app.use('/', clientsRouter)
240
241 // ----------- Errors -----------
242
243 // Catch unmatched routes
244 app.use((_req, res: express.Response) => {
245 res.status(HttpStatusCode.NOT_FOUND_404).end()
246 })
247
248 // Catch thrown errors
249 app.use((err, _req, res: express.Response, _next) => {
250 // Format error to be logged
251 let error = 'Unknown error.'
252 if (err) {
253 error = err.stack || err.message || err
254 }
255 // Handling Sequelize error traces
256 const sql = err.parent ? err.parent.sql : undefined
257 logger.error('Error in controller.', { err: error, sql })
258
259 return res.fail({
260 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
261 message: err.message,
262 type: err.name
263 })
264 })
265
266 const server = createWebsocketTrackerServer(app)
267
268 // ----------- Run -----------
269
270 async function startApplication () {
271 const port = CONFIG.LISTEN.PORT
272 const hostname = CONFIG.LISTEN.HOSTNAME
273
274 await installApplication()
275
276 // Check activity pub urls are valid
277 checkActivityPubUrls()
278 .catch(err => {
279 logger.error('Error in ActivityPub URLs checker.', { err })
280 process.exit(-1)
281 })
282
283 checkFFmpegVersion()
284 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
285
286 // Email initialization
287 Emailer.Instance.init()
288
289 await Promise.all([
290 Emailer.Instance.checkConnection(),
291 JobQueue.Instance.init(),
292 ServerConfigManager.Instance.init()
293 ])
294
295 // Caches initializations
296 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
297 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
298 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
299
300 // Enable Schedulers
301 ActorFollowScheduler.Instance.enable()
302 RemoveOldJobsScheduler.Instance.enable()
303 UpdateVideosScheduler.Instance.enable()
304 YoutubeDlUpdateScheduler.Instance.enable()
305 VideosRedundancyScheduler.Instance.enable()
306 RemoveOldHistoryScheduler.Instance.enable()
307 RemoveOldViewsScheduler.Instance.enable()
308 PluginsCheckScheduler.Instance.enable()
309 PeerTubeVersionCheckScheduler.Instance.enable()
310 AutoFollowIndexInstances.Instance.enable()
311 RemoveDanglingResumableUploadsScheduler.Instance.enable()
312 VideoViewsBufferScheduler.Instance.enable()
313 GeoIPUpdateScheduler.Instance.enable()
314 OpenTelemetryMetrics.Instance.registerMetrics()
315
316 Redis.Instance.init()
317 PeerTubeSocket.Instance.init(server)
318 VideoViewsManager.Instance.init()
319
320 updateStreamingPlaylistsInfohashesIfNeeded()
321 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
322
323 LiveManager.Instance.init()
324 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
325
326 // Make server listening
327 server.listen(port, hostname, async () => {
328 if (cliOptions.plugins) {
329 try {
330 await PluginManager.Instance.registerPluginsAndThemes()
331 } catch (err) {
332 logger.error('Cannot register plugins and themes.', { err })
333 }
334 }
335
336 logger.info('HTTP server listening on %s:%d', hostname, port)
337 logger.info('Web server: %s', WEBSERVER.URL)
338
339 Hooks.runAction('action:application.listening')
340
341 if (cliOptions['benchmarkStartup']) process.exit(0)
342 })
343
344 process.on('exit', () => {
345 JobQueue.Instance.terminate()
346 })
347
348 process.on('SIGINT', () => process.exit(0))
349 }