client.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import { constants, promises as fs } from 'fs'
  2. import * as express from 'express'
  3. import { join } from 'path'
  4. import { root } from '../helpers/core-utils'
  5. import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
  6. import { asyncMiddleware, embedCSP } from '../middlewares'
  7. import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '../../shared/models/i18n/i18n'
  8. import { ClientHtml } from '../lib/client-html'
  9. import { logger } from '../helpers/logger'
  10. import { CONFIG } from '@server/initializers/config'
  11. const clientsRouter = express.Router()
  12. const distPath = join(root(), 'client', 'dist')
  13. const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
  14. const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
  15. // Special route that add OpenGraph and oEmbed tags
  16. // Do not use a template engine for a so little thing
  17. clientsRouter.use('/videos/watch/playlist/:id', asyncMiddleware(generateWatchPlaylistHtmlPage))
  18. clientsRouter.use('/videos/watch/:id', asyncMiddleware(generateWatchHtmlPage))
  19. clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
  20. clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
  21. const embedCSPMiddleware = CONFIG.CSP.ENABLED
  22. ? embedCSP
  23. : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
  24. clientsRouter.use(
  25. '/videos/embed',
  26. embedCSPMiddleware,
  27. (req: express.Request, res: express.Response) => {
  28. res.removeHeader('X-Frame-Options')
  29. // Don't cache HTML file since it's an index to the immutable JS/CSS files
  30. res.sendFile(embedPath, { maxAge: 0 })
  31. }
  32. )
  33. clientsRouter.use(
  34. '/videos/test-embed',
  35. (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
  36. )
  37. // Static HTML/CSS/JS client files
  38. const staticClientFiles = [
  39. 'ngsw-worker.js',
  40. 'ngsw.json'
  41. ]
  42. for (const staticClientFile of staticClientFiles) {
  43. const path = join(root(), 'client', 'dist', staticClientFile)
  44. clientsRouter.get(`/${staticClientFile}`, (req: express.Request, res: express.Response) => {
  45. res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
  46. })
  47. }
  48. // Dynamic PWA manifest
  49. clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
  50. // Static client overrides
  51. const staticClientOverrides = [
  52. 'assets/images/logo.svg',
  53. 'assets/images/favicon.png',
  54. 'assets/images/icons/icon-36x36.png',
  55. 'assets/images/icons/icon-48x48.png',
  56. 'assets/images/icons/icon-72x72.png',
  57. 'assets/images/icons/icon-96x96.png',
  58. 'assets/images/icons/icon-144x144.png',
  59. 'assets/images/icons/icon-192x192.png',
  60. 'assets/images/icons/icon-512x512.png'
  61. ]
  62. for (const staticClientOverride of staticClientOverrides) {
  63. const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
  64. clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
  65. }
  66. clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
  67. clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
  68. // 404 for static files not found
  69. clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
  70. res.sendStatus(404)
  71. })
  72. // Always serve index client page (the client is a single page application, let it handle routing)
  73. // Try to provide the right language index.html
  74. clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
  75. // ---------------------------------------------------------------------------
  76. export {
  77. clientsRouter
  78. }
  79. // ---------------------------------------------------------------------------
  80. function serveServerTranslations (req: express.Request, res: express.Response) {
  81. const locale = req.params.locale
  82. const file = req.params.file
  83. if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
  84. const completeLocale = getCompleteLocale(locale)
  85. const completeFileLocale = buildFileLocale(completeLocale)
  86. const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
  87. return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
  88. }
  89. return res.sendStatus(404)
  90. }
  91. async function serveIndexHTML (req: express.Request, res: express.Response) {
  92. if (req.accepts(ACCEPT_HEADERS) === 'html') {
  93. try {
  94. await generateHTMLPage(req, res, req.params.language)
  95. return
  96. } catch (err) {
  97. logger.error('Cannot generate HTML page.', err)
  98. }
  99. }
  100. return res.status(404).end()
  101. }
  102. async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
  103. const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
  104. return sendHTML(html, res)
  105. }
  106. async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
  107. const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
  108. return sendHTML(html, res)
  109. }
  110. async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
  111. const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
  112. return sendHTML(html, res)
  113. }
  114. async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
  115. const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
  116. return sendHTML(html, res)
  117. }
  118. async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
  119. const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
  120. return sendHTML(html, res)
  121. }
  122. function sendHTML (html: string, res: express.Response) {
  123. res.set('Content-Type', 'text/html; charset=UTF-8')
  124. return res.send(html)
  125. }
  126. async function generateManifest (req: express.Request, res: express.Response) {
  127. const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
  128. const manifestJson = await fs.readFile(manifestPhysicalPath, 'utf8')
  129. const manifest = JSON.parse(manifestJson)
  130. manifest.name = CONFIG.INSTANCE.NAME
  131. manifest.short_name = CONFIG.INSTANCE.NAME
  132. manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
  133. res.json(manifest)
  134. }
  135. function serveClientOverride (path: string) {
  136. return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  137. try {
  138. await fs.access(path, constants.F_OK)
  139. // Serve override client
  140. res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
  141. } catch {
  142. // Serve dist client
  143. next()
  144. }
  145. }
  146. }