1 import * as express from 'express'
2 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/models/i18n/i18n'
3 import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, PLUGIN_GLOBAL_CSS_PATH, WEBSERVER } from '../initializers/constants'
4 import { join } from 'path'
5 import { escapeHTML, sha256 } from '../helpers/core-utils'
6 import { VideoModel } from '../models/video/video'
7 import validator from 'validator'
8 import { VideoPrivacy } from '../../shared/models/videos'
9 import { readFile } from 'fs-extra'
10 import { getActivityStreamDuration } from '../models/video/video-format-utils'
11 import { AccountModel } from '../models/account/account'
12 import { VideoChannelModel } from '../models/video/video-channel'
13 import * as Bluebird from 'bluebird'
14 import { CONFIG } from '../initializers/config'
15 import { logger } from '../helpers/logger'
16 import { MAccountActor, MChannelActor, MVideo } from '../typings/models'
18 export class ClientHtml {
20 private static htmlCache: { [ path: string ]: string } = {}
22 static invalidCache () {
23 logger.info('Cleaning HTML cache.')
25 ClientHtml.htmlCache = {}
28 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
29 const html = await ClientHtml.getIndexHTML(req, res, paramLang)
31 let customHtml = ClientHtml.addTitleTag(html)
32 customHtml = ClientHtml.addDescriptionTag(customHtml)
37 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
38 // Let Angular application handle errors
39 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
41 return ClientHtml.getIndexHTML(req, res)
44 const [ html, video ] = await Promise.all([
45 ClientHtml.getIndexHTML(req, res),
46 VideoModel.loadWithBlacklist(videoId)
49 // Let Angular application handle errors
50 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
55 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
56 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
57 customHtml = ClientHtml.addVideoOpenGraphAndOEmbedTags(customHtml, video)
62 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
63 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
66 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
67 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
70 private static async getAccountOrChannelHTMLPage (
71 loader: () => Bluebird<MAccountActor | MChannelActor>,
75 const [ html, entity ] = await Promise.all([
76 ClientHtml.getIndexHTML(req, res),
80 // Let Angular application handle errors
83 return ClientHtml.getIndexHTML(req, res)
86 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
87 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
88 customHtml = ClientHtml.addAccountOrChannelMetaTags(customHtml, entity)
93 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
94 const path = ClientHtml.getIndexPath(req, res, paramLang)
95 if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
97 const buffer = await readFile(path)
99 let html = buffer.toString()
101 html = ClientHtml.addCustomCSS(html)
102 html = await ClientHtml.addAsyncPluginCSS(html)
104 ClientHtml.htmlCache[ path ] = html
109 private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
112 // Check param lang validity
113 if (paramLang && is18nLocale(paramLang)) {
116 // Save locale in cookies
117 res.cookie('clientLanguage', lang, {
118 secure: WEBSERVER.SCHEME === 'https',
120 maxAge: 1000 * 3600 * 24 * 90 // 3 months
123 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
124 lang = req.cookies.clientLanguage
126 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
129 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
132 private static addTitleTag (htmlStringPage: string, title?: string) {
133 let text = title || CONFIG.INSTANCE.NAME
134 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
136 const titleTag = `<title>${text}</title>`
138 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
141 private static addDescriptionTag (htmlStringPage: string, description?: string) {
142 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
143 const descriptionTag = `<meta name="description" content="${content}" />`
145 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
148 private static addCustomCSS (htmlStringPage: string) {
149 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
151 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
154 private static async addAsyncPluginCSS (htmlStringPage: string) {
155 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
156 if (globalCSSContent.byteLength === 0) return htmlStringPage
158 const fileHash = sha256(globalCSSContent)
159 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
161 return htmlStringPage.replace('</head>', linkTag + '</head>')
164 private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: MVideo) {
165 const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
166 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
168 const videoNameEscaped = escapeHTML(video.name)
169 const videoDescriptionEscaped = escapeHTML(video.description)
170 const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
172 const openGraphMetaTags = {
174 'og:title': videoNameEscaped,
175 'og:image': previewUrl,
177 'og:description': videoDescriptionEscaped,
179 'og:video:url': embedUrl,
180 'og:video:secure_url': embedUrl,
181 'og:video:type': 'text/html',
182 'og:video:width': EMBED_SIZE.width,
183 'og:video:height': EMBED_SIZE.height,
185 'name': videoNameEscaped,
186 'description': videoDescriptionEscaped,
189 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
190 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
191 'twitter:title': videoNameEscaped,
192 'twitter:description': videoDescriptionEscaped,
193 'twitter:image': previewUrl,
194 'twitter:player': embedUrl,
195 'twitter:player:width': EMBED_SIZE.width,
196 'twitter:player:height': EMBED_SIZE.height
199 const oembedLinkTags = [
201 type: 'application/json+oembed',
202 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
203 title: videoNameEscaped
208 '@context': 'http://schema.org',
209 '@type': 'VideoObject',
210 name: videoNameEscaped,
211 description: videoDescriptionEscaped,
212 thumbnailUrl: previewUrl,
213 uploadDate: video.createdAt.toISOString(),
214 duration: getActivityStreamDuration(video.duration),
215 contentUrl: videoUrl,
217 interactionCount: video.views
223 Object.keys(openGraphMetaTags).forEach(tagName => {
224 const tagValue = openGraphMetaTags[ tagName ]
226 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
230 for (const oembedLinkTag of oembedLinkTags) {
231 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
235 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
237 // SEO, use origin video url so Google does not index remote videos
238 tagsString += `<link rel="canonical" href="${video.url}" />`
240 return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
243 private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: MAccountActor | MChannelActor) {
244 // SEO, use origin account or channel URL
245 const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
247 return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
250 private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
251 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)