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