server.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // ----------- Node modules -----------
  2. import express from 'express'
  3. import morgan, { token } from 'morgan'
  4. import cors from 'cors'
  5. import cookieParser from 'cookie-parser'
  6. import { frameguard } from 'helmet'
  7. import { parse } from 'useragent'
  8. import anonymize from 'ip-anonymize'
  9. import { program as cli } from 'commander'
  10. process.title = 'peertube'
  11. // Create our main app
  12. const app = express().disable('x-powered-by')
  13. // ----------- Core checker -----------
  14. import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
  15. // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
  16. import { CONFIG } from './server/initializers/config'
  17. import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
  18. import { logger } from './server/helpers/logger'
  19. const missed = checkMissedConfig()
  20. if (missed.length !== 0) {
  21. logger.error('Your configuration files miss keys: ' + missed)
  22. process.exit(-1)
  23. }
  24. checkFFmpeg(CONFIG)
  25. .catch(err => {
  26. logger.error('Error in ffmpeg check.', { err })
  27. process.exit(-1)
  28. })
  29. try {
  30. checkNodeVersion()
  31. } catch (err) {
  32. logger.error('Error in NodeJS check.', { err })
  33. process.exit(-1)
  34. }
  35. import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
  36. checkConfig()
  37. // Trust our proxy (IP forwarding...)
  38. app.set('trust proxy', CONFIG.TRUST_PROXY)
  39. // Security middleware
  40. import { baseCSP } from './server/middlewares/csp'
  41. if (CONFIG.CSP.ENABLED) {
  42. app.use(baseCSP)
  43. }
  44. if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
  45. app.use(frameguard({
  46. action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
  47. }))
  48. }
  49. // ----------- Database -----------
  50. // Initialize database and models
  51. import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
  52. checkDatabaseConnectionOrDie()
  53. import { migrate } from './server/initializers/migrator'
  54. migrate()
  55. .then(() => initDatabaseModels(false))
  56. .then(() => startApplication())
  57. .catch(err => {
  58. logger.error('Cannot start application.', { err })
  59. process.exit(-1)
  60. })
  61. // ----------- Initialize -----------
  62. loadLanguages()
  63. // ----------- PeerTube modules -----------
  64. import { installApplication } from './server/initializers/installer'
  65. import { Emailer } from './server/lib/emailer'
  66. import { JobQueue } from './server/lib/job-queue'
  67. import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
  68. import {
  69. activityPubRouter,
  70. apiRouter,
  71. clientsRouter,
  72. feedsRouter,
  73. staticRouter,
  74. lazyStaticRouter,
  75. servicesRouter,
  76. liveRouter,
  77. pluginsRouter,
  78. webfingerRouter,
  79. trackerRouter,
  80. createWebsocketTrackerServer,
  81. botsRouter,
  82. downloadRouter
  83. } from './server/controllers'
  84. import { advertiseDoNotTrack } from './server/middlewares/dnt'
  85. import { apiFailMiddleware } from './server/middlewares/error'
  86. import { Redis } from './server/lib/redis'
  87. import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
  88. import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
  89. import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
  90. import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
  91. import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
  92. import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
  93. import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
  94. import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
  95. import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
  96. import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
  97. import { GeoIPUpdateScheduler } from './server/lib/schedulers/geo-ip-update-scheduler'
  98. import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
  99. import { PeerTubeSocket } from './server/lib/peertube-socket'
  100. import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
  101. import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
  102. import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
  103. import { Hooks } from './server/lib/plugins/hooks'
  104. import { PluginManager } from './server/lib/plugins/plugin-manager'
  105. import { LiveManager } from './server/lib/live'
  106. import { HttpStatusCode } from './shared/models/http/http-error-codes'
  107. import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
  108. import { ServerConfigManager } from '@server/lib/server-config-manager'
  109. import { VideoViewsManager } from '@server/lib/views/video-views-manager'
  110. import { isTestInstance } from './server/helpers/core-utils'
  111. // ----------- Command line -----------
  112. cli
  113. .option('--no-client', 'Start PeerTube without client interface')
  114. .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
  115. .option('--benchmark-startup', 'Automatically stop server when initialized')
  116. .parse(process.argv)
  117. // ----------- App -----------
  118. // Enable CORS for develop
  119. if (isTestInstance()) {
  120. app.use(cors({
  121. origin: '*',
  122. exposedHeaders: 'Retry-After',
  123. credentials: true
  124. }))
  125. }
  126. // For the logger
  127. token('remote-addr', (req: express.Request) => {
  128. if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
  129. return anonymize(req.ip, 16, 16)
  130. }
  131. return req.ip
  132. })
  133. token('user-agent', (req: express.Request) => {
  134. if (req.get('DNT') === '1') {
  135. return parse(req.get('user-agent')).family
  136. }
  137. return req.get('user-agent')
  138. })
  139. app.use(morgan('combined', {
  140. stream: {
  141. write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
  142. },
  143. skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
  144. }))
  145. // Add .fail() helper to response
  146. app.use(apiFailMiddleware)
  147. // For body requests
  148. app.use(express.urlencoded({ extended: false }))
  149. app.use(express.json({
  150. type: [ 'application/json', 'application/*+json' ],
  151. limit: '500kb',
  152. verify: (req: express.Request, res: express.Response, buf: Buffer) => {
  153. const valid = isHTTPSignatureDigestValid(buf, req)
  154. if (valid !== true) {
  155. res.fail({
  156. status: HttpStatusCode.FORBIDDEN_403,
  157. message: 'Invalid digest'
  158. })
  159. }
  160. }
  161. }))
  162. // Cookies
  163. app.use(cookieParser())
  164. // W3C DNT Tracking Status
  165. app.use(advertiseDoNotTrack)
  166. // ----------- Views, routes and static files -----------
  167. // API
  168. const apiRoute = '/api/' + API_VERSION
  169. app.use(apiRoute, apiRouter)
  170. // Services (oembed...)
  171. app.use('/services', servicesRouter)
  172. // Live streaming
  173. app.use('/live', liveRouter)
  174. // Plugins & themes
  175. app.use('/', pluginsRouter)
  176. app.use('/', activityPubRouter)
  177. app.use('/', feedsRouter)
  178. app.use('/', webfingerRouter)
  179. app.use('/', trackerRouter)
  180. app.use('/', botsRouter)
  181. // Static files
  182. app.use('/', staticRouter)
  183. app.use('/', downloadRouter)
  184. app.use('/', lazyStaticRouter)
  185. // Client files, last valid routes!
  186. const cliOptions = cli.opts()
  187. if (cliOptions.client) app.use('/', clientsRouter)
  188. // ----------- Errors -----------
  189. // Catch unmatched routes
  190. app.use((req, res: express.Response) => {
  191. res.status(HttpStatusCode.NOT_FOUND_404).end()
  192. })
  193. // Catch thrown errors
  194. app.use((err, req, res: express.Response, next) => {
  195. // Format error to be logged
  196. let error = 'Unknown error.'
  197. if (err) {
  198. error = err.stack || err.message || err
  199. }
  200. // Handling Sequelize error traces
  201. const sql = err.parent ? err.parent.sql : undefined
  202. logger.error('Error in controller.', { err: error, sql })
  203. return res.fail({
  204. status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
  205. message: err.message,
  206. type: err.name
  207. })
  208. })
  209. const server = createWebsocketTrackerServer(app)
  210. // ----------- Run -----------
  211. async function startApplication () {
  212. const port = CONFIG.LISTEN.PORT
  213. const hostname = CONFIG.LISTEN.HOSTNAME
  214. await installApplication()
  215. // Check activity pub urls are valid
  216. checkActivityPubUrls()
  217. .catch(err => {
  218. logger.error('Error in ActivityPub URLs checker.', { err })
  219. process.exit(-1)
  220. })
  221. checkFFmpegVersion()
  222. .catch(err => logger.error('Cannot check ffmpeg version', { err }))
  223. // Email initialization
  224. Emailer.Instance.init()
  225. await Promise.all([
  226. Emailer.Instance.checkConnection(),
  227. JobQueue.Instance.init(),
  228. ServerConfigManager.Instance.init()
  229. ])
  230. // Caches initializations
  231. VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
  232. VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
  233. VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
  234. // Enable Schedulers
  235. ActorFollowScheduler.Instance.enable()
  236. RemoveOldJobsScheduler.Instance.enable()
  237. UpdateVideosScheduler.Instance.enable()
  238. YoutubeDlUpdateScheduler.Instance.enable()
  239. VideosRedundancyScheduler.Instance.enable()
  240. RemoveOldHistoryScheduler.Instance.enable()
  241. RemoveOldViewsScheduler.Instance.enable()
  242. PluginsCheckScheduler.Instance.enable()
  243. PeerTubeVersionCheckScheduler.Instance.enable()
  244. AutoFollowIndexInstances.Instance.enable()
  245. RemoveDanglingResumableUploadsScheduler.Instance.enable()
  246. VideoViewsBufferScheduler.Instance.enable()
  247. GeoIPUpdateScheduler.Instance.enable()
  248. Redis.Instance.init()
  249. PeerTubeSocket.Instance.init(server)
  250. VideoViewsManager.Instance.init()
  251. updateStreamingPlaylistsInfohashesIfNeeded()
  252. .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
  253. LiveManager.Instance.init()
  254. if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
  255. // Make server listening
  256. server.listen(port, hostname, async () => {
  257. if (cliOptions.plugins) {
  258. try {
  259. await PluginManager.Instance.registerPluginsAndThemes()
  260. } catch (err) {
  261. logger.error('Cannot register plugins and themes.', { err })
  262. }
  263. }
  264. logger.info('HTTP server listening on %s:%d', hostname, port)
  265. logger.info('Web server: %s', WEBSERVER.URL)
  266. Hooks.runAction('action:application.listening')
  267. if (cliOptions['benchmarkStartup']) process.exit(0)
  268. })
  269. process.on('exit', () => {
  270. JobQueue.Instance.terminate()
  271. })
  272. process.on('SIGINT', () => process.exit(0))
  273. }