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 express from 'express'
11 import * as morgan from 'morgan'
12 import * as cors from 'cors'
13 import * as cookieParser from 'cookie-parser'
14 import * as helmet from 'helmet'
15 import * as useragent from 'useragent'
16 import * as anonymize from 'ip-anonymize'
17 import * as cli from 'commander'
19 process.title = 'peertube'
21 // Create our main app
22 const app = express().disable("x-powered-by")
24 // ----------- Core checker -----------
25 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
27 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
28 import { CONFIG } from './server/initializers/config'
29 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
30 import { logger } from './server/helpers/logger'
32 const missed = checkMissedConfig()
33 if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
40 logger.error('Error in ffmpeg check.', { err })
46 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
48 const errorMessage = checkConfig()
49 if (errorMessage !== null) {
50 throw new Error(errorMessage)
53 // Trust our proxy (IP forwarding...)
54 app.set('trust proxy', CONFIG.TRUST_PROXY)
56 // Security middleware
57 import { baseCSP } from './server/middlewares/csp'
59 if (CONFIG.CSP.ENABLED) {
63 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
64 app.use(helmet.frameguard({
65 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
69 // ----------- Database -----------
71 // Initialize database and models
72 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
73 checkDatabaseConnectionOrDie()
75 import { migrate } from './server/initializers/migrator'
77 .then(() => initDatabaseModels(false))
78 .then(() => startApplication())
80 logger.error('Cannot start application.', { err })
84 // ----------- Initialize -----------
87 // ----------- PeerTube modules -----------
88 import { installApplication } from './server/initializers/installer'
89 import { Emailer } from './server/lib/emailer'
90 import { JobQueue } from './server/lib/job-queue'
91 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
104 createWebsocketTrackerServer,
107 } from './server/controllers'
108 import { advertiseDoNotTrack } from './server/middlewares/dnt'
109 import { apiFailMiddleware } from './server/middlewares/error'
110 import { Redis } from './server/lib/redis'
111 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
112 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
113 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
114 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
115 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
116 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
117 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
118 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
119 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
120 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
121 import { PeerTubeSocket } from './server/lib/peertube-socket'
122 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
123 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
124 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
125 import { Hooks } from './server/lib/plugins/hooks'
126 import { PluginManager } from './server/lib/plugins/plugin-manager'
127 import { LiveManager } from './server/lib/live-manager'
128 import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes'
129 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
130 import { ServerConfigManager } from '@server/lib/server-config-manager'
132 // ----------- Command line -----------
135 .option('--no-client', 'Start PeerTube without client interface')
136 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
139 // ----------- App -----------
141 // Enable CORS for develop
142 if (isTestInstance()) {
145 exposedHeaders: 'Retry-After',
151 morgan.token('remote-addr', (req: express.Request) => {
152 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
153 return anonymize(req.ip, 16, 16)
158 morgan.token('user-agent', (req: express.Request) => {
159 if (req.get('DNT') === '1') {
160 return useragent.parse(req.get('user-agent')).family
163 return req.get('user-agent')
165 app.use(morgan('combined', {
167 write: (str: string) => logger.info(str, { tags: [ 'http' ] })
169 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
172 // Add .fail() helper to response
173 app.use(apiFailMiddleware)
176 app.use(express.urlencoded({ extended: false }))
177 app.use(express.json({
178 type: [ 'application/json', 'application/*+json' ],
180 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
181 const valid = isHTTPSignatureDigestValid(buf, req)
183 if (valid !== true) {
185 status: HttpStatusCode.FORBIDDEN_403,
186 message: 'Invalid digest'
193 app.use(cookieParser())
195 // W3C DNT Tracking Status
196 app.use(advertiseDoNotTrack)
198 // ----------- Views, routes and static files -----------
201 const apiRoute = '/api/' + API_VERSION
202 app.use(apiRoute, apiRouter)
204 // Services (oembed...)
205 app.use('/services', servicesRouter)
208 app.use('/live', liveRouter)
211 app.use('/', pluginsRouter)
213 app.use('/', activityPubRouter)
214 app.use('/', feedsRouter)
215 app.use('/', webfingerRouter)
216 app.use('/', trackerRouter)
217 app.use('/', botsRouter)
220 app.use('/', staticRouter)
221 app.use('/', downloadRouter)
222 app.use('/', lazyStaticRouter)
224 // Client files, last valid routes!
225 const cliOptions = cli.opts()
226 if (cliOptions.client) app.use('/', clientsRouter)
228 // ----------- Errors -----------
230 // Catch unmatched routes
231 app.use((req, res: express.Response) => {
232 res.status(HttpStatusCode.NOT_FOUND_404).end()
235 // Catch thrown errors
236 app.use((err, req, res: express.Response, next) => {
237 // Format error to be logged
238 let error = 'Unknown error.'
240 error = err.stack || err.message || err
242 // Handling Sequelize error traces
243 const sql = err.parent ? err.parent.sql : undefined
244 logger.error('Error in controller.', { err: error, sql })
247 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
248 message: err.message,
253 const server = createWebsocketTrackerServer(app)
255 // ----------- Run -----------
257 async function startApplication () {
258 const port = CONFIG.LISTEN.PORT
259 const hostname = CONFIG.LISTEN.HOSTNAME
261 await installApplication()
263 // Check activity pub urls are valid
264 checkActivityPubUrls()
266 logger.error('Error in ActivityPub URLs checker.', { err })
271 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
273 // Email initialization
274 Emailer.Instance.init()
277 Emailer.Instance.checkConnection(),
278 JobQueue.Instance.init(),
279 ServerConfigManager.Instance.init()
282 // Caches initializations
283 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
284 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
285 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
288 ActorFollowScheduler.Instance.enable()
289 RemoveOldJobsScheduler.Instance.enable()
290 UpdateVideosScheduler.Instance.enable()
291 YoutubeDlUpdateScheduler.Instance.enable()
292 VideosRedundancyScheduler.Instance.enable()
293 RemoveOldHistoryScheduler.Instance.enable()
294 RemoveOldViewsScheduler.Instance.enable()
295 PluginsCheckScheduler.Instance.enable()
296 PeerTubeVersionCheckScheduler.Instance.enable()
297 AutoFollowIndexInstances.Instance.enable()
298 RemoveDanglingResumableUploadsScheduler.Instance.enable()
300 // Redis initialization
301 Redis.Instance.init()
303 PeerTubeSocket.Instance.init(server)
305 updateStreamingPlaylistsInfohashesIfNeeded()
306 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
308 if (cliOptions.plugins) await PluginManager.Instance.registerPluginsAndThemes()
310 LiveManager.Instance.init()
311 if (CONFIG.LIVE.ENABLED) LiveManager.Instance.run()
313 // Make server listening
314 server.listen(port, hostname, () => {
315 logger.info('HTTP server listening on %s:%d', hostname, port)
316 logger.info('Web server: %s', WEBSERVER.URL)
318 Hooks.runAction('action:application.listening')
321 process.on('exit', () => {
322 JobQueue.Instance.terminate()
325 process.on('SIGINT', () => process.exit(0))