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 * as 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)) {
40 return ClientHtml.getIndexHTML(req, res)
43 const [ html, video ] = await Promise.all([
44 ClientHtml.getIndexHTML(req, res),
45 VideoModel.loadWithBlacklist(videoId)
48 // Let Angular application handle errors
49 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
50 return ClientHtml.getIndexHTML(req, res)
53 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
54 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
55 customHtml = ClientHtml.addVideoOpenGraphAndOEmbedTags(customHtml, video)
60 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
61 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
64 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
65 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
68 private static async getAccountOrChannelHTMLPage (
69 loader: () => Bluebird<MAccountActor | MChannelActor>,
73 const [ html, entity ] = await Promise.all([
74 ClientHtml.getIndexHTML(req, res),
78 // Let Angular application handle errors
80 return ClientHtml.getIndexHTML(req, res)
83 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
84 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
85 customHtml = ClientHtml.addAccountOrChannelMetaTags(customHtml, entity)
90 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
91 const path = ClientHtml.getIndexPath(req, res, paramLang)
92 if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
94 const buffer = await readFile(path)
96 let html = buffer.toString()
98 html = ClientHtml.addCustomCSS(html)
99 html = await ClientHtml.addAsyncPluginCSS(html)
101 ClientHtml.htmlCache[ path ] = html
106 private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
109 // Check param lang validity
110 if (paramLang && is18nLocale(paramLang)) {
113 // Save locale in cookies
114 res.cookie('clientLanguage', lang, {
115 secure: WEBSERVER.SCHEME === 'https',
117 maxAge: 1000 * 3600 * 24 * 90 // 3 months
120 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
121 lang = req.cookies.clientLanguage
123 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
126 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
129 private static addTitleTag (htmlStringPage: string, title?: string) {
130 let text = title || CONFIG.INSTANCE.NAME
131 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
133 const titleTag = `<title>${text}</title>`
135 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
138 private static addDescriptionTag (htmlStringPage: string, description?: string) {
139 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
140 const descriptionTag = `<meta name="description" content="${content}" />`
142 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
145 private static addCustomCSS (htmlStringPage: string) {
146 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
148 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
151 private static async addAsyncPluginCSS (htmlStringPage: string) {
152 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
153 if (globalCSSContent.byteLength === 0) return htmlStringPage
155 const fileHash = sha256(globalCSSContent)
156 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
158 return htmlStringPage.replace('</head>', linkTag + '</head>')
161 private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: MVideo) {
162 const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
163 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
165 const videoNameEscaped = escapeHTML(video.name)
166 const videoDescriptionEscaped = escapeHTML(video.description)
167 const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
169 const openGraphMetaTags = {
171 'og:title': videoNameEscaped,
172 'og:image': previewUrl,
174 'og:description': videoDescriptionEscaped,
176 'og:video:url': embedUrl,
177 'og:video:secure_url': embedUrl,
178 'og:video:type': 'text/html',
179 'og:video:width': EMBED_SIZE.width,
180 'og:video:height': EMBED_SIZE.height,
182 'name': videoNameEscaped,
183 'description': videoDescriptionEscaped,
186 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
187 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
188 'twitter:title': videoNameEscaped,
189 'twitter:description': videoDescriptionEscaped,
190 'twitter:image': previewUrl,
191 'twitter:player': embedUrl,
192 'twitter:player:width': EMBED_SIZE.width,
193 'twitter:player:height': EMBED_SIZE.height
196 const oembedLinkTags = [
198 type: 'application/json+oembed',
199 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
200 title: videoNameEscaped
205 '@context': 'http://schema.org',
206 '@type': 'VideoObject',
207 name: videoNameEscaped,
208 description: videoDescriptionEscaped,
209 thumbnailUrl: previewUrl,
210 uploadDate: video.createdAt.toISOString(),
211 duration: getActivityStreamDuration(video.duration),
212 contentUrl: videoUrl,
214 interactionCount: video.views
220 Object.keys(openGraphMetaTags).forEach(tagName => {
221 const tagValue = openGraphMetaTags[ tagName ]
223 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
227 for (const oembedLinkTag of oembedLinkTags) {
228 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
232 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
234 // SEO, use origin video url so Google does not index remote videos
235 tagsString += `<link rel="canonical" href="${video.url}" />`
237 return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
240 private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: MAccountActor | MChannelActor) {
241 // SEO, use origin account or channel URL
242 const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
244 return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
247 private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
248 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)