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/models/http/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 { getActivityStreamDuration } from '../models/video/formatter/video-format-utils'
25 import { VideoModel } from '../models/video/video'
26 import { VideoChannelModel } from '../models/video/video-channel'
27 import { VideoPlaylistModel } from '../models/video/video-playlist'
28 import { MAccountActor, MChannelActor } from '../types/models'
29 import { ServerConfigManager } from './server-config-manager'
30 import { toCompleteUUID } from '@server/helpers/custom-validators/misc'
34 twitterCard: 'player' | 'summary' | 'summary_large_image'
63 private static htmlCache: { [path: string]: string } = {}
65 static invalidCache () {
66 logger.info('Cleaning HTML cache.')
68 ClientHtml.htmlCache = {}
71 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
72 const html = paramLang
73 ? await ClientHtml.getIndexHTML(req, res, paramLang)
74 : await ClientHtml.getIndexHTML(req, res)
76 let customHtml = ClientHtml.addTitleTag(html)
77 customHtml = ClientHtml.addDescriptionTag(customHtml)
82 static async getWatchHTMLPage (videoIdArg: string, req: express.Request, res: express.Response) {
83 const videoId = toCompleteUUID(videoIdArg)
85 // Let Angular application handle errors
86 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
87 res.status(HttpStatusCode.NOT_FOUND_404)
88 return ClientHtml.getIndexHTML(req, res)
91 const [ html, video ] = await Promise.all([
92 ClientHtml.getIndexHTML(req, res),
93 VideoModel.loadWithBlacklist(videoId)
96 // Let Angular application handle errors
97 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
98 res.status(HttpStatusCode.NOT_FOUND_404)
102 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
103 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(video.description))
105 const url = WEBSERVER.URL + video.getWatchStaticPath()
106 const originUrl = video.url
107 const title = escapeHTML(video.name)
108 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
109 const description = mdToPlainText(video.description)
112 url: WEBSERVER.URL + video.getPreviewStaticPath()
116 url: WEBSERVER.URL + video.getEmbedStaticPath(),
117 createdAt: video.createdAt.toISOString(),
118 duration: getActivityStreamDuration(video.duration),
122 const ogType = 'video'
123 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
124 const schemaType = 'VideoObject'
126 customHtml = ClientHtml.addTags(customHtml, {
142 static async getWatchPlaylistHTMLPage (videoPlaylistIdArg: string, req: express.Request, res: express.Response) {
143 const videoPlaylistId = toCompleteUUID(videoPlaylistIdArg)
145 // Let Angular application handle errors
146 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
147 res.status(HttpStatusCode.NOT_FOUND_404)
148 return ClientHtml.getIndexHTML(req, res)
151 const [ html, videoPlaylist ] = await Promise.all([
152 ClientHtml.getIndexHTML(req, res),
153 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
156 // Let Angular application handle errors
157 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
158 res.status(HttpStatusCode.NOT_FOUND_404)
162 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
163 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(videoPlaylist.description))
165 const url = WEBSERVER.URL + videoPlaylist.getWatchStaticPath()
166 const originUrl = videoPlaylist.url
167 const title = escapeHTML(videoPlaylist.name)
168 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
169 const description = mdToPlainText(videoPlaylist.description)
172 url: videoPlaylist.getThumbnailUrl()
176 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
177 createdAt: videoPlaylist.createdAt.toISOString()
181 numberOfItems: videoPlaylist.get('videosLength') as number
184 const ogType = 'video'
185 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
186 const schemaType = 'ItemList'
188 customHtml = ClientHtml.addTags(customHtml, {
205 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
206 const accountModelPromise = AccountModel.loadByNameWithHost(nameWithHost)
207 return this.getAccountOrChannelHTMLPage(() => accountModelPromise, req, res)
210 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
211 const videoChannelModelPromise = VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
212 return this.getAccountOrChannelHTMLPage(() => videoChannelModelPromise, req, res)
215 static async getActorHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
216 const [ account, channel ] = await Promise.all([
217 AccountModel.loadByNameWithHost(nameWithHost),
218 VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
221 return this.getAccountOrChannelHTMLPage(() => Promise.resolve(account || channel), req, res)
224 static async getEmbedHTML () {
225 const path = ClientHtml.getEmbedPath()
227 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
229 const buffer = await readFile(path)
230 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
232 let html = buffer.toString()
233 html = await ClientHtml.addAsyncPluginCSS(html)
234 html = ClientHtml.addCustomCSS(html)
235 html = ClientHtml.addTitleTag(html)
236 html = ClientHtml.addDescriptionTag(html)
237 html = ClientHtml.addServerConfig(html, serverConfig)
239 ClientHtml.htmlCache[path] = html
244 private static async getAccountOrChannelHTMLPage (
245 loader: () => Promise<MAccountActor | MChannelActor>,
246 req: express.Request,
247 res: express.Response
249 const [ html, entity ] = await Promise.all([
250 ClientHtml.getIndexHTML(req, res),
254 // Let Angular application handle errors
256 res.status(HttpStatusCode.NOT_FOUND_404)
257 return ClientHtml.getIndexHTML(req, res)
260 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
261 customHtml = ClientHtml.addDescriptionTag(customHtml, mdToPlainText(entity.description))
263 const url = entity.getLocalUrl()
264 const originUrl = entity.Actor.url
265 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
266 const title = escapeHTML(entity.getDisplayName())
267 const description = mdToPlainText(entity.description)
270 url: entity.Actor.getAvatarUrl(),
271 width: ACTOR_IMAGES_SIZE.AVATARS.width,
272 height: ACTOR_IMAGES_SIZE.AVATARS.height
275 const ogType = 'website'
276 const twitterCard = 'summary'
277 const schemaType = 'ProfilePage'
279 customHtml = ClientHtml.addTags(customHtml, {
294 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
295 const path = ClientHtml.getIndexPath(req, res, paramLang)
296 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
298 const buffer = await readFile(path)
299 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
301 let html = buffer.toString()
303 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
304 html = ClientHtml.addManifestContentHash(html)
305 html = ClientHtml.addFaviconContentHash(html)
306 html = ClientHtml.addLogoContentHash(html)
307 html = ClientHtml.addCustomCSS(html)
308 html = ClientHtml.addServerConfig(html, serverConfig)
309 html = await ClientHtml.addAsyncPluginCSS(html)
311 ClientHtml.htmlCache[path] = html
316 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
319 // Check param lang validity
320 if (paramLang && is18nLocale(paramLang)) {
323 // Save locale in cookies
324 res.cookie('clientLanguage', lang, {
325 secure: WEBSERVER.SCHEME === 'https',
327 maxAge: 1000 * 3600 * 24 * 90 // 3 months
330 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
331 lang = req.cookies.clientLanguage
333 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
336 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
339 private static getEmbedPath () {
340 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
343 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
344 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
347 private static addManifestContentHash (htmlStringPage: string) {
348 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
351 private static addFaviconContentHash (htmlStringPage: string) {
352 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
355 private static addLogoContentHash (htmlStringPage: string) {
356 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
359 private static addTitleTag (htmlStringPage: string, title?: string) {
360 let text = title || CONFIG.INSTANCE.NAME
361 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
363 const titleTag = `<title>${text}</title>`
365 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
368 private static addDescriptionTag (htmlStringPage: string, description?: string) {
369 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
370 const descriptionTag = `<meta name="description" content="${content}" />`
372 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
375 private static addCustomCSS (htmlStringPage: string) {
376 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
378 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
381 private static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
382 const serverConfigString = JSON.stringify(serverConfig)
383 const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = '${serverConfigString}'</script>`
385 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
388 private static async addAsyncPluginCSS (htmlStringPage: string) {
389 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
390 if (globalCSSContent.byteLength === 0) return htmlStringPage
392 const fileHash = sha256(globalCSSContent)
393 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
395 return htmlStringPage.replace('</head>', linkTag + '</head>')
398 private static generateOpenGraphMetaTags (tags: Tags) {
400 'og:type': tags.ogType,
401 'og:site_name': tags.siteName,
402 'og:title': tags.title,
403 'og:image': tags.image.url
406 if (tags.image.width && tags.image.height) {
407 metaTags['og:image:width'] = tags.image.width
408 metaTags['og:image:height'] = tags.image.height
411 metaTags['og:url'] = tags.url
412 metaTags['og:description'] = mdToPlainText(tags.description)
415 metaTags['og:video:url'] = tags.embed.url
416 metaTags['og:video:secure_url'] = tags.embed.url
417 metaTags['og:video:type'] = 'text/html'
418 metaTags['og:video:width'] = EMBED_SIZE.width
419 metaTags['og:video:height'] = EMBED_SIZE.height
425 private static generateStandardMetaTags (tags: Tags) {
428 description: mdToPlainText(tags.description),
429 image: tags.image.url
433 private static generateTwitterCardMetaTags (tags: Tags) {
435 'twitter:card': tags.twitterCard,
436 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
437 'twitter:title': tags.title,
438 'twitter:description': tags.description,
439 'twitter:image': tags.image.url
442 if (tags.image.width && tags.image.height) {
443 metaTags['twitter:image:width'] = tags.image.width
444 metaTags['twitter:image:height'] = tags.image.height
447 if (tags.twitterCard === 'player') {
448 metaTags['twitter:player'] = tags.embed.url
449 metaTags['twitter:player:width'] = EMBED_SIZE.width
450 metaTags['twitter:player:height'] = EMBED_SIZE.height
456 private static generateSchemaTags (tags: Tags) {
458 '@context': 'http://schema.org',
459 '@type': tags.schemaType,
461 'description': tags.description,
462 'image': tags.image.url,
467 schema['numberOfItems'] = tags.list.numberOfItems
468 schema['thumbnailUrl'] = tags.image.url
472 schema['embedUrl'] = tags.embed.url
473 schema['uploadDate'] = tags.embed.createdAt
475 if (tags.embed.duration) schema['duration'] = tags.embed.duration
476 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
478 schema['thumbnailUrl'] = tags.image.url
479 schema['contentUrl'] = tags.url
485 private static addTags (htmlStringPage: string, tagsValues: Tags) {
486 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
487 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
488 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
489 const schemaTags = this.generateSchemaTags(tagsValues)
491 const { url, title, embed, originUrl } = tagsValues
493 const oembedLinkTags: { type: string, href: string, title: string }[] = []
496 oembedLinkTags.push({
497 type: 'application/json+oembed',
498 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
506 Object.keys(openGraphMetaTags).forEach(tagName => {
507 const tagValue = openGraphMetaTags[tagName]
509 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
513 Object.keys(standardMetaTags).forEach(tagName => {
514 const tagValue = standardMetaTags[tagName]
516 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
520 Object.keys(twitterCardMetaTags).forEach(tagName => {
521 const tagValue = twitterCardMetaTags[tagName]
523 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
527 for (const oembedLinkTag of oembedLinkTags) {
528 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
533 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
536 // SEO, use origin URL
537 tagsString += `<link rel="canonical" href="${originUrl}" />`
539 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
543 function sendHTML (html: string, res: express.Response) {
544 res.set('Content-Type', 'text/html; charset=UTF-8')
546 return res.send(html)
549 async function serveIndexHTML (req: express.Request, res: express.Response) {
550 if (req.accepts(ACCEPT_HEADERS) === 'html' ||
551 !req.headers.accept) {
553 await generateHTMLPage(req, res, req.params.language)
556 logger.error('Cannot generate HTML page.', err)
557 return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
561 return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end()
564 // ---------------------------------------------------------------------------
572 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
573 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
575 return sendHTML(html, res)