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 * as bodyParser from 'body-parser'
11 import * as express from 'express'
12 import * as morgan from 'morgan'
13 import * as cors from 'cors'
14 import * as cookieParser from 'cookie-parser'
15 import * as helmet from 'helmet'
16 import * as useragent from 'useragent'
17 import * as anonymize from 'ip-anonymize'
18 import * as cli from 'commander'
20 process.title = 'peertube'
22 // Create our main app
23 const app = express().disable("x-powered-by")
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
28 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29 import { CONFIG } from './server/initializers/config'
30 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
31 import { logger } from './server/helpers/logger'
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35 logger.error('Your configuration files miss keys: ' + missed)
41 logger.error('Error in ffmpeg check.', { err })
47 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
49 const errorMessage = checkConfig()
50 if (errorMessage !== null) {
51 throw new Error(errorMessage)
54 // Trust our proxy (IP forwarding...)
55 app.set('trust proxy', CONFIG.TRUST_PROXY)
57 // Security middleware
58 import { baseCSP } from './server/middlewares/csp'
60 if (CONFIG.CSP.ENABLED) {
64 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
65 app.use(helmet.frameguard({
66 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
70 // ----------- Database -----------
72 // Initialize database and models
73 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
74 checkDatabaseConnectionOrDie()
76 import { migrate } from './server/initializers/migrator'
78 .then(() => initDatabaseModels(false))
79 .then(() => startApplication())
81 logger.error('Cannot start application.', { err })
85 // ----------- Initialize -----------
88 // ----------- PeerTube modules -----------
89 import { installApplication } from './server/initializers/installer'
90 import { Emailer } from './server/lib/emailer'
91 import { JobQueue } from './server/lib/job-queue'
92 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
105 createWebsocketTrackerServer,
108 } from './server/controllers'
109 import { advertiseDoNotTrack } from './server/middlewares/dnt'
110 import { Redis } from './server/lib/redis'
111 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
112 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
113 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
114 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
115 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
116 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
117 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
118 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
119 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
120 import { PeerTubeSocket } from './server/lib/peertube-socket'
121 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
122 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
123 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
124 import { Hooks } from './server/lib/plugins/hooks'
125 import { PluginManager } from './server/lib/plugins/plugin-manager'
126 import { LiveManager } from './server/lib/live-manager'
127 import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes'
128 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
130 // ----------- Command line -----------
133 .option('--no-client', 'Start PeerTube without client interface')
134 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
137 // ----------- App -----------
139 // Enable CORS for develop
140 if (isTestInstance()) {
143 exposedHeaders: 'Retry-After',
149 morgan.token('remote-addr', (req: express.Request) => {
150 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
151 return anonymize(req.ip, 16, 16)
156 morgan.token('user-agent', (req: express.Request) => {
157 if (req.get('DNT') === '1') {
158 return useragent.parse(req.get('user-agent')).family
161 return req.get('user-agent')
163 app.use(morgan('combined', {
165 write: (str: string) => logger.info(str, { tags: [ 'http' ] })
167 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
171 app.use(bodyParser.urlencoded({ extended: false }))
172 app.use(bodyParser.json({
173 type: [ 'application/json', 'application/*+json' ],
175 verify: (req: express.Request, _, buf: Buffer) => {
176 const valid = isHTTPSignatureDigestValid(buf, req)
177 if (valid !== true) throw new Error('Invalid digest')
182 app.use(cookieParser())
184 // W3C DNT Tracking Status
185 app.use(advertiseDoNotTrack)
187 // ----------- Views, routes and static files -----------
190 const apiRoute = '/api/' + API_VERSION
191 app.use(apiRoute, apiRouter)
193 // Services (oembed...)
194 app.use('/services', servicesRouter)
197 app.use('/live', liveRouter)
200 app.use('/', pluginsRouter)
202 app.use('/', activityPubRouter)
203 app.use('/', feedsRouter)
204 app.use('/', webfingerRouter)
205 app.use('/', trackerRouter)
206 app.use('/', botsRouter)
209 app.use('/', staticRouter)
210 app.use('/', downloadRouter)
211 app.use('/', lazyStaticRouter)
213 // Client files, last valid routes!
214 const cliOptions = cli.opts()
215 if (cliOptions.client) app.use('/', clientsRouter)
217 // ----------- Errors -----------
219 // Catch 404 and forward to error handler
220 app.use(function (req, res, next) {
221 const err = new Error('Not Found')
222 err['status'] = HttpStatusCode.NOT_FOUND_404
226 app.use(function (err, req, res, next) {
227 let error = 'Unknown error.'
229 error = err.stack || err.message || err
233 const sql = err.parent ? err.parent.sql : undefined
235 logger.error('Error in controller.', { err: error, sql })
236 return res.status(err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
239 const server = createWebsocketTrackerServer(app)
241 // ----------- Run -----------
243 async function startApplication () {
244 const port = CONFIG.LISTEN.PORT
245 const hostname = CONFIG.LISTEN.HOSTNAME
247 await installApplication()
249 // Check activity pub urls are valid
250 checkActivityPubUrls()
252 logger.error('Error in ActivityPub URLs checker.', { err })
257 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
259 // Email initialization
260 Emailer.Instance.init()
263 Emailer.Instance.checkConnection(),
264 JobQueue.Instance.init()
267 // Caches initializations
268 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
269 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
270 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
273 ActorFollowScheduler.Instance.enable()
274 RemoveOldJobsScheduler.Instance.enable()
275 UpdateVideosScheduler.Instance.enable()
276 YoutubeDlUpdateScheduler.Instance.enable()
277 VideosRedundancyScheduler.Instance.enable()
278 RemoveOldHistoryScheduler.Instance.enable()
279 RemoveOldViewsScheduler.Instance.enable()
280 PluginsCheckScheduler.Instance.enable()
281 PeerTubeVersionCheckScheduler.Instance.enable()
282 AutoFollowIndexInstances.Instance.enable()
284 // Redis initialization
285 Redis.Instance.init()
287 PeerTubeSocket.Instance.init(server)
289 updateStreamingPlaylistsInfohashesIfNeeded()
290 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
292 if (cliOptions.plugins) await PluginManager.Instance.registerPluginsAndThemes()
294 LiveManager.Instance.init()
295 if (CONFIG.LIVE.ENABLED) LiveManager.Instance.run()
297 // Make server listening
298 server.listen(port, hostname, () => {
299 logger.info('HTTP server listening on %s:%d', hostname, port)
300 logger.info('Web server: %s', WEBSERVER.URL)
302 Hooks.runAction('action:application.listening')
305 process.on('exit', () => {
306 JobQueue.Instance.terminate()
309 process.on('SIGINT', () => process.exit(0))