]>
Commit | Line | Data |
---|---|---|
41fb13c3 | 1 | import express from 'express' |
f9eee54f | 2 | import { pathExists, readFile } from 'fs-extra' |
b49f22d8 C |
3 | import { join } from 'path' |
4 | import validator from 'validator' | |
9452d4fd | 5 | import { isTestOrDevInstance } from '@server/helpers/core-utils' |
55cb8bc7 | 6 | import { toCompleteUUID } from '@server/helpers/custom-validators/misc' |
cc45cc9a | 7 | import { mdToOneLinePlainText } from '@server/helpers/markdown' |
d0800f76 | 8 | import { ActorImageModel } from '@server/models/actor/actor-image' |
f8360396 | 9 | import { root } from '@shared/core-utils' |
aea0b0e7 | 10 | import { escapeHTML } from '@shared/core-utils/renderer' |
f304a158 | 11 | import { sha256 } from '@shared/extra-utils' |
aea0b0e7 | 12 | import { HTMLServerConfig } from '@shared/models' |
bd45d503 | 13 | import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n' |
c0e8b12e | 14 | import { HttpStatusCode } from '../../shared/models/http/http-error-codes' |
b49f22d8 | 15 | import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos' |
b49f22d8 C |
16 | import { logger } from '../helpers/logger' |
17 | import { CONFIG } from '../initializers/config' | |
8d987ec6 | 18 | import { |
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 | 26 | import { AccountModel } from '../models/account/account' |
b49f22d8 | 27 | import { VideoModel } from '../models/video/video' |
92bf2f62 | 28 | import { VideoChannelModel } from '../models/video/video-channel' |
b49f22d8 | 29 | import { VideoPlaylistModel } from '../models/video/video-playlist' |
d91ce83d | 30 | import { MAccountActor, MChannelActor, MVideo, MVideoPlaylist } from '../types/models' |
b2111066 | 31 | import { getActivityStreamDuration } from './activitypub/activity' |
d0800f76 | 32 | import { getBiggestActorImage } from './actor-image' |
d91ce83d | 33 | import { Hooks } from './plugins/hooks' |
2539932e | 34 | import { ServerConfigManager } from './server-config-manager' |
e032aec9 | 35 | |
6fad8e51 C |
36 | type 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 |
68 | type HookContext = { |
69 | video?: MVideo | |
70 | playlist?: MVideoPlaylist | |
71 | } | |
72 | ||
f2eb23cd | 73 | class 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 | 410 | private static async addAsyncPluginCSS (htmlStringPage: string) { |
f9eee54f JL |
411 | if (!pathExists(PLUGIN_GLOBAL_CSS_PATH)) { |
412 | logger.info('Plugin Global CSS file is not available (generation may still be in progress), ignoring it.') | |
413 | return htmlStringPage | |
414 | } | |
415 | ||
416 | let globalCSSContent: Buffer | |
417 | ||
418 | try { | |
419 | globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH) | |
420 | } catch (err) { | |
421 | logger.error('Error retrieving the Plugin Global CSS file, ignoring it.', { err }) | |
422 | return htmlStringPage | |
423 | } | |
424 | ||
3e753302 | 425 | if (globalCSSContent.byteLength === 0) return htmlStringPage |
a8b666e9 C |
426 | |
427 | const fileHash = sha256(globalCSSContent) | |
428 | const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />` | |
ffb321be C |
429 | |
430 | return htmlStringPage.replace('</head>', linkTag + '</head>') | |
431 | } | |
432 | ||
6fad8e51 | 433 | private static generateOpenGraphMetaTags (tags: Tags) { |
8d987ec6 K |
434 | const metaTags = { |
435 | 'og:type': tags.ogType, | |
55cb8bc7 C |
436 | 'og:site_name': tags.escapedSiteName, |
437 | 'og:title': tags.escapedTitle, | |
8d987ec6 K |
438 | 'og:image': tags.image.url |
439 | } | |
440 | ||
441 | if (tags.image.width && tags.image.height) { | |
442 | metaTags['og:image:width'] = tags.image.width | |
443 | metaTags['og:image:height'] = tags.image.height | |
444 | } | |
e032aec9 | 445 | |
8d987ec6 | 446 | metaTags['og:url'] = tags.url |
55cb8bc7 | 447 | metaTags['og:description'] = tags.escapedDescription |
e032aec9 | 448 | |
8d987ec6 K |
449 | if (tags.embed) { |
450 | metaTags['og:video:url'] = tags.embed.url | |
451 | metaTags['og:video:secure_url'] = tags.embed.url | |
452 | metaTags['og:video:type'] = 'text/html' | |
453 | metaTags['og:video:width'] = EMBED_SIZE.width | |
454 | metaTags['og:video:height'] = EMBED_SIZE.height | |
455 | } | |
e032aec9 | 456 | |
8d987ec6 K |
457 | return metaTags |
458 | } | |
e032aec9 | 459 | |
6fad8e51 | 460 | private static generateStandardMetaTags (tags: Tags) { |
8d987ec6 | 461 | return { |
55cb8bc7 C |
462 | name: tags.escapedTitle, |
463 | description: tags.escapedDescription, | |
8d987ec6 K |
464 | image: tags.image.url |
465 | } | |
466 | } | |
e032aec9 | 467 | |
6fad8e51 | 468 | private static generateTwitterCardMetaTags (tags: Tags) { |
8d987ec6 K |
469 | const metaTags = { |
470 | 'twitter:card': tags.twitterCard, | |
e032aec9 | 471 | 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME, |
55cb8bc7 C |
472 | 'twitter:title': tags.escapedTitle, |
473 | 'twitter:description': tags.escapedDescription, | |
8d987ec6 | 474 | 'twitter:image': tags.image.url |
e032aec9 C |
475 | } |
476 | ||
8d987ec6 K |
477 | if (tags.image.width && tags.image.height) { |
478 | metaTags['twitter:image:width'] = tags.image.width | |
479 | metaTags['twitter:image:height'] = tags.image.height | |
480 | } | |
481 | ||
b96777c3 C |
482 | if (tags.twitterCard === 'player') { |
483 | metaTags['twitter:player'] = tags.embed.url | |
484 | metaTags['twitter:player:width'] = EMBED_SIZE.width | |
485 | metaTags['twitter:player:height'] = EMBED_SIZE.height | |
486 | } | |
487 | ||
8d987ec6 K |
488 | return metaTags |
489 | } | |
e032aec9 | 490 | |
d91ce83d | 491 | private static async generateSchemaTags (tags: Tags, context: HookContext) { |
8d987ec6 | 492 | const schema = { |
e032aec9 | 493 | '@context': 'http://schema.org', |
8d987ec6 | 494 | '@type': tags.schemaType, |
55cb8bc7 C |
495 | 'name': tags.escapedTitle, |
496 | 'description': tags.escapedDescription, | |
8d987ec6 K |
497 | 'image': tags.image.url, |
498 | 'url': tags.url | |
499 | } | |
500 | ||
501 | if (tags.list) { | |
502 | schema['numberOfItems'] = tags.list.numberOfItems | |
503 | schema['thumbnailUrl'] = tags.image.url | |
504 | } | |
505 | ||
506 | if (tags.embed) { | |
507 | schema['embedUrl'] = tags.embed.url | |
508 | schema['uploadDate'] = tags.embed.createdAt | |
6fad8e51 C |
509 | |
510 | if (tags.embed.duration) schema['duration'] = tags.embed.duration | |
6fad8e51 | 511 | |
8d987ec6 K |
512 | schema['thumbnailUrl'] = tags.image.url |
513 | schema['contentUrl'] = tags.url | |
514 | } | |
515 | ||
d91ce83d | 516 | return Hooks.wrapObject(schema, 'filter:html.client.json-ld.result', context) |
8d987ec6 K |
517 | } |
518 | ||
d91ce83d | 519 | private static async addTags (htmlStringPage: string, tagsValues: Tags, context: HookContext) { |
8d987ec6 K |
520 | const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues) |
521 | const standardMetaTags = this.generateStandardMetaTags(tagsValues) | |
522 | const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues) | |
d91ce83d | 523 | const schemaTags = await this.generateSchemaTags(tagsValues, context) |
8d987ec6 | 524 | |
55cb8bc7 | 525 | const { url, escapedTitle, embed, originUrl, disallowIndexation } = tagsValues |
8d987ec6 | 526 | |
55cb8bc7 | 527 | const oembedLinkTags: { type: string, href: string, escapedTitle: string }[] = [] |
8d987ec6 K |
528 | |
529 | if (embed) { | |
530 | oembedLinkTags.push({ | |
531 | type: 'application/json+oembed', | |
532 | href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url), | |
55cb8bc7 | 533 | escapedTitle |
8d987ec6 | 534 | }) |
e032aec9 C |
535 | } |
536 | ||
55cb8bc7 | 537 | let tagsStr = '' |
e032aec9 C |
538 | |
539 | // Opengraph | |
540 | Object.keys(openGraphMetaTags).forEach(tagName => { | |
a1587156 | 541 | const tagValue = openGraphMetaTags[tagName] |
e032aec9 | 542 | |
55cb8bc7 | 543 | tagsStr += `<meta property="${tagName}" content="${tagValue}" />` |
e032aec9 C |
544 | }) |
545 | ||
8d987ec6 K |
546 | // Standard |
547 | Object.keys(standardMetaTags).forEach(tagName => { | |
548 | const tagValue = standardMetaTags[tagName] | |
549 | ||
55cb8bc7 | 550 | tagsStr += `<meta property="${tagName}" content="${tagValue}" />` |
8d987ec6 K |
551 | }) |
552 | ||
553 | // Twitter card | |
554 | Object.keys(twitterCardMetaTags).forEach(tagName => { | |
555 | const tagValue = twitterCardMetaTags[tagName] | |
556 | ||
55cb8bc7 | 557 | tagsStr += `<meta property="${tagName}" content="${tagValue}" />` |
8d987ec6 K |
558 | }) |
559 | ||
e032aec9 C |
560 | // OEmbed |
561 | for (const oembedLinkTag of oembedLinkTags) { | |
55cb8bc7 | 562 | tagsStr += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.escapedTitle}" />` |
e032aec9 C |
563 | } |
564 | ||
565 | // Schema.org | |
8d987ec6 | 566 | if (schemaTags) { |
55cb8bc7 | 567 | tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>` |
8d987ec6 | 568 | } |
92bf2f62 | 569 | |
8d987ec6 | 570 | // SEO, use origin URL |
55cb8bc7 | 571 | tagsStr += `<link rel="canonical" href="${originUrl}" />` |
92bf2f62 | 572 | |
352819ef | 573 | if (disallowIndexation) { |
55cb8bc7 | 574 | tagsStr += `<meta name="robots" content="noindex" />` |
352819ef C |
575 | } |
576 | ||
55cb8bc7 | 577 | return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr) |
e032aec9 C |
578 | } |
579 | } | |
f2eb23cd | 580 | |
5fc44b57 | 581 | function sendHTML (html: string, res: express.Response, localizedHTML: boolean = false) { |
f2eb23cd RK |
582 | res.set('Content-Type', 'text/html; charset=UTF-8') |
583 | ||
5fc44b57 | 584 | if (localizedHTML) { |
585 | res.set('Vary', 'Accept-Language') | |
586 | } | |
587 | ||
f2eb23cd RK |
588 | return res.send(html) |
589 | } | |
590 | ||
591 | async function serveIndexHTML (req: express.Request, res: express.Response) { | |
8bd67ef6 | 592 | if (req.accepts(ACCEPT_HEADERS) === 'html' || !req.headers.accept) { |
f2eb23cd RK |
593 | try { |
594 | await generateHTMLPage(req, res, req.params.language) | |
595 | return | |
596 | } catch (err) { | |
1cc97746 | 597 | logger.error('Cannot generate HTML page.', { err }) |
76148b27 | 598 | return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end() |
f2eb23cd RK |
599 | } |
600 | } | |
601 | ||
76148b27 | 602 | return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end() |
f2eb23cd RK |
603 | } |
604 | ||
605 | // --------------------------------------------------------------------------- | |
606 | ||
607 | export { | |
608 | ClientHtml, | |
609 | sendHTML, | |
610 | serveIndexHTML | |
611 | } | |
612 | ||
613 | async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) { | |
614 | const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang) | |
615 | ||
5fc44b57 | 616 | return sendHTML(html, res, true) |
f2eb23cd | 617 | } |