1 require('module-alias/register')
3 // FIXME: https://github.com/nodejs/node/pull/16853
4 import { PluginManager } from './server/lib/plugins/plugin-manager'
6 require('tls').DEFAULT_ECDH_CURVE = 'auto'
8 import { isTestInstance } from './server/helpers/core-utils'
10 if (isTestInstance()) {
11 require('source-map-support').install()
14 // ----------- Node modules -----------
15 import * as bodyParser from 'body-parser'
16 import * as express from 'express'
17 import * as morgan from 'morgan'
18 import * as cors from 'cors'
19 import * as cookieParser from 'cookie-parser'
20 import * as helmet from 'helmet'
21 import * as useragent from 'useragent'
22 import * as anonymize from 'ip-anonymize'
23 import * as cli from 'commander'
25 process.title = 'peertube'
27 // Create our main app
30 // ----------- Core checker -----------
31 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
33 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
34 import { CONFIG } from './server/initializers/config'
35 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
36 import { logger } from './server/helpers/logger'
38 const missed = checkMissedConfig()
39 if (missed.length !== 0) {
40 logger.error('Your configuration files miss keys: ' + missed)
46 logger.error('Error in ffmpeg check.', { err })
52 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
54 const errorMessage = checkConfig()
55 if (errorMessage !== null) {
56 throw new Error(errorMessage)
59 // Trust our proxy (IP forwarding...)
60 app.set('trust proxy', CONFIG.TRUST_PROXY)
62 // Security middleware
63 import { baseCSP } from './server/middlewares/csp'
65 if (CONFIG.CSP.ENABLED) {
69 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
75 // ----------- Database -----------
77 // Initialize database and models
78 import { initDatabaseModels } from './server/initializers/database'
79 import { migrate } from './server/initializers/migrator'
81 .then(() => initDatabaseModels(false))
82 .then(() => startApplication())
84 logger.error('Cannot start application.', { err })
88 // ----------- Initialize -----------
91 // ----------- PeerTube modules -----------
92 import { installApplication } from './server/initializers'
93 import { Emailer } from './server/lib/emailer'
94 import { JobQueue } from './server/lib/job-queue'
95 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
107 createWebsocketTrackerServer, botsRouter
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 { Hooks } from './server/lib/plugins/hooks'
125 // ----------- Command line -----------
128 .option('--no-client', 'Start PeerTube without client interface')
129 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
132 // ----------- App -----------
134 // Enable CORS for develop
135 if (isTestInstance()) {
138 exposedHeaders: 'Retry-After',
144 morgan.token('remote-addr', req => {
145 if (req.get('DNT') === '1') {
146 return anonymize(req.ip, 16, 16)
151 morgan.token('user-agent', req => {
152 if (req.get('DNT') === '1') {
153 return useragent.parse(req.get('user-agent')).family
156 return req.get('user-agent')
158 app.use(morgan('combined', {
159 stream: { write: logger.info.bind(logger) }
163 app.use(bodyParser.urlencoded({ extended: false }))
164 app.use(bodyParser.json({
165 type: [ 'application/json', 'application/*+json' ],
167 verify: (req: express.Request, _, buf: Buffer) => {
168 const valid = isHTTPSignatureDigestValid(buf, req)
169 if (valid !== true) throw new Error('Invalid digest')
174 app.use(cookieParser())
176 // W3C DNT Tracking Status
177 app.use(advertiseDoNotTrack)
179 // ----------- Views, routes and static files -----------
182 const apiRoute = '/api/' + API_VERSION
183 app.use(apiRoute, apiRouter)
185 // Services (oembed...)
186 app.use('/services', servicesRouter)
189 app.use('/', pluginsRouter)
191 app.use('/', activityPubRouter)
192 app.use('/', feedsRouter)
193 app.use('/', webfingerRouter)
194 app.use('/', trackerRouter)
195 app.use('/', botsRouter)
198 app.use('/', staticRouter)
199 app.use('/', lazyStaticRouter)
201 // Client files, last valid routes!
202 if (cli.client) app.use('/', clientsRouter)
204 // ----------- Errors -----------
206 // Catch 404 and forward to error handler
207 app.use(function (req, res, next) {
208 const err = new Error('Not Found')
213 app.use(function (err, req, res, next) {
214 let error = 'Unknown error.'
216 error = err.stack || err.message || err
220 const sql = err.parent ? err.parent.sql : undefined
222 logger.error('Error in controller.', { err: error, sql })
223 return res.status(err.status || 500).end()
226 const server = createWebsocketTrackerServer(app)
228 // ----------- Run -----------
230 async function startApplication () {
231 const port = CONFIG.LISTEN.PORT
232 const hostname = CONFIG.LISTEN.HOSTNAME
234 await installApplication()
236 // Check activity pub urls are valid
237 checkActivityPubUrls()
239 logger.error('Error in ActivityPub URLs checker.', { err })
243 // Email initialization
244 Emailer.Instance.init()
247 Emailer.Instance.checkConnectionOrDie(),
248 JobQueue.Instance.init()
251 // Caches initializations
252 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
253 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
256 ActorFollowScheduler.Instance.enable()
257 RemoveOldJobsScheduler.Instance.enable()
258 UpdateVideosScheduler.Instance.enable()
259 YoutubeDlUpdateScheduler.Instance.enable()
260 VideosRedundancyScheduler.Instance.enable()
261 RemoveOldHistoryScheduler.Instance.enable()
262 RemoveOldViewsScheduler.Instance.enable()
263 PluginsCheckScheduler.Instance.enable()
264 AutoFollowIndexInstances.Instance.enable()
266 // Redis initialization
267 Redis.Instance.init()
269 PeerTubeSocket.Instance.init(server)
271 updateStreamingPlaylistsInfohashesIfNeeded()
272 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
274 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
276 // Make server listening
277 server.listen(port, hostname, () => {
278 logger.info('Server listening on %s:%d', hostname, port)
279 logger.info('Web server: %s', WEBSERVER.URL)
281 Hooks.runAction('action:application.listening')
284 process.on('exit', () => {
285 JobQueue.Instance.terminate()
288 process.on('SIGINT', () => process.exit(0))