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, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
32 import { CONFIG } from './server/initializers/config'
34 const missed = checkMissedConfig()
35 if (missed.length !== 0) {
36 logger.error('Your configuration files miss keys: ' + missed)
42 logger.error('Error in ffmpeg check.', { err })
46 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
48 const errorMessage = checkConfig()
49 if (errorMessage !== null) {
50 throw new Error(errorMessage)
53 // Trust our proxy (IP forwarding...)
54 app.set('trust proxy', CONFIG.TRUST_PROXY)
56 // Security middleware
57 import { baseCSP } from './server/middlewares/csp'
59 if (CONFIG.CSP.ENABLED) {
63 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
69 // ----------- Database -----------
71 // Initialize database and models
72 import { initDatabaseModels } from './server/initializers/database'
73 import { migrate } from './server/initializers/migrator'
75 .then(() => initDatabaseModels(false))
76 .then(() => startApplication())
78 logger.error('Cannot start application.', { err })
82 // ----------- Initialize -----------
85 // ----------- PeerTube modules -----------
86 import { installApplication } from './server/initializers'
87 import { Emailer } from './server/lib/emailer'
88 import { JobQueue } from './server/lib/job-queue'
89 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
99 createWebsocketTrackerServer, botsRouter
100 } from './server/controllers'
101 import { advertiseDoNotTrack } from './server/middlewares/dnt'
102 import { Redis } from './server/lib/redis'
103 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
104 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
105 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
106 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
107 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
108 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
109 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
110 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
111 import { PeerTubeSocket } from './server/lib/peertube-socket'
112 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
114 // ----------- Command line -----------
117 .option('--no-client', 'Start PeerTube without client interface')
120 // ----------- App -----------
122 // Enable CORS for develop
123 if (isTestInstance()) {
126 exposedHeaders: 'Retry-After',
132 morgan.token('remote-addr', req => {
133 if (req.get('DNT') === '1') {
134 return anonymize(req.ip, 16, 16)
139 morgan.token('user-agent', req => {
140 if (req.get('DNT') === '1') {
141 return useragent.parse(req.get('user-agent')).family
144 return req.get('user-agent')
146 app.use(morgan('combined', {
147 stream: { write: logger.info.bind(logger) }
151 app.use(bodyParser.urlencoded({ extended: false }))
152 app.use(bodyParser.json({
153 type: [ 'application/json', 'application/*+json' ],
155 verify: (req: express.Request, _, buf: Buffer) => {
156 const valid = isHTTPSignatureDigestValid(buf, req)
157 if (valid !== true) throw new Error('Invalid digest')
162 app.use(cookieParser())
164 // W3C DNT Tracking Status
165 app.use(advertiseDoNotTrack)
167 // ----------- Views, routes and static files -----------
170 const apiRoute = '/api/' + API_VERSION
171 app.use(apiRoute, apiRouter)
173 // Services (oembed...)
174 app.use('/services', servicesRouter)
176 app.use('/', activityPubRouter)
177 app.use('/', feedsRouter)
178 app.use('/', webfingerRouter)
179 app.use('/', trackerRouter)
180 app.use('/', botsRouter)
183 app.use('/', staticRouter)
185 // Client files, last valid routes!
186 if (cli.client) app.use('/', clientsRouter)
188 // ----------- Errors -----------
190 // Catch 404 and forward to error handler
191 app.use(function (req, res, next) {
192 const err = new Error('Not Found')
197 app.use(function (err, req, res, next) {
198 let error = 'Unknown error.'
200 error = err.stack || err.message || err
204 const sql = err.parent ? err.parent.sql : undefined
206 logger.error('Error in controller.', { err: error, sql })
207 return res.status(err.status || 500).end()
210 const server = createWebsocketTrackerServer(app)
212 // ----------- Run -----------
214 async function startApplication () {
215 const port = CONFIG.LISTEN.PORT
216 const hostname = CONFIG.LISTEN.HOSTNAME
218 await installApplication()
220 // Check activity pub urls are valid
221 checkActivityPubUrls()
223 logger.error('Error in ActivityPub URLs checker.', { err })
227 // Email initialization
228 Emailer.Instance.init()
231 Emailer.Instance.checkConnectionOrDie(),
232 JobQueue.Instance.init()
235 // Caches initializations
236 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
237 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
240 ActorFollowScheduler.Instance.enable()
241 RemoveOldJobsScheduler.Instance.enable()
242 UpdateVideosScheduler.Instance.enable()
243 YoutubeDlUpdateScheduler.Instance.enable()
244 VideosRedundancyScheduler.Instance.enable()
245 RemoveOldHistoryScheduler.Instance.enable()
246 RemoveOldViewsScheduler.Instance.enable()
248 // Redis initialization
249 Redis.Instance.init()
251 PeerTubeSocket.Instance.init(server)
253 updateStreamingPlaylistsInfohashesIfNeeded()
254 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
256 // Make server listening
257 server.listen(port, hostname, () => {
258 logger.info('Server listening on %s:%d', hostname, port)
259 logger.info('Web server: %s', WEBSERVER.URL)
262 process.on('exit', () => {
263 JobQueue.Instance.terminate()
266 process.on('SIGINT', () => process.exit(0))