1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { VideosCaptionCache } from './server/lib/cache/videos-caption-cache'
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 anonymise from 'ip-anonymize'
22 process.title = 'peertube'
24 // Create our main app
27 // ----------- Core checker -----------
28 import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
30 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
31 import { logger } from './server/helpers/logger'
32 import { API_VERSION, CONFIG, CACHE } from './server/initializers/constants'
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 const errorMessage = checkConfig()
47 if (errorMessage !== null) {
48 throw new Error(errorMessage)
51 // Trust our proxy (IP forwarding...)
52 app.set('trust proxy', CONFIG.TRUST_PROXY)
54 // Security middleware
57 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
61 // ----------- Database -----------
63 // Initialize database and models
64 import { initDatabaseModels } from './server/initializers/database'
65 import { migrate } from './server/initializers/migrator'
67 .then(() => initDatabaseModels(false))
68 .then(() => startApplication())
70 logger.error('Cannot start application.', { err })
74 // ----------- PeerTube modules -----------
75 import { installApplication } from './server/initializers'
76 import { Emailer } from './server/lib/emailer'
77 import { JobQueue } from './server/lib/job-queue'
78 import { VideosPreviewCache } from './server/lib/cache'
89 } from './server/controllers'
90 import { advertiseDoNotTrack } from './server/middlewares/dnt'
91 import { Redis } from './server/lib/redis'
92 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
93 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
94 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
95 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
97 // ----------- Command line -----------
99 // ----------- App -----------
101 // Enable CORS for develop
102 if (isTestInstance()) {
105 exposedHeaders: 'Retry-After',
110 morgan.token('remote-addr', req => {
111 return (req.get('DNT') === '1') ?
112 anonymise(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
113 16, // bitmask for IPv4
114 16 // bitmask for IPv6
118 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
119 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
120 app.use(morgan('combined', {
121 stream: { write: logger.info.bind(logger) }
124 app.use(bodyParser.urlencoded({ extended: false }))
125 app.use(bodyParser.json({
126 type: [ 'application/json', 'application/*+json' ],
130 app.use(cookieParser())
131 // W3C DNT Tracking Status
132 app.use(advertiseDoNotTrack)
134 // ----------- Views, routes and static files -----------
137 const apiRoute = '/api/' + API_VERSION
138 app.use(apiRoute, apiRouter)
140 // Services (oembed...)
141 app.use('/services', servicesRouter)
143 app.use('/', activityPubRouter)
144 app.use('/', feedsRouter)
145 app.use('/', webfingerRouter)
146 app.use('/', trackerRouter)
149 app.use('/', staticRouter)
151 // Client files, last valid routes!
152 app.use('/', clientsRouter)
154 // ----------- Errors -----------
156 // Catch 404 and forward to error handler
157 app.use(function (req, res, next) {
158 const err = new Error('Not Found')
163 app.use(function (err, req, res, next) {
164 let error = 'Unknown error.'
166 error = err.stack || err.message || err
169 logger.error('Error in controller.', { err: error })
170 return res.status(err.status || 500).end()
173 const server = createWebsocketServer(app)
175 // ----------- Run -----------
177 async function startApplication () {
178 const port = CONFIG.LISTEN.PORT
179 const hostname = CONFIG.LISTEN.HOSTNAME
181 await installApplication()
183 // Check activity pub urls are valid
184 checkActivityPubUrls()
186 logger.error('Error in ActivityPub URLs checker.', { err })
190 // Email initialization
191 Emailer.Instance.init()
192 await Emailer.Instance.checkConnectionOrDie()
194 await JobQueue.Instance.init()
196 // Caches initializations
197 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
198 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
201 BadActorFollowScheduler.Instance.enable()
202 RemoveOldJobsScheduler.Instance.enable()
203 UpdateVideosScheduler.Instance.enable()
204 YoutubeDlUpdateScheduler.Instance.enable()
206 // Redis initialization
207 Redis.Instance.init()
209 // Make server listening
210 server.listen(port, hostname, () => {
211 logger.info('Server listening on %s:%d', hostname, port)
212 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
215 process.on('exit', () => {
216 JobQueue.Instance.terminate()
219 process.on('SIGINT', () => process.exit(0))