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 static async getEmbedHTML () {
175 const path = ClientHtml.getEmbedPath()
177 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
179 const buffer = await readFile(path)
181 let html = buffer.toString()
182 html = await ClientHtml.addAsyncPluginCSS(html)
184 ClientHtml.htmlCache[path] = html
189 private static async getAccountOrChannelHTMLPage (
190 loader: () => Bluebird<MAccountActor | MChannelActor>,
191 req: express.Request,
192 res: express.Response
194 const [ html, entity ] = await Promise.all([
195 ClientHtml.getIndexHTML(req, res),
199 // Let Angular application handle errors
202 return ClientHtml.getIndexHTML(req, res)
205 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
206 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
208 const url = entity.Actor.url
209 const title = escapeHTML(entity.getDisplayName())
210 const description = escapeHTML(entity.description)
213 url: entity.Actor.getAvatarUrl(),
214 width: AVATARS_SIZE.width,
215 height: AVATARS_SIZE.height
218 const ogType = 'website'
219 const twitterCard = 'summary'
220 const schemaType = 'ProfilePage'
222 customHtml = ClientHtml.addTags(customHtml, { url, title, description, image, ogType, twitterCard, schemaType })
227 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
228 const path = ClientHtml.getIndexPath(req, res, paramLang)
229 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
231 const buffer = await readFile(path)
233 let html = buffer.toString()
235 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
236 html = ClientHtml.addManifestContentHash(html)
237 html = ClientHtml.addFaviconContentHash(html)
238 html = ClientHtml.addLogoContentHash(html)
239 html = ClientHtml.addCustomCSS(html)
240 html = await ClientHtml.addAsyncPluginCSS(html)
242 ClientHtml.htmlCache[path] = html
247 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
250 // Check param lang validity
251 if (paramLang && is18nLocale(paramLang)) {
254 // Save locale in cookies
255 res.cookie('clientLanguage', lang, {
256 secure: WEBSERVER.SCHEME === 'https',
258 maxAge: 1000 * 3600 * 24 * 90 // 3 months
261 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
262 lang = req.cookies.clientLanguage
264 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
267 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
270 private static getEmbedPath () {
271 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
274 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
275 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
278 private static addManifestContentHash (htmlStringPage: string) {
279 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
282 private static addFaviconContentHash (htmlStringPage: string) {
283 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
286 private static addLogoContentHash (htmlStringPage: string) {
287 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
290 private static addTitleTag (htmlStringPage: string, title?: string) {
291 let text = title || CONFIG.INSTANCE.NAME
292 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
294 const titleTag = `<title>${text}</title>`
296 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
299 private static addDescriptionTag (htmlStringPage: string, description?: string) {
300 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
301 const descriptionTag = `<meta name="description" content="${content}" />`
303 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
306 private static addCustomCSS (htmlStringPage: string) {
307 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
309 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
312 private static async addAsyncPluginCSS (htmlStringPage: string) {
313 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
314 if (globalCSSContent.byteLength === 0) return htmlStringPage
316 const fileHash = sha256(globalCSSContent)
317 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
319 return htmlStringPage.replace('</head>', linkTag + '</head>')
322 private static generateOpenGraphMetaTags (tags: Tags) {
324 'og:type': tags.ogType,
325 'og:title': tags.title,
326 'og:image': tags.image.url
329 if (tags.image.width && tags.image.height) {
330 metaTags['og:image:width'] = tags.image.width
331 metaTags['og:image:height'] = tags.image.height
334 metaTags['og:url'] = tags.url
335 metaTags['og:description'] = tags.description
338 metaTags['og:video:url'] = tags.embed.url
339 metaTags['og:video:secure_url'] = tags.embed.url
340 metaTags['og:video:type'] = 'text/html'
341 metaTags['og:video:width'] = EMBED_SIZE.width
342 metaTags['og:video:height'] = EMBED_SIZE.height
348 private static generateStandardMetaTags (tags: Tags) {
351 description: tags.description,
352 image: tags.image.url
356 private static generateTwitterCardMetaTags (tags: Tags) {
358 'twitter:card': tags.twitterCard,
359 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
360 'twitter:title': tags.title,
361 'twitter:description': tags.description,
362 'twitter:image': tags.image.url
365 if (tags.image.width && tags.image.height) {
366 metaTags['twitter:image:width'] = tags.image.width
367 metaTags['twitter:image:height'] = tags.image.height
370 if (tags.twitterCard === 'player') {
371 metaTags['twitter:player'] = tags.embed.url
372 metaTags['twitter:player:width'] = EMBED_SIZE.width
373 metaTags['twitter:player:height'] = EMBED_SIZE.height
379 private static generateSchemaTags (tags: Tags) {
381 '@context': 'http://schema.org',
382 '@type': tags.schemaType,
384 'description': tags.description,
385 'image': tags.image.url,
390 schema['numberOfItems'] = tags.list.numberOfItems
391 schema['thumbnailUrl'] = tags.image.url
395 schema['embedUrl'] = tags.embed.url
396 schema['uploadDate'] = tags.embed.createdAt
398 if (tags.embed.duration) schema['duration'] = tags.embed.duration
399 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
401 schema['thumbnailUrl'] = tags.image.url
402 schema['contentUrl'] = tags.url
408 private static addTags (htmlStringPage: string, tagsValues: Tags) {
409 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
410 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
411 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
412 const schemaTags = this.generateSchemaTags(tagsValues)
414 const { url, title, embed } = tagsValues
416 const oembedLinkTags: { type: string, href: string, title: string }[] = []
419 oembedLinkTags.push({
420 type: 'application/json+oembed',
421 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
429 Object.keys(openGraphMetaTags).forEach(tagName => {
430 const tagValue = openGraphMetaTags[tagName]
432 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
436 Object.keys(standardMetaTags).forEach(tagName => {
437 const tagValue = standardMetaTags[tagName]
439 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
443 Object.keys(twitterCardMetaTags).forEach(tagName => {
444 const tagValue = twitterCardMetaTags[tagName]
446 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
450 for (const oembedLinkTag of oembedLinkTags) {
451 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
456 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
459 // SEO, use origin URL
460 tagsString += `<link rel="canonical" href="${url}" />`
462 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)