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