]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
emit more specific status codes on video upload (#3423)
[github/Chocobozzz/PeerTube.git] / server / lib / client-html.ts
CommitLineData
e032aec9 1import * as express from 'express'
f2eb23cd 2import * as Bluebird from 'bluebird'
bd45d503 3import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
8d987ec6
K
4import {
5 AVATARS_SIZE,
6 CUSTOM_HTML_TAG_COMMENTS,
7 EMBED_SIZE,
8 PLUGIN_GLOBAL_CSS_PATH,
9 WEBSERVER,
f2eb23cd
RK
10 FILES_CONTENT_HASH,
11 ACCEPT_HEADERS
8d987ec6 12} from '../initializers/constants'
e032aec9 13import { join } from 'path'
b9da21bd 14import { escapeHTML, isTestInstance, sha256 } from '../helpers/core-utils'
e032aec9 15import { VideoModel } from '../models/video/video'
8d987ec6 16import { VideoPlaylistModel } from '../models/video/video-playlist'
7cde3b9c 17import validator from 'validator'
8d987ec6 18import { VideoPrivacy, VideoPlaylistPrivacy } from '../../shared/models/videos'
62689b94 19import { readFile } from 'fs-extra'
098eb377 20import { getActivityStreamDuration } from '../models/video/video-format-utils'
92bf2f62
C
21import { AccountModel } from '../models/account/account'
22import { VideoChannelModel } from '../models/video/video-channel'
6dd9de95 23import { CONFIG } from '../initializers/config'
3e753302 24import { logger } from '../helpers/logger'
8d987ec6 25import { MAccountActor, MChannelActor } from '../types/models'
2d53be02 26import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
e032aec9 27
6fad8e51
C
28type Tags = {
29 ogType: string
b96777c3 30 twitterCard: 'player' | 'summary' | 'summary_large_image'
6fad8e51
C
31 schemaType: string
32
33 list?: {
34 numberOfItems: number
35 }
36
865af3fd 37 siteName: string
6fad8e51
C
38 title: string
39 url: string
106fa224 40 originUrl: string
6fad8e51
C
41 description: string
42
43 embed?: {
44 url: string
45 createdAt: string
46 duration?: string
47 views?: number
48 }
49
50 image: {
51 url: string
52 width?: number
53 height?: number
54 }
55}
56
f2eb23cd 57class ClientHtml {
e032aec9 58
a1587156 59 private static htmlCache: { [path: string]: string } = {}
e032aec9
C
60
61 static invalidCache () {
3e753302
C
62 logger.info('Cleaning HTML cache.')
63
e032aec9
C
64 ClientHtml.htmlCache = {}
65 }
66
9aac4423 67 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
7738273b
RK
68 const html = paramLang
69 ? await ClientHtml.getIndexHTML(req, res, paramLang)
70 : await ClientHtml.getIndexHTML(req, res)
e032aec9 71
9aac4423
C
72 let customHtml = ClientHtml.addTitleTag(html)
73 customHtml = ClientHtml.addDescriptionTag(customHtml)
e032aec9 74
9aac4423 75 return customHtml
e032aec9
C
76 }
77
78 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
e032aec9 79 // Let Angular application handle errors
92bf2f62 80 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
2d53be02 81 res.status(HttpStatusCode.NOT_FOUND_404)
e032aec9
C
82 return ClientHtml.getIndexHTML(req, res)
83 }
84
85 const [ html, video ] = await Promise.all([
86 ClientHtml.getIndexHTML(req, res),
d636ab58 87 VideoModel.loadWithBlacklist(videoId)
e032aec9
C
88 ])
89
90 // Let Angular application handle errors
22a73cb8 91 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
2d53be02 92 res.status(HttpStatusCode.NOT_FOUND_404)
c08579e1 93 return html
e032aec9
C
94 }
95
9aac4423
C
96 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
97 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
8d987ec6
K
98
99 const url = WEBSERVER.URL + video.getWatchStaticPath()
106fa224 100 const originUrl = video.url
8d987ec6 101 const title = escapeHTML(video.name)
865af3fd 102 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
103 const description = escapeHTML(video.description)
104
105 const image = {
106 url: WEBSERVER.URL + video.getPreviewStaticPath()
107 }
108
109 const embed = {
110 url: WEBSERVER.URL + video.getEmbedStaticPath(),
111 createdAt: video.createdAt.toISOString(),
112 duration: getActivityStreamDuration(video.duration),
113 views: video.views
114 }
115
116 const ogType = 'video'
117 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
118 const schemaType = 'VideoObject'
119
106fa224 120 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
121 url,
122 originUrl,
123 siteName,
124 title,
125 description,
126 image,
127 embed,
128 ogType,
129 twitterCard,
130 schemaType
106fa224 131 })
8d987ec6
K
132
133 return customHtml
134 }
135
136 static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
137 // Let Angular application handle errors
138 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
2d53be02 139 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
140 return ClientHtml.getIndexHTML(req, res)
141 }
142
143 const [ html, videoPlaylist ] = await Promise.all([
144 ClientHtml.getIndexHTML(req, res),
145 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
146 ])
147
148 // Let Angular application handle errors
149 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
2d53be02 150 res.status(HttpStatusCode.NOT_FOUND_404)
8d987ec6
K
151 return html
152 }
153
154 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
155 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(videoPlaylist.description))
156
157 const url = videoPlaylist.getWatchUrl()
106fa224 158 const originUrl = videoPlaylist.url
8d987ec6 159 const title = escapeHTML(videoPlaylist.name)
865af3fd 160 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
161 const description = escapeHTML(videoPlaylist.description)
162
163 const image = {
164 url: videoPlaylist.getThumbnailUrl()
165 }
166
6fad8e51
C
167 const embed = {
168 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
169 createdAt: videoPlaylist.createdAt.toISOString()
170 }
171
8d987ec6 172 const list = {
6fad8e51 173 numberOfItems: videoPlaylist.get('videosLength') as number
8d987ec6
K
174 }
175
176 const ogType = 'video'
6fad8e51 177 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
8d987ec6
K
178 const schemaType = 'ItemList'
179
106fa224 180 customHtml = ClientHtml.addTags(customHtml, {
a59f210f
C
181 url,
182 originUrl,
183 siteName,
184 embed,
185 title,
186 description,
187 image,
188 list,
189 ogType,
190 twitterCard,
191 schemaType
106fa224 192 })
92bf2f62
C
193
194 return customHtml
195 }
196
197 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
198 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
199 }
200
201 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
202 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
203 }
204
cf649c2e
C
205 static async getEmbedHTML () {
206 const path = ClientHtml.getEmbedPath()
cf649c2e 207
b9da21bd 208 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
cf649c2e
C
209
210 const buffer = await readFile(path)
211
212 let html = buffer.toString()
213 html = await ClientHtml.addAsyncPluginCSS(html)
214
215 ClientHtml.htmlCache[path] = html
216
217 return html
218 }
219
92bf2f62 220 private static async getAccountOrChannelHTMLPage (
453e83ea 221 loader: () => Bluebird<MAccountActor | MChannelActor>,
92bf2f62
C
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) {
2d53be02 232 res.status(HttpStatusCode.NOT_FOUND_404)
92bf2f62
C
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))
8d987ec6 238
a59f210f 239 const url = entity.getLocalUrl()
106fa224 240 const originUrl = entity.Actor.url
865af3fd 241 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
8d987ec6
K
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
a59f210f
C
255 customHtml = ClientHtml.addTags(customHtml, {
256 url,
257 originUrl,
258 title,
259 siteName,
260 description,
261 image,
262 ogType,
263 twitterCard,
264 schemaType
265 })
9aac4423
C
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)
b9da21bd 272 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
9aac4423
C
273
274 const buffer = await readFile(path)
275
276 let html = buffer.toString()
277
7738273b 278 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
caf2aaf4
K
279 html = ClientHtml.addManifestContentHash(html)
280 html = ClientHtml.addFaviconContentHash(html)
281 html = ClientHtml.addLogoContentHash(html)
9aac4423 282 html = ClientHtml.addCustomCSS(html)
a8b666e9 283 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 284
a1587156 285 ClientHtml.htmlCache[path] = html
9aac4423
C
286
287 return html
e032aec9
C
288 }
289
7738273b 290 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
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, {
6dd9de95 299 secure: WEBSERVER.SCHEME === 'https',
bc90883f 300 sameSite: 'none',
e032aec9
C
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
cf649c2e
C
313 private static getEmbedPath () {
314 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
315 }
316
7738273b
RK
317 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
318 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
319 }
320
caf2aaf4
K
321 private static addManifestContentHash (htmlStringPage: string) {
322 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
323 }
324
1fdf8edb 325 private static addFaviconContentHash (htmlStringPage: string) {
caf2aaf4
K
326 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
327 }
328
1fdf8edb 329 private static addLogoContentHash (htmlStringPage: string) {
caf2aaf4
K
330 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
331 }
332
9aac4423
C
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>`
e032aec9
C
338
339 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
340 }
341
9aac4423
C
342 private static addDescriptionTag (htmlStringPage: string, description?: string) {
343 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
344 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
345
346 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
347 }
348
349 private static addCustomCSS (htmlStringPage: string) {
ffb321be 350 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
351
352 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
353 }
354
a8b666e9
C
355 private static async addAsyncPluginCSS (htmlStringPage: string) {
356 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 357 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
358
359 const fileHash = sha256(globalCSSContent)
360 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
361
362 return htmlStringPage.replace('</head>', linkTag + '</head>')
363 }
364
6fad8e51 365 private static generateOpenGraphMetaTags (tags: Tags) {
8d987ec6
K
366 const metaTags = {
367 'og:type': tags.ogType,
865af3fd 368 'og:site_name': tags.siteName,
8d987ec6
K
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 }
e032aec9 377
8d987ec6
K
378 metaTags['og:url'] = tags.url
379 metaTags['og:description'] = tags.description
e032aec9 380
8d987ec6
K
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 }
e032aec9 388
8d987ec6
K
389 return metaTags
390 }
e032aec9 391
6fad8e51 392 private static generateStandardMetaTags (tags: Tags) {
8d987ec6
K
393 return {
394 name: tags.title,
395 description: tags.description,
396 image: tags.image.url
397 }
398 }
e032aec9 399
6fad8e51 400 private static generateTwitterCardMetaTags (tags: Tags) {
8d987ec6
K
401 const metaTags = {
402 'twitter:card': tags.twitterCard,
e032aec9 403 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
8d987ec6
K
404 'twitter:title': tags.title,
405 'twitter:description': tags.description,
406 'twitter:image': tags.image.url
e032aec9
C
407 }
408
8d987ec6
K
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
b96777c3
C
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
8d987ec6
K
420 return metaTags
421 }
e032aec9 422
6fad8e51 423 private static generateSchemaTags (tags: Tags) {
8d987ec6 424 const schema = {
e032aec9 425 '@context': 'http://schema.org',
8d987ec6
K
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
6fad8e51
C
441
442 if (tags.embed.duration) schema['duration'] = tags.embed.duration
443 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
444
8d987ec6
K
445 schema['thumbnailUrl'] = tags.image.url
446 schema['contentUrl'] = tags.url
447 }
448
449 return schema
450 }
451
6fad8e51 452 private static addTags (htmlStringPage: string, tagsValues: Tags) {
8d987ec6
K
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
106fa224 458 const { url, title, embed, originUrl } = tagsValues
8d987ec6 459
6fad8e51 460 const oembedLinkTags: { type: string, href: string, title: string }[] = []
8d987ec6
K
461
462 if (embed) {
463 oembedLinkTags.push({
464 type: 'application/json+oembed',
465 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
466 title
467 })
e032aec9
C
468 }
469
470 let tagsString = ''
471
472 // Opengraph
473 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 474 const tagValue = openGraphMetaTags[tagName]
e032aec9
C
475
476 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
477 })
478
8d987ec6
K
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
e032aec9
C
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
8d987ec6
K
499 if (schemaTags) {
500 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
501 }
92bf2f62 502
8d987ec6 503 // SEO, use origin URL
106fa224 504 tagsString += `<link rel="canonical" href="${originUrl}" />`
92bf2f62 505
8d987ec6 506 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
e032aec9
C
507 }
508}
f2eb23cd
RK
509
510function sendHTML (html: string, res: express.Response) {
511 res.set('Content-Type', 'text/html; charset=UTF-8')
512
513 return res.send(html)
514}
515
516async 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
533export {
534 ClientHtml,
535 sendHTML,
536 serveIndexHTML
537}
538
539async 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}