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