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