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