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