client-html.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import * as express from 'express'
  2. import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/models/i18n/i18n'
  3. import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, WEBSERVER } from '../initializers/constants'
  4. import { join } from 'path'
  5. import { escapeHTML } from '../helpers/core-utils'
  6. import { VideoModel } from '../models/video/video'
  7. import * as validator from 'validator'
  8. import { VideoPrivacy } from '../../shared/models/videos'
  9. import { readFile } from 'fs-extra'
  10. import { getActivityStreamDuration } from '../models/video/video-format-utils'
  11. import { AccountModel } from '../models/account/account'
  12. import { VideoChannelModel } from '../models/video/video-channel'
  13. import * as Bluebird from 'bluebird'
  14. import { CONFIG } from '../initializers/config'
  15. export class ClientHtml {
  16. private static htmlCache: { [ path: string ]: string } = {}
  17. static invalidCache () {
  18. ClientHtml.htmlCache = {}
  19. }
  20. static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
  21. const html = await ClientHtml.getIndexHTML(req, res, paramLang)
  22. let customHtml = ClientHtml.addTitleTag(html)
  23. customHtml = ClientHtml.addDescriptionTag(customHtml)
  24. return customHtml
  25. }
  26. static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
  27. // Let Angular application handle errors
  28. if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
  29. return ClientHtml.getIndexHTML(req, res)
  30. }
  31. const [ html, video ] = await Promise.all([
  32. ClientHtml.getIndexHTML(req, res),
  33. VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
  34. ])
  35. // Let Angular application handle errors
  36. if (!video || video.privacy === VideoPrivacy.PRIVATE) {
  37. return ClientHtml.getIndexHTML(req, res)
  38. }
  39. let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
  40. customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
  41. customHtml = ClientHtml.addVideoOpenGraphAndOEmbedTags(customHtml, video)
  42. return customHtml
  43. }
  44. static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
  45. return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
  46. }
  47. static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
  48. return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
  49. }
  50. private static async getAccountOrChannelHTMLPage (
  51. loader: () => Bluebird<AccountModel | VideoChannelModel>,
  52. req: express.Request,
  53. res: express.Response
  54. ) {
  55. const [ html, entity ] = await Promise.all([
  56. ClientHtml.getIndexHTML(req, res),
  57. loader()
  58. ])
  59. // Let Angular application handle errors
  60. if (!entity) {
  61. return ClientHtml.getIndexHTML(req, res)
  62. }
  63. let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
  64. customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
  65. customHtml = ClientHtml.addAccountOrChannelMetaTags(customHtml, entity)
  66. return customHtml
  67. }
  68. private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
  69. const path = ClientHtml.getIndexPath(req, res, paramLang)
  70. if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
  71. const buffer = await readFile(path)
  72. let html = buffer.toString()
  73. html = ClientHtml.addCustomCSS(html)
  74. ClientHtml.htmlCache[ path ] = html
  75. return html
  76. }
  77. private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
  78. let lang: string
  79. // Check param lang validity
  80. if (paramLang && is18nLocale(paramLang)) {
  81. lang = paramLang
  82. // Save locale in cookies
  83. res.cookie('clientLanguage', lang, {
  84. secure: WEBSERVER.SCHEME === 'https',
  85. sameSite: true,
  86. maxAge: 1000 * 3600 * 24 * 90 // 3 months
  87. })
  88. } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
  89. lang = req.cookies.clientLanguage
  90. } else {
  91. lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
  92. }
  93. return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
  94. }
  95. private static addTitleTag (htmlStringPage: string, title?: string) {
  96. let text = title || CONFIG.INSTANCE.NAME
  97. if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
  98. const titleTag = `<title>${text}</title>`
  99. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
  100. }
  101. private static addDescriptionTag (htmlStringPage: string, description?: string) {
  102. const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
  103. const descriptionTag = `<meta name="description" content="${content}" />`
  104. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
  105. }
  106. private static addCustomCSS (htmlStringPage: string) {
  107. const styleTag = '<style class="custom-css-style">' + CONFIG.INSTANCE.CUSTOMIZATIONS.CSS + '</style>'
  108. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
  109. }
  110. private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
  111. const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
  112. const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
  113. const videoNameEscaped = escapeHTML(video.name)
  114. const videoDescriptionEscaped = escapeHTML(video.description)
  115. const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
  116. const openGraphMetaTags = {
  117. 'og:type': 'video',
  118. 'og:title': videoNameEscaped,
  119. 'og:image': previewUrl,
  120. 'og:url': videoUrl,
  121. 'og:description': videoDescriptionEscaped,
  122. 'og:video:url': embedUrl,
  123. 'og:video:secure_url': embedUrl,
  124. 'og:video:type': 'text/html',
  125. 'og:video:width': EMBED_SIZE.width,
  126. 'og:video:height': EMBED_SIZE.height,
  127. 'name': videoNameEscaped,
  128. 'description': videoDescriptionEscaped,
  129. 'image': previewUrl,
  130. 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
  131. 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
  132. 'twitter:title': videoNameEscaped,
  133. 'twitter:description': videoDescriptionEscaped,
  134. 'twitter:image': previewUrl,
  135. 'twitter:player': embedUrl,
  136. 'twitter:player:width': EMBED_SIZE.width,
  137. 'twitter:player:height': EMBED_SIZE.height
  138. }
  139. const oembedLinkTags = [
  140. {
  141. type: 'application/json+oembed',
  142. href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
  143. title: videoNameEscaped
  144. }
  145. ]
  146. const schemaTags = {
  147. '@context': 'http://schema.org',
  148. '@type': 'VideoObject',
  149. name: videoNameEscaped,
  150. description: videoDescriptionEscaped,
  151. thumbnailUrl: previewUrl,
  152. uploadDate: video.createdAt.toISOString(),
  153. duration: getActivityStreamDuration(video.duration),
  154. contentUrl: videoUrl,
  155. embedUrl: embedUrl,
  156. interactionCount: video.views
  157. }
  158. let tagsString = ''
  159. // Opengraph
  160. Object.keys(openGraphMetaTags).forEach(tagName => {
  161. const tagValue = openGraphMetaTags[ tagName ]
  162. tagsString += `<meta property="${tagName}" content="${tagValue}" />`
  163. })
  164. // OEmbed
  165. for (const oembedLinkTag of oembedLinkTags) {
  166. tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
  167. }
  168. // Schema.org
  169. tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
  170. // SEO, use origin video url so Google does not index remote videos
  171. tagsString += `<link rel="canonical" href="${video.url}" />`
  172. return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
  173. }
  174. private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: AccountModel | VideoChannelModel) {
  175. // SEO, use origin account or channel URL
  176. const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
  177. return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
  178. }
  179. private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
  180. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)
  181. }
  182. }