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