1 import * as express from 'express'
2 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
5 CUSTOM_HTML_TAG_COMMENTS,
7 PLUGIN_GLOBAL_CSS_PATH,
10 } from '../initializers/constants'
11 import { join } from 'path'
12 import { escapeHTML, sha256 } from '../helpers/core-utils'
13 import { VideoModel } from '../models/video/video'
14 import { VideoPlaylistModel } from '../models/video/video-playlist'
15 import validator from 'validator'
16 import { VideoPrivacy, VideoPlaylistPrivacy } from '../../shared/models/videos'
17 import { readFile } from 'fs-extra'
18 import { getActivityStreamDuration } from '../models/video/video-format-utils'
19 import { AccountModel } from '../models/account/account'
20 import { VideoChannelModel } from '../models/video/video-channel'
21 import * as Bluebird from 'bluebird'
22 import { CONFIG } from '../initializers/config'
23 import { logger } from '../helpers/logger'
24 import { MAccountActor, MChannelActor } from '../types/models'
28 twitterCard: 'player' | 'summary' | 'summary_large_image'
53 export class ClientHtml {
55 private static htmlCache: { [path: string]: string } = {}
57 static invalidCache () {
58 logger.info('Cleaning HTML cache.')
60 ClientHtml.htmlCache = {}
63 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
64 const html = paramLang
65 ? await ClientHtml.getIndexHTML(req, res, paramLang)
66 : await ClientHtml.getIndexHTML(req, res)
68 let customHtml = ClientHtml.addTitleTag(html)
69 customHtml = ClientHtml.addDescriptionTag(customHtml)
74 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
75 // Let Angular application handle errors
76 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
78 return ClientHtml.getIndexHTML(req, res)
81 const [ html, video ] = await Promise.all([
82 ClientHtml.getIndexHTML(req, res),
83 VideoModel.loadWithBlacklist(videoId)
86 // Let Angular application handle errors
87 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
92 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
93 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
95 const url = WEBSERVER.URL + video.getWatchStaticPath()
96 const title = escapeHTML(video.name)
97 const description = escapeHTML(video.description)
100 url: WEBSERVER.URL + video.getPreviewStaticPath()
104 url: WEBSERVER.URL + video.getEmbedStaticPath(),
105 createdAt: video.createdAt.toISOString(),
106 duration: getActivityStreamDuration(video.duration),
110 const ogType = 'video'
111 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
112 const schemaType = 'VideoObject'
114 customHtml = ClientHtml.addTags(customHtml, { url, title, description, image, embed, ogType, twitterCard, schemaType })
119 static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
120 // Let Angular application handle errors
121 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
123 return ClientHtml.getIndexHTML(req, res)
126 const [ html, videoPlaylist ] = await Promise.all([
127 ClientHtml.getIndexHTML(req, res),
128 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
131 // Let Angular application handle errors
132 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
137 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
138 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(videoPlaylist.description))
140 const url = videoPlaylist.getWatchUrl()
141 const title = escapeHTML(videoPlaylist.name)
142 const description = escapeHTML(videoPlaylist.description)
145 url: videoPlaylist.getThumbnailUrl()
149 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
150 createdAt: videoPlaylist.createdAt.toISOString()
154 numberOfItems: videoPlaylist.get('videosLength') as number
157 const ogType = 'video'
158 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
159 const schemaType = 'ItemList'
161 customHtml = ClientHtml.addTags(customHtml, { url, embed, title, description, image, list, ogType, twitterCard, schemaType })
166 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
167 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
170 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
171 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
174 private static async getAccountOrChannelHTMLPage (
175 loader: () => Bluebird<MAccountActor | MChannelActor>,
176 req: express.Request,
177 res: express.Response
179 const [ html, entity ] = await Promise.all([
180 ClientHtml.getIndexHTML(req, res),
184 // Let Angular application handle errors
187 return ClientHtml.getIndexHTML(req, res)
190 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
191 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
193 const url = entity.Actor.url
194 const title = escapeHTML(entity.getDisplayName())
195 const description = escapeHTML(entity.description)
198 url: entity.Actor.getAvatarUrl(),
199 width: AVATARS_SIZE.width,
200 height: AVATARS_SIZE.height
203 const ogType = 'website'
204 const twitterCard = 'summary'
205 const schemaType = 'ProfilePage'
207 customHtml = ClientHtml.addTags(customHtml, { url, title, description, image, ogType, twitterCard, schemaType })
212 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
213 const path = ClientHtml.getIndexPath(req, res, paramLang)
214 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
216 const buffer = await readFile(path)
218 let html = buffer.toString()
220 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
221 html = ClientHtml.addManifestContentHash(html)
222 html = ClientHtml.addFaviconContentHash(html)
223 html = ClientHtml.addLogoContentHash(html)
224 html = ClientHtml.addCustomCSS(html)
225 html = await ClientHtml.addAsyncPluginCSS(html)
227 ClientHtml.htmlCache[path] = html
232 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
235 // Check param lang validity
236 if (paramLang && is18nLocale(paramLang)) {
239 // Save locale in cookies
240 res.cookie('clientLanguage', lang, {
241 secure: WEBSERVER.SCHEME === 'https',
243 maxAge: 1000 * 3600 * 24 * 90 // 3 months
246 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
247 lang = req.cookies.clientLanguage
249 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
252 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
255 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
256 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
259 private static addManifestContentHash (htmlStringPage: string) {
260 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
263 private static addFaviconContentHash (htmlStringPage: string) {
264 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
267 private static addLogoContentHash (htmlStringPage: string) {
268 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
271 private static addTitleTag (htmlStringPage: string, title?: string) {
272 let text = title || CONFIG.INSTANCE.NAME
273 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
275 const titleTag = `<title>${text}</title>`
277 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
280 private static addDescriptionTag (htmlStringPage: string, description?: string) {
281 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
282 const descriptionTag = `<meta name="description" content="${content}" />`
284 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
287 private static addCustomCSS (htmlStringPage: string) {
288 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
290 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
293 private static async addAsyncPluginCSS (htmlStringPage: string) {
294 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
295 if (globalCSSContent.byteLength === 0) return htmlStringPage
297 const fileHash = sha256(globalCSSContent)
298 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
300 return htmlStringPage.replace('</head>', linkTag + '</head>')
303 private static generateOpenGraphMetaTags (tags: Tags) {
305 'og:type': tags.ogType,
306 'og:title': tags.title,
307 'og:image': tags.image.url
310 if (tags.image.width && tags.image.height) {
311 metaTags['og:image:width'] = tags.image.width
312 metaTags['og:image:height'] = tags.image.height
315 metaTags['og:url'] = tags.url
316 metaTags['og:description'] = tags.description
319 metaTags['og:video:url'] = tags.embed.url
320 metaTags['og:video:secure_url'] = tags.embed.url
321 metaTags['og:video:type'] = 'text/html'
322 metaTags['og:video:width'] = EMBED_SIZE.width
323 metaTags['og:video:height'] = EMBED_SIZE.height
329 private static generateStandardMetaTags (tags: Tags) {
332 description: tags.description,
333 image: tags.image.url
337 private static generateTwitterCardMetaTags (tags: Tags) {
339 'twitter:card': tags.twitterCard,
340 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
341 'twitter:title': tags.title,
342 'twitter:description': tags.description,
343 'twitter:image': tags.image.url
346 if (tags.image.width && tags.image.height) {
347 metaTags['twitter:image:width'] = tags.image.width
348 metaTags['twitter:image:height'] = tags.image.height
351 if (tags.twitterCard === 'player') {
352 metaTags['twitter:player'] = tags.embed.url
353 metaTags['twitter:player:width'] = EMBED_SIZE.width
354 metaTags['twitter:player:height'] = EMBED_SIZE.height
360 private static generateSchemaTags (tags: Tags) {
362 '@context': 'http://schema.org',
363 '@type': tags.schemaType,
365 'description': tags.description,
366 'image': tags.image.url,
371 schema['numberOfItems'] = tags.list.numberOfItems
372 schema['thumbnailUrl'] = tags.image.url
376 schema['embedUrl'] = tags.embed.url
377 schema['uploadDate'] = tags.embed.createdAt
379 if (tags.embed.duration) schema['duration'] = tags.embed.duration
380 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
382 schema['thumbnailUrl'] = tags.image.url
383 schema['contentUrl'] = tags.url
389 private static addTags (htmlStringPage: string, tagsValues: Tags) {
390 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
391 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
392 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
393 const schemaTags = this.generateSchemaTags(tagsValues)
395 const { url, title, embed } = tagsValues
397 const oembedLinkTags: { type: string, href: string, title: string }[] = []
400 oembedLinkTags.push({
401 type: 'application/json+oembed',
402 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
410 Object.keys(openGraphMetaTags).forEach(tagName => {
411 const tagValue = openGraphMetaTags[tagName]
413 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
417 Object.keys(standardMetaTags).forEach(tagName => {
418 const tagValue = standardMetaTags[tagName]
420 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
424 Object.keys(twitterCardMetaTags).forEach(tagName => {
425 const tagValue = twitterCardMetaTags[tagName]
427 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
431 for (const oembedLinkTag of oembedLinkTags) {
432 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
437 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
440 // SEO, use origin URL
441 tagsString += `<link rel="canonical" href="${url}" />`
443 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)