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 http from 'http'
14 import * as morgan from 'morgan'
15 import * as bitTorrentTracker from 'bittorrent-tracker'
16 import * as cors from 'cors'
17 import { Server as WebSocketServer } from 'ws'
19 const TrackerServer = bitTorrentTracker.Server
21 process.title = 'peertube'
23 // Create our main app
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
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, STATIC_PATHS } 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 const errorMessage = checkConfig()
46 if (errorMessage !== null) {
47 throw new Error(errorMessage)
50 // Trust our proxy (IP forwarding...)
51 app.set('trust proxy', CONFIG.TRUST_PROXY)
53 // ----------- Database -----------
55 // Initialize database and models
56 import { initDatabaseModels } from './server/initializers/database'
57 import { migrate } from './server/initializers/migrator'
59 .then(() => initDatabaseModels(false))
60 .then(() => startApplication())
62 logger.error('Cannot start application.', { err })
66 // ----------- PeerTube modules -----------
67 import { installApplication } from './server/initializers'
68 import { Emailer } from './server/lib/emailer'
69 import { JobQueue } from './server/lib/job-queue'
70 import { VideosPreviewCache } from './server/lib/cache'
79 } from './server/controllers'
80 import { Redis } from './server/lib/redis'
81 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
82 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
83 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
85 // ----------- Command line -----------
87 // ----------- App -----------
89 // Enable CORS for develop
90 if (isTestInstance()) {
91 app.use((req, res, next) => {
92 // These routes have already cors
94 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
95 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
99 exposedHeaders: 'Retry-After',
109 app.use(morgan('combined', {
110 stream: { write: logger.info.bind(logger) }
113 app.use(bodyParser.urlencoded({ extended: false }))
114 app.use(bodyParser.json({
115 type: [ 'application/json', 'application/*+json' ],
119 // ----------- Tracker -----------
121 const trackerServer = new TrackerServer({
128 trackerServer.on('error', function (err) {
129 logger.error('Error in websocket tracker.', err)
132 trackerServer.on('warning', function (err) {
133 logger.error('Warning in websocket tracker.', err)
136 const server = http.createServer(app)
137 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
138 wss.on('connection', function (ws) {
139 trackerServer.onWebSocketConnection(ws)
142 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
143 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
144 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
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)
160 app.use('/', staticRouter)
162 // Client files, last valid routes!
163 app.use('/', clientsRouter)
165 // ----------- Errors -----------
167 // Catch 404 and forward to error handler
168 app.use(function (req, res, next) {
169 const err = new Error('Not Found')
174 app.use(function (err, req, res, next) {
175 let error = 'Unknown error.'
177 error = err.stack || err.message || err
180 logger.error('Error in controller.', { error })
181 return res.status(err.status || 500).end()
184 // ----------- Run -----------
186 async function startApplication () {
187 const port = CONFIG.LISTEN.PORT
188 const hostname = CONFIG.LISTEN.HOSTNAME
190 await installApplication()
192 // Check activity pub urls are valid
193 checkActivityPubUrls()
195 logger.error('Error in ActivityPub URLs checker.', { err })
199 // Email initialization
200 Emailer.Instance.init()
201 await Emailer.Instance.checkConnectionOrDie()
203 await JobQueue.Instance.init()
205 // Caches initializations
206 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
209 BadActorFollowScheduler.Instance.enable()
210 RemoveOldJobsScheduler.Instance.enable()
211 UpdateVideosScheduler.Instance.enable()
213 // Redis initialization
214 Redis.Instance.init()
216 // Make server listening
217 server.listen(port, hostname, () => {
218 logger.info('Server listening on %s:%d', hostname, port)
219 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)