]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Increase test timeout
[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
45checkConfig()
46
47// Trust our proxy (IP forwarding...)
48app.set('trust proxy', CONFIG.TRUST_PROXY)
49
50// Security middleware
51import { baseCSP } from './server/middlewares/csp'
52
53if (CONFIG.CSP.ENABLED) {
54 app.use(baseCSP)
55}
56
57if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
58 app.use(frameguard({
59 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
60 }))
61}
62
63// ----------- Database -----------
64
65// Initialize database and models
66import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
67checkDatabaseConnectionOrDie()
68
69import { migrate } from './server/initializers/migrator'
70migrate()
71 .then(() => initDatabaseModels(false))
72 .then(() => startApplication())
73 .catch(err => {
74 logger.error('Cannot start application.', { err })
75 process.exit(-1)
76 })
77
78// ----------- Initialize -----------
79loadLanguages()
80
81// ----------- PeerTube modules -----------
82import { installApplication } from './server/initializers/installer'
83import { Emailer } from './server/lib/emailer'
84import { JobQueue } from './server/lib/job-queue'
85import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
86import {
87 activityPubRouter,
88 apiRouter,
89 clientsRouter,
90 feedsRouter,
91 staticRouter,
92 lazyStaticRouter,
93 servicesRouter,
94 liveRouter,
95 pluginsRouter,
96 webfingerRouter,
97 trackerRouter,
98 createWebsocketTrackerServer,
99 botsRouter,
100 downloadRouter
101} from './server/controllers'
102import { advertiseDoNotTrack } from './server/middlewares/dnt'
103import { apiFailMiddleware } from './server/middlewares/error'
104import { Redis } from './server/lib/redis'
105import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
106import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
107import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
108import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
109import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
110import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
111import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
112import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
113import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
114import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
115import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-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 { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
121import { Hooks } from './server/lib/plugins/hooks'
122import { PluginManager } from './server/lib/plugins/plugin-manager'
123import { LiveManager } from './server/lib/live'
124import { HttpStatusCode } from './shared/models/http/http-error-codes'
125import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
126import { ServerConfigManager } from '@server/lib/server-config-manager'
127import { VideoViewsManager } from '@server/lib/views/video-views-manager'
128import { isTestInstance } from './server/helpers/core-utils'
129
130// ----------- Command line -----------
131
132cli
133 .option('--no-client', 'Start PeerTube without client interface')
134 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
135 .option('--benchmark-startup', 'Automatically stop server when initialized')
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
150token('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})
157token('user-agent', (req: express.Request) => {
158 if (req.get('DNT') === '1') {
159 return 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.trim(), { tags: [ 'http' ] })
167 },
168 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
169}))
170
171// Add .fail() helper to response
172app.use(apiFailMiddleware)
173
174// For body requests
175app.use(express.urlencoded({ extended: false }))
176app.use(express.json({
177 type: [ 'application/json', 'application/*+json' ],
178 limit: '500kb',
179 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
180 const valid = isHTTPSignatureDigestValid(buf, req)
181
182 if (valid !== true) {
183 res.fail({
184 status: HttpStatusCode.FORBIDDEN_403,
185 message: 'Invalid digest'
186 })
187 }
188 }
189}))
190
191// Cookies
192app.use(cookieParser())
193
194// W3C DNT Tracking Status
195app.use(advertiseDoNotTrack)
196
197// ----------- Views, routes and static files -----------
198
199// API
200const apiRoute = '/api/' + API_VERSION
201app.use(apiRoute, apiRouter)
202
203// Services (oembed...)
204app.use('/services', servicesRouter)
205
206// Live streaming
207app.use('/live', liveRouter)
208
209// Plugins & themes
210app.use('/', pluginsRouter)
211
212app.use('/', activityPubRouter)
213app.use('/', feedsRouter)
214app.use('/', webfingerRouter)
215app.use('/', trackerRouter)
216app.use('/', botsRouter)
217
218// Static files
219app.use('/', staticRouter)
220app.use('/', downloadRouter)
221app.use('/', lazyStaticRouter)
222
223// Client files, last valid routes!
224const cliOptions = cli.opts()
225if (cliOptions.client) app.use('/', clientsRouter)
226
227// ----------- Errors -----------
228
229// Catch unmatched routes
230app.use((req, res: express.Response) => {
231 res.status(HttpStatusCode.NOT_FOUND_404).end()
232})
233
234// Catch thrown errors
235app.use((err, req, res: express.Response, next) => {
236 // Format error to be logged
237 let error = 'Unknown error.'
238 if (err) {
239 error = err.stack || err.message || err
240 }
241 // Handling Sequelize error traces
242 const sql = err.parent ? err.parent.sql : undefined
243 logger.error('Error in controller.', { err: error, sql })
244
245 return res.fail({
246 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
247 message: err.message,
248 type: err.name
249 })
250})
251
252const server = createWebsocketTrackerServer(app)
253
254// ----------- Run -----------
255
256async function startApplication () {
257 const port = CONFIG.LISTEN.PORT
258 const hostname = CONFIG.LISTEN.HOSTNAME
259
260 await installApplication()
261
262 // Check activity pub urls are valid
263 checkActivityPubUrls()
264 .catch(err => {
265 logger.error('Error in ActivityPub URLs checker.', { err })
266 process.exit(-1)
267 })
268
269 checkFFmpegVersion()
270 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
271
272 // Email initialization
273 Emailer.Instance.init()
274
275 await Promise.all([
276 Emailer.Instance.checkConnection(),
277 JobQueue.Instance.init(),
278 ServerConfigManager.Instance.init()
279 ])
280
281 // Caches initializations
282 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
283 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
284 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
285
286 // Enable Schedulers
287 ActorFollowScheduler.Instance.enable()
288 RemoveOldJobsScheduler.Instance.enable()
289 UpdateVideosScheduler.Instance.enable()
290 YoutubeDlUpdateScheduler.Instance.enable()
291 VideosRedundancyScheduler.Instance.enable()
292 RemoveOldHistoryScheduler.Instance.enable()
293 RemoveOldViewsScheduler.Instance.enable()
294 PluginsCheckScheduler.Instance.enable()
295 PeerTubeVersionCheckScheduler.Instance.enable()
296 AutoFollowIndexInstances.Instance.enable()
297 RemoveDanglingResumableUploadsScheduler.Instance.enable()
298 VideoViewsBufferScheduler.Instance.enable()
299 GeoIPUpdateScheduler.Instance.enable()
300
301 Redis.Instance.init()
302 PeerTubeSocket.Instance.init(server)
303 VideoViewsManager.Instance.init()
304
305 updateStreamingPlaylistsInfohashesIfNeeded()
306 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
307
308 LiveManager.Instance.init()
309 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
310
311 // Make server listening
312 server.listen(port, hostname, async () => {
313 if (cliOptions.plugins) {
314 try {
315 await PluginManager.Instance.registerPluginsAndThemes()
316 } catch (err) {
317 logger.error('Cannot register plugins and themes.', { err })
318 }
319 }
320
321 logger.info('HTTP server listening on %s:%d', hostname, port)
322 logger.info('Web server: %s', WEBSERVER.URL)
323
324 Hooks.runAction('action:application.listening')
325
326 if (cliOptions['benchmarkStartup']) process.exit(0)
327 })
328
329 process.on('exit', () => {
330 JobQueue.Instance.terminate()
331 })
332
333 process.on('SIGINT', () => process.exit(0))
334}