1 // ----------- Node modules -----------
2 import { registerOpentelemetryTracing } from './server/lib/opentelemetry/tracing'
3 registerOpentelemetryTracing()
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'
14 process.title = 'peertube'
16 // Create our main app
17 const app = express().disable('x-powered-by')
19 // ----------- Core checker -----------
20 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
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'
27 const missed = checkMissedConfig()
28 if (missed.length !== 0) {
29 logger.error('Your configuration files miss keys: ' + missed)
35 logger.error('Error in ffmpeg check.', { err })
42 logger.error('Error in NodeJS check.', { err })
46 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
50 // Trust our proxy (IP forwarding...)
51 app.set('trust proxy', CONFIG.TRUST_PROXY)
53 app.use((_req, res, next) => {
54 res.locals.requestStart = Date.now()
59 // Security middleware
60 import { baseCSP } from './server/middlewares/csp'
62 if (CONFIG.CSP.ENABLED) {
66 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
68 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
72 // ----------- Database -----------
74 // Initialize database and models
75 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
76 checkDatabaseConnectionOrDie()
78 import { migrate } from './server/initializers/migrator'
80 .then(() => initDatabaseModels(false))
81 .then(() => startApplication())
83 logger.error('Cannot start application.', { err })
87 // ----------- Initialize -----------
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'
109 createWebsocketTrackerServer,
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'
144 // ----------- Command line -----------
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')
152 // ----------- App -----------
154 // Enable CORS for develop
155 if (isTestOrDevInstance()) {
158 exposedHeaders: 'Retry-After',
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)
171 token('user-agent', (req: express.Request) => {
172 if (req.get('DNT') === '1') {
173 return parse(req.get('user-agent')).family
176 return req.get('user-agent')
178 app.use(morgan('combined', {
180 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
182 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
185 // Add .fail() helper to response
186 app.use(apiFailMiddleware)
189 app.use(express.urlencoded({ extended: false }))
190 app.use(express.json({
191 type: [ 'application/json', 'application/*+json' ],
193 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
194 const valid = isHTTPSignatureDigestValid(buf, req)
196 if (valid !== true) {
198 status: HttpStatusCode.FORBIDDEN_403,
199 message: 'Invalid digest'
206 app.use(cookieParser())
208 // W3C DNT Tracking Status
209 app.use(advertiseDoNotTrack)
211 // ----------- Open Telemetry -----------
213 OpenTelemetryMetrics.Instance.init(app)
215 // ----------- Views, routes and static files -----------
218 const apiRoute = '/api/' + API_VERSION
219 app.use(apiRoute, apiRouter)
221 // Services (oembed...)
222 app.use('/services', servicesRouter)
225 app.use('/live', liveRouter)
228 app.use('/', pluginsRouter)
230 app.use('/', activityPubRouter)
231 app.use('/', feedsRouter)
232 app.use('/', webfingerRouter)
233 app.use('/', trackerRouter)
234 app.use('/', botsRouter)
237 app.use('/', staticRouter)
238 app.use('/', wellKnownRouter)
239 app.use('/', miscRouter)
240 app.use('/', downloadRouter)
241 app.use('/', lazyStaticRouter)
243 // Client files, last valid routes!
244 const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
245 if (cliOptions.client) app.use('/', clientsRouter)
247 // ----------- Errors -----------
249 // Catch unmatched routes
250 app.use((_req, res: express.Response) => {
251 res.status(HttpStatusCode.NOT_FOUND_404).end()
254 // Catch thrown errors
255 app.use((err, _req, res: express.Response, _next) => {
256 // Format error to be logged
257 let error = 'Unknown error.'
259 error = err.stack || err.message || err
262 // Handling Sequelize error traces
263 const sql = err?.parent ? err.parent.sql : undefined
265 // Help us to debug SequelizeConnectionAcquireTimeoutError errors
266 const activeRequests = err?.name === 'SequelizeConnectionAcquireTimeoutError' && typeof (process as any)._getActiveRequests !== 'function'
267 ? (process as any)._getActiveRequests()
270 logger.error('Error in controller.', { err: error, sql, activeRequests })
273 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
274 message: err.message,
279 const server = createWebsocketTrackerServer(app)
281 // ----------- Run -----------
283 async function startApplication () {
284 const port = CONFIG.LISTEN.PORT
285 const hostname = CONFIG.LISTEN.HOSTNAME
287 await installApplication()
289 // Check activity pub urls are valid
290 checkActivityPubUrls()
292 logger.error('Error in ActivityPub URLs checker.', { err })
297 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
299 Redis.Instance.init()
300 Emailer.Instance.init()
303 Emailer.Instance.checkConnection(),
304 JobQueue.Instance.init(),
305 ServerConfigManager.Instance.init()
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)
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()
330 PeerTubeSocket.Instance.init(server)
331 VideoViewsManager.Instance.init()
333 updateStreamingPlaylistsInfohashesIfNeeded()
334 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
336 LiveManager.Instance.init()
337 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
339 // Make server listening
340 server.listen(port, hostname, async () => {
341 if (cliOptions.plugins) {
343 await PluginManager.Instance.rebuildNativePluginsIfNeeded()
345 await PluginManager.Instance.registerPluginsAndThemes()
347 logger.error('Cannot register plugins and themes.', { err })
351 ApplicationModel.updateNodeVersions()
352 .catch(err => logger.error('Cannot update node versions.', { err }))
354 logger.info('HTTP server listening on %s:%d', hostname, port)
355 logger.info('Web server: %s', WEBSERVER.URL)
357 Hooks.runAction('action:application.listening')
359 if (cliOptions['benchmarkStartup']) process.exit(0)
362 process.on('exit', () => {
363 JobQueue.Instance.terminate()
364 .catch(err => logger.error('Cannot terminate job queue.', { err }))
367 process.on('SIGINT', () => process.exit(0))