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