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 } 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
56 import { baseCSP } from './server/middlewares'
61 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
66 // ----------- Database -----------
68 // Initialize database and models
69 import { initDatabaseModels } from './server/initializers/database'
70 import { migrate } from './server/initializers/migrator'
72 .then(() => initDatabaseModels(false))
73 .then(() => startApplication())
75 logger.error('Cannot start application.', { err })
79 // ----------- PeerTube modules -----------
80 import { installApplication } from './server/initializers'
81 import { Emailer } from './server/lib/emailer'
82 import { JobQueue } from './server/lib/job-queue'
83 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
93 createWebsocketTrackerServer, botsRouter
94 } from './server/controllers'
95 import { advertiseDoNotTrack } from './server/middlewares/dnt'
96 import { Redis } from './server/lib/redis'
97 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
98 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
99 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
100 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
101 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
102 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
103 import { PeerTubeSocket } from './server/lib/peertube-socket'
105 // ----------- Command line -----------
108 .option('--no-client', 'Start PeerTube without client interface')
111 // ----------- App -----------
113 // Enable CORS for develop
114 if (isTestInstance()) {
117 exposedHeaders: 'Retry-After',
122 morgan.token('remote-addr', req => {
123 return (req.get('DNT') === '1') ?
124 anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
125 16, // bitmask for IPv4
126 16 // bitmask for IPv6
130 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
131 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
132 app.use(morgan('combined', {
133 stream: { write: logger.info.bind(logger) }
136 app.use(bodyParser.urlencoded({ extended: false }))
137 app.use(bodyParser.json({
138 type: [ 'application/json', 'application/*+json' ],
140 verify: (req: express.Request, _, buf: Buffer) => {
141 const valid = isHTTPSignatureDigestValid(buf, req)
142 if (valid !== true) throw new Error('Invalid digest')
146 app.use(cookieParser())
147 // W3C DNT Tracking Status
148 app.use(advertiseDoNotTrack)
150 // ----------- Views, routes and static files -----------
153 const apiRoute = '/api/' + API_VERSION
154 app.use(apiRoute, apiRouter)
156 // Services (oembed...)
157 app.use('/services', servicesRouter)
159 app.use('/', activityPubRouter)
160 app.use('/', feedsRouter)
161 app.use('/', webfingerRouter)
162 app.use('/', trackerRouter)
163 app.use('/', botsRouter)
166 app.use('/', staticRouter)
168 // Client files, last valid routes!
169 if (cli.client) app.use('/', clientsRouter)
171 // ----------- Errors -----------
173 // Catch 404 and forward to error handler
174 app.use(function (req, res, next) {
175 const err = new Error('Not Found')
180 app.use(function (err, req, res, next) {
181 let error = 'Unknown error.'
183 error = err.stack || err.message || err
187 const sql = err.parent ? err.parent.sql : undefined
189 logger.error('Error in controller.', { err: error, sql })
190 return res.status(err.status || 500).end()
193 const server = createWebsocketTrackerServer(app)
195 // ----------- Run -----------
197 async function startApplication () {
198 const port = CONFIG.LISTEN.PORT
199 const hostname = CONFIG.LISTEN.HOSTNAME
201 await installApplication()
203 // Check activity pub urls are valid
204 checkActivityPubUrls()
206 logger.error('Error in ActivityPub URLs checker.', { err })
210 // Email initialization
211 Emailer.Instance.init()
214 Emailer.Instance.checkConnectionOrDie(),
215 JobQueue.Instance.init()
218 // Caches initializations
219 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
220 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
223 ActorFollowScheduler.Instance.enable()
224 RemoveOldJobsScheduler.Instance.enable()
225 UpdateVideosScheduler.Instance.enable()
226 YoutubeDlUpdateScheduler.Instance.enable()
227 VideosRedundancyScheduler.Instance.enable()
229 // Redis initialization
230 Redis.Instance.init()
232 PeerTubeSocket.Instance.init(server)
234 // Make server listening
235 server.listen(port, hostname, () => {
236 logger.info('Server listening on %s:%d', hostname, port)
237 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
240 process.on('exit', () => {
241 JobQueue.Instance.terminate()
244 process.on('SIGINT', () => process.exit(0))