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