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