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