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 } 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 })
48 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
50 const errorMessage = checkConfig()
51 if (errorMessage !== null) {
52 throw new Error(errorMessage)
55 // Trust our proxy (IP forwarding...)
56 app.set('trust proxy', CONFIG.TRUST_PROXY)
58 // Security middleware
59 import { baseCSP } from './server/middlewares/csp'
61 if (CONFIG.CSP.ENABLED) {
65 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
71 // ----------- Database -----------
73 // Initialize database and models
74 import { initDatabaseModels } from './server/initializers/database'
75 import { migrate } from './server/initializers/migrator'
77 .then(() => initDatabaseModels(false))
78 .then(() => startApplication())
80 logger.error('Cannot start application.', { err })
84 // ----------- Initialize -----------
87 // ----------- PeerTube modules -----------
88 import { installApplication } from './server/initializers'
89 import { Emailer } from './server/lib/emailer'
90 import { JobQueue } from './server/lib/job-queue'
91 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
102 createWebsocketTrackerServer, botsRouter
103 } from './server/controllers'
104 import { advertiseDoNotTrack } from './server/middlewares/dnt'
105 import { Redis } from './server/lib/redis'
106 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
107 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
108 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
109 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
110 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
111 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
112 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
113 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
114 import { PeerTubeSocket } from './server/lib/peertube-socket'
115 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
116 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
117 import { Hooks } from './server/lib/plugins/hooks'
119 // ----------- Command line -----------
122 .option('--no-client', 'Start PeerTube without client interface')
123 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
126 // ----------- App -----------
128 // Enable CORS for develop
129 if (isTestInstance()) {
132 exposedHeaders: 'Retry-After',
138 morgan.token('remote-addr', req => {
139 if (req.get('DNT') === '1') {
140 return anonymize(req.ip, 16, 16)
145 morgan.token('user-agent', req => {
146 if (req.get('DNT') === '1') {
147 return useragent.parse(req.get('user-agent')).family
150 return req.get('user-agent')
152 app.use(morgan('combined', {
153 stream: { write: logger.info.bind(logger) }
157 app.use(bodyParser.urlencoded({ extended: false }))
158 app.use(bodyParser.json({
159 type: [ 'application/json', 'application/*+json' ],
161 verify: (req: express.Request, _, buf: Buffer) => {
162 const valid = isHTTPSignatureDigestValid(buf, req)
163 if (valid !== true) throw new Error('Invalid digest')
168 app.use(cookieParser())
170 // W3C DNT Tracking Status
171 app.use(advertiseDoNotTrack)
173 // ----------- Views, routes and static files -----------
176 const apiRoute = '/api/' + API_VERSION
177 app.use(apiRoute, apiRouter)
179 // Services (oembed...)
180 app.use('/services', servicesRouter)
183 app.use('/', pluginsRouter)
185 app.use('/', activityPubRouter)
186 app.use('/', feedsRouter)
187 app.use('/', webfingerRouter)
188 app.use('/', trackerRouter)
189 app.use('/', botsRouter)
192 app.use('/', staticRouter)
194 // Client files, last valid routes!
195 if (cli.client) app.use('/', clientsRouter)
197 // ----------- Errors -----------
199 // Catch 404 and forward to error handler
200 app.use(function (req, res, next) {
201 const err = new Error('Not Found')
206 app.use(function (err, req, res, next) {
207 let error = 'Unknown error.'
209 error = err.stack || err.message || err
213 const sql = err.parent ? err.parent.sql : undefined
215 logger.error('Error in controller.', { err: error, sql })
216 return res.status(err.status || 500).end()
219 const server = createWebsocketTrackerServer(app)
221 // ----------- Run -----------
223 async function startApplication () {
224 const port = CONFIG.LISTEN.PORT
225 const hostname = CONFIG.LISTEN.HOSTNAME
227 await installApplication()
229 // Check activity pub urls are valid
230 checkActivityPubUrls()
232 logger.error('Error in ActivityPub URLs checker.', { err })
236 // Email initialization
237 Emailer.Instance.init()
240 Emailer.Instance.checkConnectionOrDie(),
241 JobQueue.Instance.init()
244 // Caches initializations
245 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
246 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
249 ActorFollowScheduler.Instance.enable()
250 RemoveOldJobsScheduler.Instance.enable()
251 UpdateVideosScheduler.Instance.enable()
252 YoutubeDlUpdateScheduler.Instance.enable()
253 VideosRedundancyScheduler.Instance.enable()
254 RemoveOldHistoryScheduler.Instance.enable()
255 RemoveOldViewsScheduler.Instance.enable()
256 PluginsCheckScheduler.Instance.enable()
258 // Redis initialization
259 Redis.Instance.init()
261 PeerTubeSocket.Instance.init(server)
263 updateStreamingPlaylistsInfohashesIfNeeded()
264 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
266 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
268 // Make server listening
269 server.listen(port, hostname, () => {
270 logger.info('Server listening on %s:%d', hostname, port)
271 logger.info('Web server: %s', WEBSERVER.URL)
273 Hooks.runAction('action:application.listening')
276 process.on('exit', () => {
277 JobQueue.Instance.terminate()
280 process.on('SIGINT', () => process.exit(0))