]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Upgrade sequelize to v6
[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'
8import { escapeHTML, isTestInstance, sha256 } from '../helpers/core-utils'
9import { logger } from '../helpers/logger'
10import { CONFIG } from '../initializers/config'
8d987ec6 11import {
b49f22d8 12 ACCEPT_HEADERS,
8d987ec6
K
13 AVATARS_SIZE,
14 CUSTOM_HTML_TAG_COMMENTS,
15 EMBED_SIZE,
f2eb23cd 16 FILES_CONTENT_HASH,
b49f22d8
C
17 PLUGIN_GLOBAL_CSS_PATH,
18 WEBSERVER
8d987ec6 19} from '../initializers/constants'
92bf2f62 20import { AccountModel } from '../models/account/account'
b49f22d8 21import { VideoModel } from '../models/video/video'
92bf2f62 22import { VideoChannelModel } from '../models/video/video-channel'
b49f22d8
C
23import { getActivityStreamDuration } from '../models/video/video-format-utils'
24import { VideoPlaylistModel } from '../models/video/video-playlist'
8d987ec6 25import { MAccountActor, MChannelActor } from '../types/models'
e032aec9 26
6fad8e51
C
27type Tags = {
28 ogType: string
b96777c3 29 twitterCard: 'player' | 'summary' | 'summary_large_image'
6fad8e51
C
30 schemaType: string
31
32 list?: {
33 numberOfItems: number
34 }
35
865af3fd 36 siteName: string
6fad8e51
C
37 title: string
38 url: string
106fa224 39 originUrl: string
6fad8e51
C
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
f2eb23cd 56class ClientHtml {
e032aec9 57
a1587156 58 private static htmlCache: { [path: string]: string } = {}
e032aec9
C
59
60 static invalidCache () {
3e753302
C
61 logger.info('Cleaning HTML cache.')
62
e032aec9
C
63 ClientHtml.htmlCache = {}
64 }
65
9aac4423 66 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
7738273b
RK
67 const html = paramLang
68 ? await ClientHtml.getIndexHTML(req, res, paramLang)
69 : await ClientHtml.getIndexHTML(req, res)
e032aec9 70
9aac4423
C
71 let customHtml = ClientHtml.addTitleTag(html)
72 customHtml = ClientHtml.addDescriptionTag(customHtml)
e032aec9 73
9aac4423 74 return customHtml
e032aec9
C
75 }
76
77 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
e032aec9 78 // Let Angular application handle errors
92bf2f62 79 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
2d53be02 80 res.status(HttpStatusCode.NOT_FOUND_404)
e032aec9
C
81 return ClientHtml.getIndexHTML(req, res)
82 }
83
84 const [ html, video ] = await Promise.all([
85 ClientHtml.getIndexHTML(req, res),
d636ab58 86 VideoModel.loadWithBlacklist(videoId)
e032aec9
C
87 ])
88
89 // Let Angular application handle errors
22a73cb8 90 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
2d53be02 91 res.status(HttpStatusCode.NOT_FOUND_404)
c08579e1 92 return html
e032aec9
C
93 }
94
9aac4423
C
95 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
96 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
8d987ec6
K
97
98 const url = WEBSERVER.URL + video.getWatchStaticPath()
106fa224 99 const originUrl = video.url
8d987ec6 100 const title = escapeHTML(video.name)
865af3fd 101 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
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
106fa224 119 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
120 url,
121 originUrl,
122 siteName,
123 title,
124 description,
125 image,
126 embed,
127 ogType,
128 twitterCard,
129 schemaType
106fa224 130 })
8d987ec6
K
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)) {
2d53be02 138 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
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) {
2d53be02 149 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
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()
106fa224 157 const originUrl = videoPlaylist.url
8d987ec6 158 const title = escapeHTML(videoPlaylist.name)
865af3fd 159 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
160 const description = escapeHTML(videoPlaylist.description)
161
162 const image = {
163 url: videoPlaylist.getThumbnailUrl()
164 }
165
6fad8e51
C
166 const embed = {
167 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
168 createdAt: videoPlaylist.createdAt.toISOString()
169 }
170
8d987ec6 171 const list = {
6fad8e51 172 numberOfItems: videoPlaylist.get('videosLength') as number
8d987ec6
K
173 }
174
175 const ogType = 'video'
6fad8e51 176 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
8d987ec6
K
177 const schemaType = 'ItemList'
178
106fa224 179 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
180 url,
181 originUrl,
182 siteName,
183 embed,
184 title,
185 description,
186 image,
187 list,
188 ogType,
189 twitterCard,
190 schemaType
106fa224 191 })
92bf2f62
C
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
cf649c2e
C
204 static async getEmbedHTML () {
205 const path = ClientHtml.getEmbedPath()
cf649c2e 206
b9da21bd 207 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
cf649c2e
C
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
92bf2f62 219 private static async getAccountOrChannelHTMLPage (
b49f22d8 220 loader: () => Promise<MAccountActor | MChannelActor>,
92bf2f62
C
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) {
2d53be02 231 res.status(HttpStatusCode.NOT_FOUND_404)
92bf2f62
C
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))
8d987ec6 237
a59f210f 238 const url = entity.getLocalUrl()
106fa224 239 const originUrl = entity.Actor.url
865af3fd 240 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
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
a59f210f
C
254 customHtml = ClientHtml.addTags(customHtml, {
255 url,
256 originUrl,
257 title,
258 siteName,
259 description,
260 image,
261 ogType,
262 twitterCard,
263 schemaType
264 })
9aac4423
C
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)
b9da21bd 271 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
9aac4423
C
272
273 const buffer = await readFile(path)
274
275 let html = buffer.toString()
276
7738273b 277 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
caf2aaf4
K
278 html = ClientHtml.addManifestContentHash(html)
279 html = ClientHtml.addFaviconContentHash(html)
280 html = ClientHtml.addLogoContentHash(html)
9aac4423 281 html = ClientHtml.addCustomCSS(html)
a8b666e9 282 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 283
a1587156 284 ClientHtml.htmlCache[path] = html
9aac4423
C
285
286 return html
e032aec9
C
287 }
288
7738273b 289 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
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, {
6dd9de95 298 secure: WEBSERVER.SCHEME === 'https',
bc90883f 299 sameSite: 'none',
e032aec9
C
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
cf649c2e
C
312 private static getEmbedPath () {
313 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
314 }
315
7738273b
RK
316 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
317 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
318 }
319
caf2aaf4
K
320 private static addManifestContentHash (htmlStringPage: string) {
321 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
322 }
323
1fdf8edb 324 private static addFaviconContentHash (htmlStringPage: string) {
caf2aaf4
K
325 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
326 }
327
1fdf8edb 328 private static addLogoContentHash (htmlStringPage: string) {
caf2aaf4
K
329 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
330 }
331
9aac4423
C
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>`
e032aec9
C
337
338 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
339 }
340
9aac4423
C
341 private static addDescriptionTag (htmlStringPage: string, description?: string) {
342 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
343 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
344
345 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
346 }
347
348 private static addCustomCSS (htmlStringPage: string) {
ffb321be 349 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
350
351 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
352 }
353
a8b666e9
C
354 private static async addAsyncPluginCSS (htmlStringPage: string) {
355 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 356 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
357
358 const fileHash = sha256(globalCSSContent)
359 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
360
361 return htmlStringPage.replace('</head>', linkTag + '</head>')
362 }
363
6fad8e51 364 private static generateOpenGraphMetaTags (tags: Tags) {
8d987ec6
K
365 const metaTags = {
366 'og:type': tags.ogType,
865af3fd 367 'og:site_name': tags.siteName,
8d987ec6
K
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 }
e032aec9 376
8d987ec6
K
377 metaTags['og:url'] = tags.url
378 metaTags['og:description'] = tags.description
e032aec9 379
8d987ec6
K
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 }
e032aec9 387
8d987ec6
K
388 return metaTags
389 }
e032aec9 390
6fad8e51 391 private static generateStandardMetaTags (tags: Tags) {
8d987ec6
K
392 return {
393 name: tags.title,
394 description: tags.description,
395 image: tags.image.url
396 }
397 }
e032aec9 398
6fad8e51 399 private static generateTwitterCardMetaTags (tags: Tags) {
8d987ec6
K
400 const metaTags = {
401 'twitter:card': tags.twitterCard,
e032aec9 402 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
8d987ec6
K
403 'twitter:title': tags.title,
404 'twitter:description': tags.description,
405 'twitter:image': tags.image.url
e032aec9
C
406 }
407
8d987ec6
K
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
b96777c3
C
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
8d987ec6
K
419 return metaTags
420 }
e032aec9 421
6fad8e51 422 private static generateSchemaTags (tags: Tags) {
8d987ec6 423 const schema = {
e032aec9 424 '@context': 'http://schema.org',
8d987ec6
K
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
6fad8e51
C
440
441 if (tags.embed.duration) schema['duration'] = tags.embed.duration
442 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
443
8d987ec6
K
444 schema['thumbnailUrl'] = tags.image.url
445 schema['contentUrl'] = tags.url
446 }
447
448 return schema
449 }
450
6fad8e51 451 private static addTags (htmlStringPage: string, tagsValues: Tags) {
8d987ec6
K
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
106fa224 457 const { url, title, embed, originUrl } = tagsValues
8d987ec6 458
6fad8e51 459 const oembedLinkTags: { type: string, href: string, title: string }[] = []
8d987ec6
K
460
461 if (embed) {
462 oembedLinkTags.push({
463 type: 'application/json+oembed',
464 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
465 title
466 })
e032aec9
C
467 }
468
469 let tagsString = ''
470
471 // Opengraph
472 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 473 const tagValue = openGraphMetaTags[tagName]
e032aec9
C
474
475 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
476 })
477
8d987ec6
K
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
e032aec9
C
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
8d987ec6
K
498 if (schemaTags) {
499 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
500 }
92bf2f62 501
8d987ec6 502 // SEO, use origin URL
106fa224 503 tagsString += `<link rel="canonical" href="${originUrl}" />`
92bf2f62 504
8d987ec6 505 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
e032aec9
C
506 }
507}
f2eb23cd
RK
508
509function sendHTML (html: string, res: express.Response) {
510 res.set('Content-Type', 'text/html; charset=UTF-8')
511
512 return res.send(html)
513}
514
515async 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
532export {
533 ClientHtml,
534 sendHTML,
535 serveIndexHTML
536}
537
538async 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}