1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { VideosCaptionCache } from './server/lib/cache/videos-caption-cache'
4 require('tls').DEFAULT_ECDH_CURVE = 'auto'
6 import { isTestInstance } from './server/helpers/core-utils'
8 if (isTestInstance()) {
9 require('source-map-support').install()
12 // ----------- Node modules -----------
13 import * as bodyParser from 'body-parser'
14 import * as express from 'express'
15 import * as morgan from 'morgan'
16 import * as cors from 'cors'
17 import * as cookieParser from 'cookie-parser'
18 import * as helmet from 'helmet'
20 process.title = 'peertube'
22 // Create our main app
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
28 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29 import { logger } from './server/helpers/logger'
30 import { API_VERSION, CONFIG, STATIC_PATHS, CACHE } from './server/initializers/constants'
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 })
44 const errorMessage = checkConfig()
45 if (errorMessage !== null) {
46 throw new Error(errorMessage)
49 // Trust our proxy (IP forwarding...)
50 app.set('trust proxy', CONFIG.TRUST_PROXY)
52 // Security middlewares
55 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
60 contentSecurityPolicy: {
64 mediaSrc: ['*', 'https:'],
65 objectSrc: ["'none'"],
66 scriptSrc: ["'self'"],
68 upgradeInsecureRequests: true
70 browserSniff: false // assumes a modern browser, but allows CDN in front
73 policy: 'strict-origin-when-cross-origin'
77 // ----------- Database -----------
79 // Initialize database and models
80 import { initDatabaseModels } from './server/initializers/database'
81 import { migrate } from './server/initializers/migrator'
83 .then(() => initDatabaseModels(false))
84 .then(() => startApplication())
86 logger.error('Cannot start application.', { err })
90 // ----------- PeerTube modules -----------
91 import { installApplication } from './server/initializers'
92 import { Emailer } from './server/lib/emailer'
93 import { JobQueue } from './server/lib/job-queue'
94 import { VideosPreviewCache } from './server/lib/cache'
104 createWebsocketServer
105 } from './server/controllers'
106 import { Redis } from './server/lib/redis'
107 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
108 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
109 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
111 // ----------- Command line -----------
113 // ----------- App -----------
115 // Enable CORS for develop
116 if (isTestInstance()) {
119 exposedHeaders: 'Retry-After',
125 app.use(morgan('combined', {
126 stream: { write: logger.info.bind(logger) }
129 app.use(bodyParser.urlencoded({ extended: false }))
130 app.use(bodyParser.json({
131 type: [ 'application/json', 'application/*+json' ],
135 app.use(cookieParser())
137 // ----------- Views, routes and static files -----------
140 const apiRoute = '/api/' + API_VERSION
141 app.use(apiRoute, apiRouter)
143 // Services (oembed...)
144 app.use('/services', servicesRouter)
146 app.use('/', activityPubRouter)
147 app.use('/', feedsRouter)
148 app.use('/', webfingerRouter)
149 app.use('/', trackerRouter)
152 app.use('/', staticRouter)
154 // Client files, last valid routes!
155 app.use('/', clientsRouter)
157 // ----------- Errors -----------
159 // Catch 404 and forward to error handler
160 app.use(function (req, res, next) {
161 const err = new Error('Not Found')
166 app.use(function (err, req, res, next) {
167 let error = 'Unknown error.'
169 error = err.stack || err.message || err
172 logger.error('Error in controller.', { error })
173 return res.status(err.status || 500).end()
176 const server = createWebsocketServer(app)
178 // ----------- Run -----------
180 async function startApplication () {
181 const port = CONFIG.LISTEN.PORT
182 const hostname = CONFIG.LISTEN.HOSTNAME
184 await installApplication()
186 // Check activity pub urls are valid
187 checkActivityPubUrls()
189 logger.error('Error in ActivityPub URLs checker.', { err })
193 // Email initialization
194 Emailer.Instance.init()
195 await Emailer.Instance.checkConnectionOrDie()
197 await JobQueue.Instance.init()
199 // Caches initializations
200 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
201 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
204 BadActorFollowScheduler.Instance.enable()
205 RemoveOldJobsScheduler.Instance.enable()
206 UpdateVideosScheduler.Instance.enable()
208 // Redis initialization
209 Redis.Instance.init()
211 // Make server listening
212 server.listen(port, hostname, () => {
213 logger.info('Server listening on %s:%d', hostname, port)
214 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)