1 import { registerTSPaths } from './server/helpers/register-ts-paths'
4 import { isTestInstance } from './server/helpers/core-utils'
5 if (isTestInstance()) {
6 require('source-map-support').install()
9 // ----------- Node modules -----------
10 import express from 'express'
11 import morgan, { token } from 'morgan'
12 import cors from 'cors'
13 import cookieParser from 'cookie-parser'
14 import { frameguard } from 'helmet'
15 import { parse } from 'useragent'
16 import anonymize from 'ip-anonymize'
17 import { program as cli } from 'commander'
19 process.title = 'peertube'
21 // Create our main app
22 const app = express().disable("x-powered-by")
24 // ----------- Core checker -----------
25 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
27 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
28 import { CONFIG } from './server/initializers/config'
29 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
30 import { logger } from './server/helpers/logger'
32 const missed = checkMissedConfig()
33 if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
40 logger.error('Error in ffmpeg check.', { err })
47 logger.error('Error in NodeJS check.', { err })
51 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
53 const errorMessage = checkConfig()
54 if (errorMessage !== null) {
55 throw new Error(errorMessage)
58 // Trust our proxy (IP forwarding...)
59 app.set('trust proxy', CONFIG.TRUST_PROXY)
61 // Security middleware
62 import { baseCSP } from './server/middlewares/csp'
64 if (CONFIG.CSP.ENABLED) {
68 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
70 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
74 // ----------- Database -----------
76 // Initialize database and models
77 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
78 checkDatabaseConnectionOrDie()
80 import { migrate } from './server/initializers/migrator'
82 .then(() => initDatabaseModels(false))
83 .then(() => startApplication())
85 logger.error('Cannot start application.', { err })
89 // ----------- Initialize -----------
92 // ----------- PeerTube modules -----------
93 import { installApplication } from './server/initializers/installer'
94 import { Emailer } from './server/lib/emailer'
95 import { JobQueue } from './server/lib/job-queue'
96 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 { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
127 import { PeerTubeSocket } from './server/lib/peertube-socket'
128 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
129 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
130 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
131 import { Hooks } from './server/lib/plugins/hooks'
132 import { PluginManager } from './server/lib/plugins/plugin-manager'
133 import { LiveManager } from './server/lib/live'
134 import { HttpStatusCode } from './shared/models/http/http-error-codes'
135 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
136 import { ServerConfigManager } from '@server/lib/server-config-manager'
137 import { VideoViews } from '@server/lib/video-views'
139 // ----------- Command line -----------
142 .option('--no-client', 'Start PeerTube without client interface')
143 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
144 .option('--benchmark-startup', 'Automatically stop server when initialized')
147 // ----------- App -----------
149 // Enable CORS for develop
150 if (isTestInstance()) {
153 exposedHeaders: 'Retry-After',
159 token('remote-addr', (req: express.Request) => {
160 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
161 return anonymize(req.ip, 16, 16)
166 token('user-agent', (req: express.Request) => {
167 if (req.get('DNT') === '1') {
168 return parse(req.get('user-agent')).family
171 return req.get('user-agent')
173 app.use(morgan('combined', {
175 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
177 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
180 // Add .fail() helper to response
181 app.use(apiFailMiddleware)
184 app.use(express.urlencoded({ extended: false }))
185 app.use(express.json({
186 type: [ 'application/json', 'application/*+json' ],
188 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
189 const valid = isHTTPSignatureDigestValid(buf, req)
191 if (valid !== true) {
193 status: HttpStatusCode.FORBIDDEN_403,
194 message: 'Invalid digest'
201 app.use(cookieParser())
203 // W3C DNT Tracking Status
204 app.use(advertiseDoNotTrack)
206 // ----------- Views, routes and static files -----------
209 const apiRoute = '/api/' + API_VERSION
210 app.use(apiRoute, apiRouter)
212 // Services (oembed...)
213 app.use('/services', servicesRouter)
216 app.use('/live', liveRouter)
219 app.use('/', pluginsRouter)
221 app.use('/', activityPubRouter)
222 app.use('/', feedsRouter)
223 app.use('/', webfingerRouter)
224 app.use('/', trackerRouter)
225 app.use('/', botsRouter)
228 app.use('/', staticRouter)
229 app.use('/', downloadRouter)
230 app.use('/', lazyStaticRouter)
232 // Client files, last valid routes!
233 const cliOptions = cli.opts()
234 if (cliOptions.client) app.use('/', clientsRouter)
236 // ----------- Errors -----------
238 // Catch unmatched routes
239 app.use((req, res: express.Response) => {
240 res.status(HttpStatusCode.NOT_FOUND_404).end()
243 // Catch thrown errors
244 app.use((err, req, res: express.Response, next) => {
245 // Format error to be logged
246 let error = 'Unknown error.'
248 error = err.stack || err.message || err
250 // Handling Sequelize error traces
251 const sql = err.parent ? err.parent.sql : undefined
252 logger.error('Error in controller.', { err: error, sql })
255 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
256 message: err.message,
261 const server = createWebsocketTrackerServer(app)
263 // ----------- Run -----------
265 async function startApplication () {
266 const port = CONFIG.LISTEN.PORT
267 const hostname = CONFIG.LISTEN.HOSTNAME
269 await installApplication()
271 // Check activity pub urls are valid
272 checkActivityPubUrls()
274 logger.error('Error in ActivityPub URLs checker.', { err })
279 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
281 // Email initialization
282 Emailer.Instance.init()
285 Emailer.Instance.checkConnection(),
286 JobQueue.Instance.init(),
287 ServerConfigManager.Instance.init()
290 // Caches initializations
291 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
292 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
293 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
296 ActorFollowScheduler.Instance.enable()
297 RemoveOldJobsScheduler.Instance.enable()
298 UpdateVideosScheduler.Instance.enable()
299 YoutubeDlUpdateScheduler.Instance.enable()
300 VideosRedundancyScheduler.Instance.enable()
301 RemoveOldHistoryScheduler.Instance.enable()
302 RemoveOldViewsScheduler.Instance.enable()
303 PluginsCheckScheduler.Instance.enable()
304 PeerTubeVersionCheckScheduler.Instance.enable()
305 AutoFollowIndexInstances.Instance.enable()
306 RemoveDanglingResumableUploadsScheduler.Instance.enable()
307 VideoViewsBufferScheduler.Instance.enable()
309 Redis.Instance.init()
310 PeerTubeSocket.Instance.init(server)
311 VideoViews.Instance.init()
313 updateStreamingPlaylistsInfohashesIfNeeded()
314 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
316 LiveManager.Instance.init()
317 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
319 // Make server listening
320 server.listen(port, hostname, async () => {
321 if (cliOptions.plugins) {
323 await PluginManager.Instance.registerPluginsAndThemes()
325 logger.error('Cannot register plugins and themes.', { err })
329 logger.info('HTTP server listening on %s:%d', hostname, port)
330 logger.info('Web server: %s', WEBSERVER.URL)
332 Hooks.runAction('action:application.listening')
334 if (cliOptions['benchmarkStartup']) process.exit(0)
337 process.on('exit', () => {
338 JobQueue.Instance.terminate()
341 process.on('SIGINT', () => process.exit(0))