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