]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Update changelog
[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 miscRouter,
99 clientsRouter,
100 feedsRouter,
101 staticRouter,
102 wellKnownRouter,
103 lazyStaticRouter,
104 servicesRouter,
105 liveRouter,
106 pluginsRouter,
107 webfingerRouter,
108 trackerRouter,
109 createWebsocketTrackerServer,
110 botsRouter,
111 downloadRouter
112 } from './server/controllers'
113 import { advertiseDoNotTrack } from './server/middlewares/dnt'
114 import { apiFailMiddleware } from './server/middlewares/error'
115 import { Redis } from './server/lib/redis'
116 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
117 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
118 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
119 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
120 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
121 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
122 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
123 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
124 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
125 import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
126 import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
127 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
128 import { PeerTubeSocket } from './server/lib/peertube-socket'
129 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
130 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
131 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
132 import { Hooks } from './server/lib/plugins/hooks'
133 import { PluginManager } from './server/lib/plugins/plugin-manager'
134 import { LiveManager } from './server/lib/live'
135 import { HttpStatusCode } from './shared/models/http/http-error-codes'
136 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
137 import { ServerConfigManager } from '@server/lib/server-config-manager'
138 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
139 import { isTestOrDevInstance } from './server/helpers/core-utils'
140 import { OpenTelemetryMetrics } from '@server/lib/opentelemetry/metrics'
141 import { ApplicationModel } from '@server/models/application/application'
142 import { VideoChannelSyncLatestScheduler } from '@server/lib/schedulers/video-channel-sync-latest-scheduler'
143
144 // ----------- Command line -----------
145
146 cli
147 .option('--no-client', 'Start PeerTube without client interface')
148 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
149 .option('--benchmark-startup', 'Automatically stop server when initialized')
150 .parse(process.argv)
151
152 // ----------- App -----------
153
154 // Enable CORS for develop
155 if (isTestOrDevInstance()) {
156 app.use(cors({
157 origin: '*',
158 exposedHeaders: 'Retry-After',
159 credentials: true
160 }))
161 }
162
163 // For the logger
164 token('remote-addr', (req: express.Request) => {
165 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
166 return anonymize(req.ip, 16, 16)
167 }
168
169 return req.ip
170 })
171 token('user-agent', (req: express.Request) => {
172 if (req.get('DNT') === '1') {
173 return parse(req.get('user-agent')).family
174 }
175
176 return req.get('user-agent')
177 })
178 app.use(morgan('combined', {
179 stream: {
180 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
181 },
182 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
183 }))
184
185 // Add .fail() helper to response
186 app.use(apiFailMiddleware)
187
188 // For body requests
189 app.use(express.urlencoded({ extended: false }))
190 app.use(express.json({
191 type: [ 'application/json', 'application/*+json' ],
192 limit: '500kb',
193 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
194 const valid = isHTTPSignatureDigestValid(buf, req)
195
196 if (valid !== true) {
197 res.fail({
198 status: HttpStatusCode.FORBIDDEN_403,
199 message: 'Invalid digest'
200 })
201 }
202 }
203 }))
204
205 // Cookies
206 app.use(cookieParser())
207
208 // W3C DNT Tracking Status
209 app.use(advertiseDoNotTrack)
210
211 // ----------- Open Telemetry -----------
212
213 OpenTelemetryMetrics.Instance.init(app)
214
215 // ----------- Views, routes and static files -----------
216
217 // API
218 const apiRoute = '/api/' + API_VERSION
219 app.use(apiRoute, apiRouter)
220
221 // Services (oembed...)
222 app.use('/services', servicesRouter)
223
224 // Live streaming
225 app.use('/live', liveRouter)
226
227 // Plugins & themes
228 app.use('/', pluginsRouter)
229
230 app.use('/', activityPubRouter)
231 app.use('/', feedsRouter)
232 app.use('/', webfingerRouter)
233 app.use('/', trackerRouter)
234 app.use('/', botsRouter)
235
236 // Static files
237 app.use('/', staticRouter)
238 app.use('/', wellKnownRouter)
239 app.use('/', miscRouter)
240 app.use('/', downloadRouter)
241 app.use('/', lazyStaticRouter)
242
243 // Client files, last valid routes!
244 const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
245 if (cliOptions.client) app.use('/', clientsRouter)
246
247 // ----------- Errors -----------
248
249 // Catch unmatched routes
250 app.use((_req, res: express.Response) => {
251 res.status(HttpStatusCode.NOT_FOUND_404).end()
252 })
253
254 // Catch thrown errors
255 app.use((err, _req, res: express.Response, _next) => {
256 // Format error to be logged
257 let error = 'Unknown error.'
258 if (err) {
259 error = err.stack || err.message || err
260 }
261
262 // Handling Sequelize error traces
263 const sql = err?.parent ? err.parent.sql : undefined
264
265 // Help us to debug SequelizeConnectionAcquireTimeoutError errors
266 const activeRequests = err?.name === 'SequelizeConnectionAcquireTimeoutError' && typeof (process as any)._getActiveRequests !== 'function'
267 ? (process as any)._getActiveRequests()
268 : undefined
269
270 logger.error('Error in controller.', { err: error, sql, activeRequests })
271
272 return res.fail({
273 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
274 message: err.message,
275 type: err.name
276 })
277 })
278
279 const server = createWebsocketTrackerServer(app)
280
281 // ----------- Run -----------
282
283 async function startApplication () {
284 const port = CONFIG.LISTEN.PORT
285 const hostname = CONFIG.LISTEN.HOSTNAME
286
287 await installApplication()
288
289 // Check activity pub urls are valid
290 checkActivityPubUrls()
291 .catch(err => {
292 logger.error('Error in ActivityPub URLs checker.', { err })
293 process.exit(-1)
294 })
295
296 checkFFmpegVersion()
297 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
298
299 Redis.Instance.init()
300 Emailer.Instance.init()
301
302 await Promise.all([
303 Emailer.Instance.checkConnection(),
304 JobQueue.Instance.init(),
305 ServerConfigManager.Instance.init()
306 ])
307
308 // Caches initializations
309 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
310 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
311 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
312
313 // Enable Schedulers
314 ActorFollowScheduler.Instance.enable()
315 RemoveOldJobsScheduler.Instance.enable()
316 UpdateVideosScheduler.Instance.enable()
317 YoutubeDlUpdateScheduler.Instance.enable()
318 VideosRedundancyScheduler.Instance.enable()
319 RemoveOldHistoryScheduler.Instance.enable()
320 RemoveOldViewsScheduler.Instance.enable()
321 PluginsCheckScheduler.Instance.enable()
322 PeerTubeVersionCheckScheduler.Instance.enable()
323 AutoFollowIndexInstances.Instance.enable()
324 RemoveDanglingResumableUploadsScheduler.Instance.enable()
325 VideoChannelSyncLatestScheduler.Instance.enable()
326 VideoViewsBufferScheduler.Instance.enable()
327 GeoIPUpdateScheduler.Instance.enable()
328 OpenTelemetryMetrics.Instance.registerMetrics()
329
330 PeerTubeSocket.Instance.init(server)
331 VideoViewsManager.Instance.init()
332
333 updateStreamingPlaylistsInfohashesIfNeeded()
334 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
335
336 LiveManager.Instance.init()
337 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
338
339 // Make server listening
340 server.listen(port, hostname, async () => {
341 if (cliOptions.plugins) {
342 try {
343 await PluginManager.Instance.rebuildNativePluginsIfNeeded()
344
345 await PluginManager.Instance.registerPluginsAndThemes()
346 } catch (err) {
347 logger.error('Cannot register plugins and themes.', { err })
348 }
349 }
350
351 ApplicationModel.updateNodeVersions()
352 .catch(err => logger.error('Cannot update node versions.', { err }))
353
354 logger.info('HTTP server listening on %s:%d', hostname, port)
355 logger.info('Web server: %s', WEBSERVER.URL)
356
357 Hooks.runAction('action:application.listening')
358
359 if (cliOptions['benchmarkStartup']) process.exit(0)
360 })
361
362 process.on('exit', () => {
363 JobQueue.Instance.terminate()
364 .catch(err => logger.error('Cannot terminate job queue.', { err }))
365 })
366
367 process.on('SIGINT', () => process.exit(0))
368 }