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