client-html.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. import * as express from 'express'
  2. import { readFile } from 'fs-extra'
  3. import { join } from 'path'
  4. import validator from 'validator'
  5. import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
  6. import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
  7. import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
  8. import { escapeHTML, isTestInstance, sha256 } from '../helpers/core-utils'
  9. import { logger } from '../helpers/logger'
  10. import { CONFIG } from '../initializers/config'
  11. import {
  12. ACCEPT_HEADERS,
  13. AVATARS_SIZE,
  14. CUSTOM_HTML_TAG_COMMENTS,
  15. EMBED_SIZE,
  16. FILES_CONTENT_HASH,
  17. PLUGIN_GLOBAL_CSS_PATH,
  18. WEBSERVER
  19. } from '../initializers/constants'
  20. import { AccountModel } from '../models/account/account'
  21. import { VideoModel } from '../models/video/video'
  22. import { VideoChannelModel } from '../models/video/video-channel'
  23. import { getActivityStreamDuration } from '../models/video/video-format-utils'
  24. import { VideoPlaylistModel } from '../models/video/video-playlist'
  25. import { MAccountActor, MChannelActor } from '../types/models'
  26. type Tags = {
  27. ogType: string
  28. twitterCard: 'player' | 'summary' | 'summary_large_image'
  29. schemaType: string
  30. list?: {
  31. numberOfItems: number
  32. }
  33. siteName: string
  34. title: string
  35. url: string
  36. originUrl: string
  37. description: string
  38. embed?: {
  39. url: string
  40. createdAt: string
  41. duration?: string
  42. views?: number
  43. }
  44. image: {
  45. url: string
  46. width?: number
  47. height?: number
  48. }
  49. }
  50. class ClientHtml {
  51. private static htmlCache: { [path: string]: string } = {}
  52. static invalidCache () {
  53. logger.info('Cleaning HTML cache.')
  54. ClientHtml.htmlCache = {}
  55. }
  56. static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
  57. const html = paramLang
  58. ? await ClientHtml.getIndexHTML(req, res, paramLang)
  59. : await ClientHtml.getIndexHTML(req, res)
  60. let customHtml = ClientHtml.addTitleTag(html)
  61. customHtml = ClientHtml.addDescriptionTag(customHtml)
  62. return customHtml
  63. }
  64. static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
  65. // Let Angular application handle errors
  66. if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
  67. res.status(HttpStatusCode.NOT_FOUND_404)
  68. return ClientHtml.getIndexHTML(req, res)
  69. }
  70. const [ html, video ] = await Promise.all([
  71. ClientHtml.getIndexHTML(req, res),
  72. VideoModel.loadWithBlacklist(videoId)
  73. ])
  74. // Let Angular application handle errors
  75. if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
  76. res.status(HttpStatusCode.NOT_FOUND_404)
  77. return html
  78. }
  79. let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
  80. customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
  81. const url = WEBSERVER.URL + video.getWatchStaticPath()
  82. const originUrl = video.url
  83. const title = escapeHTML(video.name)
  84. const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
  85. const description = escapeHTML(video.description)
  86. const image = {
  87. url: WEBSERVER.URL + video.getPreviewStaticPath()
  88. }
  89. const embed = {
  90. url: WEBSERVER.URL + video.getEmbedStaticPath(),
  91. createdAt: video.createdAt.toISOString(),
  92. duration: getActivityStreamDuration(video.duration),
  93. views: video.views
  94. }
  95. const ogType = 'video'
  96. const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
  97. const schemaType = 'VideoObject'
  98. customHtml = ClientHtml.addTags(customHtml, {
  99. url,
  100. originUrl,
  101. siteName,
  102. title,
  103. description,
  104. image,
  105. embed,
  106. ogType,
  107. twitterCard,
  108. schemaType
  109. })
  110. return customHtml
  111. }
  112. static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
  113. // Let Angular application handle errors
  114. if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
  115. res.status(HttpStatusCode.NOT_FOUND_404)
  116. return ClientHtml.getIndexHTML(req, res)
  117. }
  118. const [ html, videoPlaylist ] = await Promise.all([
  119. ClientHtml.getIndexHTML(req, res),
  120. VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
  121. ])
  122. // Let Angular application handle errors
  123. if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
  124. res.status(HttpStatusCode.NOT_FOUND_404)
  125. return html
  126. }
  127. let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
  128. customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(videoPlaylist.description))
  129. const url = videoPlaylist.getWatchUrl()
  130. const originUrl = videoPlaylist.url
  131. const title = escapeHTML(videoPlaylist.name)
  132. const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
  133. const description = escapeHTML(videoPlaylist.description)
  134. const image = {
  135. url: videoPlaylist.getThumbnailUrl()
  136. }
  137. const embed = {
  138. url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
  139. createdAt: videoPlaylist.createdAt.toISOString()
  140. }
  141. const list = {
  142. numberOfItems: videoPlaylist.get('videosLength') as number
  143. }
  144. const ogType = 'video'
  145. const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
  146. const schemaType = 'ItemList'
  147. customHtml = ClientHtml.addTags(customHtml, {
  148. url,
  149. originUrl,
  150. siteName,
  151. embed,
  152. title,
  153. description,
  154. image,
  155. list,
  156. ogType,
  157. twitterCard,
  158. schemaType
  159. })
  160. return customHtml
  161. }
  162. static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
  163. return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
  164. }
  165. static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
  166. return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
  167. }
  168. static async getEmbedHTML () {
  169. const path = ClientHtml.getEmbedPath()
  170. if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
  171. const buffer = await readFile(path)
  172. let html = buffer.toString()
  173. html = await ClientHtml.addAsyncPluginCSS(html)
  174. html = ClientHtml.addCustomCSS(html)
  175. html = ClientHtml.addTitleTag(html)
  176. ClientHtml.htmlCache[path] = html
  177. return html
  178. }
  179. private static async getAccountOrChannelHTMLPage (
  180. loader: () => Promise<MAccountActor | MChannelActor>,
  181. req: express.Request,
  182. res: express.Response
  183. ) {
  184. const [ html, entity ] = await Promise.all([
  185. ClientHtml.getIndexHTML(req, res),
  186. loader()
  187. ])
  188. // Let Angular application handle errors
  189. if (!entity) {
  190. res.status(HttpStatusCode.NOT_FOUND_404)
  191. return ClientHtml.getIndexHTML(req, res)
  192. }
  193. let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
  194. customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
  195. const url = entity.getLocalUrl()
  196. const originUrl = entity.Actor.url
  197. const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
  198. const title = escapeHTML(entity.getDisplayName())
  199. const description = escapeHTML(entity.description)
  200. const image = {
  201. url: entity.Actor.getAvatarUrl(),
  202. width: AVATARS_SIZE.width,
  203. height: AVATARS_SIZE.height
  204. }
  205. const ogType = 'website'
  206. const twitterCard = 'summary'
  207. const schemaType = 'ProfilePage'
  208. customHtml = ClientHtml.addTags(customHtml, {
  209. url,
  210. originUrl,
  211. title,
  212. siteName,
  213. description,
  214. image,
  215. ogType,
  216. twitterCard,
  217. schemaType
  218. })
  219. return customHtml
  220. }
  221. private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
  222. const path = ClientHtml.getIndexPath(req, res, paramLang)
  223. if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
  224. const buffer = await readFile(path)
  225. let html = buffer.toString()
  226. if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
  227. html = ClientHtml.addManifestContentHash(html)
  228. html = ClientHtml.addFaviconContentHash(html)
  229. html = ClientHtml.addLogoContentHash(html)
  230. html = ClientHtml.addCustomCSS(html)
  231. html = await ClientHtml.addAsyncPluginCSS(html)
  232. ClientHtml.htmlCache[path] = html
  233. return html
  234. }
  235. private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
  236. let lang: string
  237. // Check param lang validity
  238. if (paramLang && is18nLocale(paramLang)) {
  239. lang = paramLang
  240. // Save locale in cookies
  241. res.cookie('clientLanguage', lang, {
  242. secure: WEBSERVER.SCHEME === 'https',
  243. sameSite: 'none',
  244. maxAge: 1000 * 3600 * 24 * 90 // 3 months
  245. })
  246. } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
  247. lang = req.cookies.clientLanguage
  248. } else {
  249. lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
  250. }
  251. return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
  252. }
  253. private static getEmbedPath () {
  254. return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
  255. }
  256. private static addHtmlLang (htmlStringPage: string, paramLang: string) {
  257. return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
  258. }
  259. private static addManifestContentHash (htmlStringPage: string) {
  260. return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
  261. }
  262. private static addFaviconContentHash (htmlStringPage: string) {
  263. return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
  264. }
  265. private static addLogoContentHash (htmlStringPage: string) {
  266. return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
  267. }
  268. private static addTitleTag (htmlStringPage: string, title?: string) {
  269. let text = title || CONFIG.INSTANCE.NAME
  270. if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
  271. const titleTag = `<title>${text}</title>`
  272. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
  273. }
  274. private static addDescriptionTag (htmlStringPage: string, description?: string) {
  275. const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
  276. const descriptionTag = `<meta name="description" content="${content}" />`
  277. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
  278. }
  279. private static addCustomCSS (htmlStringPage: string) {
  280. const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
  281. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
  282. }
  283. private static async addAsyncPluginCSS (htmlStringPage: string) {
  284. const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
  285. if (globalCSSContent.byteLength === 0) return htmlStringPage
  286. const fileHash = sha256(globalCSSContent)
  287. const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
  288. return htmlStringPage.replace('</head>', linkTag + '</head>')
  289. }
  290. private static generateOpenGraphMetaTags (tags: Tags) {
  291. const metaTags = {
  292. 'og:type': tags.ogType,
  293. 'og:site_name': tags.siteName,
  294. 'og:title': tags.title,
  295. 'og:image': tags.image.url
  296. }
  297. if (tags.image.width && tags.image.height) {
  298. metaTags['og:image:width'] = tags.image.width
  299. metaTags['og:image:height'] = tags.image.height
  300. }
  301. metaTags['og:url'] = tags.url
  302. metaTags['og:description'] = tags.description
  303. if (tags.embed) {
  304. metaTags['og:video:url'] = tags.embed.url
  305. metaTags['og:video:secure_url'] = tags.embed.url
  306. metaTags['og:video:type'] = 'text/html'
  307. metaTags['og:video:width'] = EMBED_SIZE.width
  308. metaTags['og:video:height'] = EMBED_SIZE.height
  309. }
  310. return metaTags
  311. }
  312. private static generateStandardMetaTags (tags: Tags) {
  313. return {
  314. name: tags.title,
  315. description: tags.description,
  316. image: tags.image.url
  317. }
  318. }
  319. private static generateTwitterCardMetaTags (tags: Tags) {
  320. const metaTags = {
  321. 'twitter:card': tags.twitterCard,
  322. 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
  323. 'twitter:title': tags.title,
  324. 'twitter:description': tags.description,
  325. 'twitter:image': tags.image.url
  326. }
  327. if (tags.image.width && tags.image.height) {
  328. metaTags['twitter:image:width'] = tags.image.width
  329. metaTags['twitter:image:height'] = tags.image.height
  330. }
  331. if (tags.twitterCard === 'player') {
  332. metaTags['twitter:player'] = tags.embed.url
  333. metaTags['twitter:player:width'] = EMBED_SIZE.width
  334. metaTags['twitter:player:height'] = EMBED_SIZE.height
  335. }
  336. return metaTags
  337. }
  338. private static generateSchemaTags (tags: Tags) {
  339. const schema = {
  340. '@context': 'http://schema.org',
  341. '@type': tags.schemaType,
  342. 'name': tags.title,
  343. 'description': tags.description,
  344. 'image': tags.image.url,
  345. 'url': tags.url
  346. }
  347. if (tags.list) {
  348. schema['numberOfItems'] = tags.list.numberOfItems
  349. schema['thumbnailUrl'] = tags.image.url
  350. }
  351. if (tags.embed) {
  352. schema['embedUrl'] = tags.embed.url
  353. schema['uploadDate'] = tags.embed.createdAt
  354. if (tags.embed.duration) schema['duration'] = tags.embed.duration
  355. if (tags.embed.views) schema['iterationCount'] = tags.embed.views
  356. schema['thumbnailUrl'] = tags.image.url
  357. schema['contentUrl'] = tags.url
  358. }
  359. return schema
  360. }
  361. private static addTags (htmlStringPage: string, tagsValues: Tags) {
  362. const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
  363. const standardMetaTags = this.generateStandardMetaTags(tagsValues)
  364. const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
  365. const schemaTags = this.generateSchemaTags(tagsValues)
  366. const { url, title, embed, originUrl } = tagsValues
  367. const oembedLinkTags: { type: string, href: string, title: string }[] = []
  368. if (embed) {
  369. oembedLinkTags.push({
  370. type: 'application/json+oembed',
  371. href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
  372. title
  373. })
  374. }
  375. let tagsString = ''
  376. // Opengraph
  377. Object.keys(openGraphMetaTags).forEach(tagName => {
  378. const tagValue = openGraphMetaTags[tagName]
  379. tagsString += `<meta property="${tagName}" content="${tagValue}" />`
  380. })
  381. // Standard
  382. Object.keys(standardMetaTags).forEach(tagName => {
  383. const tagValue = standardMetaTags[tagName]
  384. tagsString += `<meta property="${tagName}" content="${tagValue}" />`
  385. })
  386. // Twitter card
  387. Object.keys(twitterCardMetaTags).forEach(tagName => {
  388. const tagValue = twitterCardMetaTags[tagName]
  389. tagsString += `<meta property="${tagName}" content="${tagValue}" />`
  390. })
  391. // OEmbed
  392. for (const oembedLinkTag of oembedLinkTags) {
  393. tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
  394. }
  395. // Schema.org
  396. if (schemaTags) {
  397. tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
  398. }
  399. // SEO, use origin URL
  400. tagsString += `<link rel="canonical" href="${originUrl}" />`
  401. return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
  402. }
  403. }
  404. function sendHTML (html: string, res: express.Response) {
  405. res.set('Content-Type', 'text/html; charset=UTF-8')
  406. return res.send(html)
  407. }
  408. async function serveIndexHTML (req: express.Request, res: express.Response) {
  409. if (req.accepts(ACCEPT_HEADERS) === 'html' ||
  410. !req.headers.accept) {
  411. try {
  412. await generateHTMLPage(req, res, req.params.language)
  413. return
  414. } catch (err) {
  415. logger.error('Cannot generate HTML page.', err)
  416. return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
  417. }
  418. }
  419. return res.sendStatus(HttpStatusCode.NOT_ACCEPTABLE_406)
  420. }
  421. // ---------------------------------------------------------------------------
  422. export {
  423. ClientHtml,
  424. sendHTML,
  425. serveIndexHTML
  426. }
  427. async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
  428. const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
  429. return sendHTML(html, res)
  430. }