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, isTestInstance, 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'
25 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
29 twitterCard: 'player' | 'summary' | 'summary_large_image'
55 export class ClientHtml {
57 private static htmlCache: { [path: string]: string } = {}
59 static invalidCache () {
60 logger.info('Cleaning HTML cache.')
62 ClientHtml.htmlCache = {}
65 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
66 const html = paramLang
67 ? await ClientHtml.getIndexHTML(req, res, paramLang)
68 : await ClientHtml.getIndexHTML(req, res)
70 let customHtml = ClientHtml.addTitleTag(html)
71 customHtml = ClientHtml.addDescriptionTag(customHtml)
76 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
77 // Let Angular application handle errors
78 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
79 res.status(HttpStatusCode.NOT_FOUND_404)
80 return ClientHtml.getIndexHTML(req, res)
83 const [ html, video ] = await Promise.all([
84 ClientHtml.getIndexHTML(req, res),
85 VideoModel.loadWithBlacklist(videoId)
88 // Let Angular application handle errors
89 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
90 res.status(HttpStatusCode.NOT_FOUND_404)
94 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
95 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
97 const url = WEBSERVER.URL + video.getWatchStaticPath()
98 const title = escapeHTML(video.name)
99 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
100 const description = escapeHTML(video.description)
103 url: WEBSERVER.URL + video.getPreviewStaticPath()
107 url: WEBSERVER.URL + video.getEmbedStaticPath(),
108 createdAt: video.createdAt.toISOString(),
109 duration: getActivityStreamDuration(video.duration),
113 const ogType = 'video'
114 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
115 const schemaType = 'VideoObject'
117 customHtml = ClientHtml.addTags(customHtml, { url, siteName, title, description, image, embed, ogType, twitterCard, schemaType })
122 static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
123 // Let Angular application handle errors
124 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
125 res.status(HttpStatusCode.NOT_FOUND_404)
126 return ClientHtml.getIndexHTML(req, res)
129 const [ html, videoPlaylist ] = await Promise.all([
130 ClientHtml.getIndexHTML(req, res),
131 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
134 // Let Angular application handle errors
135 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
136 res.status(HttpStatusCode.NOT_FOUND_404)
140 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
141 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(videoPlaylist.description))
143 const url = videoPlaylist.getWatchUrl()
144 const title = escapeHTML(videoPlaylist.name)
145 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
146 const description = escapeHTML(videoPlaylist.description)
149 url: videoPlaylist.getThumbnailUrl()
153 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
154 createdAt: videoPlaylist.createdAt.toISOString()
158 numberOfItems: videoPlaylist.get('videosLength') as number
161 const ogType = 'video'
162 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
163 const schemaType = 'ItemList'
165 customHtml = ClientHtml.addTags(customHtml, { url, siteName, embed, title, description, image, list, ogType, twitterCard, schemaType })
170 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
171 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
174 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
175 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
178 static async getEmbedHTML () {
179 const path = ClientHtml.getEmbedPath()
181 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
183 const buffer = await readFile(path)
185 let html = buffer.toString()
186 html = await ClientHtml.addAsyncPluginCSS(html)
188 ClientHtml.htmlCache[path] = html
193 private static async getAccountOrChannelHTMLPage (
194 loader: () => Bluebird<MAccountActor | MChannelActor>,
195 req: express.Request,
196 res: express.Response
198 const [ html, entity ] = await Promise.all([
199 ClientHtml.getIndexHTML(req, res),
203 // Let Angular application handle errors
205 res.status(HttpStatusCode.NOT_FOUND_404)
206 return ClientHtml.getIndexHTML(req, res)
209 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
210 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
212 const url = entity.Actor.url
213 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
214 const title = escapeHTML(entity.getDisplayName())
215 const description = escapeHTML(entity.description)
218 url: entity.Actor.getAvatarUrl(),
219 width: AVATARS_SIZE.width,
220 height: AVATARS_SIZE.height
223 const ogType = 'website'
224 const twitterCard = 'summary'
225 const schemaType = 'ProfilePage'
227 customHtml = ClientHtml.addTags(customHtml, { url, title, siteName, description, image, ogType, twitterCard, schemaType })
232 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
233 const path = ClientHtml.getIndexPath(req, res, paramLang)
234 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
236 const buffer = await readFile(path)
238 let html = buffer.toString()
240 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
241 html = ClientHtml.addManifestContentHash(html)
242 html = ClientHtml.addFaviconContentHash(html)
243 html = ClientHtml.addLogoContentHash(html)
244 html = ClientHtml.addCustomCSS(html)
245 html = await ClientHtml.addAsyncPluginCSS(html)
247 ClientHtml.htmlCache[path] = html
252 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
255 // Check param lang validity
256 if (paramLang && is18nLocale(paramLang)) {
259 // Save locale in cookies
260 res.cookie('clientLanguage', lang, {
261 secure: WEBSERVER.SCHEME === 'https',
263 maxAge: 1000 * 3600 * 24 * 90 // 3 months
266 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
267 lang = req.cookies.clientLanguage
269 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
272 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
275 private static getEmbedPath () {
276 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
279 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
280 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
283 private static addManifestContentHash (htmlStringPage: string) {
284 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
287 private static addFaviconContentHash (htmlStringPage: string) {
288 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
291 private static addLogoContentHash (htmlStringPage: string) {
292 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
295 private static addTitleTag (htmlStringPage: string, title?: string) {
296 let text = title || CONFIG.INSTANCE.NAME
297 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
299 const titleTag = `<title>${text}</title>`
301 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
304 private static addDescriptionTag (htmlStringPage: string, description?: string) {
305 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
306 const descriptionTag = `<meta name="description" content="${content}" />`
308 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
311 private static addCustomCSS (htmlStringPage: string) {
312 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
314 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
317 private static async addAsyncPluginCSS (htmlStringPage: string) {
318 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
319 if (globalCSSContent.byteLength === 0) return htmlStringPage
321 const fileHash = sha256(globalCSSContent)
322 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
324 return htmlStringPage.replace('</head>', linkTag + '</head>')
327 private static generateOpenGraphMetaTags (tags: Tags) {
329 'og:type': tags.ogType,
330 'og:site_name': tags.siteName,
331 'og:title': tags.title,
332 'og:image': tags.image.url
335 if (tags.image.width && tags.image.height) {
336 metaTags['og:image:width'] = tags.image.width
337 metaTags['og:image:height'] = tags.image.height
340 metaTags['og:url'] = tags.url
341 metaTags['og:description'] = tags.description
344 metaTags['og:video:url'] = tags.embed.url
345 metaTags['og:video:secure_url'] = tags.embed.url
346 metaTags['og:video:type'] = 'text/html'
347 metaTags['og:video:width'] = EMBED_SIZE.width
348 metaTags['og:video:height'] = EMBED_SIZE.height
354 private static generateStandardMetaTags (tags: Tags) {
357 description: tags.description,
358 image: tags.image.url
362 private static generateTwitterCardMetaTags (tags: Tags) {
364 'twitter:card': tags.twitterCard,
365 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
366 'twitter:title': tags.title,
367 'twitter:description': tags.description,
368 'twitter:image': tags.image.url
371 if (tags.image.width && tags.image.height) {
372 metaTags['twitter:image:width'] = tags.image.width
373 metaTags['twitter:image:height'] = tags.image.height
376 if (tags.twitterCard === 'player') {
377 metaTags['twitter:player'] = tags.embed.url
378 metaTags['twitter:player:width'] = EMBED_SIZE.width
379 metaTags['twitter:player:height'] = EMBED_SIZE.height
385 private static generateSchemaTags (tags: Tags) {
387 '@context': 'http://schema.org',
388 '@type': tags.schemaType,
390 'description': tags.description,
391 'image': tags.image.url,
396 schema['numberOfItems'] = tags.list.numberOfItems
397 schema['thumbnailUrl'] = tags.image.url
401 schema['embedUrl'] = tags.embed.url
402 schema['uploadDate'] = tags.embed.createdAt
404 if (tags.embed.duration) schema['duration'] = tags.embed.duration
405 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
407 schema['thumbnailUrl'] = tags.image.url
408 schema['contentUrl'] = tags.url
414 private static addTags (htmlStringPage: string, tagsValues: Tags) {
415 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
416 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
417 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
418 const schemaTags = this.generateSchemaTags(tagsValues)
420 const { url, title, embed } = tagsValues
422 const oembedLinkTags: { type: string, href: string, title: string }[] = []
425 oembedLinkTags.push({
426 type: 'application/json+oembed',
427 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
435 Object.keys(openGraphMetaTags).forEach(tagName => {
436 const tagValue = openGraphMetaTags[tagName]
438 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
442 Object.keys(standardMetaTags).forEach(tagName => {
443 const tagValue = standardMetaTags[tagName]
445 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
449 Object.keys(twitterCardMetaTags).forEach(tagName => {
450 const tagValue = twitterCardMetaTags[tagName]
452 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
456 for (const oembedLinkTag of oembedLinkTags) {
457 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
462 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
465 // SEO, use origin URL
466 tagsString += `<link rel="canonical" href="${url}" />`
468 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)