]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Add ability to add custom css/javascript
[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
30const missed = checkMissedConfig()
31if (missed.length !== 0) {
32 throw new Error('Your configuration files miss keys: ' + missed)
33}
34
35import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
36checkFFmpeg(CONFIG)
37
38const errorMessage = checkConfig()
39if (errorMessage !== null) {
40 throw new Error(errorMessage)
41}
42
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'
46
47// Initialize database and models
48import { initDatabaseModels } from './server/initializers/database'
49import { migrate } from './server/initializers/migrator'
50migrate()
51 .then(() => initDatabaseModels(false))
52 .then(() => onDatabaseInitDone())
53
54// ----------- PeerTube modules -----------
55import { installApplication } from './server/initializers'
56import { Emailer } from './server/lib/emailer'
57import { JobQueue } from './server/lib/job-queue'
58import { VideosPreviewCache } from './server/lib/cache'
59import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
60import { Redis } from './server/lib/redis'
61import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
62import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
63
64// ----------- Command line -----------
65
66// ----------- App -----------
67
68// Enable CORS for develop
69if (isTestInstance()) {
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 })
84}
85
86// For the logger
87app.use(morgan('combined', {
88 stream: { write: logger.info.bind(logger) }
89}))
90// For body requests
91app.use(bodyParser.json({
92 type: [ 'application/json', 'application/*+json' ],
93 limit: '500kb'
94}))
95app.use(bodyParser.urlencoded({ extended: false }))
96
97// ----------- Tracker -----------
98
99const trackerServer = new TrackerServer({
100 http: false,
101 udp: false,
102 ws: false,
103 dht: false
104})
105
106trackerServer.on('error', function (err) {
107 logger.error('Error in websocket tracker.', err)
108})
109
110trackerServer.on('warning', function (err) {
111 logger.error('Warning in websocket tracker.', err)
112})
113
114const server = http.createServer(app)
115const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
116wss.on('connection', function (ws) {
117 trackerServer.onWebSocketConnection(ws)
118})
119
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
133app.use('/', webfingerRouter)
134app.use('/', activityPubRouter)
135
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) {
144 if (req.accepts(ACCEPT_HEADERS) === 'html') {
145 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
146 }
147
148 return res.status(404).end()
149})
150
151// ----------- Errors -----------
152
153// Catch 404 and forward to error handler
154app.use(function (req, res, next) {
155 const err = new Error('Not Found')
156 err['status'] = 404
157 next(err)
158})
159
160app.use(function (err, req, res, next) {
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()
168})
169
170// ----------- Run -----------
171
172function onDatabaseInitDone () {
173 const port = CONFIG.LISTEN.PORT
174
175 installApplication()
176 .then(() => {
177 // ----------- Make the server listening -----------
178 server.listen(port, () => {
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
185 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
186
187 // Enable Schedulers
188 BadActorFollowScheduler.Instance.enable()
189 RemoveOldJobsScheduler.Instance.enable()
190
191 // Redis initialization
192 Redis.Instance.init()
193
194 logger.info('Server listening on port %d', port)
195 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
196 })
197 })
198}