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