1 import * as express from 'express'
2 import { readFile } from 'fs-extra'
3 import { join } from 'path'
4 import validator from 'validator'
5 import { escapeHTML } from '@shared/core-utils/renderer'
6 import { HTMLServerConfig } from '@shared/models'
7 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
8 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
9 import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
10 import { isTestInstance, sha256 } from '../helpers/core-utils'
11 import { logger } from '../helpers/logger'
12 import { mdToPlainText } from '../helpers/markdown'
13 import { CONFIG } from '../initializers/config'
17 CUSTOM_HTML_TAG_COMMENTS,
20 PLUGIN_GLOBAL_CSS_PATH,
22 } from '../initializers/constants'
23 import { AccountModel } from '../models/account/account'
24 import { VideoModel } from '../models/video/video'
25 import { VideoChannelModel } from '../models/video/video-channel'
26 import { getActivityStreamDuration } from '../models/video/video-format-utils'
27 import { VideoPlaylistModel } from '../models/video/video-playlist'
28 import { MAccountActor, MChannelActor } from '../types/models'
29 import { ServerConfigManager } from './server-config-manager'
33 twitterCard: 'player' | 'summary' | 'summary_large_image'
62 private static htmlCache: { [path: string]: string } = {}
64 static invalidCache () {
65 logger.info('Cleaning HTML cache.')
67 ClientHtml.htmlCache = {}
70 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
71 const html = paramLang
72 ? await ClientHtml.getIndexHTML(req, res, paramLang)
73 : await ClientHtml.getIndexHTML(req, res)
75 let customHtml = ClientHtml.addTitleTag(html)
76 customHtml = ClientHtml.addDescriptionTag(customHtml)
81 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
82 // Let Angular application handle errors
83 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
84 res.status(HttpStatusCode.NOT_FOUND_404)
85 return ClientHtml.getIndexHTML(req, res)
88 const [ html, video ] = await Promise.all([
89 ClientHtml.getIndexHTML(req, res),
90 VideoModel.loadWithBlacklist(videoId)
93 // Let Angular application handle errors
94 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
95 res.status(HttpStatusCode.NOT_FOUND_404)
99 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
100 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(video.description))
102 const url = WEBSERVER.URL + video.getWatchStaticPath()
103 const originUrl = video.url
104 const title = escapeHTML(video.name)
105 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
106 const description = mdToPlainText(video.description)
109 url: WEBSERVER.URL + video.getPreviewStaticPath()
113 url: WEBSERVER.URL + video.getEmbedStaticPath(),
114 createdAt: video.createdAt.toISOString(),
115 duration: getActivityStreamDuration(video.duration),
119 const ogType = 'video'
120 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
121 const schemaType = 'VideoObject'
123 customHtml = ClientHtml.addTags(customHtml, {
139 static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
140 // Let Angular application handle errors
141 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
142 res.status(HttpStatusCode.NOT_FOUND_404)
143 return ClientHtml.getIndexHTML(req, res)
146 const [ html, videoPlaylist ] = await Promise.all([
147 ClientHtml.getIndexHTML(req, res),
148 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
151 // Let Angular application handle errors
152 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
153 res.status(HttpStatusCode.NOT_FOUND_404)
157 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
158 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(videoPlaylist.description))
160 const url = videoPlaylist.getWatchUrl()
161 const originUrl = videoPlaylist.url
162 const title = escapeHTML(videoPlaylist.name)
163 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
164 const description = mdToPlainText(videoPlaylist.description)
167 url: videoPlaylist.getThumbnailUrl()
171 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
172 createdAt: videoPlaylist.createdAt.toISOString()
176 numberOfItems: videoPlaylist.get('videosLength') as number
179 const ogType = 'video'
180 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
181 const schemaType = 'ItemList'
183 customHtml = ClientHtml.addTags(customHtml, {
200 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
201 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
204 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
205 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
208 static async getEmbedHTML () {
209 const path = ClientHtml.getEmbedPath()
211 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
213 const buffer = await readFile(path)
214 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
216 let html = buffer.toString()
217 html = await ClientHtml.addAsyncPluginCSS(html)
218 html = ClientHtml.addCustomCSS(html)
219 html = ClientHtml.addTitleTag(html)
220 html = ClientHtml.addDescriptionTag(html)
221 html = ClientHtml.addServerConfig(html, serverConfig)
223 ClientHtml.htmlCache[path] = html
228 private static async getAccountOrChannelHTMLPage (
229 loader: () => Promise<MAccountActor | MChannelActor>,
230 req: express.Request,
231 res: express.Response
233 const [ html, entity ] = await Promise.all([
234 ClientHtml.getIndexHTML(req, res),
238 // Let Angular application handle errors
240 res.status(HttpStatusCode.NOT_FOUND_404)
241 return ClientHtml.getIndexHTML(req, res)
244 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
245 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(entity.description))
247 const url = entity.getLocalUrl()
248 const originUrl = entity.Actor.url
249 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
250 const title = escapeHTML(entity.getDisplayName())
251 const description = mdToPlainText(entity.description)
254 url: entity.Actor.getAvatarUrl(),
255 width: ACTOR_IMAGES_SIZE.AVATARS.width,
256 height: ACTOR_IMAGES_SIZE.AVATARS.height
259 const ogType = 'website'
260 const twitterCard = 'summary'
261 const schemaType = 'ProfilePage'
263 customHtml = ClientHtml.addTags(customHtml, {
278 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
279 const path = ClientHtml.getIndexPath(req, res, paramLang)
280 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
282 const buffer = await readFile(path)
283 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
285 let html = buffer.toString()
287 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
288 html = ClientHtml.addManifestContentHash(html)
289 html = ClientHtml.addFaviconContentHash(html)
290 html = ClientHtml.addLogoContentHash(html)
291 html = ClientHtml.addCustomCSS(html)
292 html = ClientHtml.addServerConfig(html, serverConfig)
293 html = await ClientHtml.addAsyncPluginCSS(html)
295 ClientHtml.htmlCache[path] = html
300 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
303 // Check param lang validity
304 if (paramLang && is18nLocale(paramLang)) {
307 // Save locale in cookies
308 res.cookie('clientLanguage', lang, {
309 secure: WEBSERVER.SCHEME === 'https',
311 maxAge: 1000 * 3600 * 24 * 90 // 3 months
314 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
315 lang = req.cookies.clientLanguage
317 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
320 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
323 private static getEmbedPath () {
324 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
327 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
328 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
331 private static addManifestContentHash (htmlStringPage: string) {
332 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
335 private static addFaviconContentHash (htmlStringPage: string) {
336 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
339 private static addLogoContentHash (htmlStringPage: string) {
340 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
343 private static addTitleTag (htmlStringPage: string, title?: string) {
344 let text = title || CONFIG.INSTANCE.NAME
345 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
347 const titleTag = `<title>${text}</title>`
349 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
352 private static addDescriptionTag (htmlStringPage: string, description?: string) {
353 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
354 const descriptionTag = `<meta name="description" content="${content}" />`
356 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
359 private static addCustomCSS (htmlStringPage: string) {
360 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
362 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
365 private static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
366 const serverConfigString = JSON.stringify(serverConfig)
367 const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = '${serverConfigString}'</script>`
369 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
372 private static async addAsyncPluginCSS (htmlStringPage: string) {
373 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
374 if (globalCSSContent.byteLength === 0) return htmlStringPage
376 const fileHash = sha256(globalCSSContent)
377 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
379 return htmlStringPage.replace('</head>', linkTag + '</head>')
382 private static generateOpenGraphMetaTags (tags: Tags) {
384 'og:type': tags.ogType,
385 'og:site_name': tags.siteName,
386 'og:title': tags.title,
387 'og:image': tags.image.url
390 if (tags.image.width && tags.image.height) {
391 metaTags['og:image:width'] = tags.image.width
392 metaTags['og:image:height'] = tags.image.height
395 metaTags['og:url'] = tags.url
396 metaTags['og:description'] = mdToPlainText(tags.description)
399 metaTags['og:video:url'] = tags.embed.url
400 metaTags['og:video:secure_url'] = tags.embed.url
401 metaTags['og:video:type'] = 'text/html'
402 metaTags['og:video:width'] = EMBED_SIZE.width
403 metaTags['og:video:height'] = EMBED_SIZE.height
409 private static generateStandardMetaTags (tags: Tags) {
412 description: mdToPlainText(tags.description),
413 image: tags.image.url
417 private static generateTwitterCardMetaTags (tags: Tags) {
419 'twitter:card': tags.twitterCard,
420 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
421 'twitter:title': tags.title,
422 'twitter:description': tags.description,
423 'twitter:image': tags.image.url
426 if (tags.image.width && tags.image.height) {
427 metaTags['twitter:image:width'] = tags.image.width
428 metaTags['twitter:image:height'] = tags.image.height
431 if (tags.twitterCard === 'player') {
432 metaTags['twitter:player'] = tags.embed.url
433 metaTags['twitter:player:width'] = EMBED_SIZE.width
434 metaTags['twitter:player:height'] = EMBED_SIZE.height
440 private static generateSchemaTags (tags: Tags) {
442 '@context': 'http://schema.org',
443 '@type': tags.schemaType,
445 'description': tags.description,
446 'image': tags.image.url,
451 schema['numberOfItems'] = tags.list.numberOfItems
452 schema['thumbnailUrl'] = tags.image.url
456 schema['embedUrl'] = tags.embed.url
457 schema['uploadDate'] = tags.embed.createdAt
459 if (tags.embed.duration) schema['duration'] = tags.embed.duration
460 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
462 schema['thumbnailUrl'] = tags.image.url
463 schema['contentUrl'] = tags.url
469 private static addTags (htmlStringPage: string, tagsValues: Tags) {
470 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
471 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
472 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
473 const schemaTags = this.generateSchemaTags(tagsValues)
475 const { url, title, embed, originUrl } = tagsValues
477 const oembedLinkTags: { type: string, href: string, title: string }[] = []
480 oembedLinkTags.push({
481 type: 'application/json+oembed',
482 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
490 Object.keys(openGraphMetaTags).forEach(tagName => {
491 const tagValue = openGraphMetaTags[tagName]
493 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
497 Object.keys(standardMetaTags).forEach(tagName => {
498 const tagValue = standardMetaTags[tagName]
500 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
504 Object.keys(twitterCardMetaTags).forEach(tagName => {
505 const tagValue = twitterCardMetaTags[tagName]
507 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
511 for (const oembedLinkTag of oembedLinkTags) {
512 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
517 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
520 // SEO, use origin URL
521 tagsString += `<link rel="canonical" href="${originUrl}" />`
523 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
527 function sendHTML (html: string, res: express.Response) {
528 res.set('Content-Type', 'text/html; charset=UTF-8')
530 return res.send(html)
533 async function serveIndexHTML (req: express.Request, res: express.Response) {
534 if (req.accepts(ACCEPT_HEADERS) === 'html' ||
535 !req.headers.accept) {
537 await generateHTMLPage(req, res, req.params.language)
540 logger.error('Cannot generate HTML page.', err)
541 return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
545 return res.sendStatus(HttpStatusCode.NOT_ACCEPTABLE_406)
548 // ---------------------------------------------------------------------------
556 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
557 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
559 return sendHTML(html, res)