]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Add validator channelName for create-user api
[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
174 private static async getAccountOrChannelHTMLPage (
453e83ea 175 loader: () => Bluebird<MAccountActor | MChannelActor>,
92bf2f62
C
176 req: express.Request,
177 res: express.Response
178 ) {
179 const [ html, entity ] = await Promise.all([
180 ClientHtml.getIndexHTML(req, res),
181 loader()
182 ])
183
184 // Let Angular application handle errors
185 if (!entity) {
c08579e1 186 res.status(404)
92bf2f62
C
187 return ClientHtml.getIndexHTML(req, res)
188 }
189
190 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
191 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
8d987ec6
K
192
193 const url = entity.Actor.url
194 const title = escapeHTML(entity.getDisplayName())
195 const description = escapeHTML(entity.description)
196
197 const image = {
198 url: entity.Actor.getAvatarUrl(),
199 width: AVATARS_SIZE.width,
200 height: AVATARS_SIZE.height
201 }
202
203 const ogType = 'website'
204 const twitterCard = 'summary'
205 const schemaType = 'ProfilePage'
206
207 customHtml = ClientHtml.addTags(customHtml, { url, title, description, image, ogType, twitterCard, schemaType })
9aac4423
C
208
209 return customHtml
210 }
211
212 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
213 const path = ClientHtml.getIndexPath(req, res, paramLang)
a1587156 214 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
9aac4423
C
215
216 const buffer = await readFile(path)
217
218 let html = buffer.toString()
219
7738273b 220 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
caf2aaf4
K
221 html = ClientHtml.addManifestContentHash(html)
222 html = ClientHtml.addFaviconContentHash(html)
223 html = ClientHtml.addLogoContentHash(html)
9aac4423 224 html = ClientHtml.addCustomCSS(html)
a8b666e9 225 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 226
a1587156 227 ClientHtml.htmlCache[path] = html
9aac4423
C
228
229 return html
e032aec9
C
230 }
231
7738273b 232 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
233 let lang: string
234
235 // Check param lang validity
236 if (paramLang && is18nLocale(paramLang)) {
237 lang = paramLang
238
239 // Save locale in cookies
240 res.cookie('clientLanguage', lang, {
6dd9de95 241 secure: WEBSERVER.SCHEME === 'https',
bc90883f 242 sameSite: 'none',
e032aec9
C
243 maxAge: 1000 * 3600 * 24 * 90 // 3 months
244 })
245
246 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
247 lang = req.cookies.clientLanguage
248 } else {
249 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
250 }
251
252 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
253 }
254
7738273b
RK
255 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
256 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
257 }
258
caf2aaf4
K
259 private static addManifestContentHash (htmlStringPage: string) {
260 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
261 }
262
1fdf8edb 263 private static addFaviconContentHash (htmlStringPage: string) {
caf2aaf4
K
264 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
265 }
266
1fdf8edb 267 private static addLogoContentHash (htmlStringPage: string) {
caf2aaf4
K
268 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
269 }
270
9aac4423
C
271 private static addTitleTag (htmlStringPage: string, title?: string) {
272 let text = title || CONFIG.INSTANCE.NAME
273 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
274
275 const titleTag = `<title>${text}</title>`
e032aec9
C
276
277 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
278 }
279
9aac4423
C
280 private static addDescriptionTag (htmlStringPage: string, description?: string) {
281 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
282 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
283
284 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
285 }
286
287 private static addCustomCSS (htmlStringPage: string) {
ffb321be 288 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
289
290 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
291 }
292
a8b666e9
C
293 private static async addAsyncPluginCSS (htmlStringPage: string) {
294 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 295 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
296
297 const fileHash = sha256(globalCSSContent)
298 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
299
300 return htmlStringPage.replace('</head>', linkTag + '</head>')
301 }
302
6fad8e51 303 private static generateOpenGraphMetaTags (tags: Tags) {
8d987ec6
K
304 const metaTags = {
305 'og:type': tags.ogType,
306 'og:title': tags.title,
307 'og:image': tags.image.url
308 }
309
310 if (tags.image.width && tags.image.height) {
311 metaTags['og:image:width'] = tags.image.width
312 metaTags['og:image:height'] = tags.image.height
313 }
e032aec9 314
8d987ec6
K
315 metaTags['og:url'] = tags.url
316 metaTags['og:description'] = tags.description
e032aec9 317
8d987ec6
K
318 if (tags.embed) {
319 metaTags['og:video:url'] = tags.embed.url
320 metaTags['og:video:secure_url'] = tags.embed.url
321 metaTags['og:video:type'] = 'text/html'
322 metaTags['og:video:width'] = EMBED_SIZE.width
323 metaTags['og:video:height'] = EMBED_SIZE.height
324 }
e032aec9 325
8d987ec6
K
326 return metaTags
327 }
e032aec9 328
6fad8e51 329 private static generateStandardMetaTags (tags: Tags) {
8d987ec6
K
330 return {
331 name: tags.title,
332 description: tags.description,
333 image: tags.image.url
334 }
335 }
e032aec9 336
6fad8e51 337 private static generateTwitterCardMetaTags (tags: Tags) {
8d987ec6
K
338 const metaTags = {
339 'twitter:card': tags.twitterCard,
e032aec9 340 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
8d987ec6
K
341 'twitter:title': tags.title,
342 'twitter:description': tags.description,
343 'twitter:image': tags.image.url
e032aec9
C
344 }
345
8d987ec6
K
346 if (tags.image.width && tags.image.height) {
347 metaTags['twitter:image:width'] = tags.image.width
348 metaTags['twitter:image:height'] = tags.image.height
349 }
350
b96777c3
C
351 if (tags.twitterCard === 'player') {
352 metaTags['twitter:player'] = tags.embed.url
353 metaTags['twitter:player:width'] = EMBED_SIZE.width
354 metaTags['twitter:player:height'] = EMBED_SIZE.height
355 }
356
8d987ec6
K
357 return metaTags
358 }
e032aec9 359
6fad8e51 360 private static generateSchemaTags (tags: Tags) {
8d987ec6 361 const schema = {
e032aec9 362 '@context': 'http://schema.org',
8d987ec6
K
363 '@type': tags.schemaType,
364 'name': tags.title,
365 'description': tags.description,
366 'image': tags.image.url,
367 'url': tags.url
368 }
369
370 if (tags.list) {
371 schema['numberOfItems'] = tags.list.numberOfItems
372 schema['thumbnailUrl'] = tags.image.url
373 }
374
375 if (tags.embed) {
376 schema['embedUrl'] = tags.embed.url
377 schema['uploadDate'] = tags.embed.createdAt
6fad8e51
C
378
379 if (tags.embed.duration) schema['duration'] = tags.embed.duration
380 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
381
8d987ec6
K
382 schema['thumbnailUrl'] = tags.image.url
383 schema['contentUrl'] = tags.url
384 }
385
386 return schema
387 }
388
6fad8e51 389 private static addTags (htmlStringPage: string, tagsValues: Tags) {
8d987ec6
K
390 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
391 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
392 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
393 const schemaTags = this.generateSchemaTags(tagsValues)
394
395 const { url, title, embed } = tagsValues
396
6fad8e51 397 const oembedLinkTags: { type: string, href: string, title: string }[] = []
8d987ec6
K
398
399 if (embed) {
400 oembedLinkTags.push({
401 type: 'application/json+oembed',
402 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
403 title
404 })
e032aec9
C
405 }
406
407 let tagsString = ''
408
409 // Opengraph
410 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 411 const tagValue = openGraphMetaTags[tagName]
e032aec9
C
412
413 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
414 })
415
8d987ec6
K
416 // Standard
417 Object.keys(standardMetaTags).forEach(tagName => {
418 const tagValue = standardMetaTags[tagName]
419
420 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
421 })
422
423 // Twitter card
424 Object.keys(twitterCardMetaTags).forEach(tagName => {
425 const tagValue = twitterCardMetaTags[tagName]
426
427 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
428 })
429
e032aec9
C
430 // OEmbed
431 for (const oembedLinkTag of oembedLinkTags) {
432 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
433 }
434
435 // Schema.org
8d987ec6
K
436 if (schemaTags) {
437 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
438 }
92bf2f62 439
8d987ec6
K
440 // SEO, use origin URL
441 tagsString += `<link rel="canonical" href="${url}" />`
92bf2f62 442
8d987ec6 443 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
e032aec9
C
444 }
445}