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