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