1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { ScheduleVideoUpdateModel } from './server/models/video/schedule-video-update'
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 http from 'http'
16 import * as morgan from 'morgan'
17 import * as bitTorrentTracker from 'bittorrent-tracker'
18 import * as cors from 'cors'
19 import { Server as WebSocketServer } from 'ws'
21 const TrackerServer = bitTorrentTracker.Server
23 process.title = 'peertube'
25 // Create our main app
28 // ----------- Core checker -----------
29 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
31 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
32 import { logger } from './server/helpers/logger'
33 import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
35 const missed = checkMissedConfig()
36 if (missed.length !== 0) {
37 logger.error('Your configuration files miss keys: ' + missed)
43 logger.error('Error in ffmpeg check.', { err })
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49 throw new Error(errorMessage)
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
55 // ----------- Database -----------
57 // Initialize database and models
58 import { initDatabaseModels } from './server/initializers/database'
59 import { migrate } from './server/initializers/migrator'
61 .then(() => initDatabaseModels(false))
62 .then(() => startApplication())
64 logger.error('Cannot start application.', { err })
68 // ----------- PeerTube modules -----------
69 import { installApplication } from './server/initializers'
70 import { Emailer } from './server/lib/emailer'
71 import { JobQueue } from './server/lib/job-queue'
72 import { VideosPreviewCache } from './server/lib/cache'
81 } from './server/controllers'
82 import { Redis } from './server/lib/redis'
83 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
84 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
85 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
87 // ----------- Command line -----------
89 // ----------- App -----------
91 // Enable CORS for develop
92 if (isTestInstance()) {
93 app.use((req, res, next) => {
94 // These routes have already cors
96 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
97 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
101 exposedHeaders: 'Retry-After',
111 app.use(morgan('combined', {
112 stream: { write: logger.info.bind(logger) }
115 app.use(bodyParser.urlencoded({ extended: false }))
116 app.use(bodyParser.json({
117 type: [ 'application/json', 'application/*+json' ],
121 // ----------- Tracker -----------
123 const trackerServer = new TrackerServer({
130 trackerServer.on('error', function (err) {
131 logger.error('Error in websocket tracker.', err)
134 trackerServer.on('warning', function (err) {
135 logger.error('Warning in websocket tracker.', err)
138 const server = http.createServer(app)
139 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
140 wss.on('connection', function (ws) {
141 trackerServer.onWebSocketConnection(ws)
144 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
145 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
146 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
148 // ----------- Views, routes and static files -----------
151 const apiRoute = '/api/' + API_VERSION
152 app.use(apiRoute, apiRouter)
154 // Services (oembed...)
155 app.use('/services', servicesRouter)
157 app.use('/', activityPubRouter)
158 app.use('/', feedsRouter)
159 app.use('/', webfingerRouter)
162 app.use('/', staticRouter)
164 // Client files, last valid routes!
165 app.use('/', clientsRouter)
167 // ----------- Errors -----------
169 // Catch 404 and forward to error handler
170 app.use(function (req, res, next) {
171 const err = new Error('Not Found')
176 app.use(function (err, req, res, next) {
177 let error = 'Unknown error.'
179 error = err.stack || err.message || err
182 logger.error('Error in controller.', { error })
183 return res.status(err.status || 500).end()
186 // ----------- Run -----------
188 async function startApplication () {
189 const port = CONFIG.LISTEN.PORT
190 const hostname = CONFIG.LISTEN.HOSTNAME
192 await installApplication()
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)
204 BadActorFollowScheduler.Instance.enable()
205 RemoveOldJobsScheduler.Instance.enable()
206 UpdateVideosScheduler.Instance.enable()
208 // Redis initialization
209 Redis.Instance.init()
211 // Make server listening
212 server.listen(port, hostname, () => {
213 logger.info('Server listening on %s:%d', hostname, port)
214 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)