]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Log into the console torrent errors
[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, checkActivityPubUrls } 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 { 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'
83import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
84
85// ----------- Command line -----------
86
87// ----------- App -----------
88
89// Enable CORS for develop
90if (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
109app.use(morgan('combined', {
110 stream: { write: logger.info.bind(logger) }
111}))
112// For body requests
113app.use(bodyParser.urlencoded({ extended: false }))
114app.use(bodyParser.json({
115 type: [ 'application/json', 'application/*+json' ],
116 limit: '500kb'
117}))
118
119// ----------- Tracker -----------
120
121const trackerServer = new TrackerServer({
122 http: false,
123 udp: false,
124 ws: false,
125 dht: false
126})
127
128trackerServer.on('error', function (err) {
129 logger.error('Error in websocket tracker.', err)
130})
131
132trackerServer.on('warning', function (err) {
133 logger.error('Warning in websocket tracker.', err)
134})
135
136const server = http.createServer(app)
137const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
138wss.on('connection', function (ws) {
139 trackerServer.onWebSocketConnection(ws)
140})
141
142const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
143app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
144app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
145
146// ----------- Views, routes and static files -----------
147
148// API
149const apiRoute = '/api/' + API_VERSION
150app.use(apiRoute, apiRouter)
151
152// Services (oembed...)
153app.use('/services', servicesRouter)
154
155app.use('/', activityPubRouter)
156app.use('/', feedsRouter)
157app.use('/', webfingerRouter)
158
159// Static files
160app.use('/', staticRouter)
161
162// Client files, last valid routes!
163app.use('/', clientsRouter)
164
165// ----------- Errors -----------
166
167// Catch 404 and forward to error handler
168app.use(function (req, res, next) {
169 const err = new Error('Not Found')
170 err['status'] = 404
171 next(err)
172})
173
174app.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
186async function startApplication () {
187 const port = CONFIG.LISTEN.PORT
188 const hostname = CONFIG.LISTEN.HOSTNAME
189
190 await installApplication()
191
192 // Check activity pub urls are valid
193 checkActivityPubUrls()
194 .catch(err => {
195 logger.error('Error in ActivityPub URLs checker.', { err })
196 process.exit(-1)
197 })
198
199 // Email initialization
200 Emailer.Instance.init()
201 await Emailer.Instance.checkConnectionOrDie()
202
203 await JobQueue.Instance.init()
204
205 // Caches initializations
206 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
207
208 // Enable Schedulers
209 BadActorFollowScheduler.Instance.enable()
210 RemoveOldJobsScheduler.Instance.enable()
211 UpdateVideosScheduler.Instance.enable()
212
213 // Redis initialization
214 Redis.Instance.init()
215
216 // Make server listening
217 server.listen(port, hostname, () => {
218 logger.info('Server listening on %s:%d', hostname, port)
219 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
220 })
221}