]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Handle error on websocket error
[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 const missed = checkMissedConfig()
31 if (missed.length !== 0) {
32 throw new Error('Your configuration files miss keys: ' + missed)
33 }
34
35 import { ACCEPT_HEADERS, API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
36 checkFFmpeg(CONFIG)
37
38 const errorMessage = checkConfig()
39 if (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)
45 import { logger } from './server/helpers/logger'
46
47 // Initialize database and models
48 import { initDatabaseModels } from './server/initializers/database'
49 import { migrate } from './server/initializers/migrator'
50 migrate()
51 .then(() => initDatabaseModels(false))
52 .then(() => onDatabaseInitDone())
53
54 // ----------- PeerTube modules -----------
55 import { installApplication } from './server/initializers'
56 import { Emailer } from './server/lib/emailer'
57 import { JobQueue } from './server/lib/job-queue'
58 import { VideosPreviewCache } from './server/lib/cache'
59 import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
60 import { Redis } from './server/lib/redis'
61 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
62 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
63
64 // ----------- Command line -----------
65
66 // ----------- App -----------
67
68 // Enable CORS for develop
69 if (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
87 app.use(morgan('combined', {
88 stream: { write: logger.info.bind(logger) }
89 }))
90 // For body requests
91 app.use(bodyParser.json({
92 type: [ 'application/json', 'application/*+json' ],
93 limit: '500kb'
94 }))
95 app.use(bodyParser.urlencoded({ extended: false }))
96
97 // ----------- Tracker -----------
98
99 const trackerServer = new TrackerServer({
100 http: false,
101 udp: false,
102 ws: false,
103 dht: false
104 })
105
106 trackerServer.on('error', function (err) {
107 logger.error(err)
108 })
109
110 trackerServer.on('warning', function (err) {
111 logger.error(err)
112 })
113
114 const server = http.createServer(app)
115 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
116 wss.on('connection', function (ws) {
117 trackerServer.onWebSocketConnection(ws)
118 })
119 wss.on('error', err => logger.error('Error in websocket server.', err))
120
121 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
122 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
123 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
124
125 // ----------- Views, routes and static files -----------
126
127 // API
128 const apiRoute = '/api/' + API_VERSION
129 app.use(apiRoute, apiRouter)
130
131 // Services (oembed...)
132 app.use('/services', servicesRouter)
133
134 app.use('/', webfingerRouter)
135 app.use('/', activityPubRouter)
136
137 // Client files
138 app.use('/', clientsRouter)
139
140 // Static files
141 app.use('/', staticRouter)
142
143 // Always serve index client page (the client is a single page application, let it handle routing)
144 app.use('/*', function (req, res) {
145 if (req.accepts(ACCEPT_HEADERS) === 'html') {
146 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
147 }
148
149 return res.status(404).end()
150 })
151
152 // ----------- Errors -----------
153
154 // Catch 404 and forward to error handler
155 app.use(function (req, res, next) {
156 const err = new Error('Not Found')
157 err['status'] = 404
158 next(err)
159 })
160
161 app.use(function (err, req, res, next) {
162 logger.error(err, err)
163 res.sendStatus(err.status || 500)
164 })
165
166 // ----------- Run -----------
167
168 function onDatabaseInitDone () {
169 const port = CONFIG.LISTEN.PORT
170
171 installApplication()
172 .then(() => {
173 // ----------- Make the server listening -----------
174 server.listen(port, () => {
175 // Emailer initialization and then job queue initialization
176 Emailer.Instance.init()
177 Emailer.Instance.checkConnectionOrDie()
178 .then(() => JobQueue.Instance.init())
179
180 // Caches initializations
181 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
182
183 // Enable Schedulers
184 BadActorFollowScheduler.Instance.enable()
185 RemoveOldJobsScheduler.Instance.enable()
186
187 // Redis initialization
188 Redis.Instance.init()
189
190 logger.info('Server listening on port %d', port)
191 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
192 })
193 })
194 }