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
62 // ----------- Database -----------
64 // Initialize database and models
65 import { initDatabaseModels } from './server/initializers/database'
66 import { migrate } from './server/initializers/migrator'
68 .then(() => initDatabaseModels(false))
69 .then(() => startApplication())
71 logger.error('Cannot start application.', { err })
75 // ----------- PeerTube modules -----------
76 import { installApplication } from './server/initializers'
77 import { Emailer } from './server/lib/emailer'
78 import { JobQueue } from './server/lib/job-queue'
79 import { VideosPreviewCache } from './server/lib/cache'
90 } from './server/controllers'
91 import { advertiseDoNotTrack } from './server/middlewares/dnt'
92 import { Redis } from './server/lib/redis'
93 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
94 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
95 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
96 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
98 // ----------- Command line -----------
100 // ----------- App -----------
102 // Enable CORS for develop
103 if (isTestInstance()) {
106 exposedHeaders: 'Retry-After',
111 morgan.token('remote-addr', req => {
112 return (req.get('DNT') === '1') ?
113 anonymise(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
114 16, // bitmask for IPv4
115 16 // bitmask for IPv6
119 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
120 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
121 app.use(morgan('combined', {
122 stream: { write: logger.info.bind(logger) }
125 app.use(bodyParser.urlencoded({ extended: false }))
126 app.use(bodyParser.json({
127 type: [ 'application/json', 'application/*+json' ],
131 app.use(cookieParser())
132 // W3C DNT Tracking Status
133 app.use(advertiseDoNotTrack)
135 // ----------- Views, routes and static files -----------
138 const apiRoute = '/api/' + API_VERSION
139 app.use(apiRoute, apiRouter)
141 // Services (oembed...)
142 app.use('/services', servicesRouter)
144 app.use('/', activityPubRouter)
145 app.use('/', feedsRouter)
146 app.use('/', webfingerRouter)
147 app.use('/', trackerRouter)
150 app.use('/', staticRouter)
152 // Client files, last valid routes!
153 app.use('/', clientsRouter)
155 // ----------- Errors -----------
157 // Catch 404 and forward to error handler
158 app.use(function (req, res, next) {
159 const err = new Error('Not Found')
164 app.use(function (err, req, res, next) {
165 let error = 'Unknown error.'
167 error = err.stack || err.message || err
171 const sql = err.parent ? err.parent.sql : undefined
173 logger.error('Error in controller.', { err: error, sql })
174 return res.status(err.status || 500).end()
177 const server = createWebsocketServer(app)
179 // ----------- Run -----------
181 async function startApplication () {
182 const port = CONFIG.LISTEN.PORT
183 const hostname = CONFIG.LISTEN.HOSTNAME
185 await installApplication()
187 // Check activity pub urls are valid
188 checkActivityPubUrls()
190 logger.error('Error in ActivityPub URLs checker.', { err })
194 // Email initialization
195 Emailer.Instance.init()
196 await Emailer.Instance.checkConnectionOrDie()
198 await JobQueue.Instance.init()
200 // Caches initializations
201 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
202 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
205 BadActorFollowScheduler.Instance.enable()
206 RemoveOldJobsScheduler.Instance.enable()
207 UpdateVideosScheduler.Instance.enable()
208 YoutubeDlUpdateScheduler.Instance.enable()
210 // Redis initialization
211 Redis.Instance.init()
213 // Make server listening
214 server.listen(port, hostname, () => {
215 logger.info('Server listening on %s:%d', hostname, port)
216 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
219 process.on('exit', () => {
220 JobQueue.Instance.terminate()
223 process.on('SIGINT', () => process.exit(0))