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