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