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()
179 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
181 const buffer = await readFile(path)
183 let html = buffer.toString()
184 html = await ClientHtml.addAsyncPluginCSS(html)
186 ClientHtml.htmlCache[path] = html
191 private static async getAccountOrChannelHTMLPage (
192 loader: () => Bluebird<MAccountActor | MChannelActor>,
193 req: express.Request,
194 res: express.Response
196 const [ html, entity ] = await Promise.all([
197 ClientHtml.getIndexHTML(req, res),
201 // Let Angular application handle errors
204 return ClientHtml.getIndexHTML(req, res)
207 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
208 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
210 const url = entity.Actor.url
211 const title = escapeHTML(entity.getDisplayName())
212 const description = escapeHTML(entity.description)
215 url: entity.Actor.getAvatarUrl(),
216 width: AVATARS_SIZE.width,
217 height: AVATARS_SIZE.height
220 const ogType = 'website'
221 const twitterCard = 'summary'
222 const schemaType = 'ProfilePage'
224 customHtml = ClientHtml.addTags(customHtml, { url, title, description, image, ogType, twitterCard, schemaType })
229 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
230 const path = ClientHtml.getIndexPath(req, res, paramLang)
231 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
233 const buffer = await readFile(path)
235 let html = buffer.toString()
237 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
238 html = ClientHtml.addManifestContentHash(html)
239 html = ClientHtml.addFaviconContentHash(html)
240 html = ClientHtml.addLogoContentHash(html)
241 html = ClientHtml.addCustomCSS(html)
242 html = await ClientHtml.addAsyncPluginCSS(html)
244 ClientHtml.htmlCache[path] = html
249 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
252 // Check param lang validity
253 if (paramLang && is18nLocale(paramLang)) {
256 // Save locale in cookies
257 res.cookie('clientLanguage', lang, {
258 secure: WEBSERVER.SCHEME === 'https',
260 maxAge: 1000 * 3600 * 24 * 90 // 3 months
263 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
264 lang = req.cookies.clientLanguage
266 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
269 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
272 private static getEmbedPath () {
273 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
276 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
277 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
280 private static addManifestContentHash (htmlStringPage: string) {
281 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
284 private static addFaviconContentHash (htmlStringPage: string) {
285 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
288 private static addLogoContentHash (htmlStringPage: string) {
289 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
292 private static addTitleTag (htmlStringPage: string, title?: string) {
293 let text = title || CONFIG.INSTANCE.NAME
294 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
296 const titleTag = `<title>${text}</title>`
298 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
301 private static addDescriptionTag (htmlStringPage: string, description?: string) {
302 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
303 const descriptionTag = `<meta name="description" content="${content}" />`
305 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
308 private static addCustomCSS (htmlStringPage: string) {
309 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
311 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
314 private static async addAsyncPluginCSS (htmlStringPage: string) {
315 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
316 if (globalCSSContent.byteLength === 0) return htmlStringPage
318 const fileHash = sha256(globalCSSContent)
319 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
321 return htmlStringPage.replace('</head>', linkTag + '</head>')
324 private static generateOpenGraphMetaTags (tags: Tags) {
326 'og:type': tags.ogType,
327 'og:title': tags.title,
328 'og:image': tags.image.url
331 if (tags.image.width && tags.image.height) {
332 metaTags['og:image:width'] = tags.image.width
333 metaTags['og:image:height'] = tags.image.height
336 metaTags['og:url'] = tags.url
337 metaTags['og:description'] = tags.description
340 metaTags['og:video:url'] = tags.embed.url
341 metaTags['og:video:secure_url'] = tags.embed.url
342 metaTags['og:video:type'] = 'text/html'
343 metaTags['og:video:width'] = EMBED_SIZE.width
344 metaTags['og:video:height'] = EMBED_SIZE.height
350 private static generateStandardMetaTags (tags: Tags) {
353 description: tags.description,
354 image: tags.image.url
358 private static generateTwitterCardMetaTags (tags: Tags) {
360 'twitter:card': tags.twitterCard,
361 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
362 'twitter:title': tags.title,
363 'twitter:description': tags.description,
364 'twitter:image': tags.image.url
367 if (tags.image.width && tags.image.height) {
368 metaTags['twitter:image:width'] = tags.image.width
369 metaTags['twitter:image:height'] = tags.image.height
372 if (tags.twitterCard === 'player') {
373 metaTags['twitter:player'] = tags.embed.url
374 metaTags['twitter:player:width'] = EMBED_SIZE.width
375 metaTags['twitter:player:height'] = EMBED_SIZE.height
381 private static generateSchemaTags (tags: Tags) {
383 '@context': 'http://schema.org',
384 '@type': tags.schemaType,
386 'description': tags.description,
387 'image': tags.image.url,
392 schema['numberOfItems'] = tags.list.numberOfItems
393 schema['thumbnailUrl'] = tags.image.url
397 schema['embedUrl'] = tags.embed.url
398 schema['uploadDate'] = tags.embed.createdAt
400 if (tags.embed.duration) schema['duration'] = tags.embed.duration
401 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
403 schema['thumbnailUrl'] = tags.image.url
404 schema['contentUrl'] = tags.url
410 private static addTags (htmlStringPage: string, tagsValues: Tags) {
411 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
412 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
413 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
414 const schemaTags = this.generateSchemaTags(tagsValues)
416 const { url, title, embed } = tagsValues
418 const oembedLinkTags: { type: string, href: string, title: string }[] = []
421 oembedLinkTags.push({
422 type: 'application/json+oembed',
423 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
431 Object.keys(openGraphMetaTags).forEach(tagName => {
432 const tagValue = openGraphMetaTags[tagName]
434 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
438 Object.keys(standardMetaTags).forEach(tagName => {
439 const tagValue = standardMetaTags[tagName]
441 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
445 Object.keys(twitterCardMetaTags).forEach(tagName => {
446 const tagValue = twitterCardMetaTags[tagName]
448 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
452 for (const oembedLinkTag of oembedLinkTags) {
453 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
458 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
461 // SEO, use origin URL
462 tagsString += `<link rel="canonical" href="${url}" />`
464 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)