]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server.ts
fix lint test
[github/Chocobozzz/PeerTube.git] / server.ts
CommitLineData
6b467fd5
C
1// FIXME: https://github.com/nodejs/node/pull/16853
2require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
1840c2f7
C
4import { isTestInstance } from './server/helpers/core-utils'
5
6if (isTestInstance()) {
e02643f3
C
7 require('source-map-support').install()
8}
9
a030a9b2 10// ----------- Node modules -----------
4d4e5cd4
C
11import * as bodyParser from 'body-parser'
12import * as express from 'express'
4d4e5cd4 13import * as morgan from 'morgan'
1840c2f7 14import * as cors from 'cors'
8afc19a6 15import * as cookieParser from 'cookie-parser'
d00e2393 16import * as helmet from 'helmet'
aad0ec24 17import * as useragent from 'useragent'
e5565833 18import * as anonymize from 'ip-anonymize'
a030a9b2 19
9f540774
C
20process.title = 'peertube'
21
a030a9b2 22// Create our main app
13ce1d01 23const app = express()
a030a9b2 24
3482688c 25// ----------- Core checker -----------
e5565833 26import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
69b0a27c 27
d5b7d911
C
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'
aad0ec24 30import { API_VERSION, CONFIG, CACHE } from './server/initializers/constants'
d5b7d911 31
65fcc311 32const missed = checkMissedConfig()
b65c27aa 33if (missed.length !== 0) {
d5b7d911
C
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
b65c27aa 36}
3482688c 37
3482688c 38checkFFmpeg(CONFIG)
d5b7d911
C
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
b65c27aa 43
e5565833
C
44import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
45
65fcc311 46const errorMessage = checkConfig()
b65c27aa
C
47if (errorMessage !== null) {
48 throw new Error(errorMessage)
69b0a27c
C
49}
50
490b595a
C
51// Trust our proxy (IP forwarding...)
52app.set('trust proxy', CONFIG.TRUST_PROXY)
53
57c36b27 54// Security middleware
d00e2393
RK
55app.use(helmet({
56 frameguard: {
4bdd9473 57 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
6328da8c
RK
58 },
59 hsts: false
d00e2393
RK
60}))
61
3482688c 62// ----------- Database -----------
91fea9fc 63
3482688c 64// Initialize database and models
91fea9fc
C
65import { initDatabaseModels } from './server/initializers/database'
66import { migrate } from './server/initializers/migrator'
67migrate()
68 .then(() => initDatabaseModels(false))
3d3441d6
C
69 .then(() => startApplication())
70 .catch(err => {
71 logger.error('Cannot start application.', { err })
72 process.exit(-1)
73 })
3482688c 74
00057e85 75// ----------- PeerTube modules -----------
91fea9fc 76import { installApplication } from './server/initializers'
ecb4e35f 77import { Emailer } from './server/lib/emailer'
94a5ff8a 78import { JobQueue } from './server/lib/job-queue'
e5565833 79import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
244e76a5
RK
80import {
81 activityPubRouter,
82 apiRouter,
83 clientsRouter,
84 feedsRouter,
85 staticRouter,
86 servicesRouter,
9b67da3d
C
87 webfingerRouter,
88 trackerRouter,
89 createWebsocketServer
244e76a5 90} from './server/controllers'
aad0ec24 91import { advertiseDoNotTrack } from './server/middlewares/dnt'
ecb4e35f 92import { Redis } from './server/lib/redis'
60650c77 93import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
94a5ff8a 94import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
2baea0c7 95import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
ce32426b 96import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
c48e82b5 97import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
a030a9b2 98
a030a9b2
C
99// ----------- Command line -----------
100
101// ----------- App -----------
102
12daa837
WL
103// Enable CORS for develop
104if (isTestInstance()) {
62945f06
C
105 app.use(cors({
106 origin: '*',
107 exposedHeaders: 'Retry-After',
108 credentials: true
109 }))
12daa837 110}
a030a9b2 111// For the logger
aad0ec24
RK
112morgan.token('remote-addr', req => {
113 return (req.get('DNT') === '1') ?
e5565833 114 anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
aad0ec24
RK
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'))
e02643f3 122app.use(morgan('combined', {
23e27dd5 123 stream: { write: logger.info.bind(logger) }
e02643f3 124}))
a030a9b2 125// For body requests
bf9ae5ce 126app.use(bodyParser.urlencoded({ extended: false }))
165cdc75 127app.use(bodyParser.json({
86d13ec2 128 type: [ 'application/json', 'application/*+json' ],
165cdc75
C
129 limit: '500kb'
130}))
8afc19a6
C
131// Cookies
132app.use(cookieParser())
aad0ec24
RK
133// W3C DNT Tracking Status
134app.use(advertiseDoNotTrack)
a030a9b2 135
a96aed15
C
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
350e31d6 145app.use('/', activityPubRouter)
244e76a5
RK
146app.use('/', feedsRouter)
147app.use('/', webfingerRouter)
9b67da3d 148app.use('/', trackerRouter)
350e31d6 149
a96aed15
C
150// Static files
151app.use('/', staticRouter)
152
989e526a
C
153// Client files, last valid routes!
154app.use('/', clientsRouter)
a96aed15 155
a030a9b2
C
156// ----------- Errors -----------
157
158// Catch 404 and forward to error handler
159app.use(function (req, res, next) {
13ce1d01 160 const err = new Error('Not Found')
65fcc311 161 err['status'] = 404
a030a9b2
C
162 next(err)
163})
164
6f4e2522 165app.use(function (err, req, res, next) {
e3a682a8
C
166 let error = 'Unknown error.'
167 if (err) {
168 error = err.stack || err.message || err
169 }
170
328e607d
C
171 // Sequelize error
172 const sql = err.parent ? err.parent.sql : undefined
173
174 logger.error('Error in controller.', { err: error, sql })
e3a682a8 175 return res.status(err.status || 500).end()
6f4e2522 176})
a030a9b2 177
9b67da3d
C
178const server = createWebsocketServer(app)
179
79530164
C
180// ----------- Run -----------
181
3d3441d6 182async function startApplication () {
65fcc311 183 const port = CONFIG.LISTEN.PORT
cff8b272 184 const hostname = CONFIG.LISTEN.HOSTNAME
91fea9fc 185
3d3441d6
C
186 await installApplication()
187
23687332
C
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
3d3441d6
C
195 // Email initialization
196 Emailer.Instance.init()
197 await Emailer.Instance.checkConnectionOrDie()
198
199 await JobQueue.Instance.init()
200
201 // Caches initializations
f4001cf4
C
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)
3d3441d6
C
204
205 // Enable Schedulers
206 BadActorFollowScheduler.Instance.enable()
207 RemoveOldJobsScheduler.Instance.enable()
2baea0c7 208 UpdateVideosScheduler.Instance.enable()
ce32426b 209 YoutubeDlUpdateScheduler.Instance.enable()
c48e82b5 210 VideosRedundancyScheduler.Instance.enable()
3d3441d6
C
211
212 // Redis initialization
213 Redis.Instance.init()
214
215 // Make server listening
f55e5a7b
C
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 })
14f2b3ad
C
220
221 process.on('exit', () => {
222 JobQueue.Instance.terminate()
223 })
224
225 process.on('SIGINT', () => process.exit(0))
5804c0db 226}