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