1 import { registerTSPaths } from './server/helpers/register-ts-paths'
4 import { isTestInstance } from './server/helpers/core-utils'
5 if (isTestInstance()) {
6 require('source-map-support').install()
9 // ----------- Node modules -----------
10 import * as bodyParser from 'body-parser'
11 import * as express from 'express'
12 import * as morgan from 'morgan'
13 import * as cors from 'cors'
14 import * as cookieParser from 'cookie-parser'
15 import * as helmet from 'helmet'
16 import * as useragent from 'useragent'
17 import * as anonymize from 'ip-anonymize'
18 import * as cli from 'commander'
20 process.title = 'peertube'
22 // Create our main app
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
28 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29 import { CONFIG } from './server/initializers/config'
30 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
31 import { logger } from './server/helpers/logger'
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35 logger.error('Your configuration files miss keys: ' + missed)
41 logger.error('Error in ffmpeg check.', { err })
47 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
49 const errorMessage = checkConfig()
50 if (errorMessage !== null) {
51 throw new Error(errorMessage)
54 // Trust our proxy (IP forwarding...)
55 app.set('trust proxy', CONFIG.TRUST_PROXY)
57 // Security middleware
58 import { baseCSP } from './server/middlewares/csp'
60 if (CONFIG.CSP.ENABLED) {
64 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
70 // ----------- Database -----------
72 // Initialize database and models
73 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
74 checkDatabaseConnectionOrDie()
76 import { migrate } from './server/initializers/migrator'
78 .then(() => initDatabaseModels(false))
79 .then(() => startApplication())
81 logger.error('Cannot start application.', { err })
85 // ----------- Initialize -----------
88 // ----------- PeerTube modules -----------
89 import { installApplication } from './server/initializers/installer'
90 import { Emailer } from './server/lib/emailer'
91 import { JobQueue } from './server/lib/job-queue'
92 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
104 createWebsocketTrackerServer, botsRouter
105 } from './server/controllers'
106 import { advertiseDoNotTrack } from './server/middlewares/dnt'
107 import { Redis } from './server/lib/redis'
108 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
109 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
110 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
111 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
112 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
113 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
114 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
115 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
116 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
117 import { PeerTubeSocket } from './server/lib/peertube-socket'
118 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
119 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
120 import { Hooks } from './server/lib/plugins/hooks'
121 import { PluginManager } from './server/lib/plugins/plugin-manager'
123 // ----------- Command line -----------
126 .option('--no-client', 'Start PeerTube without client interface')
127 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
130 // ----------- App -----------
132 // Enable CORS for develop
133 if (isTestInstance()) {
136 exposedHeaders: 'Retry-After',
142 morgan.token<express.Request>('remote-addr', req => {
143 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
144 return anonymize(req.ip, 16, 16)
149 morgan.token<express.Request>('user-agent', req => {
150 if (req.get('DNT') === '1') {
151 return useragent.parse(req.get('user-agent')).family
154 return req.get('user-agent')
156 app.use(morgan('combined', {
157 stream: { write: logger.info.bind(logger) }
161 app.use(bodyParser.urlencoded({ extended: false }))
162 app.use(bodyParser.json({
163 type: [ 'application/json', 'application/*+json' ],
165 verify: (req: express.Request, _, buf: Buffer) => {
166 const valid = isHTTPSignatureDigestValid(buf, req)
167 if (valid !== true) throw new Error('Invalid digest')
172 app.use(cookieParser())
174 // W3C DNT Tracking Status
175 app.use(advertiseDoNotTrack)
177 // ----------- Views, routes and static files -----------
180 const apiRoute = '/api/' + API_VERSION
181 app.use(apiRoute, apiRouter)
183 // Services (oembed...)
184 app.use('/services', servicesRouter)
187 app.use('/', pluginsRouter)
189 app.use('/', activityPubRouter)
190 app.use('/', feedsRouter)
191 app.use('/', webfingerRouter)
192 app.use('/', trackerRouter)
193 app.use('/', botsRouter)
196 app.use('/', staticRouter)
197 app.use('/', lazyStaticRouter)
199 // Client files, last valid routes!
200 if (cli.client) app.use('/', clientsRouter)
202 // ----------- Errors -----------
204 // Catch 404 and forward to error handler
205 app.use(function (req, res, next) {
206 const err = new Error('Not Found')
211 app.use(function (err, req, res, next) {
212 let error = 'Unknown error.'
214 error = err.stack || err.message || err
218 const sql = err.parent ? err.parent.sql : undefined
220 logger.error('Error in controller.', { err: error, sql })
221 return res.status(err.status || 500).end()
224 const server = createWebsocketTrackerServer(app)
226 // ----------- Run -----------
228 async function startApplication () {
229 const port = CONFIG.LISTEN.PORT
230 const hostname = CONFIG.LISTEN.HOSTNAME
232 await installApplication()
234 // Check activity pub urls are valid
235 checkActivityPubUrls()
237 logger.error('Error in ActivityPub URLs checker.', { err })
241 // Email initialization
242 Emailer.Instance.init()
245 Emailer.Instance.checkConnectionOrDie(),
246 JobQueue.Instance.init()
249 // Caches initializations
250 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
251 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
254 ActorFollowScheduler.Instance.enable()
255 RemoveOldJobsScheduler.Instance.enable()
256 UpdateVideosScheduler.Instance.enable()
257 YoutubeDlUpdateScheduler.Instance.enable()
258 VideosRedundancyScheduler.Instance.enable()
259 RemoveOldHistoryScheduler.Instance.enable()
260 RemoveOldViewsScheduler.Instance.enable()
261 PluginsCheckScheduler.Instance.enable()
262 AutoFollowIndexInstances.Instance.enable()
264 // Redis initialization
265 Redis.Instance.init()
267 PeerTubeSocket.Instance.init(server)
269 updateStreamingPlaylistsInfohashesIfNeeded()
270 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
272 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
274 // Make server listening
275 server.listen(port, hostname, () => {
276 logger.info('Server listening on %s:%d', hostname, port)
277 logger.info('Web server: %s', WEBSERVER.URL)
279 Hooks.runAction('action:application.listening')
282 process.on('exit', () => {
283 JobQueue.Instance.terminate()
286 process.on('SIGINT', () => process.exit(0))