]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Fix docker build on gitlab cci
[github/Chocobozzz/PeerTube.git] / server.ts
... / ...
CommitLineData
1// FIXME: https://github.com/nodejs/node/pull/16853
2import { PluginManager } from './server/lib/plugins/plugin-manager'
3
4require('tls').DEFAULT_ECDH_CURVE = 'auto'
5
6import { isTestInstance } from './server/helpers/core-utils'
7
8if (isTestInstance()) {
9 require('source-map-support').install()
10}
11
12// ----------- Node modules -----------
13import * as bodyParser from 'body-parser'
14import * as express from 'express'
15import * as morgan from 'morgan'
16import * as cors from 'cors'
17import * as cookieParser from 'cookie-parser'
18import * as helmet from 'helmet'
19import * as useragent from 'useragent'
20import * as anonymize from 'ip-anonymize'
21import * as cli from 'commander'
22
23process.title = 'peertube'
24
25// Create our main app
26const app = express()
27
28// ----------- Core checker -----------
29import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
30
31// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
32import { CONFIG } from './server/initializers/config'
33import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
34import { logger } from './server/helpers/logger'
35
36const missed = checkMissedConfig()
37if (missed.length !== 0) {
38 logger.error('Your configuration files miss keys: ' + missed)
39 process.exit(-1)
40}
41
42checkFFmpeg(CONFIG)
43 .catch(err => {
44 logger.error('Error in ffmpeg check.', { err })
45 process.exit(-1)
46 })
47
48checkNodeVersion()
49
50import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
51
52const errorMessage = checkConfig()
53if (errorMessage !== null) {
54 throw new Error(errorMessage)
55}
56
57// Trust our proxy (IP forwarding...)
58app.set('trust proxy', CONFIG.TRUST_PROXY)
59
60// Security middleware
61import { baseCSP } from './server/middlewares/csp'
62
63if (CONFIG.CSP.ENABLED) {
64 app.use(baseCSP)
65 app.use(helmet({
66 frameguard: {
67 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
68 },
69 hsts: false
70 }))
71}
72
73// ----------- Database -----------
74
75// Initialize database and models
76import { initDatabaseModels } from './server/initializers/database'
77import { migrate } from './server/initializers/migrator'
78migrate()
79 .then(() => initDatabaseModels(false))
80 .then(() => startApplication())
81 .catch(err => {
82 logger.error('Cannot start application.', { err })
83 process.exit(-1)
84 })
85
86// ----------- Initialize -----------
87loadLanguages()
88
89// ----------- PeerTube modules -----------
90import { installApplication } from './server/initializers'
91import { Emailer } from './server/lib/emailer'
92import { JobQueue } from './server/lib/job-queue'
93import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
94import {
95 activityPubRouter,
96 apiRouter,
97 clientsRouter,
98 feedsRouter,
99 staticRouter,
100 lazyStaticRouter,
101 servicesRouter,
102 pluginsRouter,
103 webfingerRouter,
104 trackerRouter,
105 createWebsocketTrackerServer, botsRouter
106} from './server/controllers'
107import { advertiseDoNotTrack } from './server/middlewares/dnt'
108import { Redis } from './server/lib/redis'
109import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
110import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
111import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
112import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
113import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
114import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
115import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
116import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
117import { PeerTubeSocket } from './server/lib/peertube-socket'
118import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
119import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
120import { Hooks } from './server/lib/plugins/hooks'
121
122// ----------- Command line -----------
123
124cli
125 .option('--no-client', 'Start PeerTube without client interface')
126 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
127 .parse(process.argv)
128
129// ----------- App -----------
130
131// Enable CORS for develop
132if (isTestInstance()) {
133 app.use(cors({
134 origin: '*',
135 exposedHeaders: 'Retry-After',
136 credentials: true
137 }))
138}
139
140// For the logger
141morgan.token('remote-addr', req => {
142 if (req.get('DNT') === '1') {
143 return anonymize(req.ip, 16, 16)
144 }
145
146 return req.ip
147})
148morgan.token('user-agent', req => {
149 if (req.get('DNT') === '1') {
150 return useragent.parse(req.get('user-agent')).family
151 }
152
153 return req.get('user-agent')
154})
155app.use(morgan('combined', {
156 stream: { write: logger.info.bind(logger) }
157}))
158
159// For body requests
160app.use(bodyParser.urlencoded({ extended: false }))
161app.use(bodyParser.json({
162 type: [ 'application/json', 'application/*+json' ],
163 limit: '500kb',
164 verify: (req: express.Request, _, buf: Buffer) => {
165 const valid = isHTTPSignatureDigestValid(buf, req)
166 if (valid !== true) throw new Error('Invalid digest')
167 }
168}))
169
170// Cookies
171app.use(cookieParser())
172
173// W3C DNT Tracking Status
174app.use(advertiseDoNotTrack)
175
176// ----------- Views, routes and static files -----------
177
178// API
179const apiRoute = '/api/' + API_VERSION
180app.use(apiRoute, apiRouter)
181
182// Services (oembed...)
183app.use('/services', servicesRouter)
184
185// Plugins & themes
186app.use('/', pluginsRouter)
187
188app.use('/', activityPubRouter)
189app.use('/', feedsRouter)
190app.use('/', webfingerRouter)
191app.use('/', trackerRouter)
192app.use('/', botsRouter)
193
194// Static files
195app.use('/', staticRouter)
196app.use('/', lazyStaticRouter)
197
198// Client files, last valid routes!
199if (cli.client) app.use('/', clientsRouter)
200
201// ----------- Errors -----------
202
203// Catch 404 and forward to error handler
204app.use(function (req, res, next) {
205 const err = new Error('Not Found')
206 err['status'] = 404
207 next(err)
208})
209
210app.use(function (err, req, res, next) {
211 let error = 'Unknown error.'
212 if (err) {
213 error = err.stack || err.message || err
214 }
215
216 // Sequelize error
217 const sql = err.parent ? err.parent.sql : undefined
218
219 logger.error('Error in controller.', { err: error, sql })
220 return res.status(err.status || 500).end()
221})
222
223const server = createWebsocketTrackerServer(app)
224
225// ----------- Run -----------
226
227async function startApplication () {
228 const port = CONFIG.LISTEN.PORT
229 const hostname = CONFIG.LISTEN.HOSTNAME
230
231 await installApplication()
232
233 // Check activity pub urls are valid
234 checkActivityPubUrls()
235 .catch(err => {
236 logger.error('Error in ActivityPub URLs checker.', { err })
237 process.exit(-1)
238 })
239
240 // Email initialization
241 Emailer.Instance.init()
242
243 await Promise.all([
244 Emailer.Instance.checkConnectionOrDie(),
245 JobQueue.Instance.init()
246 ])
247
248 // Caches initializations
249 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
250 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
251
252 // Enable Schedulers
253 ActorFollowScheduler.Instance.enable()
254 RemoveOldJobsScheduler.Instance.enable()
255 UpdateVideosScheduler.Instance.enable()
256 YoutubeDlUpdateScheduler.Instance.enable()
257 VideosRedundancyScheduler.Instance.enable()
258 RemoveOldHistoryScheduler.Instance.enable()
259 RemoveOldViewsScheduler.Instance.enable()
260 PluginsCheckScheduler.Instance.enable()
261
262 // Redis initialization
263 Redis.Instance.init()
264
265 PeerTubeSocket.Instance.init(server)
266
267 updateStreamingPlaylistsInfohashesIfNeeded()
268 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
269
270 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
271
272 // Make server listening
273 server.listen(port, hostname, () => {
274 logger.info('Server listening on %s:%d', hostname, port)
275 logger.info('Web server: %s', WEBSERVER.URL)
276
277 Hooks.runAction('action:application.listening')
278 })
279
280 process.on('exit', () => {
281 JobQueue.Instance.terminate()
282 })
283
284 process.on('SIGINT', () => process.exit(0))
285}