1 // ----------- Node modules -----------
2 import express from 'express'
3 import morgan, { token } from 'morgan'
4 import cors from 'cors'
5 import cookieParser from 'cookie-parser'
6 import { frameguard } from 'helmet'
7 import { parse } from 'useragent'
8 import anonymize from 'ip-anonymize'
9 import { program as cli } from 'commander'
11 process.title = 'peertube'
13 // Create our main app
14 const app = express().disable('x-powered-by')
16 // ----------- Core checker -----------
17 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
19 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
20 import { CONFIG } from './server/initializers/config'
21 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
22 import { logger } from './server/helpers/logger'
24 const missed = checkMissedConfig()
25 if (missed.length !== 0) {
26 logger.error('Your configuration files miss keys: ' + missed)
32 logger.error('Error in ffmpeg check.', { err })
39 logger.error('Error in NodeJS check.', { err })
43 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
45 const errorMessage = checkConfig()
46 if (errorMessage !== null) {
47 throw new Error(errorMessage)
50 // Trust our proxy (IP forwarding...)
51 app.set('trust proxy', CONFIG.TRUST_PROXY)
53 // Security middleware
54 import { baseCSP } from './server/middlewares/csp'
56 if (CONFIG.CSP.ENABLED) {
60 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
62 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
66 // ----------- Database -----------
68 // Initialize database and models
69 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
70 checkDatabaseConnectionOrDie()
72 import { migrate } from './server/initializers/migrator'
74 .then(() => initDatabaseModels(false))
75 .then(() => startApplication())
77 logger.error('Cannot start application.', { err })
81 // ----------- Initialize -----------
84 // ----------- PeerTube modules -----------
85 import { installApplication } from './server/initializers/installer'
86 import { Emailer } from './server/lib/emailer'
87 import { JobQueue } from './server/lib/job-queue'
88 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
101 createWebsocketTrackerServer,
104 } from './server/controllers'
105 import { advertiseDoNotTrack } from './server/middlewares/dnt'
106 import { apiFailMiddleware } from './server/middlewares/error'
107 import { Redis } from './server/lib/redis'
108 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
109 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
110 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
111 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
112 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
113 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
114 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
115 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
116 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
117 import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
118 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
119 import { PeerTubeSocket } from './server/lib/peertube-socket'
120 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
121 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
122 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
123 import { Hooks } from './server/lib/plugins/hooks'
124 import { PluginManager } from './server/lib/plugins/plugin-manager'
125 import { LiveManager } from './server/lib/live'
126 import { HttpStatusCode } from './shared/models/http/http-error-codes'
127 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
128 import { ServerConfigManager } from '@server/lib/server-config-manager'
129 import { VideoViews } from '@server/lib/video-views'
130 import { isTestInstance } from './server/helpers/core-utils'
132 // ----------- Command line -----------
135 .option('--no-client', 'Start PeerTube without client interface')
136 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
137 .option('--benchmark-startup', 'Automatically stop server when initialized')
140 // ----------- App -----------
142 // Enable CORS for develop
143 if (isTestInstance()) {
146 exposedHeaders: 'Retry-After',
152 token('remote-addr', (req: express.Request) => {
153 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
154 return anonymize(req.ip, 16, 16)
159 token('user-agent', (req: express.Request) => {
160 if (req.get('DNT') === '1') {
161 return parse(req.get('user-agent')).family
164 return req.get('user-agent')
166 app.use(morgan('combined', {
168 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
170 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
173 // Add .fail() helper to response
174 app.use(apiFailMiddleware)
177 app.use(express.urlencoded({ extended: false }))
178 app.use(express.json({
179 type: [ 'application/json', 'application/*+json' ],
181 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
182 const valid = isHTTPSignatureDigestValid(buf, req)
184 if (valid !== true) {
186 status: HttpStatusCode.FORBIDDEN_403,
187 message: 'Invalid digest'
194 app.use(cookieParser())
196 // W3C DNT Tracking Status
197 app.use(advertiseDoNotTrack)
199 // ----------- Views, routes and static files -----------
202 const apiRoute = '/api/' + API_VERSION
203 app.use(apiRoute, apiRouter)
205 // Services (oembed...)
206 app.use('/services', servicesRouter)
209 app.use('/live', liveRouter)
212 app.use('/', pluginsRouter)
214 app.use('/', activityPubRouter)
215 app.use('/', feedsRouter)
216 app.use('/', webfingerRouter)
217 app.use('/', trackerRouter)
218 app.use('/', botsRouter)
221 app.use('/', staticRouter)
222 app.use('/', downloadRouter)
223 app.use('/', lazyStaticRouter)
225 // Client files, last valid routes!
226 const cliOptions = cli.opts()
227 if (cliOptions.client) app.use('/', clientsRouter)
229 // ----------- Errors -----------
231 // Catch unmatched routes
232 app.use((req, res: express.Response) => {
233 res.status(HttpStatusCode.NOT_FOUND_404).end()
236 // Catch thrown errors
237 app.use((err, req, res: express.Response, next) => {
238 // Format error to be logged
239 let error = 'Unknown error.'
241 error = err.stack || err.message || err
243 // Handling Sequelize error traces
244 const sql = err.parent ? err.parent.sql : undefined
245 logger.error('Error in controller.', { err: error, sql })
248 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
249 message: err.message,
254 const server = createWebsocketTrackerServer(app)
256 // ----------- Run -----------
258 async function startApplication () {
259 const port = CONFIG.LISTEN.PORT
260 const hostname = CONFIG.LISTEN.HOSTNAME
262 await installApplication()
264 // Check activity pub urls are valid
265 checkActivityPubUrls()
267 logger.error('Error in ActivityPub URLs checker.', { err })
272 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
274 // Email initialization
275 Emailer.Instance.init()
278 Emailer.Instance.checkConnection(),
279 JobQueue.Instance.init(),
280 ServerConfigManager.Instance.init()
283 // Caches initializations
284 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
285 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
286 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
289 ActorFollowScheduler.Instance.enable()
290 RemoveOldJobsScheduler.Instance.enable()
291 UpdateVideosScheduler.Instance.enable()
292 YoutubeDlUpdateScheduler.Instance.enable()
293 VideosRedundancyScheduler.Instance.enable()
294 RemoveOldHistoryScheduler.Instance.enable()
295 RemoveOldViewsScheduler.Instance.enable()
296 PluginsCheckScheduler.Instance.enable()
297 PeerTubeVersionCheckScheduler.Instance.enable()
298 AutoFollowIndexInstances.Instance.enable()
299 RemoveDanglingResumableUploadsScheduler.Instance.enable()
300 VideoViewsBufferScheduler.Instance.enable()
302 Redis.Instance.init()
303 PeerTubeSocket.Instance.init(server)
304 VideoViews.Instance.init()
306 updateStreamingPlaylistsInfohashesIfNeeded()
307 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
309 LiveManager.Instance.init()
310 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
312 // Make server listening
313 server.listen(port, hostname, async () => {
314 if (cliOptions.plugins) {
316 await PluginManager.Instance.registerPluginsAndThemes()
318 logger.error('Cannot register plugins and themes.', { err })
322 logger.info('HTTP server listening on %s:%d', hostname, port)
323 logger.info('Web server: %s', WEBSERVER.URL)
325 Hooks.runAction('action:application.listening')
327 if (cliOptions['benchmarkStartup']) process.exit(0)
330 process.on('exit', () => {
331 JobQueue.Instance.terminate()
334 process.on('SIGINT', () => process.exit(0))