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'
47 // Trust our proxy (IP forwarding...)
48 app.set('trust proxy', CONFIG.TRUST_PROXY)
50 // Security middleware
51 import { baseCSP } from './server/middlewares/csp'
53 if (CONFIG.CSP.ENABLED) {
57 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
59 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
63 // ----------- Database -----------
65 // Initialize database and models
66 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
67 checkDatabaseConnectionOrDie()
69 import { migrate } from './server/initializers/migrator'
71 .then(() => initDatabaseModels(false))
72 .then(() => startApplication())
74 logger.error('Cannot start application.', { err })
78 // ----------- Initialize -----------
81 // ----------- PeerTube modules -----------
82 import { installApplication } from './server/initializers/installer'
83 import { Emailer } from './server/lib/emailer'
84 import { JobQueue } from './server/lib/job-queue'
85 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
98 createWebsocketTrackerServer,
101 } from './server/controllers'
102 import { advertiseDoNotTrack } from './server/middlewares/dnt'
103 import { apiFailMiddleware } from './server/middlewares/error'
104 import { Redis } from './server/lib/redis'
105 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
106 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
107 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
108 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
109 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
110 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
111 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
112 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
113 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
114 import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
115 import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
116 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
117 import { PeerTubeSocket } from './server/lib/peertube-socket'
118 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
119 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
120 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
121 import { Hooks } from './server/lib/plugins/hooks'
122 import { PluginManager } from './server/lib/plugins/plugin-manager'
123 import { LiveManager } from './server/lib/live'
124 import { HttpStatusCode } from './shared/models/http/http-error-codes'
125 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
126 import { ServerConfigManager } from '@server/lib/server-config-manager'
127 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
128 import { isTestInstance } from './server/helpers/core-utils'
130 // ----------- Command line -----------
133 .option('--no-client', 'Start PeerTube without client interface')
134 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
135 .option('--benchmark-startup', 'Automatically stop server when initialized')
138 // ----------- App -----------
140 // Enable CORS for develop
141 if (isTestInstance()) {
144 exposedHeaders: 'Retry-After',
150 token('remote-addr', (req: express.Request) => {
151 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
152 return anonymize(req.ip, 16, 16)
157 token('user-agent', (req: express.Request) => {
158 if (req.get('DNT') === '1') {
159 return parse(req.get('user-agent')).family
162 return req.get('user-agent')
164 app.use(morgan('combined', {
166 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
168 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
171 // Add .fail() helper to response
172 app.use(apiFailMiddleware)
175 app.use(express.urlencoded({ extended: false }))
176 app.use(express.json({
177 type: [ 'application/json', 'application/*+json' ],
179 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
180 const valid = isHTTPSignatureDigestValid(buf, req)
182 if (valid !== true) {
184 status: HttpStatusCode.FORBIDDEN_403,
185 message: 'Invalid digest'
192 app.use(cookieParser())
194 // W3C DNT Tracking Status
195 app.use(advertiseDoNotTrack)
197 // ----------- Views, routes and static files -----------
200 const apiRoute = '/api/' + API_VERSION
201 app.use(apiRoute, apiRouter)
203 // Services (oembed...)
204 app.use('/services', servicesRouter)
207 app.use('/live', liveRouter)
210 app.use('/', pluginsRouter)
212 app.use('/', activityPubRouter)
213 app.use('/', feedsRouter)
214 app.use('/', webfingerRouter)
215 app.use('/', trackerRouter)
216 app.use('/', botsRouter)
219 app.use('/', staticRouter)
220 app.use('/', downloadRouter)
221 app.use('/', lazyStaticRouter)
223 // Client files, last valid routes!
224 const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
225 if (cliOptions.client) app.use('/', clientsRouter)
227 // ----------- Errors -----------
229 // Catch unmatched routes
230 app.use((_req, res: express.Response) => {
231 res.status(HttpStatusCode.NOT_FOUND_404).end()
234 // Catch thrown errors
235 app.use((err, _req, res: express.Response, _next) => {
236 // Format error to be logged
237 let error = 'Unknown error.'
239 error = err.stack || err.message || err
241 // Handling Sequelize error traces
242 const sql = err.parent ? err.parent.sql : undefined
243 logger.error('Error in controller.', { err: error, sql })
246 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
247 message: err.message,
252 const server = createWebsocketTrackerServer(app)
254 // ----------- Run -----------
256 async function startApplication () {
257 const port = CONFIG.LISTEN.PORT
258 const hostname = CONFIG.LISTEN.HOSTNAME
260 await installApplication()
262 // Check activity pub urls are valid
263 checkActivityPubUrls()
265 logger.error('Error in ActivityPub URLs checker.', { err })
270 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
272 // Email initialization
273 Emailer.Instance.init()
276 Emailer.Instance.checkConnection(),
277 JobQueue.Instance.init(),
278 ServerConfigManager.Instance.init()
281 // Caches initializations
282 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
283 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
284 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
287 ActorFollowScheduler.Instance.enable()
288 RemoveOldJobsScheduler.Instance.enable()
289 UpdateVideosScheduler.Instance.enable()
290 YoutubeDlUpdateScheduler.Instance.enable()
291 VideosRedundancyScheduler.Instance.enable()
292 RemoveOldHistoryScheduler.Instance.enable()
293 RemoveOldViewsScheduler.Instance.enable()
294 PluginsCheckScheduler.Instance.enable()
295 PeerTubeVersionCheckScheduler.Instance.enable()
296 AutoFollowIndexInstances.Instance.enable()
297 RemoveDanglingResumableUploadsScheduler.Instance.enable()
298 VideoViewsBufferScheduler.Instance.enable()
299 GeoIPUpdateScheduler.Instance.enable()
301 Redis.Instance.init()
302 PeerTubeSocket.Instance.init(server)
303 VideoViewsManager.Instance.init()
305 updateStreamingPlaylistsInfohashesIfNeeded()
306 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
308 LiveManager.Instance.init()
309 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
311 // Make server listening
312 server.listen(port, hostname, async () => {
313 if (cliOptions.plugins) {
315 await PluginManager.Instance.registerPluginsAndThemes()
317 logger.error('Cannot register plugins and themes.', { err })
321 logger.info('HTTP server listening on %s:%d', hostname, port)
322 logger.info('Web server: %s', WEBSERVER.URL)
324 Hooks.runAction('action:application.listening')
326 if (cliOptions['benchmarkStartup']) process.exit(0)
329 process.on('exit', () => {
330 JobQueue.Instance.terminate()
333 process.on('SIGINT', () => process.exit(0))