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 path from 'path'
16 import * as bitTorrentTracker from 'bittorrent-tracker'
17 import * as cors from 'cors'
18 import { Server as WebSocketServer } from 'ws'
20 const TrackerServer = bitTorrentTracker.Server
22 process.title = 'peertube'
24 // Create our main app
27 // ----------- Core checker -----------
28 import { checkMissedConfig, checkFFmpeg, checkConfig } 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 { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } 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 // ----------- Database -----------
56 // Initialize database and models
57 import { initDatabaseModels } from './server/initializers/database'
58 import { migrate } from './server/initializers/migrator'
60 .then(() => initDatabaseModels(false))
61 .then(() => onDatabaseInitDone())
63 // ----------- PeerTube modules -----------
64 import { installApplication } from './server/initializers'
65 import { Emailer } from './server/lib/emailer'
66 import { JobQueue } from './server/lib/job-queue'
67 import { VideosPreviewCache } from './server/lib/cache'
68 import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
69 import { Redis } from './server/lib/redis'
70 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
71 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
73 // ----------- Command line -----------
75 // ----------- App -----------
77 // Enable CORS for develop
78 if (isTestInstance()) {
79 app.use((req, res, next) => {
80 // These routes have already cors
82 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
83 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
86 origin: 'http://localhost:3000',
87 exposedHeaders: 'Retry-After',
97 app.use(morgan('combined', {
98 stream: { write: logger.info.bind(logger) }
101 app.use(bodyParser.urlencoded({ extended: false }))
102 app.use(bodyParser.json({
103 type: [ 'application/json', 'application/*+json' ],
107 // ----------- Tracker -----------
109 const trackerServer = new TrackerServer({
116 trackerServer.on('error', function (err) {
117 logger.error('Error in websocket tracker.', err)
120 trackerServer.on('warning', function (err) {
121 logger.error('Warning in websocket tracker.', err)
124 const server = http.createServer(app)
125 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
126 wss.on('connection', function (ws) {
127 trackerServer.onWebSocketConnection(ws)
130 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
131 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
132 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
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('/', webfingerRouter)
144 app.use('/', activityPubRouter)
147 app.use('/', clientsRouter)
150 app.use('/', staticRouter)
152 // Always serve index client page (the client is a single page application, let it handle routing)
153 app.use('/*', function (req, res) {
154 if (req.accepts(ACCEPT_HEADERS) === 'html') {
155 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
158 return res.status(404).end()
161 // ----------- Errors -----------
163 // Catch 404 and forward to error handler
164 app.use(function (req, res, next) {
165 const err = new Error('Not Found')
170 app.use(function (err, req, res, next) {
171 let error = 'Unknown error.'
173 error = err.stack || err.message || err
176 logger.error('Error in controller.', { error })
177 return res.status(err.status || 500).end()
180 // ----------- Run -----------
182 function onDatabaseInitDone () {
183 const port = CONFIG.LISTEN.PORT
187 // ----------- Make the server listening -----------
188 server.listen(port, () => {
189 // Emailer initialization and then job queue initialization
190 Emailer.Instance.init()
191 Emailer.Instance.checkConnectionOrDie()
192 .then(() => JobQueue.Instance.init())
194 // Caches initializations
195 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
198 BadActorFollowScheduler.Instance.enable()
199 RemoveOldJobsScheduler.Instance.enable()
201 // Redis initialization
202 Redis.Instance.init()
204 logger.info('Server listening on port %d', port)
205 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)