1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { PluginManager } from './server/lib/plugins/plugin-manager'
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'
19 import * as useragent from 'useragent'
20 import * as anonymize from 'ip-anonymize'
21 import * as cli from 'commander'
23 process.title = 'peertube'
25 // Create our main app
28 // ----------- Core checker -----------
29 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
31 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
32 import { CONFIG } from './server/initializers/config'
33 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
34 import { logger } from './server/helpers/logger'
36 const missed = checkMissedConfig()
37 if (missed.length !== 0) {
38 logger.error('Your configuration files miss keys: ' + missed)
44 logger.error('Error in ffmpeg check.', { err })
50 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
52 const errorMessage = checkConfig()
53 if (errorMessage !== null) {
54 throw new Error(errorMessage)
57 // Trust our proxy (IP forwarding...)
58 app.set('trust proxy', CONFIG.TRUST_PROXY)
60 // Security middleware
61 import { baseCSP } from './server/middlewares/csp'
63 if (CONFIG.CSP.ENABLED) {
67 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
73 // ----------- Database -----------
75 // Initialize database and models
76 import { initDatabaseModels } from './server/initializers/database'
77 import { migrate } from './server/initializers/migrator'
79 .then(() => initDatabaseModels(false))
80 .then(() => startApplication())
82 logger.error('Cannot start application.', { err })
86 // ----------- Initialize -----------
89 // ----------- PeerTube modules -----------
90 import { installApplication } from './server/initializers'
91 import { Emailer } from './server/lib/emailer'
92 import { JobQueue } from './server/lib/job-queue'
93 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
105 createWebsocketTrackerServer, botsRouter
106 } from './server/controllers'
107 import { advertiseDoNotTrack } from './server/middlewares/dnt'
108 import { Redis } from './server/lib/redis'
109 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
110 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
111 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
112 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
113 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
114 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
115 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-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 { Hooks } from './server/lib/plugins/hooks'
122 // ----------- Command line -----------
125 .option('--no-client', 'Start PeerTube without client interface')
126 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
129 // ----------- App -----------
131 // Enable CORS for develop
132 if (isTestInstance()) {
135 exposedHeaders: 'Retry-After',
141 morgan.token('remote-addr', req => {
142 if (req.get('DNT') === '1') {
143 return anonymize(req.ip, 16, 16)
148 morgan.token('user-agent', req => {
149 if (req.get('DNT') === '1') {
150 return useragent.parse(req.get('user-agent')).family
153 return req.get('user-agent')
155 app.use(morgan('combined', {
156 stream: { write: logger.info.bind(logger) }
160 app.use(bodyParser.urlencoded({ extended: false }))
161 app.use(bodyParser.json({
162 type: [ 'application/json', 'application/*+json' ],
164 verify: (req: express.Request, _, buf: Buffer) => {
165 const valid = isHTTPSignatureDigestValid(buf, req)
166 if (valid !== true) throw new Error('Invalid digest')
171 app.use(cookieParser())
173 // W3C DNT Tracking Status
174 app.use(advertiseDoNotTrack)
176 // ----------- Views, routes and static files -----------
179 const apiRoute = '/api/' + API_VERSION
180 app.use(apiRoute, apiRouter)
182 // Services (oembed...)
183 app.use('/services', servicesRouter)
186 app.use('/', pluginsRouter)
188 app.use('/', activityPubRouter)
189 app.use('/', feedsRouter)
190 app.use('/', webfingerRouter)
191 app.use('/', trackerRouter)
192 app.use('/', botsRouter)
195 app.use('/', staticRouter)
196 app.use('/', lazyStaticRouter)
198 // Client files, last valid routes!
199 if (cli.client) app.use('/', clientsRouter)
201 // ----------- Errors -----------
203 // Catch 404 and forward to error handler
204 app.use(function (req, res, next) {
205 const err = new Error('Not Found')
210 app.use(function (err, req, res, next) {
211 let error = 'Unknown error.'
213 error = err.stack || err.message || err
217 const sql = err.parent ? err.parent.sql : undefined
219 logger.error('Error in controller.', { err: error, sql })
220 return res.status(err.status || 500).end()
223 const server = createWebsocketTrackerServer(app)
225 // ----------- Run -----------
227 async function startApplication () {
228 const port = CONFIG.LISTEN.PORT
229 const hostname = CONFIG.LISTEN.HOSTNAME
231 await installApplication()
233 // Check activity pub urls are valid
234 checkActivityPubUrls()
236 logger.error('Error in ActivityPub URLs checker.', { err })
240 // Email initialization
241 Emailer.Instance.init()
244 Emailer.Instance.checkConnectionOrDie(),
245 JobQueue.Instance.init()
248 // Caches initializations
249 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
250 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
253 ActorFollowScheduler.Instance.enable()
254 RemoveOldJobsScheduler.Instance.enable()
255 UpdateVideosScheduler.Instance.enable()
256 YoutubeDlUpdateScheduler.Instance.enable()
257 VideosRedundancyScheduler.Instance.enable()
258 RemoveOldHistoryScheduler.Instance.enable()
259 RemoveOldViewsScheduler.Instance.enable()
260 PluginsCheckScheduler.Instance.enable()
262 // Redis initialization
263 Redis.Instance.init()
265 PeerTubeSocket.Instance.init(server)
267 updateStreamingPlaylistsInfohashesIfNeeded()
268 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
270 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
272 // Make server listening
273 server.listen(port, hostname, () => {
274 logger.info('Server listening on %s:%d', hostname, port)
275 logger.info('Web server: %s', WEBSERVER.URL)
277 Hooks.runAction('action:application.listening')
280 process.on('exit', () => {
281 JobQueue.Instance.terminate()
284 process.on('SIGINT', () => process.exit(0))