1 import express from 'express'
2 import { pathExists, readFile } from 'fs-extra'
3 import { join } from 'path'
4 import validator from 'validator'
5 import { isTestOrDevInstance } from '@server/helpers/core-utils'
6 import { toCompleteUUID } from '@server/helpers/custom-validators/misc'
7 import { mdToOneLinePlainText } from '@server/helpers/markdown'
8 import { ActorImageModel } from '@server/models/actor/actor-image'
9 import { root } from '@shared/core-utils'
10 import { escapeHTML } from '@shared/core-utils/renderer'
11 import { sha256 } from '@shared/extra-utils'
12 import { HTMLServerConfig } from '@shared/models'
13 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
14 import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
15 import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
16 import { logger } from '../helpers/logger'
17 import { CONFIG } from '../initializers/config'
20 CUSTOM_HTML_TAG_COMMENTS,
23 PLUGIN_GLOBAL_CSS_PATH,
25 } from '../initializers/constants'
26 import { AccountModel } from '../models/account/account'
27 import { VideoModel } from '../models/video/video'
28 import { VideoChannelModel } from '../models/video/video-channel'
29 import { VideoPlaylistModel } from '../models/video/video-playlist'
30 import { MAccountHost, MChannelHost, MVideo, MVideoPlaylist } from '../types/models'
31 import { getActivityStreamDuration } from './activitypub/activity'
32 import { getBiggestActorImage } from './actor-image'
33 import { Hooks } from './plugins/hooks'
34 import { ServerConfigManager } from './server-config-manager'
38 twitterCard: 'player' | 'summary' | 'summary_large_image'
45 escapedSiteName: string
47 escapedDescription: string
52 disallowIndexation?: boolean
70 playlist?: MVideoPlaylist
75 private static htmlCache: { [path: string]: string } = {}
77 static invalidCache () {
78 logger.info('Cleaning HTML cache.')
80 ClientHtml.htmlCache = {}
83 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
84 const html = paramLang
85 ? await ClientHtml.getIndexHTML(req, res, paramLang)
86 : await ClientHtml.getIndexHTML(req, res)
88 let customHtml = ClientHtml.addTitleTag(html)
89 customHtml = ClientHtml.addDescriptionTag(customHtml)
94 static async getWatchHTMLPage (videoIdArg: string, req: express.Request, res: express.Response) {
95 const videoId = toCompleteUUID(videoIdArg)
97 // Let Angular application handle errors
98 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
99 res.status(HttpStatusCode.NOT_FOUND_404)
100 return ClientHtml.getIndexHTML(req, res)
103 const [ html, video ] = await Promise.all([
104 ClientHtml.getIndexHTML(req, res),
105 VideoModel.loadWithBlacklist(videoId)
108 // Let Angular application handle errors
109 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
110 res.status(HttpStatusCode.NOT_FOUND_404)
113 const description = mdToOneLinePlainText(video.description)
115 let customHtml = ClientHtml.addTitleTag(html, video.name)
116 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
118 const url = WEBSERVER.URL + video.getWatchStaticPath()
119 const originUrl = video.url
120 const title = video.name
121 const siteName = CONFIG.INSTANCE.NAME
124 url: WEBSERVER.URL + video.getPreviewStaticPath()
128 url: WEBSERVER.URL + video.getEmbedStaticPath(),
129 createdAt: video.createdAt.toISOString(),
130 duration: getActivityStreamDuration(video.duration),
134 const ogType = 'video'
135 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
136 const schemaType = 'VideoObject'
138 customHtml = await ClientHtml.addTags(customHtml, {
141 escapedSiteName: escapeHTML(siteName),
142 escapedTitle: escapeHTML(title),
143 escapedDescription: escapeHTML(description),
144 disallowIndexation: video.privacy !== VideoPrivacy.PUBLIC,
155 static async getWatchPlaylistHTMLPage (videoPlaylistIdArg: string, req: express.Request, res: express.Response) {
156 const videoPlaylistId = toCompleteUUID(videoPlaylistIdArg)
158 // Let Angular application handle errors
159 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
160 res.status(HttpStatusCode.NOT_FOUND_404)
161 return ClientHtml.getIndexHTML(req, res)
164 const [ html, videoPlaylist ] = await Promise.all([
165 ClientHtml.getIndexHTML(req, res),
166 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
169 // Let Angular application handle errors
170 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
171 res.status(HttpStatusCode.NOT_FOUND_404)
175 const description = mdToOneLinePlainText(videoPlaylist.description)
177 let customHtml = ClientHtml.addTitleTag(html, videoPlaylist.name)
178 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
180 const url = WEBSERVER.URL + videoPlaylist.getWatchStaticPath()
181 const originUrl = videoPlaylist.url
182 const title = videoPlaylist.name
183 const siteName = CONFIG.INSTANCE.NAME
186 url: videoPlaylist.getThumbnailUrl()
190 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
191 createdAt: videoPlaylist.createdAt.toISOString()
195 numberOfItems: videoPlaylist.get('videosLength') as number
198 const ogType = 'video'
199 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
200 const schemaType = 'ItemList'
202 customHtml = await ClientHtml.addTags(customHtml, {
205 escapedSiteName: escapeHTML(siteName),
206 escapedTitle: escapeHTML(title),
207 escapedDescription: escapeHTML(description),
208 disallowIndexation: videoPlaylist.privacy !== VideoPlaylistPrivacy.PUBLIC,
215 }, { playlist: videoPlaylist })
220 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
221 const accountModelPromise = AccountModel.loadByNameWithHost(nameWithHost)
222 return this.getAccountOrChannelHTMLPage(() => accountModelPromise, req, res)
225 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
226 const videoChannelModelPromise = VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
227 return this.getAccountOrChannelHTMLPage(() => videoChannelModelPromise, req, res)
230 static async getActorHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
231 const [ account, channel ] = await Promise.all([
232 AccountModel.loadByNameWithHost(nameWithHost),
233 VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
236 return this.getAccountOrChannelHTMLPage(() => Promise.resolve(account || channel), req, res)
239 static async getEmbedHTML () {
240 const path = ClientHtml.getEmbedPath()
242 // Disable HTML cache in dev mode because webpack can regenerate JS files
243 if (!isTestOrDevInstance() && ClientHtml.htmlCache[path]) {
244 return ClientHtml.htmlCache[path]
247 const buffer = await readFile(path)
248 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
250 let html = buffer.toString()
251 html = await ClientHtml.addAsyncPluginCSS(html)
252 html = ClientHtml.addCustomCSS(html)
253 html = ClientHtml.addTitleTag(html)
254 html = ClientHtml.addDescriptionTag(html)
255 html = ClientHtml.addServerConfig(html, serverConfig)
257 ClientHtml.htmlCache[path] = html
262 private static async getAccountOrChannelHTMLPage (
263 loader: () => Promise<MAccountHost | MChannelHost>,
264 req: express.Request,
265 res: express.Response
267 const [ html, entity ] = await Promise.all([
268 ClientHtml.getIndexHTML(req, res),
272 // Let Angular application handle errors
274 res.status(HttpStatusCode.NOT_FOUND_404)
275 return ClientHtml.getIndexHTML(req, res)
278 const description = mdToOneLinePlainText(entity.description)
280 let customHtml = ClientHtml.addTitleTag(html, entity.getDisplayName())
281 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
283 const url = entity.getClientUrl()
284 const originUrl = entity.Actor.url
285 const siteName = CONFIG.INSTANCE.NAME
286 const title = entity.getDisplayName()
288 const avatar = getBiggestActorImage(entity.Actor.Avatars)
290 url: ActorImageModel.getImageUrl(avatar),
291 width: avatar?.width,
292 height: avatar?.height
295 const ogType = 'website'
296 const twitterCard = 'summary'
297 const schemaType = 'ProfilePage'
299 customHtml = await ClientHtml.addTags(customHtml, {
302 escapedTitle: escapeHTML(title),
303 escapedSiteName: escapeHTML(siteName),
304 escapedDescription: escapeHTML(description),
309 disallowIndexation: !entity.Actor.isOwned()
315 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
316 const path = ClientHtml.getIndexPath(req, res, paramLang)
317 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
319 const buffer = await readFile(path)
320 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
322 let html = buffer.toString()
324 html = ClientHtml.addManifestContentHash(html)
325 html = ClientHtml.addFaviconContentHash(html)
326 html = ClientHtml.addLogoContentHash(html)
327 html = ClientHtml.addCustomCSS(html)
328 html = ClientHtml.addServerConfig(html, serverConfig)
329 html = await ClientHtml.addAsyncPluginCSS(html)
331 ClientHtml.htmlCache[path] = html
336 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
339 // Check param lang validity
340 if (paramLang && is18nLocale(paramLang)) {
343 // Save locale in cookies
344 res.cookie('clientLanguage', lang, {
345 secure: WEBSERVER.SCHEME === 'https',
347 maxAge: 1000 * 3600 * 24 * 90 // 3 months
350 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
351 lang = req.cookies.clientLanguage
353 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
357 'Serving %s HTML language', buildFileLocale(lang),
358 { cookie: req.cookies?.clientLanguage, paramLang, acceptLanguage: req.headers['accept-language'] }
361 return join(root(), 'client', 'dist', buildFileLocale(lang), 'index.html')
364 private static getEmbedPath () {
365 return join(root(), 'client', 'dist', 'standalone', 'videos', 'embed.html')
368 private static addManifestContentHash (htmlStringPage: string) {
369 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
372 private static addFaviconContentHash (htmlStringPage: string) {
373 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
376 private static addLogoContentHash (htmlStringPage: string) {
377 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
380 private static addTitleTag (htmlStringPage: string, title?: string) {
381 let text = title || CONFIG.INSTANCE.NAME
382 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
384 const titleTag = `<title>${escapeHTML(text)}</title>`
386 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
389 private static addDescriptionTag (htmlStringPage: string, description?: string) {
390 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
391 const descriptionTag = `<meta name="description" content="${escapeHTML(content)}" />`
393 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
396 private static addCustomCSS (htmlStringPage: string) {
397 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
399 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
402 private static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
403 // Stringify the JSON object, and then stringify the string object so we can inject it into the HTML
404 const serverConfigString = JSON.stringify(JSON.stringify(serverConfig))
405 const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = ${serverConfigString}</script>`
407 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
410 private static async addAsyncPluginCSS (htmlStringPage: string) {
411 if (!pathExists(PLUGIN_GLOBAL_CSS_PATH)) {
412 logger.info('Plugin Global CSS file is not available (generation may still be in progress), ignoring it.')
413 return htmlStringPage
416 let globalCSSContent: Buffer
419 globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
421 logger.error('Error retrieving the Plugin Global CSS file, ignoring it.', { err })
422 return htmlStringPage
425 if (globalCSSContent.byteLength === 0) return htmlStringPage
427 const fileHash = sha256(globalCSSContent)
428 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
430 return htmlStringPage.replace('</head>', linkTag + '</head>')
433 private static generateOpenGraphMetaTags (tags: Tags) {
435 'og:type': tags.ogType,
436 'og:site_name': tags.escapedSiteName,
437 'og:title': tags.escapedTitle,
438 'og:image': tags.image.url
441 if (tags.image.width && tags.image.height) {
442 metaTags['og:image:width'] = tags.image.width
443 metaTags['og:image:height'] = tags.image.height
446 metaTags['og:url'] = tags.url
447 metaTags['og:description'] = tags.escapedDescription
450 metaTags['og:video:url'] = tags.embed.url
451 metaTags['og:video:secure_url'] = tags.embed.url
452 metaTags['og:video:type'] = 'text/html'
453 metaTags['og:video:width'] = EMBED_SIZE.width
454 metaTags['og:video:height'] = EMBED_SIZE.height
460 private static generateStandardMetaTags (tags: Tags) {
462 name: tags.escapedTitle,
463 description: tags.escapedDescription,
464 image: tags.image.url
468 private static generateTwitterCardMetaTags (tags: Tags) {
470 'twitter:card': tags.twitterCard,
471 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
472 'twitter:title': tags.escapedTitle,
473 'twitter:description': tags.escapedDescription,
474 'twitter:image': tags.image.url
477 if (tags.image.width && tags.image.height) {
478 metaTags['twitter:image:width'] = tags.image.width
479 metaTags['twitter:image:height'] = tags.image.height
482 if (tags.twitterCard === 'player') {
483 metaTags['twitter:player'] = tags.embed.url
484 metaTags['twitter:player:width'] = EMBED_SIZE.width
485 metaTags['twitter:player:height'] = EMBED_SIZE.height
491 private static async generateSchemaTags (tags: Tags, context: HookContext) {
493 '@context': 'http://schema.org',
494 '@type': tags.schemaType,
495 'name': tags.escapedTitle,
496 'description': tags.escapedDescription,
497 'image': tags.image.url,
502 schema['numberOfItems'] = tags.list.numberOfItems
503 schema['thumbnailUrl'] = tags.image.url
507 schema['embedUrl'] = tags.embed.url
508 schema['uploadDate'] = tags.embed.createdAt
510 if (tags.embed.duration) schema['duration'] = tags.embed.duration
512 schema['thumbnailUrl'] = tags.image.url
513 schema['contentUrl'] = tags.url
516 return Hooks.wrapObject(schema, 'filter:html.client.json-ld.result', context)
519 private static async addTags (htmlStringPage: string, tagsValues: Tags, context: HookContext) {
520 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
521 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
522 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
523 const schemaTags = await this.generateSchemaTags(tagsValues, context)
525 const { url, escapedTitle, embed, originUrl, disallowIndexation } = tagsValues
527 const oembedLinkTags: { type: string, href: string, escapedTitle: string }[] = []
530 oembedLinkTags.push({
531 type: 'application/json+oembed',
532 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
540 Object.keys(openGraphMetaTags).forEach(tagName => {
541 const tagValue = openGraphMetaTags[tagName]
543 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
547 Object.keys(standardMetaTags).forEach(tagName => {
548 const tagValue = standardMetaTags[tagName]
550 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
554 Object.keys(twitterCardMetaTags).forEach(tagName => {
555 const tagValue = twitterCardMetaTags[tagName]
557 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
561 for (const oembedLinkTag of oembedLinkTags) {
562 tagsStr += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.escapedTitle}" />`
567 tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
570 // SEO, use origin URL
571 tagsStr += `<link rel="canonical" href="${originUrl}" />`
573 if (disallowIndexation) {
574 tagsStr += `<meta name="robots" content="noindex" />`
577 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr)
581 function sendHTML (html: string, res: express.Response, localizedHTML: boolean = false) {
582 res.set('Content-Type', 'text/html; charset=UTF-8')
585 res.set('Vary', 'Accept-Language')
588 return res.send(html)
591 async function serveIndexHTML (req: express.Request, res: express.Response) {
592 if (req.accepts(ACCEPT_HEADERS) === 'html' || !req.headers.accept) {
594 await generateHTMLPage(req, res, req.params.language)
597 logger.error('Cannot generate HTML page.', { err })
598 return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
602 return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end()
605 // ---------------------------------------------------------------------------
613 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
614 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
616 return sendHTML(html, res, true)