]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
parametrize gpg key in release script
[github/Chocobozzz/PeerTube.git] / server.ts
... / ...
CommitLineData
1// FIXME: https://github.com/nodejs/node/pull/16853
2require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4import { isTestInstance } from './server/helpers/core-utils'
5
6if (isTestInstance()) {
7 require('source-map-support').install()
8}
9
10// ----------- Node modules -----------
11import * as bodyParser from 'body-parser'
12import * as express from 'express'
13import * as morgan from 'morgan'
14import * as cors from 'cors'
15import * as cookieParser from 'cookie-parser'
16import * as helmet from 'helmet'
17import * as useragent from 'useragent'
18import * as anonymize from 'ip-anonymize'
19
20process.title = 'peertube'
21
22// Create our main app
23const app = express()
24
25// ----------- Core checker -----------
26import { checkMissedConfig, checkFFmpeg } 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 { logger } from './server/helpers/logger'
30import { API_VERSION, CONFIG, CACHE } from './server/initializers/constants'
31
32const missed = checkMissedConfig()
33if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
36}
37
38checkFFmpeg(CONFIG)
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
43
44import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
45
46const errorMessage = checkConfig()
47if (errorMessage !== null) {
48 throw new Error(errorMessage)
49}
50
51// Trust our proxy (IP forwarding...)
52app.set('trust proxy', CONFIG.TRUST_PROXY)
53
54// Security middleware
55app.use(helmet({
56 frameguard: {
57 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
58 },
59 hsts: false
60}))
61
62// ----------- Database -----------
63
64// Initialize database and models
65import { initDatabaseModels } from './server/initializers/database'
66import { migrate } from './server/initializers/migrator'
67migrate()
68 .then(() => initDatabaseModels(false))
69 .then(() => startApplication())
70 .catch(err => {
71 logger.error('Cannot start application.', { err })
72 process.exit(-1)
73 })
74
75// ----------- PeerTube modules -----------
76import { installApplication } from './server/initializers'
77import { Emailer } from './server/lib/emailer'
78import { JobQueue } from './server/lib/job-queue'
79import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
80import {
81 activityPubRouter,
82 apiRouter,
83 clientsRouter,
84 feedsRouter,
85 staticRouter,
86 servicesRouter,
87 webfingerRouter,
88 trackerRouter,
89 createWebsocketServer
90} from './server/controllers'
91import { advertiseDoNotTrack } from './server/middlewares/dnt'
92import { Redis } from './server/lib/redis'
93import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
94import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
95import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
96import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
97import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
98
99// ----------- Command line -----------
100
101// ----------- App -----------
102
103// Enable CORS for develop
104if (isTestInstance()) {
105 app.use(cors({
106 origin: '*',
107 exposedHeaders: 'Retry-After',
108 credentials: true
109 }))
110}
111// For the logger
112morgan.token('remote-addr', req => {
113 return (req.get('DNT') === '1') ?
114 anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
115 16, // bitmask for IPv4
116 16 // bitmask for IPv6
117 ) :
118 req.ip
119})
120morgan.token('user-agent', req => (req.get('DNT') === '1') ?
121 useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
122app.use(morgan('combined', {
123 stream: { write: logger.info.bind(logger) }
124}))
125// For body requests
126app.use(bodyParser.urlencoded({ extended: false }))
127app.use(bodyParser.json({
128 type: [ 'application/json', 'application/*+json' ],
129 limit: '500kb'
130}))
131// Cookies
132app.use(cookieParser())
133// W3C DNT Tracking Status
134app.use(advertiseDoNotTrack)
135
136// ----------- Views, routes and static files -----------
137
138// API
139const apiRoute = '/api/' + API_VERSION
140app.use(apiRoute, apiRouter)
141
142// Services (oembed...)
143app.use('/services', servicesRouter)
144
145app.use('/', activityPubRouter)
146app.use('/', feedsRouter)
147app.use('/', webfingerRouter)
148app.use('/', trackerRouter)
149
150// Static files
151app.use('/', staticRouter)
152
153// Client files, last valid routes!
154app.use('/', clientsRouter)
155
156// ----------- Errors -----------
157
158// Catch 404 and forward to error handler
159app.use(function (req, res, next) {
160 const err = new Error('Not Found')
161 err['status'] = 404
162 next(err)
163})
164
165app.use(function (err, req, res, next) {
166 let error = 'Unknown error.'
167 if (err) {
168 error = err.stack || err.message || err
169 }
170
171 // Sequelize error
172 const sql = err.parent ? err.parent.sql : undefined
173
174 logger.error('Error in controller.', { err: error, sql })
175 return res.status(err.status || 500).end()
176})
177
178const server = createWebsocketServer(app)
179
180// ----------- Run -----------
181
182async function startApplication () {
183 const port = CONFIG.LISTEN.PORT
184 const hostname = CONFIG.LISTEN.HOSTNAME
185
186 await installApplication()
187
188 // Check activity pub urls are valid
189 checkActivityPubUrls()
190 .catch(err => {
191 logger.error('Error in ActivityPub URLs checker.', { err })
192 process.exit(-1)
193 })
194
195 // Email initialization
196 Emailer.Instance.init()
197 await Emailer.Instance.checkConnectionOrDie()
198
199 await JobQueue.Instance.init()
200
201 // Caches initializations
202 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
203 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
204
205 // Enable Schedulers
206 BadActorFollowScheduler.Instance.enable()
207 RemoveOldJobsScheduler.Instance.enable()
208 UpdateVideosScheduler.Instance.enable()
209 YoutubeDlUpdateScheduler.Instance.enable()
210 VideosRedundancyScheduler.Instance.enable()
211
212 // Redis initialization
213 Redis.Instance.init()
214
215 // Make server listening
216 server.listen(port, hostname, () => {
217 logger.info('Server listening on %s:%d', hostname, port)
218 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
219 })
220
221 process.on('exit', () => {
222 JobQueue.Instance.terminate()
223 })
224
225 process.on('SIGINT', () => process.exit(0))
226}