]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Move job queue to redis
[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 { JobQueue } from './server/lib/job-queue'
57 import { VideosPreviewCache } from './server/lib/cache'
58 import { apiRouter, clientsRouter, staticRouter, servicesRouter, webfingerRouter, activityPubRouter } from './server/controllers'
59 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
60 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
61
62 // ----------- Command line -----------
63
64 // ----------- App -----------
65
66 // Enable CORS for develop
67 if (isTestInstance()) {
68 app.use((req, res, next) => {
69 // These routes have already cors
70 if (
71 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
72 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
73 ) {
74 return (cors({
75 origin: 'http://localhost:3000',
76 credentials: true
77 }))(req, res, next)
78 }
79
80 return next()
81 })
82 }
83
84 // For the logger
85 app.use(morgan('combined', {
86 stream: { write: logger.info.bind(logger) }
87 }))
88 // For body requests
89 app.use(bodyParser.json({
90 type: [ 'application/json', 'application/*+json' ],
91 limit: '500kb'
92 }))
93 app.use(bodyParser.urlencoded({ extended: false }))
94
95 // ----------- Tracker -----------
96
97 const trackerServer = new TrackerServer({
98 http: false,
99 udp: false,
100 ws: false,
101 dht: false
102 })
103
104 trackerServer.on('error', function (err) {
105 logger.error(err)
106 })
107
108 trackerServer.on('warning', function (err) {
109 logger.error(err)
110 })
111
112 const server = http.createServer(app)
113 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
114 wss.on('connection', function (ws) {
115 trackerServer.onWebSocketConnection(ws)
116 })
117
118 const onHttpRequest = trackerServer.onHttpRequest.bind(trackerServer)
119 app.get('/tracker/announce', (req, res) => onHttpRequest(req, res, { action: 'announce' }))
120 app.get('/tracker/scrape', (req, res) => onHttpRequest(req, res, { action: 'scrape' }))
121
122 // ----------- Views, routes and static files -----------
123
124 // API
125 const apiRoute = '/api/' + API_VERSION
126 app.use(apiRoute, apiRouter)
127
128 // Services (oembed...)
129 app.use('/services', servicesRouter)
130
131 app.use('/', webfingerRouter)
132 app.use('/', activityPubRouter)
133
134 // Client files
135 app.use('/', clientsRouter)
136
137 // Static files
138 app.use('/', staticRouter)
139
140 // Always serve index client page (the client is a single page application, let it handle routing)
141 app.use('/*', function (req, res) {
142 if (req.accepts(ACCEPT_HEADERS) === 'html') {
143 return res.sendFile(path.join(__dirname, '../client/dist/index.html'))
144 }
145
146 return res.status(404).end()
147 })
148
149 // ----------- Errors -----------
150
151 // Catch 404 and forward to error handler
152 app.use(function (req, res, next) {
153 const err = new Error('Not Found')
154 err['status'] = 404
155 next(err)
156 })
157
158 app.use(function (err, req, res, next) {
159 logger.error(err, err)
160 res.sendStatus(err.status || 500)
161 })
162
163 // ----------- Run -----------
164
165 function onDatabaseInitDone () {
166 const port = CONFIG.LISTEN.PORT
167
168 installApplication()
169 .then(() => {
170 // ----------- Make the server listening -----------
171 server.listen(port, () => {
172 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
173 BadActorFollowScheduler.Instance.enable()
174 RemoveOldJobsScheduler.Instance.enable()
175 JobQueue.Instance.init()
176
177 logger.info('Server listening on port %d', port)
178 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
179 })
180 })
181 }