]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/client-html.ts
Live views update
[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
214 ClientHtml.htmlCache[path] = html
215
216 return html
217 }
218
219 private static async getAccountOrChannelHTMLPage (
220 loader: () => Promise<MAccountActor | MChannelActor>,
221 req: express.Request,
222 res: express.Response
223 ) {
224 const [ html, entity ] = await Promise.all([
225 ClientHtml.getIndexHTML(req, res),
226 loader()
227 ])
228
229 // Let Angular application handle errors
230 if (!entity) {
231 res.status(HttpStatusCode.NOT_FOUND_404)
232 return ClientHtml.getIndexHTML(req, res)
233 }
234
235 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
236 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
237
238 const url = entity.getLocalUrl()
239 const originUrl = entity.Actor.url
240 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
241 const title = escapeHTML(entity.getDisplayName())
242 const description = escapeHTML(entity.description)
243
244 const image = {
245 url: entity.Actor.getAvatarUrl(),
246 width: AVATARS_SIZE.width,
247 height: AVATARS_SIZE.height
248 }
249
250 const ogType = 'website'
251 const twitterCard = 'summary'
252 const schemaType = 'ProfilePage'
253
254 customHtml = ClientHtml.addTags(customHtml, {
255 url,
256 originUrl,
257 title,
258 siteName,
259 description,
260 image,
261 ogType,
262 twitterCard,
263 schemaType
264 })
265
266 return customHtml
267 }
268
269 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
270 const path = ClientHtml.getIndexPath(req, res, paramLang)
271 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
272
273 const buffer = await readFile(path)
274
275 let html = buffer.toString()
276
277 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
278 html = ClientHtml.addManifestContentHash(html)
279 html = ClientHtml.addFaviconContentHash(html)
280 html = ClientHtml.addLogoContentHash(html)
281 html = ClientHtml.addCustomCSS(html)
282 html = await ClientHtml.addAsyncPluginCSS(html)
283
284 ClientHtml.htmlCache[path] = html
285
286 return html
287 }
288
289 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
290 let lang: string
291
292 // Check param lang validity
293 if (paramLang && is18nLocale(paramLang)) {
294 lang = paramLang
295
296 // Save locale in cookies
297 res.cookie('clientLanguage', lang, {
298 secure: WEBSERVER.SCHEME === 'https',
299 sameSite: 'none',
300 maxAge: 1000 * 3600 * 24 * 90 // 3 months
301 })
302
303 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
304 lang = req.cookies.clientLanguage
305 } else {
306 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
307 }
308
309 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
310 }
311
312 private static getEmbedPath () {
313 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
314 }
315
316 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
317 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
318 }
319
320 private static addManifestContentHash (htmlStringPage: string) {
321 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
322 }
323
324 private static addFaviconContentHash (htmlStringPage: string) {
325 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
326 }
327
328 private static addLogoContentHash (htmlStringPage: string) {
329 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
330 }
331
332 private static addTitleTag (htmlStringPage: string, title?: string) {
333 let text = title || CONFIG.INSTANCE.NAME
334 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
335
336 const titleTag = `<title>${text}</title>`
337
338 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
339 }
340
341 private static addDescriptionTag (htmlStringPage: string, description?: string) {
342 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
343 const descriptionTag = `<meta name="description" content="${content}" />`
344
345 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
346 }
347
348 private static addCustomCSS (htmlStringPage: string) {
349 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
350
351 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
352 }
353
354 private static async addAsyncPluginCSS (htmlStringPage: string) {
355 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
356 if (globalCSSContent.byteLength === 0) return htmlStringPage
357
358 const fileHash = sha256(globalCSSContent)
359 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
360
361 return htmlStringPage.replace('</head>', linkTag + '</head>')
362 }
363
364 private static generateOpenGraphMetaTags (tags: Tags) {
365 const metaTags = {
366 'og:type': tags.ogType,
367 'og:site_name': tags.siteName,
368 'og:title': tags.title,
369 'og:image': tags.image.url
370 }
371
372 if (tags.image.width && tags.image.height) {
373 metaTags['og:image:width'] = tags.image.width
374 metaTags['og:image:height'] = tags.image.height
375 }
376
377 metaTags['og:url'] = tags.url
378 metaTags['og:description'] = tags.description
379
380 if (tags.embed) {
381 metaTags['og:video:url'] = tags.embed.url
382 metaTags['og:video:secure_url'] = tags.embed.url
383 metaTags['og:video:type'] = 'text/html'
384 metaTags['og:video:width'] = EMBED_SIZE.width
385 metaTags['og:video:height'] = EMBED_SIZE.height
386 }
387
388 return metaTags
389 }
390
391 private static generateStandardMetaTags (tags: Tags) {
392 return {
393 name: tags.title,
394 description: tags.description,
395 image: tags.image.url
396 }
397 }
398
399 private static generateTwitterCardMetaTags (tags: Tags) {
400 const metaTags = {
401 'twitter:card': tags.twitterCard,
402 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
403 'twitter:title': tags.title,
404 'twitter:description': tags.description,
405 'twitter:image': tags.image.url
406 }
407
408 if (tags.image.width && tags.image.height) {
409 metaTags['twitter:image:width'] = tags.image.width
410 metaTags['twitter:image:height'] = tags.image.height
411 }
412
413 if (tags.twitterCard === 'player') {
414 metaTags['twitter:player'] = tags.embed.url
415 metaTags['twitter:player:width'] = EMBED_SIZE.width
416 metaTags['twitter:player:height'] = EMBED_SIZE.height
417 }
418
419 return metaTags
420 }
421
422 private static generateSchemaTags (tags: Tags) {
423 const schema = {
424 '@context': 'http://schema.org',
425 '@type': tags.schemaType,
426 'name': tags.title,
427 'description': tags.description,
428 'image': tags.image.url,
429 'url': tags.url
430 }
431
432 if (tags.list) {
433 schema['numberOfItems'] = tags.list.numberOfItems
434 schema['thumbnailUrl'] = tags.image.url
435 }
436
437 if (tags.embed) {
438 schema['embedUrl'] = tags.embed.url
439 schema['uploadDate'] = tags.embed.createdAt
440
441 if (tags.embed.duration) schema['duration'] = tags.embed.duration
442 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
443
444 schema['thumbnailUrl'] = tags.image.url
445 schema['contentUrl'] = tags.url
446 }
447
448 return schema
449 }
450
451 private static addTags (htmlStringPage: string, tagsValues: Tags) {
452 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
453 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
454 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
455 const schemaTags = this.generateSchemaTags(tagsValues)
456
457 const { url, title, embed, originUrl } = tagsValues
458
459 const oembedLinkTags: { type: string, href: string, title: string }[] = []
460
461 if (embed) {
462 oembedLinkTags.push({
463 type: 'application/json+oembed',
464 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
465 title
466 })
467 }
468
469 let tagsString = ''
470
471 // Opengraph
472 Object.keys(openGraphMetaTags).forEach(tagName => {
473 const tagValue = openGraphMetaTags[tagName]
474
475 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
476 })
477
478 // Standard
479 Object.keys(standardMetaTags).forEach(tagName => {
480 const tagValue = standardMetaTags[tagName]
481
482 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
483 })
484
485 // Twitter card
486 Object.keys(twitterCardMetaTags).forEach(tagName => {
487 const tagValue = twitterCardMetaTags[tagName]
488
489 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
490 })
491
492 // OEmbed
493 for (const oembedLinkTag of oembedLinkTags) {
494 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
495 }
496
497 // Schema.org
498 if (schemaTags) {
499 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
500 }
501
502 // SEO, use origin URL
503 tagsString += `<link rel="canonical" href="${originUrl}" />`
504
505 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
506 }
507 }
508
509 function sendHTML (html: string, res: express.Response) {
510 res.set('Content-Type', 'text/html; charset=UTF-8')
511
512 return res.send(html)
513 }
514
515 async function serveIndexHTML (req: express.Request, res: express.Response) {
516 if (req.accepts(ACCEPT_HEADERS) === 'html' ||
517 !req.headers.accept) {
518 try {
519 await generateHTMLPage(req, res, req.params.language)
520 return
521 } catch (err) {
522 logger.error('Cannot generate HTML page.', err)
523 return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
524 }
525 }
526
527 return res.sendStatus(HttpStatusCode.NOT_ACCEPTABLE_406)
528 }
529
530 // ---------------------------------------------------------------------------
531
532 export {
533 ClientHtml,
534 sendHTML,
535 serveIndexHTML
536 }
537
538 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
539 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
540
541 return sendHTML(html, res)
542 }