]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Fix little typo in variable.
[github/Chocobozzz/PeerTube.git] / server.ts
... / ...
CommitLineData
1// FIXME: https://github.com/nodejs/node/pull/16853
2require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4import { isTestInstance } from './server/helpers/core-utils'
5
6if (isTestInstance()) {
7 require('source-map-support').install()
8}
9
10// ----------- Node modules -----------
11import * as bodyParser from 'body-parser'
12import * as express from 'express'
13import * as http from 'http'
14import * as morgan from 'morgan'
15import * as path from 'path'
16import * as bitTorrentTracker from 'bittorrent-tracker'
17import * as cors from 'cors'
18import { Server as WebSocketServer } from 'ws'
19
20const TrackerServer = bitTorrentTracker.Server
21
22process.title = 'peertube'
23
24// Create our main app
25const app = express()
26
27// ----------- Core checker -----------
28import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
29
30// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
31import { logger } from './server/helpers/logger'
32import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
33
34const missed = checkMissedConfig()
35if (missed.length !== 0) {
36 logger.error('Your configuration files miss keys: ' + missed)
37 process.exit(-1)
38}
39
40checkFFmpeg(CONFIG)
41 .catch(err => {
42 logger.error('Error in ffmpeg check.', { err })
43 process.exit(-1)
44 })
45
46const errorMessage = checkConfig()
47if (errorMessage !== null) {
48 throw new Error(errorMessage)
49}
50
51// Trust our proxy (IP forwarding...)
52app.set('trust proxy', CONFIG.TRUST_PROXY)
53
54// ----------- Database -----------
55
56// Initialize database and models
57import { initDatabaseModels } from './server/initializers/database'
58import { migrate } from './server/initializers/migrator'
59migrate()
60 .then(() => initDatabaseModels(false))
61 .then(() => onDatabaseInitDone())
62
63// ----------- PeerTube modules -----------
64import { installApplication } from './server/initializers'
65import { Emailer } from './server/lib/emailer'
66import { JobQueue } from './server/lib/job-queue'
67import { VideosPreviewCache } from './server/lib/cache'
68import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
69import { Redis } from './server/lib/redis'
70import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
71import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
72
73// ----------- Command line -----------
74
75// ----------- App -----------
76
77// Enable CORS for develop
78if (isTestInstance()) {
79 app.use((req, res, next) => {
80 // These routes have already cors
81 if (
82 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
83 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
84 ) {
85 return (cors({
86 origin: 'http://localhost:3000',
87 exposedHeaders: 'Retry-After',
88 credentials: true
89 }))(req, res, next)
90 }
91
92 return next()
93 })
94}
95
96// For the logger
97app.use(morgan('combined', {
98 stream: { write: logger.info.bind(logger) }
99}))
100// For body requests
101app.use(bodyParser.urlencoded({ extended: false }))
102app.use(bodyParser.json({
103 type: [ 'application/json', 'application/*+json' ],
104 limit: '500kb'
105}))
106
107// ----------- Tracker -----------
108
109const trackerServer = new TrackerServer({
110 http: false,
111 udp: false,
112 ws: false,
113 dht: false
114})
115
116trackerServer.on('error', function (err) {
117 logger.error('Error in websocket tracker.', err)
118})
119
120trackerServer.on('warning', function (err) {
121 logger.error('Warning in websocket tracker.', err)
122})
123
124const server = http.createServer(app)
125const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
126wss.on('connection', function (ws) {
127 trackerServer.onWebSocketConnection(ws)
128})
129
130const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
131app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
132app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
133
134// ----------- Views, routes and static files -----------
135
136// API
137const apiRoute = '/api/' + API_VERSION
138app.use(apiRoute, apiRouter)
139
140// Services (oembed...)
141app.use('/services', servicesRouter)
142
143app.use('/', webfingerRouter)
144app.use('/', activityPubRouter)
145
146// Client files
147app.use('/', clientsRouter)
148
149// Static files
150app.use('/', staticRouter)
151
152// Always serve index client page (the client is a single page application, let it handle routing)
153app.use('/*', function (req, res) {
154 if (req.accepts(ACCEPT_HEADERS) === 'html') {
155 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
156 }
157
158 return res.status(404).end()
159})
160
161// ----------- Errors -----------
162
163// Catch 404 and forward to error handler
164app.use(function (req, res, next) {
165 const err = new Error('Not Found')
166 err['status'] = 404
167 next(err)
168})
169
170app.use(function (err, req, res, next) {
171 let error = 'Unknown error.'
172 if (err) {
173 error = err.stack || err.message || err
174 }
175
176 logger.error('Error in controller.', { error })
177 return res.status(err.status || 500).end()
178})
179
180// ----------- Run -----------
181
182function onDatabaseInitDone () {
183 const port = CONFIG.LISTEN.PORT
184
185 installApplication()
186 .then(() => {
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())
193
194 // Caches initializations
195 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
196
197 // Enable Schedulers
198 BadActorFollowScheduler.Instance.enable()
199 RemoveOldJobsScheduler.Instance.enable()
200
201 // Redis initialization
202 Redis.Instance.init()
203
204 logger.info('Server listening on port %d', port)
205 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
206 })
207 })
208}