1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
4 import { isTestInstance } from './server/helpers/core-utils'
6 if (isTestInstance()) {
7 require('source-map-support').install()
10 // ----------- Node modules -----------
11 import * as bodyParser from 'body-parser'
12 import * as express from 'express'
13 import * as morgan from 'morgan'
14 import * as cors from 'cors'
15 import * as cookieParser from 'cookie-parser'
16 import * as helmet from 'helmet'
17 import * as useragent from 'useragent'
18 import * as anonymize from 'ip-anonymize'
19 import * as cli from 'commander'
21 process.title = 'peertube'
23 // Create our main app
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
29 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30 import { logger } from './server/helpers/logger'
31 import { API_VERSION, CONFIG, CACHE, HTTP_SIGNATURE } from './server/initializers/constants'
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 })
45 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49 throw new Error(errorMessage)
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
55 // Security middleware
58 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
63 // ----------- Database -----------
65 // Initialize database and models
66 import { initDatabaseModels } from './server/initializers/database'
67 import { migrate } from './server/initializers/migrator'
69 .then(() => initDatabaseModels(false))
70 .then(() => startApplication())
72 logger.error('Cannot start application.', { err })
76 // ----------- PeerTube modules -----------
77 import { installApplication } from './server/initializers'
78 import { Emailer } from './server/lib/emailer'
79 import { JobQueue } from './server/lib/job-queue'
80 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
91 } from './server/controllers'
92 import { advertiseDoNotTrack } from './server/middlewares/dnt'
93 import { Redis } from './server/lib/redis'
94 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
95 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
96 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
97 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
98 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
99 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
101 // ----------- Command line -----------
104 .option('--no-client', 'Start PeerTube without client interface')
107 // ----------- App -----------
109 // Enable CORS for develop
110 if (isTestInstance()) {
113 exposedHeaders: 'Retry-After',
118 morgan.token('remote-addr', req => {
119 return (req.get('DNT') === '1') ?
120 anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
121 16, // bitmask for IPv4
122 16 // bitmask for IPv6
126 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
127 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
128 app.use(morgan('combined', {
129 stream: { write: logger.info.bind(logger) }
132 app.use(bodyParser.urlencoded({ extended: false }))
133 app.use(bodyParser.json({
134 type: [ 'application/json', 'application/*+json' ],
136 verify: (req: express.Request, _, buf: Buffer, encoding: string) => {
137 const valid = isHTTPSignatureDigestValid(buf, req)
138 if (valid !== true) throw new Error('Invalid digest')
142 app.use(cookieParser())
143 // W3C DNT Tracking Status
144 app.use(advertiseDoNotTrack)
146 // ----------- Views, routes and static files -----------
149 const apiRoute = '/api/' + API_VERSION
150 app.use(apiRoute, apiRouter)
152 // Services (oembed...)
153 app.use('/services', servicesRouter)
155 app.use('/', activityPubRouter)
156 app.use('/', feedsRouter)
157 app.use('/', webfingerRouter)
158 app.use('/', trackerRouter)
161 app.use('/', staticRouter)
163 // Client files, last valid routes!
164 if (cli.client) app.use('/', clientsRouter)
166 // ----------- Errors -----------
168 // Catch 404 and forward to error handler
169 app.use(function (req, res, next) {
170 const err = new Error('Not Found')
175 app.use(function (err, req, res, next) {
176 let error = 'Unknown error.'
178 error = err.stack || err.message || err
182 const sql = err.parent ? err.parent.sql : undefined
184 logger.error('Error in controller.', { err: error, sql })
185 return res.status(err.status || 500).end()
188 const server = createWebsocketServer(app)
190 // ----------- Run -----------
192 async function startApplication () {
193 const port = CONFIG.LISTEN.PORT
194 const hostname = CONFIG.LISTEN.HOSTNAME
196 await installApplication()
198 // Check activity pub urls are valid
199 checkActivityPubUrls()
201 logger.error('Error in ActivityPub URLs checker.', { err })
205 // Email initialization
206 Emailer.Instance.init()
207 await Emailer.Instance.checkConnectionOrDie()
209 await JobQueue.Instance.init()
211 // Caches initializations
212 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
213 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
216 BadActorFollowScheduler.Instance.enable()
217 RemoveOldJobsScheduler.Instance.enable()
218 UpdateVideosScheduler.Instance.enable()
219 YoutubeDlUpdateScheduler.Instance.enable()
220 VideosRedundancyScheduler.Instance.enable()
222 // Redis initialization
223 Redis.Instance.init()
225 // Make server listening
226 server.listen(port, hostname, () => {
227 logger.info('Server listening on %s:%d', hostname, port)
228 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
231 process.on('exit', () => {
232 JobQueue.Instance.terminate()
235 process.on('SIGINT', () => process.exit(0))