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