]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Fix client html performance regression
[github/Chocobozzz/PeerTube.git] / server / lib / client-html.ts
CommitLineData
41fb13c3 1import express from 'express'
b49f22d8 2import { readFile } from 'fs-extra'
f7ac03ee 3import memoizee from 'memoizee'
b49f22d8
C
4import { join } from 'path'
5import validator from 'validator'
55cb8bc7 6import { toCompleteUUID } from '@server/helpers/custom-validators/misc'
d0800f76 7import { ActorImageModel } from '@server/models/actor/actor-image'
f8360396 8import { root } from '@shared/core-utils'
aea0b0e7 9import { escapeHTML } from '@shared/core-utils/renderer'
f304a158 10import { sha256 } from '@shared/extra-utils'
aea0b0e7 11import { HTMLServerConfig } from '@shared/models'
bd45d503 12import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
c0e8b12e 13import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
b49f22d8 14import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
06aad801 15import { isTestInstance } from '../helpers/core-utils'
b49f22d8 16import { logger } from '../helpers/logger'
c68e2b2d 17import { mdToOneLinePlainText } from '../helpers/markdown'
b49f22d8 18import { CONFIG } from '../initializers/config'
8d987ec6 19import {
b49f22d8 20 ACCEPT_HEADERS,
8d987ec6
K
21 CUSTOM_HTML_TAG_COMMENTS,
22 EMBED_SIZE,
f2eb23cd 23 FILES_CONTENT_HASH,
f7ac03ee
C
24 MEMOIZE_LENGTH,
25 MEMOIZE_TTL,
b49f22d8
C
26 PLUGIN_GLOBAL_CSS_PATH,
27 WEBSERVER
8d987ec6 28} from '../initializers/constants'
92bf2f62 29import { AccountModel } from '../models/account/account'
e5dbd508 30import { getActivityStreamDuration } from '../models/video/formatter/video-format-utils'
b49f22d8 31import { VideoModel } from '../models/video/video'
92bf2f62 32import { VideoChannelModel } from '../models/video/video-channel'
b49f22d8 33import { VideoPlaylistModel } from '../models/video/video-playlist'
8d987ec6 34import { MAccountActor, MChannelActor } from '../types/models'
d0800f76 35import { getBiggestActorImage } from './actor-image'
2539932e 36import { ServerConfigManager } from './server-config-manager'
e032aec9 37
f7ac03ee
C
38const getPlainTextDescriptionCached = memoizee(mdToOneLinePlainText, {
39 maxAge: MEMOIZE_TTL.MD_TO_PLAIN_TEXT_CLIENT_HTML,
40 max: MEMOIZE_LENGTH.MD_TO_PLAIN_TEXT_CLIENT_HTML
41})
42
6fad8e51
C
43type Tags = {
44 ogType: string
b96777c3 45 twitterCard: 'player' | 'summary' | 'summary_large_image'
6fad8e51
C
46 schemaType: string
47
48 list?: {
49 numberOfItems: number
50 }
51
55cb8bc7
C
52 escapedSiteName: string
53 escapedTitle: string
54 escapedDescription: string
55
6fad8e51 56 url: string
106fa224 57 originUrl: string
6fad8e51 58
352819ef
C
59 disallowIndexation?: boolean
60
6fad8e51
C
61 embed?: {
62 url: string
63 createdAt: string
64 duration?: string
65 views?: number
66 }
67
68 image: {
69 url: string
70 width?: number
71 height?: number
72 }
73}
74
f2eb23cd 75class ClientHtml {
e032aec9 76
a1587156 77 private static htmlCache: { [path: string]: string } = {}
e032aec9
C
78
79 static invalidCache () {
3e753302
C
80 logger.info('Cleaning HTML cache.')
81
e032aec9
C
82 ClientHtml.htmlCache = {}
83 }
84
9aac4423 85 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
7738273b
RK
86 const html = paramLang
87 ? await ClientHtml.getIndexHTML(req, res, paramLang)
88 : await ClientHtml.getIndexHTML(req, res)
e032aec9 89
9aac4423
C
90 let customHtml = ClientHtml.addTitleTag(html)
91 customHtml = ClientHtml.addDescriptionTag(customHtml)
e032aec9 92
9aac4423 93 return customHtml
e032aec9
C
94 }
95
d4a8e7a6
C
96 static async getWatchHTMLPage (videoIdArg: string, req: express.Request, res: express.Response) {
97 const videoId = toCompleteUUID(videoIdArg)
98
e032aec9 99 // Let Angular application handle errors
92bf2f62 100 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
2d53be02 101 res.status(HttpStatusCode.NOT_FOUND_404)
e032aec9
C
102 return ClientHtml.getIndexHTML(req, res)
103 }
104
105 const [ html, video ] = await Promise.all([
106 ClientHtml.getIndexHTML(req, res),
d636ab58 107 VideoModel.loadWithBlacklist(videoId)
e032aec9
C
108 ])
109
110 // Let Angular application handle errors
22a73cb8 111 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
2d53be02 112 res.status(HttpStatusCode.NOT_FOUND_404)
c08579e1 113 return html
e032aec9 114 }
f7ac03ee 115 const description = getPlainTextDescriptionCached(video.description)
e032aec9 116
55cb8bc7
C
117 let customHtml = ClientHtml.addTitleTag(html, video.name)
118 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
8d987ec6
K
119
120 const url = WEBSERVER.URL + video.getWatchStaticPath()
106fa224 121 const originUrl = video.url
55cb8bc7
C
122 const title = video.name
123 const siteName = CONFIG.INSTANCE.NAME
8d987ec6
K
124
125 const image = {
126 url: WEBSERVER.URL + video.getPreviewStaticPath()
127 }
128
129 const embed = {
130 url: WEBSERVER.URL + video.getEmbedStaticPath(),
131 createdAt: video.createdAt.toISOString(),
132 duration: getActivityStreamDuration(video.duration),
133 views: video.views
134 }
135
136 const ogType = 'video'
137 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
138 const schemaType = 'VideoObject'
139
106fa224 140 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
141 url,
142 originUrl,
55cb8bc7
C
143 escapedSiteName: escapeHTML(siteName),
144 escapedTitle: escapeHTML(title),
145 escapedDescription: escapeHTML(description),
a59f210f
C
146 image,
147 embed,
148 ogType,
149 twitterCard,
150 schemaType
106fa224 151 })
8d987ec6
K
152
153 return customHtml
154 }
155
d4a8e7a6
C
156 static async getWatchPlaylistHTMLPage (videoPlaylistIdArg: string, req: express.Request, res: express.Response) {
157 const videoPlaylistId = toCompleteUUID(videoPlaylistIdArg)
158
8d987ec6
K
159 // Let Angular application handle errors
160 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
2d53be02 161 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
162 return ClientHtml.getIndexHTML(req, res)
163 }
164
165 const [ html, videoPlaylist ] = await Promise.all([
166 ClientHtml.getIndexHTML(req, res),
167 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
168 ])
169
170 // Let Angular application handle errors
171 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
2d53be02 172 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
173 return html
174 }
175
f7ac03ee 176 const description = getPlainTextDescriptionCached(videoPlaylist.description)
55cb8bc7
C
177
178 let customHtml = ClientHtml.addTitleTag(html, videoPlaylist.name)
179 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
8d987ec6 180
a892c54a 181 const url = WEBSERVER.URL + videoPlaylist.getWatchStaticPath()
106fa224 182 const originUrl = videoPlaylist.url
55cb8bc7
C
183 const title = videoPlaylist.name
184 const siteName = CONFIG.INSTANCE.NAME
8d987ec6
K
185
186 const image = {
187 url: videoPlaylist.getThumbnailUrl()
188 }
189
6fad8e51
C
190 const embed = {
191 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
192 createdAt: videoPlaylist.createdAt.toISOString()
193 }
194
8d987ec6 195 const list = {
6fad8e51 196 numberOfItems: videoPlaylist.get('videosLength') as number
8d987ec6
K
197 }
198
199 const ogType = 'video'
6fad8e51 200 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
8d987ec6
K
201 const schemaType = 'ItemList'
202
106fa224 203 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
204 url,
205 originUrl,
55cb8bc7
C
206 escapedSiteName: escapeHTML(siteName),
207 escapedTitle: escapeHTML(title),
208 escapedDescription: escapeHTML(description),
a59f210f 209 embed,
a59f210f
C
210 image,
211 list,
212 ogType,
213 twitterCard,
214 schemaType
106fa224 215 })
92bf2f62
C
216
217 return customHtml
218 }
219
220 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
9a911038
K
221 const accountModelPromise = AccountModel.loadByNameWithHost(nameWithHost)
222 return this.getAccountOrChannelHTMLPage(() => accountModelPromise, req, res)
92bf2f62
C
223 }
224
225 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
9a911038
K
226 const videoChannelModelPromise = VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
227 return this.getAccountOrChannelHTMLPage(() => videoChannelModelPromise, req, res)
228 }
229
230 static async getActorHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
012580d9
C
231 const [ account, channel ] = await Promise.all([
232 AccountModel.loadByNameWithHost(nameWithHost),
233 VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
234 ])
9a911038 235
012580d9 236 return this.getAccountOrChannelHTMLPage(() => Promise.resolve(account || channel), req, res)
92bf2f62
C
237 }
238
cf649c2e
C
239 static async getEmbedHTML () {
240 const path = ClientHtml.getEmbedPath()
cf649c2e 241
b9da21bd 242 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
cf649c2e
C
243
244 const buffer = await readFile(path)
2539932e 245 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
cf649c2e
C
246
247 let html = buffer.toString()
248 html = await ClientHtml.addAsyncPluginCSS(html)
2564d97e 249 html = ClientHtml.addCustomCSS(html)
915e2bbb 250 html = ClientHtml.addTitleTag(html)
aea0b0e7
C
251 html = ClientHtml.addDescriptionTag(html)
252 html = ClientHtml.addServerConfig(html, serverConfig)
cf649c2e
C
253
254 ClientHtml.htmlCache[path] = html
255
256 return html
257 }
258
92bf2f62 259 private static async getAccountOrChannelHTMLPage (
b49f22d8 260 loader: () => Promise<MAccountActor | MChannelActor>,
92bf2f62
C
261 req: express.Request,
262 res: express.Response
263 ) {
264 const [ html, entity ] = await Promise.all([
265 ClientHtml.getIndexHTML(req, res),
266 loader()
267 ])
268
269 // Let Angular application handle errors
270 if (!entity) {
2d53be02 271 res.status(HttpStatusCode.NOT_FOUND_404)
92bf2f62
C
272 return ClientHtml.getIndexHTML(req, res)
273 }
274
f7ac03ee 275 const description = getPlainTextDescriptionCached(entity.description)
55cb8bc7
C
276
277 let customHtml = ClientHtml.addTitleTag(html, entity.getDisplayName())
278 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
8d987ec6 279
a59f210f 280 const url = entity.getLocalUrl()
106fa224 281 const originUrl = entity.Actor.url
55cb8bc7
C
282 const siteName = CONFIG.INSTANCE.NAME
283 const title = entity.getDisplayName()
8d987ec6 284
d0800f76 285 const avatar = getBiggestActorImage(entity.Actor.Avatars)
8d987ec6 286 const image = {
d0800f76 287 url: ActorImageModel.getImageUrl(avatar),
288 width: avatar?.width,
289 height: avatar?.height
8d987ec6
K
290 }
291
292 const ogType = 'website'
293 const twitterCard = 'summary'
294 const schemaType = 'ProfilePage'
295
a59f210f
C
296 customHtml = ClientHtml.addTags(customHtml, {
297 url,
298 originUrl,
55cb8bc7
C
299 escapedTitle: escapeHTML(title),
300 escapedSiteName: escapeHTML(siteName),
301 escapedDescription: escapeHTML(description),
a59f210f
C
302 image,
303 ogType,
304 twitterCard,
352819ef
C
305 schemaType,
306 disallowIndexation: !entity.Actor.isOwned()
a59f210f 307 })
9aac4423
C
308
309 return customHtml
310 }
311
312 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
313 const path = ClientHtml.getIndexPath(req, res, paramLang)
b9da21bd 314 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
9aac4423
C
315
316 const buffer = await readFile(path)
2539932e 317 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
9aac4423
C
318
319 let html = buffer.toString()
320
caf2aaf4
K
321 html = ClientHtml.addManifestContentHash(html)
322 html = ClientHtml.addFaviconContentHash(html)
323 html = ClientHtml.addLogoContentHash(html)
9aac4423 324 html = ClientHtml.addCustomCSS(html)
aea0b0e7 325 html = ClientHtml.addServerConfig(html, serverConfig)
a8b666e9 326 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 327
a1587156 328 ClientHtml.htmlCache[path] = html
9aac4423
C
329
330 return html
e032aec9
C
331 }
332
7738273b 333 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
334 let lang: string
335
336 // Check param lang validity
337 if (paramLang && is18nLocale(paramLang)) {
338 lang = paramLang
339
340 // Save locale in cookies
341 res.cookie('clientLanguage', lang, {
6dd9de95 342 secure: WEBSERVER.SCHEME === 'https',
bc90883f 343 sameSite: 'none',
e032aec9
C
344 maxAge: 1000 * 3600 * 24 * 90 // 3 months
345 })
346
347 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
348 lang = req.cookies.clientLanguage
349 } else {
350 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
351 }
352
450de91e
C
353 logger.debug(
354 'Serving %s HTML language', buildFileLocale(lang),
355 { cookie: req.cookies?.clientLanguage, paramLang, acceptLanguage: req.headers['accept-language'] }
356 )
357
f8360396 358 return join(root(), 'client', 'dist', buildFileLocale(lang), 'index.html')
e032aec9
C
359 }
360
cf649c2e 361 private static getEmbedPath () {
f8360396 362 return join(root(), 'client', 'dist', 'standalone', 'videos', 'embed.html')
cf649c2e
C
363 }
364
caf2aaf4
K
365 private static addManifestContentHash (htmlStringPage: string) {
366 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
367 }
368
1fdf8edb 369 private static addFaviconContentHash (htmlStringPage: string) {
caf2aaf4
K
370 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
371 }
372
1fdf8edb 373 private static addLogoContentHash (htmlStringPage: string) {
caf2aaf4
K
374 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
375 }
376
9aac4423
C
377 private static addTitleTag (htmlStringPage: string, title?: string) {
378 let text = title || CONFIG.INSTANCE.NAME
379 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
380
55cb8bc7 381 const titleTag = `<title>${escapeHTML(text)}</title>`
e032aec9
C
382
383 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
384 }
385
9aac4423
C
386 private static addDescriptionTag (htmlStringPage: string, description?: string) {
387 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
55cb8bc7 388 const descriptionTag = `<meta name="description" content="${escapeHTML(content)}" />`
e032aec9
C
389
390 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
391 }
392
393 private static addCustomCSS (htmlStringPage: string) {
ffb321be 394 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
395
396 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
397 }
398
aea0b0e7 399 private static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
b4c945f3
C
400 // Stringify the JSON object, and then stringify the string object so we can inject it into the HTML
401 const serverConfigString = JSON.stringify(JSON.stringify(serverConfig))
402 const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = ${serverConfigString}</script>`
aea0b0e7
C
403
404 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
405 }
406
a8b666e9
C
407 private static async addAsyncPluginCSS (htmlStringPage: string) {
408 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 409 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
410
411 const fileHash = sha256(globalCSSContent)
412 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
413
414 return htmlStringPage.replace('</head>', linkTag + '</head>')
415 }
416
6fad8e51 417 private static generateOpenGraphMetaTags (tags: Tags) {
8d987ec6
K
418 const metaTags = {
419 'og:type': tags.ogType,
55cb8bc7
C
420 'og:site_name': tags.escapedSiteName,
421 'og:title': tags.escapedTitle,
8d987ec6
K
422 'og:image': tags.image.url
423 }
424
425 if (tags.image.width && tags.image.height) {
426 metaTags['og:image:width'] = tags.image.width
427 metaTags['og:image:height'] = tags.image.height
428 }
e032aec9 429
8d987ec6 430 metaTags['og:url'] = tags.url
55cb8bc7 431 metaTags['og:description'] = tags.escapedDescription
e032aec9 432
8d987ec6
K
433 if (tags.embed) {
434 metaTags['og:video:url'] = tags.embed.url
435 metaTags['og:video:secure_url'] = tags.embed.url
436 metaTags['og:video:type'] = 'text/html'
437 metaTags['og:video:width'] = EMBED_SIZE.width
438 metaTags['og:video:height'] = EMBED_SIZE.height
439 }
e032aec9 440
8d987ec6
K
441 return metaTags
442 }
e032aec9 443
6fad8e51 444 private static generateStandardMetaTags (tags: Tags) {
8d987ec6 445 return {
55cb8bc7
C
446 name: tags.escapedTitle,
447 description: tags.escapedDescription,
8d987ec6
K
448 image: tags.image.url
449 }
450 }
e032aec9 451
6fad8e51 452 private static generateTwitterCardMetaTags (tags: Tags) {
8d987ec6
K
453 const metaTags = {
454 'twitter:card': tags.twitterCard,
e032aec9 455 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
55cb8bc7
C
456 'twitter:title': tags.escapedTitle,
457 'twitter:description': tags.escapedDescription,
8d987ec6 458 'twitter:image': tags.image.url
e032aec9
C
459 }
460
8d987ec6
K
461 if (tags.image.width && tags.image.height) {
462 metaTags['twitter:image:width'] = tags.image.width
463 metaTags['twitter:image:height'] = tags.image.height
464 }
465
b96777c3
C
466 if (tags.twitterCard === 'player') {
467 metaTags['twitter:player'] = tags.embed.url
468 metaTags['twitter:player:width'] = EMBED_SIZE.width
469 metaTags['twitter:player:height'] = EMBED_SIZE.height
470 }
471
8d987ec6
K
472 return metaTags
473 }
e032aec9 474
6fad8e51 475 private static generateSchemaTags (tags: Tags) {
8d987ec6 476 const schema = {
e032aec9 477 '@context': 'http://schema.org',
8d987ec6 478 '@type': tags.schemaType,
55cb8bc7
C
479 'name': tags.escapedTitle,
480 'description': tags.escapedDescription,
8d987ec6
K
481 'image': tags.image.url,
482 'url': tags.url
483 }
484
485 if (tags.list) {
486 schema['numberOfItems'] = tags.list.numberOfItems
487 schema['thumbnailUrl'] = tags.image.url
488 }
489
490 if (tags.embed) {
491 schema['embedUrl'] = tags.embed.url
492 schema['uploadDate'] = tags.embed.createdAt
6fad8e51
C
493
494 if (tags.embed.duration) schema['duration'] = tags.embed.duration
495 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
496
8d987ec6
K
497 schema['thumbnailUrl'] = tags.image.url
498 schema['contentUrl'] = tags.url
499 }
500
501 return schema
502 }
503
6fad8e51 504 private static addTags (htmlStringPage: string, tagsValues: Tags) {
8d987ec6
K
505 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
506 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
507 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
508 const schemaTags = this.generateSchemaTags(tagsValues)
509
55cb8bc7 510 const { url, escapedTitle, embed, originUrl, disallowIndexation } = tagsValues
8d987ec6 511
55cb8bc7 512 const oembedLinkTags: { type: string, href: string, escapedTitle: string }[] = []
8d987ec6
K
513
514 if (embed) {
515 oembedLinkTags.push({
516 type: 'application/json+oembed',
517 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
55cb8bc7 518 escapedTitle
8d987ec6 519 })
e032aec9
C
520 }
521
55cb8bc7 522 let tagsStr = ''
e032aec9
C
523
524 // Opengraph
525 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 526 const tagValue = openGraphMetaTags[tagName]
e032aec9 527
55cb8bc7 528 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
e032aec9
C
529 })
530
8d987ec6
K
531 // Standard
532 Object.keys(standardMetaTags).forEach(tagName => {
533 const tagValue = standardMetaTags[tagName]
534
55cb8bc7 535 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
8d987ec6
K
536 })
537
538 // Twitter card
539 Object.keys(twitterCardMetaTags).forEach(tagName => {
540 const tagValue = twitterCardMetaTags[tagName]
541
55cb8bc7 542 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
8d987ec6
K
543 })
544
e032aec9
C
545 // OEmbed
546 for (const oembedLinkTag of oembedLinkTags) {
55cb8bc7 547 tagsStr += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.escapedTitle}" />`
e032aec9
C
548 }
549
550 // Schema.org
8d987ec6 551 if (schemaTags) {
55cb8bc7 552 tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
8d987ec6 553 }
92bf2f62 554
8d987ec6 555 // SEO, use origin URL
55cb8bc7 556 tagsStr += `<link rel="canonical" href="${originUrl}" />`
92bf2f62 557
352819ef 558 if (disallowIndexation) {
55cb8bc7 559 tagsStr += `<meta name="robots" content="noindex" />`
352819ef
C
560 }
561
55cb8bc7 562 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr)
e032aec9
C
563 }
564}
f2eb23cd 565
5fc44b57 566function sendHTML (html: string, res: express.Response, localizedHTML: boolean = false) {
f2eb23cd
RK
567 res.set('Content-Type', 'text/html; charset=UTF-8')
568
5fc44b57 569 if (localizedHTML) {
570 res.set('Vary', 'Accept-Language')
571 }
572
f2eb23cd
RK
573 return res.send(html)
574}
575
576async function serveIndexHTML (req: express.Request, res: express.Response) {
8bd67ef6 577 if (req.accepts(ACCEPT_HEADERS) === 'html' || !req.headers.accept) {
f2eb23cd
RK
578 try {
579 await generateHTMLPage(req, res, req.params.language)
580 return
581 } catch (err) {
582 logger.error('Cannot generate HTML page.', err)
76148b27 583 return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
f2eb23cd
RK
584 }
585 }
586
76148b27 587 return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end()
f2eb23cd
RK
588}
589
590// ---------------------------------------------------------------------------
591
592export {
593 ClientHtml,
594 sendHTML,
595 serveIndexHTML
596}
597
598async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
599 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
600
5fc44b57 601 return sendHTML(html, res, true)
f2eb23cd 602}