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(() => startApplication())
63 logger.error('Cannot start application.', { err })
67 // ----------- PeerTube modules -----------
68 import { installApplication } from './server/initializers'
69 import { Emailer } from './server/lib/emailer'
70 import { JobQueue } from './server/lib/job-queue'
71 import { VideosPreviewCache } from './server/lib/cache'
80 } from './server/controllers'
81 import { Redis } from './server/lib/redis'
82 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
83 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-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
98 origin: 'http://localhost:3000',
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('/', clientsRouter)
163 app.use('/', staticRouter)
165 // Always serve index client page (the client is a single page application, let it handle routing)
166 app.use('/*', function (req, res) {
167 if (req.accepts(ACCEPT_HEADERS) === 'html') {
168 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
171 return res.status(404).end()
174 // ----------- Errors -----------
176 // Catch 404 and forward to error handler
177 app.use(function (req, res, next) {
178 const err = new Error('Not Found')
183 app.use(function (err, req, res, next) {
184 let error = 'Unknown error.'
186 error = err.stack || err.message || err
189 logger.error('Error in controller.', { error })
190 return res.status(err.status || 500).end()
193 // ----------- Run -----------
195 async function startApplication () {
196 const port = CONFIG.LISTEN.PORT
197 const hostname = CONFIG.LISTEN.HOSTNAME
199 await installApplication()
201 // Email initialization
202 Emailer.Instance.init()
203 await Emailer.Instance.checkConnectionOrDie()
205 await JobQueue.Instance.init()
207 // Caches initializations
208 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
211 BadActorFollowScheduler.Instance.enable()
212 RemoveOldJobsScheduler.Instance.enable()
214 // Redis initialization
215 Redis.Instance.init()
217 // Make server listening
218 server.listen(port, hostname, () => {
219 logger.info('Server listening on %s:%d', hostname, port)
220 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)