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