server.ts 9.3 KB

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