ニジカ投稿局 https://tv.nizika.tv
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

257 lines
8.7 KiB

  1. import express from 'express'
  2. import { constants, promises as fs } from 'fs'
  3. import { readFile } from 'fs/promises'
  4. import { join } from 'path'
  5. import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '@peertube/peertube-core-utils'
  6. import { HttpStatusCode } from '@peertube/peertube-models'
  7. import { logger } from '@server/helpers/logger.js'
  8. import { CONFIG } from '@server/initializers/config.js'
  9. import { Hooks } from '@server/lib/plugins/hooks.js'
  10. import { currentDir, root } from '@peertube/peertube-node-utils'
  11. import { STATIC_MAX_AGE } from '../initializers/constants.js'
  12. import { ClientHtml, sendHTML, serveIndexHTML } from '../lib/html/client-html.js'
  13. import { asyncMiddleware, buildRateLimiter, embedCSP } from '../middlewares/index.js'
  14. const clientsRouter = express.Router()
  15. const clientsRateLimiter = buildRateLimiter({
  16. windowMs: CONFIG.RATES_LIMIT.CLIENT.WINDOW_MS,
  17. max: CONFIG.RATES_LIMIT.CLIENT.MAX
  18. })
  19. const distPath = join(root(), 'client', 'dist')
  20. const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
  21. // Special route that add OpenGraph and oEmbed tags
  22. // Do not use a template engine for a so little thing
  23. clientsRouter.use([ '/w/p/:id', '/videos/watch/playlist/:id' ],
  24. clientsRateLimiter,
  25. asyncMiddleware(generateWatchPlaylistHtmlPage)
  26. )
  27. clientsRouter.use([ '/w/:id', '/videos/watch/:id' ],
  28. clientsRateLimiter,
  29. asyncMiddleware(generateWatchHtmlPage)
  30. )
  31. clientsRouter.use([ '/accounts/:nameWithHost', '/a/:nameWithHost' ],
  32. clientsRateLimiter,
  33. asyncMiddleware(generateAccountHtmlPage)
  34. )
  35. clientsRouter.use([ '/video-channels/:nameWithHost', '/c/:nameWithHost' ],
  36. clientsRateLimiter,
  37. asyncMiddleware(generateVideoChannelHtmlPage)
  38. )
  39. clientsRouter.use('/@:nameWithHost',
  40. clientsRateLimiter,
  41. asyncMiddleware(generateActorHtmlPage)
  42. )
  43. // ---------------------------------------------------------------------------
  44. const embedMiddlewares = [
  45. clientsRateLimiter,
  46. CONFIG.CSP.ENABLED
  47. ? embedCSP
  48. : (req: express.Request, res: express.Response, next: express.NextFunction) => next(),
  49. // Set headers
  50. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  51. res.removeHeader('X-Frame-Options')
  52. // Don't cache HTML file since it's an index to the immutable JS/CSS files
  53. res.setHeader('Cache-Control', 'public, max-age=0')
  54. next()
  55. }
  56. ]
  57. clientsRouter.use('/videos/embed/:id', ...embedMiddlewares, asyncMiddleware(generateVideoEmbedHtmlPage))
  58. clientsRouter.use('/video-playlists/embed/:id', ...embedMiddlewares, asyncMiddleware(generateVideoPlaylistEmbedHtmlPage))
  59. // ---------------------------------------------------------------------------
  60. const testEmbedController = (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
  61. clientsRouter.use('/videos/test-embed', clientsRateLimiter, testEmbedController)
  62. clientsRouter.use('/video-playlists/test-embed', clientsRateLimiter, testEmbedController)
  63. // ---------------------------------------------------------------------------
  64. // Dynamic PWA manifest
  65. clientsRouter.get('/manifest.webmanifest', clientsRateLimiter, asyncMiddleware(generateManifest))
  66. // Static client overrides
  67. // Must be consistent with static client overrides redirections in /support/nginx/peertube
  68. const staticClientOverrides = [
  69. 'assets/images/logo.svg',
  70. 'assets/images/favicon.png',
  71. 'assets/images/icons/icon-36x36.png',
  72. 'assets/images/icons/icon-48x48.png',
  73. 'assets/images/icons/icon-72x72.png',
  74. 'assets/images/icons/icon-96x96.png',
  75. 'assets/images/icons/icon-144x144.png',
  76. 'assets/images/icons/icon-192x192.png',
  77. 'assets/images/icons/icon-512x512.png',
  78. 'assets/images/default-playlist.jpg',
  79. 'assets/images/default-avatar-account.png',
  80. 'assets/images/default-avatar-account-48x48.png',
  81. 'assets/images/default-avatar-video-channel.png',
  82. 'assets/images/default-avatar-video-channel-48x48.png'
  83. ]
  84. for (const staticClientOverride of staticClientOverrides) {
  85. const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
  86. clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
  87. }
  88. clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
  89. clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
  90. // 404 for static files not found
  91. clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
  92. res.status(HttpStatusCode.NOT_FOUND_404).end()
  93. })
  94. // Always serve index client page (the client is a single page application, let it handle routing)
  95. // Try to provide the right language index.html
  96. clientsRouter.use('/(:language)?',
  97. clientsRateLimiter,
  98. asyncMiddleware(serveIndexHTML)
  99. )
  100. // ---------------------------------------------------------------------------
  101. export {
  102. clientsRouter
  103. }
  104. // ---------------------------------------------------------------------------
  105. function serveServerTranslations (req: express.Request, res: express.Response) {
  106. const locale = req.params.locale
  107. const file = req.params.file
  108. if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
  109. const completeLocale = getCompleteLocale(locale)
  110. const completeFileLocale = buildFileLocale(completeLocale)
  111. const path = join(currentDir(import.meta.url), `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
  112. return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
  113. }
  114. return res.status(HttpStatusCode.NOT_FOUND_404).end()
  115. }
  116. async function generateVideoEmbedHtmlPage (req: express.Request, res: express.Response) {
  117. const allowParameters = { req }
  118. const allowedResult = await Hooks.wrapFun(
  119. isEmbedAllowed,
  120. allowParameters,
  121. 'filter:html.embed.video.allowed.result'
  122. )
  123. if (!allowedResult || allowedResult.allowed !== true) {
  124. logger.info('Embed is not allowed.', { allowedResult })
  125. return sendHTML(allowedResult?.html || '', res)
  126. }
  127. const html = await ClientHtml.getVideoEmbedHTML(req.params.id)
  128. return sendHTML(html, res)
  129. }
  130. async function generateVideoPlaylistEmbedHtmlPage (req: express.Request, res: express.Response) {
  131. const allowParameters = { req }
  132. const allowedResult = await Hooks.wrapFun(
  133. isEmbedAllowed,
  134. allowParameters,
  135. 'filter:html.embed.video-playlist.allowed.result'
  136. )
  137. if (!allowedResult || allowedResult.allowed !== true) {
  138. logger.info('Embed is not allowed.', { allowedResult })
  139. return sendHTML(allowedResult?.html || '', res)
  140. }
  141. const html = await ClientHtml.getVideoPlaylistEmbedHTML(req.params.id)
  142. return sendHTML(html, res)
  143. }
  144. async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
  145. // Thread link is '/w/:videoId;threadId=:threadId'
  146. // So to get the videoId we need to remove the last part
  147. let videoId = req.params.id + ''
  148. const threadIdIndex = videoId.indexOf(';threadId')
  149. if (threadIdIndex !== -1) videoId = videoId.substring(0, threadIdIndex)
  150. const html = await ClientHtml.getWatchHTMLPage(videoId, req, res)
  151. return sendHTML(html, res, true)
  152. }
  153. async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
  154. const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
  155. return sendHTML(html, res, true)
  156. }
  157. async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
  158. const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
  159. return sendHTML(html, res, true)
  160. }
  161. async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
  162. const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
  163. return sendHTML(html, res, true)
  164. }
  165. async function generateActorHtmlPage (req: express.Request, res: express.Response) {
  166. const html = await ClientHtml.getActorHTMLPage(req.params.nameWithHost, req, res)
  167. return sendHTML(html, res, true)
  168. }
  169. async function generateManifest (req: express.Request, res: express.Response) {
  170. const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
  171. const manifestJson = await readFile(manifestPhysicalPath, 'utf8')
  172. const manifest = JSON.parse(manifestJson)
  173. manifest.name = CONFIG.INSTANCE.NAME
  174. manifest.short_name = CONFIG.INSTANCE.NAME
  175. manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
  176. res.json(manifest)
  177. }
  178. function serveClientOverride (path: string) {
  179. return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
  180. try {
  181. await fs.access(path, constants.F_OK)
  182. // Serve override client
  183. res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
  184. } catch {
  185. // Serve dist client
  186. next()
  187. }
  188. }
  189. }
  190. type AllowedResult = { allowed: boolean, html?: string }
  191. function isEmbedAllowed (_object: {
  192. req: express.Request
  193. }): AllowedResult {
  194. return { allowed: true }
  195. }