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