]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Move /var/www/peertube to $PEERTUBE_PATH in upgrade.sh
[github/Chocobozzz/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 {
73 activityPubRouter,
74 apiRouter,
75 clientsRouter,
76 feedsRouter,
77 staticRouter,
78 servicesRouter,
79 webfingerRouter
80 } from './server/controllers'
81 import { Redis } from './server/lib/redis'
82 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
83 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
84
85 // ----------- Command line -----------
86
87 // ----------- App -----------
88
89 // Enable CORS for develop
90 if (isTestInstance()) {
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: '*',
99 exposedHeaders: 'Retry-After',
100 credentials: true
101 }))(req, res, next)
102 }
103
104 return next()
105 })
106 }
107
108 // For the logger
109 app.use(morgan('combined', {
110 stream: { write: logger.info.bind(logger) }
111 }))
112 // For body requests
113 app.use(bodyParser.urlencoded({ extended: false }))
114 app.use(bodyParser.json({
115 type: [ 'application/json', 'application/*+json' ],
116 limit: '500kb'
117 }))
118
119 // ----------- Tracker -----------
120
121 const trackerServer = new TrackerServer({
122 http: false,
123 udp: false,
124 ws: false,
125 dht: false
126 })
127
128 trackerServer.on('error', function (err) {
129 logger.error('Error in websocket tracker.', err)
130 })
131
132 trackerServer.on('warning', function (err) {
133 logger.error('Warning in websocket tracker.', err)
134 })
135
136 const server = http.createServer(app)
137 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
138 wss.on('connection', function (ws) {
139 trackerServer.onWebSocketConnection(ws)
140 })
141
142 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
143 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
144 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
145
146 // ----------- Views, routes and static files -----------
147
148 // API
149 const apiRoute = '/api/' + API_VERSION
150 app.use(apiRoute, apiRouter)
151
152 // Services (oembed...)
153 app.use('/services', servicesRouter)
154
155 app.use('/', activityPubRouter)
156 app.use('/', feedsRouter)
157 app.use('/', webfingerRouter)
158
159 // Client files
160 app.use('/', clientsRouter)
161
162 // Static files
163 app.use('/', staticRouter)
164
165 // Always serve index client page (the client is a single page application, let it handle routing)
166 app.use('/*', function (req, res) {
167 if (req.accepts(ACCEPT_HEADERS) === 'html') {
168 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
169 }
170
171 return res.status(404).end()
172 })
173
174 // ----------- Errors -----------
175
176 // Catch 404 and forward to error handler
177 app.use(function (req, res, next) {
178 const err = new Error('Not Found')
179 err['status'] = 404
180 next(err)
181 })
182
183 app.use(function (err, req, res, next) {
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()
191 })
192
193 // ----------- Run -----------
194
195 async function startApplication () {
196 const port = CONFIG.LISTEN.PORT
197 const hostname = CONFIG.LISTEN.HOSTNAME
198
199 await installApplication()
200
201 // Email initialization
202 Emailer.Instance.init()
203 await Emailer.Instance.checkConnectionOrDie()
204
205 await JobQueue.Instance.init()
206
207 // Caches initializations
208 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
209
210 // Enable Schedulers
211 BadActorFollowScheduler.Instance.enable()
212 RemoveOldJobsScheduler.Instance.enable()
213
214 // Redis initialization
215 Redis.Instance.init()
216
217 // Make server listening
218 server.listen(port, hostname, () => {
219 logger.info('Server listening on %s:%d', hostname, port)
220 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
221 })
222 }