]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Update tsconfig
[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 { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
116 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
117 import { PeerTubeSocket } from './server/lib/peertube-socket'
118 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
119 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
120 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
121 import { Hooks } from './server/lib/plugins/hooks'
122 import { PluginManager } from './server/lib/plugins/plugin-manager'
123 import { LiveManager } from './server/lib/live'
124 import { HttpStatusCode } from './shared/models/http/http-error-codes'
125 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
126 import { ServerConfigManager } from '@server/lib/server-config-manager'
127 import { VideoViewsManager } from '@server/lib/views/video-views-manager'
128 import { isTestInstance } from './server/helpers/core-utils'
129
130 // ----------- Command line -----------
131
132 cli
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
141 if (isTestInstance()) {
142 app.use(cors({
143 origin: '*',
144 exposedHeaders: 'Retry-After',
145 credentials: true
146 }))
147 }
148
149 // For the logger
150 token('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 })
157 token('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 })
164 app.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
172 app.use(apiFailMiddleware)
173
174 // For body requests
175 app.use(express.urlencoded({ extended: false }))
176 app.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
192 app.use(cookieParser())
193
194 // W3C DNT Tracking Status
195 app.use(advertiseDoNotTrack)
196
197 // ----------- Views, routes and static files -----------
198
199 // API
200 const apiRoute = '/api/' + API_VERSION
201 app.use(apiRoute, apiRouter)
202
203 // Services (oembed...)
204 app.use('/services', servicesRouter)
205
206 // Live streaming
207 app.use('/live', liveRouter)
208
209 // Plugins & themes
210 app.use('/', pluginsRouter)
211
212 app.use('/', activityPubRouter)
213 app.use('/', feedsRouter)
214 app.use('/', webfingerRouter)
215 app.use('/', trackerRouter)
216 app.use('/', botsRouter)
217
218 // Static files
219 app.use('/', staticRouter)
220 app.use('/', downloadRouter)
221 app.use('/', lazyStaticRouter)
222
223 // Client files, last valid routes!
224 const cliOptions = cli.opts<{ client: boolean, plugins: boolean }>()
225 if (cliOptions.client) app.use('/', clientsRouter)
226
227 // ----------- Errors -----------
228
229 // Catch unmatched routes
230 app.use((_req, res: express.Response) => {
231 res.status(HttpStatusCode.NOT_FOUND_404).end()
232 })
233
234 // Catch thrown errors
235 app.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
252 const server = createWebsocketTrackerServer(app)
253
254 // ----------- Run -----------
255
256 async 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 }