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