]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
fixing #595 by using the account name instead of the displayName
[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 bitTorrentTracker from 'bittorrent-tracker'
16import * as cors from 'cors'
17import { Server as WebSocketServer } from 'ws'
18
19const TrackerServer = bitTorrentTracker.Server
20
21process.title = 'peertube'
22
23// Create our main app
24const app = express()
25
26// ----------- Core checker -----------
27import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
28
29// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30import { logger } from './server/helpers/logger'
31import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
32
33const missed = checkMissedConfig()
34if (missed.length !== 0) {
35 logger.error('Your configuration files miss keys: ' + missed)
36 process.exit(-1)
37}
38
39checkFFmpeg(CONFIG)
40 .catch(err => {
41 logger.error('Error in ffmpeg check.', { err })
42 process.exit(-1)
43 })
44
45const errorMessage = checkConfig()
46if (errorMessage !== null) {
47 throw new Error(errorMessage)
48}
49
50// Trust our proxy (IP forwarding...)
51app.set('trust proxy', CONFIG.TRUST_PROXY)
52
53// ----------- Database -----------
54
55// Initialize database and models
56import { initDatabaseModels } from './server/initializers/database'
57import { migrate } from './server/initializers/migrator'
58migrate()
59 .then(() => initDatabaseModels(false))
60 .then(() => startApplication())
61 .catch(err => {
62 logger.error('Cannot start application.', { err })
63 process.exit(-1)
64 })
65
66// ----------- PeerTube modules -----------
67import { installApplication } from './server/initializers'
68import { Emailer } from './server/lib/emailer'
69import { JobQueue } from './server/lib/job-queue'
70import { VideosPreviewCache } from './server/lib/cache'
71import {
72 activityPubRouter,
73 apiRouter,
74 clientsRouter,
75 feedsRouter,
76 staticRouter,
77 servicesRouter,
78 webfingerRouter
79} from './server/controllers'
80import { Redis } from './server/lib/redis'
81import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
82import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
83
84// ----------- Command line -----------
85
86// ----------- App -----------
87
88// Enable CORS for develop
89if (isTestInstance()) {
90 app.use((req, res, next) => {
91 // These routes have already cors
92 if (
93 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
94 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
95 ) {
96 return (cors({
97 origin: '*',
98 exposedHeaders: 'Retry-After',
99 credentials: true
100 }))(req, res, next)
101 }
102
103 return next()
104 })
105}
106
107// For the logger
108app.use(morgan('combined', {
109 stream: { write: logger.info.bind(logger) }
110}))
111// For body requests
112app.use(bodyParser.urlencoded({ extended: false }))
113app.use(bodyParser.json({
114 type: [ 'application/json', 'application/*+json' ],
115 limit: '500kb'
116}))
117
118// ----------- Tracker -----------
119
120const trackerServer = new TrackerServer({
121 http: false,
122 udp: false,
123 ws: false,
124 dht: false
125})
126
127trackerServer.on('error', function (err) {
128 logger.error('Error in websocket tracker.', err)
129})
130
131trackerServer.on('warning', function (err) {
132 logger.error('Warning in websocket tracker.', err)
133})
134
135const server = http.createServer(app)
136const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
137wss.on('connection', function (ws) {
138 trackerServer.onWebSocketConnection(ws)
139})
140
141const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
142app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
143app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
144
145// ----------- Views, routes and static files -----------
146
147// API
148const apiRoute = '/api/' + API_VERSION
149app.use(apiRoute, apiRouter)
150
151// Services (oembed...)
152app.use('/services', servicesRouter)
153
154app.use('/', activityPubRouter)
155app.use('/', feedsRouter)
156app.use('/', webfingerRouter)
157
158// Static files
159app.use('/', staticRouter)
160
161// Client files, last valid routes!
162app.use('/', clientsRouter)
163
164// ----------- Errors -----------
165
166// Catch 404 and forward to error handler
167app.use(function (req, res, next) {
168 const err = new Error('Not Found')
169 err['status'] = 404
170 next(err)
171})
172
173app.use(function (err, req, res, next) {
174 let error = 'Unknown error.'
175 if (err) {
176 error = err.stack || err.message || err
177 }
178
179 logger.error('Error in controller.', { error })
180 return res.status(err.status || 500).end()
181})
182
183// ----------- Run -----------
184
185async function startApplication () {
186 const port = CONFIG.LISTEN.PORT
187 const hostname = CONFIG.LISTEN.HOSTNAME
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, hostname, () => {
209 logger.info('Server listening on %s:%d', hostname, port)
210 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
211 })
212}