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