]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server.ts
Move CLI dependencies in their own package.json
[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'
b83b8dd5 19import * as cli from 'commander'
a030a9b2 20
9f540774
C
21process.title = 'peertube'
22
a030a9b2 23// Create our main app
13ce1d01 24const app = express()
a030a9b2 25
3482688c 26// ----------- Core checker -----------
e5565833 27import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
69b0a27c 28
d5b7d911
C
29// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30import { logger } from './server/helpers/logger'
74dc3bca
C
31import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
32import { CONFIG } from './server/initializers/config'
d5b7d911 33
65fcc311 34const missed = checkMissedConfig()
b65c27aa 35if (missed.length !== 0) {
d5b7d911
C
36 logger.error('Your configuration files miss keys: ' + missed)
37 process.exit(-1)
b65c27aa 38}
3482688c 39
3482688c 40checkFFmpeg(CONFIG)
d5b7d911
C
41 .catch(err => {
42 logger.error('Error in ffmpeg check.', { err })
43 process.exit(-1)
44 })
b65c27aa 45
e5565833
C
46import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
47
65fcc311 48const errorMessage = checkConfig()
b65c27aa
C
49if (errorMessage !== null) {
50 throw new Error(errorMessage)
69b0a27c
C
51}
52
490b595a
C
53// Trust our proxy (IP forwarding...)
54app.set('trust proxy', CONFIG.TRUST_PROXY)
55
57c36b27 56// Security middleware
418d092a 57import { baseCSP } from './server/middlewares/csp'
5e755fff 58
539d3f4f
C
59if (CONFIG.CSP.ENABLED) {
60 app.use(baseCSP)
61 app.use(helmet({
62 frameguard: {
63 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
64 },
65 hsts: false
66 }))
67}
d00e2393 68
3482688c 69// ----------- Database -----------
91fea9fc 70
3482688c 71// Initialize database and models
91fea9fc
C
72import { initDatabaseModels } from './server/initializers/database'
73import { migrate } from './server/initializers/migrator'
74migrate()
75 .then(() => initDatabaseModels(false))
3d3441d6
C
76 .then(() => startApplication())
77 .catch(err => {
78 logger.error('Cannot start application.', { err })
79 process.exit(-1)
80 })
3482688c 81
74dc3bca
C
82// ----------- Initialize -----------
83loadLanguages()
84
00057e85 85// ----------- PeerTube modules -----------
91fea9fc 86import { installApplication } from './server/initializers'
ecb4e35f 87import { Emailer } from './server/lib/emailer'
94a5ff8a 88import { JobQueue } from './server/lib/job-queue'
d74d29ad 89import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
244e76a5
RK
90import {
91 activityPubRouter,
92 apiRouter,
93 clientsRouter,
94 feedsRouter,
95 staticRouter,
96 servicesRouter,
9b67da3d
C
97 webfingerRouter,
98 trackerRouter,
cef534ed 99 createWebsocketTrackerServer, botsRouter
244e76a5 100} from './server/controllers'
aad0ec24 101import { advertiseDoNotTrack } from './server/middlewares/dnt'
ecb4e35f 102import { Redis } from './server/lib/redis'
2f5c6b2f 103import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
cda03765 104import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
94a5ff8a 105import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
2baea0c7 106import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
ce32426b 107import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
c48e82b5 108import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
8f0bc73d 109import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
df66d815 110import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
cef534ed 111import { PeerTubeSocket } from './server/lib/peertube-socket'
ae9bbed4 112import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
a030a9b2 113
a030a9b2
C
114// ----------- Command line -----------
115
b83b8dd5
RK
116cli
117 .option('--no-client', 'Start PeerTube without client interface')
118 .parse(process.argv)
119
a030a9b2
C
120// ----------- App -----------
121
12daa837
WL
122// Enable CORS for develop
123if (isTestInstance()) {
62945f06
C
124 app.use(cors({
125 origin: '*',
126 exposedHeaders: 'Retry-After',
127 credentials: true
128 }))
12daa837 129}
74dc3bca 130
a030a9b2 131// For the logger
aad0ec24 132morgan.token('remote-addr', req => {
74dc3bca
C
133 if (req.get('DNT') === '1') {
134 return anonymize(req.ip, 16, 16)
135 }
136
137 return req.ip
138})
139morgan.token('user-agent', req => {
140 if (req.get('DNT') === '1') {
141 return useragent.parse(req.get('user-agent')).family
142 }
143
144 return req.get('user-agent')
aad0ec24 145})
e02643f3 146app.use(morgan('combined', {
23e27dd5 147 stream: { write: logger.info.bind(logger) }
e02643f3 148}))
74dc3bca 149
a030a9b2 150// For body requests
bf9ae5ce 151app.use(bodyParser.urlencoded({ extended: false }))
165cdc75 152app.use(bodyParser.json({
86d13ec2 153 type: [ 'application/json', 'application/*+json' ],
df66d815 154 limit: '500kb',
cef534ed 155 verify: (req: express.Request, _, buf: Buffer) => {
df66d815
C
156 const valid = isHTTPSignatureDigestValid(buf, req)
157 if (valid !== true) throw new Error('Invalid digest')
158 }
165cdc75 159}))
74dc3bca 160
8afc19a6
C
161// Cookies
162app.use(cookieParser())
74dc3bca 163
aad0ec24
RK
164// W3C DNT Tracking Status
165app.use(advertiseDoNotTrack)
a030a9b2 166
a96aed15
C
167// ----------- Views, routes and static files -----------
168
169// API
170const apiRoute = '/api/' + API_VERSION
171app.use(apiRoute, apiRouter)
172
173// Services (oembed...)
174app.use('/services', servicesRouter)
175
350e31d6 176app.use('/', activityPubRouter)
244e76a5
RK
177app.use('/', feedsRouter)
178app.use('/', webfingerRouter)
9b67da3d 179app.use('/', trackerRouter)
2feebf3e 180app.use('/', botsRouter)
350e31d6 181
a96aed15
C
182// Static files
183app.use('/', staticRouter)
184
989e526a 185// Client files, last valid routes!
b83b8dd5 186if (cli.client) app.use('/', clientsRouter)
a96aed15 187
a030a9b2
C
188// ----------- Errors -----------
189
190// Catch 404 and forward to error handler
191app.use(function (req, res, next) {
13ce1d01 192 const err = new Error('Not Found')
65fcc311 193 err['status'] = 404
a030a9b2
C
194 next(err)
195})
196
6f4e2522 197app.use(function (err, req, res, next) {
e3a682a8
C
198 let error = 'Unknown error.'
199 if (err) {
200 error = err.stack || err.message || err
201 }
202
328e607d
C
203 // Sequelize error
204 const sql = err.parent ? err.parent.sql : undefined
205
206 logger.error('Error in controller.', { err: error, sql })
e3a682a8 207 return res.status(err.status || 500).end()
6f4e2522 208})
a030a9b2 209
cef534ed 210const server = createWebsocketTrackerServer(app)
9b67da3d 211
79530164
C
212// ----------- Run -----------
213
3d3441d6 214async function startApplication () {
65fcc311 215 const port = CONFIG.LISTEN.PORT
cff8b272 216 const hostname = CONFIG.LISTEN.HOSTNAME
91fea9fc 217
3d3441d6
C
218 await installApplication()
219
23687332
C
220 // Check activity pub urls are valid
221 checkActivityPubUrls()
222 .catch(err => {
223 logger.error('Error in ActivityPub URLs checker.', { err })
224 process.exit(-1)
225 })
226
3d3441d6
C
227 // Email initialization
228 Emailer.Instance.init()
3d3441d6 229
0b2f03d3
C
230 await Promise.all([
231 Emailer.Instance.checkConnectionOrDie(),
232 JobQueue.Instance.init()
233 ])
3d3441d6
C
234
235 // Caches initializations
d74d29ad
C
236 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
237 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
3d3441d6
C
238
239 // Enable Schedulers
2f5c6b2f 240 ActorFollowScheduler.Instance.enable()
3d3441d6 241 RemoveOldJobsScheduler.Instance.enable()
2baea0c7 242 UpdateVideosScheduler.Instance.enable()
ce32426b 243 YoutubeDlUpdateScheduler.Instance.enable()
c48e82b5 244 VideosRedundancyScheduler.Instance.enable()
8f0bc73d 245 RemoveOldHistoryScheduler.Instance.enable()
cda03765 246 RemoveOldViewsScheduler.Instance.enable()
3d3441d6
C
247
248 // Redis initialization
249 Redis.Instance.init()
250
cef534ed
C
251 PeerTubeSocket.Instance.init(server)
252
ae9bbed4
C
253 updateStreamingPlaylistsInfohashesIfNeeded()
254 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
255
3d3441d6 256 // Make server listening
f55e5a7b
C
257 server.listen(port, hostname, () => {
258 logger.info('Server listening on %s:%d', hostname, port)
74dc3bca 259 logger.info('Web server: %s', WEBSERVER.URL)
f55e5a7b 260 })
14f2b3ad
C
261
262 process.on('exit', () => {
263 JobQueue.Instance.terminate()
264 })
265
266 process.on('SIGINT', () => process.exit(0))
5804c0db 267}