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 } from './server/initializers/database'
74 import { migrate } from './server/initializers/migrator'
76 .then(() => initDatabaseModels(false))
77 .then(() => startApplication())
79 logger.error('Cannot start application.', { err })
83 // ----------- Initialize -----------
86 // ----------- PeerTube modules -----------
87 import { installApplication } from './server/initializers'
88 import { Emailer } from './server/lib/emailer'
89 import { JobQueue } from './server/lib/job-queue'
90 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
102 createWebsocketTrackerServer, botsRouter
103 } from './server/controllers'
104 import { advertiseDoNotTrack } from './server/middlewares/dnt'
105 import { Redis } from './server/lib/redis'
106 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
107 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
108 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
109 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
110 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
111 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
112 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
113 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
114 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
115 import { PeerTubeSocket } from './server/lib/peertube-socket'
116 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
117 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
118 import { Hooks } from './server/lib/plugins/hooks'
119 import { PluginManager } from './server/lib/plugins/plugin-manager'
121 // ----------- Command line -----------
124 .option('--no-client', 'Start PeerTube without client interface')
125 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
128 // ----------- App -----------
130 // Enable CORS for develop
131 if (isTestInstance()) {
134 exposedHeaders: 'Retry-After',
140 morgan.token('remote-addr', req => {
141 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
142 return anonymize(req.ip, 16, 16)
147 morgan.token('user-agent', req => {
148 if (req.get('DNT') === '1') {
149 return useragent.parse(req.get('user-agent')).family
152 return req.get('user-agent')
154 app.use(morgan('combined', {
155 stream: { write: logger.info.bind(logger) }
159 app.use(bodyParser.urlencoded({ extended: false }))
160 app.use(bodyParser.json({
161 type: [ 'application/json', 'application/*+json' ],
163 verify: (req: express.Request, _, buf: Buffer) => {
164 const valid = isHTTPSignatureDigestValid(buf, req)
165 if (valid !== true) throw new Error('Invalid digest')
170 app.use(cookieParser())
172 // W3C DNT Tracking Status
173 app.use(advertiseDoNotTrack)
175 // ----------- Views, routes and static files -----------
178 const apiRoute = '/api/' + API_VERSION
179 app.use(apiRoute, apiRouter)
181 // Services (oembed...)
182 app.use('/services', servicesRouter)
185 app.use('/', pluginsRouter)
187 app.use('/', activityPubRouter)
188 app.use('/', feedsRouter)
189 app.use('/', webfingerRouter)
190 app.use('/', trackerRouter)
191 app.use('/', botsRouter)
194 app.use('/', staticRouter)
195 app.use('/', lazyStaticRouter)
197 // Client files, last valid routes!
198 if (cli.client) app.use('/', clientsRouter)
200 // ----------- Errors -----------
202 // Catch 404 and forward to error handler
203 app.use(function (req, res, next) {
204 const err = new Error('Not Found')
209 app.use(function (err, req, res, next) {
210 let error = 'Unknown error.'
212 error = err.stack || err.message || err
216 const sql = err.parent ? err.parent.sql : undefined
218 logger.error('Error in controller.', { err: error, sql })
219 return res.status(err.status || 500).end()
222 const server = createWebsocketTrackerServer(app)
224 // ----------- Run -----------
226 async function startApplication () {
227 const port = CONFIG.LISTEN.PORT
228 const hostname = CONFIG.LISTEN.HOSTNAME
230 await installApplication()
232 // Check activity pub urls are valid
233 checkActivityPubUrls()
235 logger.error('Error in ActivityPub URLs checker.', { err })
239 // Email initialization
240 Emailer.Instance.init()
243 Emailer.Instance.checkConnectionOrDie(),
244 JobQueue.Instance.init()
247 // Caches initializations
248 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
249 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
252 ActorFollowScheduler.Instance.enable()
253 RemoveOldJobsScheduler.Instance.enable()
254 UpdateVideosScheduler.Instance.enable()
255 YoutubeDlUpdateScheduler.Instance.enable()
256 VideosRedundancyScheduler.Instance.enable()
257 RemoveOldHistoryScheduler.Instance.enable()
258 RemoveOldViewsScheduler.Instance.enable()
259 PluginsCheckScheduler.Instance.enable()
260 AutoFollowIndexInstances.Instance.enable()
262 // Redis initialization
263 Redis.Instance.init()
265 PeerTubeSocket.Instance.init(server)
267 updateStreamingPlaylistsInfohashesIfNeeded()
268 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
270 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
272 // Make server listening
273 server.listen(port, hostname, () => {
274 logger.info('Server listening on %s:%d', hostname, port)
275 logger.info('Web server: %s', WEBSERVER.URL)
277 Hooks.runAction('action:application.listening')
280 process.on('exit', () => {
281 JobQueue.Instance.terminate()
284 process.on('SIGINT', () => process.exit(0))