server.ts 10.0 KB

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