1 import express from 'express'
2 import { readFile } from 'fs-extra'
3 import { join } from 'path'
4 import validator from 'validator'
5 import { toCompleteUUID } from '@server/helpers/custom-validators/misc'
6 import { escapeHTML } from '@shared/core-utils/renderer'
7 import { sha256 } from '@shared/extra-utils'
8 import { HTMLServerConfig } from '@shared/models'
9 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
10 import { HttpStatusCode } from '../../shared/models/http/http-error-codes'
11 import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
12 import { isTestInstance } from '../helpers/core-utils'
13 import { logger } from '../helpers/logger'
14 import { mdToPlainText } from '../helpers/markdown'
15 import { CONFIG } from '../initializers/config'
19 CUSTOM_HTML_TAG_COMMENTS,
22 PLUGIN_GLOBAL_CSS_PATH,
24 } from '../initializers/constants'
25 import { AccountModel } from '../models/account/account'
26 import { getActivityStreamDuration } from '../models/video/formatter/video-format-utils'
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 { MAccountActor, MChannelActor } from '../types/models'
31 import { ServerConfigManager } from './server-config-manager'
35 twitterCard: 'player' | 'summary' | 'summary_large_image'
42 escapedSiteName: string
44 escapedDescription: string
49 disallowIndexation?: boolean
67 private static htmlCache: { [path: string]: string } = {}
69 static invalidCache () {
70 logger.info('Cleaning HTML cache.')
72 ClientHtml.htmlCache = {}
75 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
76 const html = paramLang
77 ? await ClientHtml.getIndexHTML(req, res, paramLang)
78 : await ClientHtml.getIndexHTML(req, res)
80 let customHtml = ClientHtml.addTitleTag(html)
81 customHtml = ClientHtml.addDescriptionTag(customHtml)
86 static async getWatchHTMLPage (videoIdArg: string, req: express.Request, res: express.Response) {
87 const videoId = toCompleteUUID(videoIdArg)
89 // Let Angular application handle errors
90 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
91 res.status(HttpStatusCode.NOT_FOUND_404)
92 return ClientHtml.getIndexHTML(req, res)
95 const [ html, video ] = await Promise.all([
96 ClientHtml.getIndexHTML(req, res),
97 VideoModel.loadWithBlacklist(videoId)
100 // Let Angular application handle errors
101 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
102 res.status(HttpStatusCode.NOT_FOUND_404)
105 const description = mdToPlainText(video.description)
107 let customHtml = ClientHtml.addTitleTag(html, video.name)
108 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
110 const url = WEBSERVER.URL + video.getWatchStaticPath()
111 const originUrl = video.url
112 const title = video.name
113 const siteName = CONFIG.INSTANCE.NAME
116 url: WEBSERVER.URL + video.getPreviewStaticPath()
120 url: WEBSERVER.URL + video.getEmbedStaticPath(),
121 createdAt: video.createdAt.toISOString(),
122 duration: getActivityStreamDuration(video.duration),
126 const ogType = 'video'
127 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
128 const schemaType = 'VideoObject'
130 customHtml = ClientHtml.addTags(customHtml, {
133 escapedSiteName: escapeHTML(siteName),
134 escapedTitle: escapeHTML(title),
135 escapedDescription: escapeHTML(description),
146 static async getWatchPlaylistHTMLPage (videoPlaylistIdArg: string, req: express.Request, res: express.Response) {
147 const videoPlaylistId = toCompleteUUID(videoPlaylistIdArg)
149 // Let Angular application handle errors
150 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
151 res.status(HttpStatusCode.NOT_FOUND_404)
152 return ClientHtml.getIndexHTML(req, res)
155 const [ html, videoPlaylist ] = await Promise.all([
156 ClientHtml.getIndexHTML(req, res),
157 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
160 // Let Angular application handle errors
161 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
162 res.status(HttpStatusCode.NOT_FOUND_404)
166 const description = mdToPlainText(videoPlaylist.description)
168 let customHtml = ClientHtml.addTitleTag(html, videoPlaylist.name)
169 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
171 const url = WEBSERVER.URL + videoPlaylist.getWatchStaticPath()
172 const originUrl = videoPlaylist.url
173 const title = videoPlaylist.name
174 const siteName = CONFIG.INSTANCE.NAME
177 url: videoPlaylist.getThumbnailUrl()
181 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
182 createdAt: videoPlaylist.createdAt.toISOString()
186 numberOfItems: videoPlaylist.get('videosLength') as number
189 const ogType = 'video'
190 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
191 const schemaType = 'ItemList'
193 customHtml = ClientHtml.addTags(customHtml, {
196 escapedSiteName: escapeHTML(siteName),
197 escapedTitle: escapeHTML(title),
198 escapedDescription: escapeHTML(description),
210 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
211 const accountModelPromise = AccountModel.loadByNameWithHost(nameWithHost)
212 return this.getAccountOrChannelHTMLPage(() => accountModelPromise, req, res)
215 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
216 const videoChannelModelPromise = VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
217 return this.getAccountOrChannelHTMLPage(() => videoChannelModelPromise, req, res)
220 static async getActorHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
221 const [ account, channel ] = await Promise.all([
222 AccountModel.loadByNameWithHost(nameWithHost),
223 VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost)
226 return this.getAccountOrChannelHTMLPage(() => Promise.resolve(account || channel), req, res)
229 static async getEmbedHTML () {
230 const path = ClientHtml.getEmbedPath()
232 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
234 const buffer = await readFile(path)
235 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
237 let html = buffer.toString()
238 html = await ClientHtml.addAsyncPluginCSS(html)
239 html = ClientHtml.addCustomCSS(html)
240 html = ClientHtml.addTitleTag(html)
241 html = ClientHtml.addDescriptionTag(html)
242 html = ClientHtml.addServerConfig(html, serverConfig)
244 ClientHtml.htmlCache[path] = html
249 private static async getAccountOrChannelHTMLPage (
250 loader: () => Promise<MAccountActor | MChannelActor>,
251 req: express.Request,
252 res: express.Response
254 const [ html, entity ] = await Promise.all([
255 ClientHtml.getIndexHTML(req, res),
259 // Let Angular application handle errors
261 res.status(HttpStatusCode.NOT_FOUND_404)
262 return ClientHtml.getIndexHTML(req, res)
265 const description = mdToPlainText(entity.description)
267 let customHtml = ClientHtml.addTitleTag(html, entity.getDisplayName())
268 customHtml = ClientHtml.addDescriptionTag(customHtml, description)
270 const url = entity.getLocalUrl()
271 const originUrl = entity.Actor.url
272 const siteName = CONFIG.INSTANCE.NAME
273 const title = entity.getDisplayName()
276 url: entity.Actor.getAvatarUrl(),
277 width: ACTOR_IMAGES_SIZE.AVATARS.width,
278 height: ACTOR_IMAGES_SIZE.AVATARS.height
281 const ogType = 'website'
282 const twitterCard = 'summary'
283 const schemaType = 'ProfilePage'
285 customHtml = ClientHtml.addTags(customHtml, {
288 escapedTitle: escapeHTML(title),
289 escapedSiteName: escapeHTML(siteName),
290 escapedDescription: escapeHTML(description),
295 disallowIndexation: !entity.Actor.isOwned()
301 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
302 const path = ClientHtml.getIndexPath(req, res, paramLang)
303 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
305 const buffer = await readFile(path)
306 const serverConfig = await ServerConfigManager.Instance.getHTMLServerConfig()
308 let html = buffer.toString()
310 html = ClientHtml.addManifestContentHash(html)
311 html = ClientHtml.addFaviconContentHash(html)
312 html = ClientHtml.addLogoContentHash(html)
313 html = ClientHtml.addCustomCSS(html)
314 html = ClientHtml.addServerConfig(html, serverConfig)
315 html = await ClientHtml.addAsyncPluginCSS(html)
317 ClientHtml.htmlCache[path] = html
322 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
325 // Check param lang validity
326 if (paramLang && is18nLocale(paramLang)) {
329 // Save locale in cookies
330 res.cookie('clientLanguage', lang, {
331 secure: WEBSERVER.SCHEME === 'https',
333 maxAge: 1000 * 3600 * 24 * 90 // 3 months
336 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
337 lang = req.cookies.clientLanguage
339 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
343 'Serving %s HTML language', buildFileLocale(lang),
344 { cookie: req.cookies?.clientLanguage, paramLang, acceptLanguage: req.headers['accept-language'] }
347 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
350 private static getEmbedPath () {
351 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
354 private static addManifestContentHash (htmlStringPage: string) {
355 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
358 private static addFaviconContentHash (htmlStringPage: string) {
359 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
362 private static addLogoContentHash (htmlStringPage: string) {
363 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
366 private static addTitleTag (htmlStringPage: string, title?: string) {
367 let text = title || CONFIG.INSTANCE.NAME
368 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
370 const titleTag = `<title>${escapeHTML(text)}</title>`
372 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
375 private static addDescriptionTag (htmlStringPage: string, description?: string) {
376 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
377 const descriptionTag = `<meta name="description" content="${escapeHTML(content)}" />`
379 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
382 private static addCustomCSS (htmlStringPage: string) {
383 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
385 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
388 private static addServerConfig (htmlStringPage: string, serverConfig: HTMLServerConfig) {
389 // Stringify the JSON object, and then stringify the string object so we can inject it into the HTML
390 const serverConfigString = JSON.stringify(JSON.stringify(serverConfig))
391 const configScriptTag = `<script type="application/javascript">window.PeerTubeServerConfig = ${serverConfigString}</script>`
393 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.SERVER_CONFIG, configScriptTag)
396 private static async addAsyncPluginCSS (htmlStringPage: string) {
397 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
398 if (globalCSSContent.byteLength === 0) return htmlStringPage
400 const fileHash = sha256(globalCSSContent)
401 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
403 return htmlStringPage.replace('</head>', linkTag + '</head>')
406 private static generateOpenGraphMetaTags (tags: Tags) {
408 'og:type': tags.ogType,
409 'og:site_name': tags.escapedSiteName,
410 'og:title': tags.escapedTitle,
411 'og:image': tags.image.url
414 if (tags.image.width && tags.image.height) {
415 metaTags['og:image:width'] = tags.image.width
416 metaTags['og:image:height'] = tags.image.height
419 metaTags['og:url'] = tags.url
420 metaTags['og:description'] = tags.escapedDescription
423 metaTags['og:video:url'] = tags.embed.url
424 metaTags['og:video:secure_url'] = tags.embed.url
425 metaTags['og:video:type'] = 'text/html'
426 metaTags['og:video:width'] = EMBED_SIZE.width
427 metaTags['og:video:height'] = EMBED_SIZE.height
433 private static generateStandardMetaTags (tags: Tags) {
435 name: tags.escapedTitle,
436 description: tags.escapedDescription,
437 image: tags.image.url
441 private static generateTwitterCardMetaTags (tags: Tags) {
443 'twitter:card': tags.twitterCard,
444 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
445 'twitter:title': tags.escapedTitle,
446 'twitter:description': tags.escapedDescription,
447 'twitter:image': tags.image.url
450 if (tags.image.width && tags.image.height) {
451 metaTags['twitter:image:width'] = tags.image.width
452 metaTags['twitter:image:height'] = tags.image.height
455 if (tags.twitterCard === 'player') {
456 metaTags['twitter:player'] = tags.embed.url
457 metaTags['twitter:player:width'] = EMBED_SIZE.width
458 metaTags['twitter:player:height'] = EMBED_SIZE.height
464 private static generateSchemaTags (tags: Tags) {
466 '@context': 'http://schema.org',
467 '@type': tags.schemaType,
468 'name': tags.escapedTitle,
469 'description': tags.escapedDescription,
470 'image': tags.image.url,
475 schema['numberOfItems'] = tags.list.numberOfItems
476 schema['thumbnailUrl'] = tags.image.url
480 schema['embedUrl'] = tags.embed.url
481 schema['uploadDate'] = tags.embed.createdAt
483 if (tags.embed.duration) schema['duration'] = tags.embed.duration
484 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
486 schema['thumbnailUrl'] = tags.image.url
487 schema['contentUrl'] = tags.url
493 private static addTags (htmlStringPage: string, tagsValues: Tags) {
494 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
495 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
496 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
497 const schemaTags = this.generateSchemaTags(tagsValues)
499 const { url, escapedTitle, embed, originUrl, disallowIndexation } = tagsValues
501 const oembedLinkTags: { type: string, href: string, escapedTitle: string }[] = []
504 oembedLinkTags.push({
505 type: 'application/json+oembed',
506 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
514 Object.keys(openGraphMetaTags).forEach(tagName => {
515 const tagValue = openGraphMetaTags[tagName]
517 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
521 Object.keys(standardMetaTags).forEach(tagName => {
522 const tagValue = standardMetaTags[tagName]
524 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
528 Object.keys(twitterCardMetaTags).forEach(tagName => {
529 const tagValue = twitterCardMetaTags[tagName]
531 tagsStr += `<meta property="${tagName}" content="${tagValue}" />`
535 for (const oembedLinkTag of oembedLinkTags) {
536 tagsStr += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.escapedTitle}" />`
541 tagsStr += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
544 // SEO, use origin URL
545 tagsStr += `<link rel="canonical" href="${originUrl}" />`
547 if (disallowIndexation) {
548 tagsStr += `<meta name="robots" content="noindex" />`
551 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsStr)
555 function sendHTML (html: string, res: express.Response, localizedHTML: boolean = false) {
556 res.set('Content-Type', 'text/html; charset=UTF-8')
559 res.set('Vary', 'Accept-Language')
562 return res.send(html)
565 async function serveIndexHTML (req: express.Request, res: express.Response) {
566 if (req.accepts(ACCEPT_HEADERS) === 'html' || !req.headers.accept) {
568 await generateHTMLPage(req, res, req.params.language)
571 logger.error('Cannot generate HTML page.', err)
572 return res.status(HttpStatusCode.INTERNAL_SERVER_ERROR_500).end()
576 return res.status(HttpStatusCode.NOT_ACCEPTABLE_406).end()
579 // ---------------------------------------------------------------------------
587 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
588 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
590 return sendHTML(html, res, true)