]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
refactor scoped token service
[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()
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 } 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} from './server/controllers'
108import { advertiseDoNotTrack } from './server/middlewares/dnt'
109import { Redis } from './server/lib/redis'
110import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
111import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
112import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
113import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
114import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
115import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
116import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
117import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
118import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
119import { PeerTubeSocket } from './server/lib/peertube-socket'
120import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
121import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
122import { Hooks } from './server/lib/plugins/hooks'
123import { PluginManager } from './server/lib/plugins/plugin-manager'
124import { LiveManager } from '@server/lib/live-manager'
125
126// ----------- Command line -----------
127
128cli
129 .option('--no-client', 'Start PeerTube without client interface')
130 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
131 .parse(process.argv)
132
133// ----------- App -----------
134
135// Enable CORS for develop
136if (isTestInstance()) {
137 app.use(cors({
138 origin: '*',
139 exposedHeaders: 'Retry-After',
140 credentials: true
141 }))
142}
143
144// For the logger
145morgan.token('remote-addr', (req: express.Request) => {
146 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
147 return anonymize(req.ip, 16, 16)
148 }
149
150 return req.ip
151})
152morgan.token('user-agent', (req: express.Request) => {
153 if (req.get('DNT') === '1') {
154 return useragent.parse(req.get('user-agent')).family
155 }
156
157 return req.get('user-agent')
158})
159app.use(morgan('combined', {
160 stream: { write: logger.info.bind(logger) }
161}))
162
163// For body requests
164app.use(bodyParser.urlencoded({ extended: false }))
165app.use(bodyParser.json({
166 type: [ 'application/json', 'application/*+json' ],
167 limit: '500kb',
168 verify: (req: express.Request, _, buf: Buffer) => {
169 const valid = isHTTPSignatureDigestValid(buf, req)
170 if (valid !== true) throw new Error('Invalid digest')
171 }
172}))
173
174// Cookies
175app.use(cookieParser())
176
177// W3C DNT Tracking Status
178app.use(advertiseDoNotTrack)
179
180// ----------- Views, routes and static files -----------
181
182// API
183const apiRoute = '/api/' + API_VERSION
184app.use(apiRoute, apiRouter)
185
186// Services (oembed...)
187app.use('/services', servicesRouter)
188
189// Live streaming
190app.use('/live', liveRouter)
191
192// Plugins & themes
193app.use('/', pluginsRouter)
194
195app.use('/', activityPubRouter)
196app.use('/', feedsRouter)
197app.use('/', webfingerRouter)
198app.use('/', trackerRouter)
199app.use('/', botsRouter)
200
201// Static files
202app.use('/', staticRouter)
203app.use('/', lazyStaticRouter)
204
205// Client files, last valid routes!
206if (cli.client) app.use('/', clientsRouter)
207
208// ----------- Errors -----------
209
210// Catch 404 and forward to error handler
211app.use(function (req, res, next) {
212 const err = new Error('Not Found')
213 err['status'] = 404
214 next(err)
215})
216
217app.use(function (err, req, res, next) {
218 let error = 'Unknown error.'
219 if (err) {
220 error = err.stack || err.message || err
221 }
222
223 // Sequelize error
224 const sql = err.parent ? err.parent.sql : undefined
225
226 logger.error('Error in controller.', { err: error, sql })
227 return res.status(err.status || 500).end()
228})
229
230const server = createWebsocketTrackerServer(app)
231
232// ----------- Run -----------
233
234async function startApplication () {
235 const port = CONFIG.LISTEN.PORT
236 const hostname = CONFIG.LISTEN.HOSTNAME
237
238 await installApplication()
239
240 // Check activity pub urls are valid
241 checkActivityPubUrls()
242 .catch(err => {
243 logger.error('Error in ActivityPub URLs checker.', { err })
244 process.exit(-1)
245 })
246
247 // Email initialization
248 Emailer.Instance.init()
249
250 await Promise.all([
251 Emailer.Instance.checkConnectionOrDie(),
252 JobQueue.Instance.init()
253 ])
254
255 // Caches initializations
256 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
257 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
258
259 // Enable Schedulers
260 ActorFollowScheduler.Instance.enable()
261 RemoveOldJobsScheduler.Instance.enable()
262 UpdateVideosScheduler.Instance.enable()
263 YoutubeDlUpdateScheduler.Instance.enable()
264 VideosRedundancyScheduler.Instance.enable()
265 RemoveOldHistoryScheduler.Instance.enable()
266 RemoveOldViewsScheduler.Instance.enable()
267 PluginsCheckScheduler.Instance.enable()
268 AutoFollowIndexInstances.Instance.enable()
269
270 // Redis initialization
271 Redis.Instance.init()
272
273 PeerTubeSocket.Instance.init(server)
274
275 updateStreamingPlaylistsInfohashesIfNeeded()
276 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
277
278 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
279
280 LiveManager.Instance.init()
281 if (CONFIG.LIVE.ENABLED) LiveManager.Instance.run()
282
283 // Make server listening
284 server.listen(port, hostname, () => {
285 logger.info('Server listening on %s:%d', hostname, port)
286 logger.info('Web server: %s', WEBSERVER.URL)
287
288 Hooks.runAction('action:application.listening')
289 })
290
291 process.on('exit', () => {
292 JobQueue.Instance.terminate()
293 })
294
295 process.on('SIGINT', () => process.exit(0))
296}