1 import * as express from 'express'
2 import { readFile } from 'fs-extra'
3 import { join } from 'path'
4 import validator from 'validator'
5 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/core-utils/i18n/i18n'
6 import { HttpStatusCode } from '../../shared/core-utils/miscs/http-error-codes'
7 import { VideoPlaylistPrivacy, VideoPrivacy } from '../../shared/models/videos'
8 import { isTestInstance, sha256 } from '../helpers/core-utils'
9 import { escapeHTML } from '@shared/core-utils/renderer'
10 import { logger } from '../helpers/logger'
11 import { CONFIG } from '../initializers/config'
15 CUSTOM_HTML_TAG_COMMENTS,
18 PLUGIN_GLOBAL_CSS_PATH,
20 } from '../initializers/constants'
21 import { AccountModel } from '../models/account/account'
22 import { VideoModel } from '../models/video/video'
23 import { VideoChannelModel } from '../models/video/video-channel'
24 import { getActivityStreamDuration } from '../models/video/video-format-utils'
25 import { VideoPlaylistModel } from '../models/video/video-playlist'
26 import { MAccountActor, MChannelActor } from '../types/models'
27 import { toSafeHtml } from '../helpers/markdown'
31 twitterCard: 'player' | 'summary' | 'summary_large_image'
58 const toPlainText = (content: string) => {
59 return toSafeHtml(content).replace(/<[^>]+>/g, '')
64 private static htmlCache: { [path: string]: string } = {}
66 static invalidCache () {
67 logger.info('Cleaning HTML cache.')
69 ClientHtml.htmlCache = {}
72 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
73 const html = paramLang
74 ? await ClientHtml.getIndexHTML(req, res, paramLang)
75 : await ClientHtml.getIndexHTML(req, res)
77 let customHtml = ClientHtml.addTitleTag(html)
78 customHtml = ClientHtml.addDescriptionTag(customHtml)
83 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
84 // Let Angular application handle errors
85 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
86 res.status(HttpStatusCode.NOT_FOUND_404)
87 return ClientHtml.getIndexHTML(req, res)
90 const [ html, video ] = await Promise.all([
91 ClientHtml.getIndexHTML(req, res),
92 VideoModel.loadWithBlacklist(videoId)
95 // Let Angular application handle errors
96 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
97 res.status(HttpStatusCode.NOT_FOUND_404)
101 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
102 customHtml = ClientHtml.addDescriptionTag(customHtml, toPlainText(video.description))
104 const url = WEBSERVER.URL + video.getWatchStaticPath()
105 const originUrl = video.url
106 const title = escapeHTML(video.name)
107 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
108 const description = toPlainText(video.description)
111 url: WEBSERVER.URL + video.getPreviewStaticPath()
115 url: WEBSERVER.URL + video.getEmbedStaticPath(),
116 createdAt: video.createdAt.toISOString(),
117 duration: getActivityStreamDuration(video.duration),
121 const ogType = 'video'
122 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image'
123 const schemaType = 'VideoObject'
125 customHtml = ClientHtml.addTags(customHtml, {
141 static async getWatchPlaylistHTMLPage (videoPlaylistId: string, req: express.Request, res: express.Response) {
142 // Let Angular application handle errors
143 if (!validator.isInt(videoPlaylistId) && !validator.isUUID(videoPlaylistId, 4)) {
144 res.status(HttpStatusCode.NOT_FOUND_404)
145 return ClientHtml.getIndexHTML(req, res)
148 const [ html, videoPlaylist ] = await Promise.all([
149 ClientHtml.getIndexHTML(req, res),
150 VideoPlaylistModel.loadWithAccountAndChannel(videoPlaylistId, null)
153 // Let Angular application handle errors
154 if (!videoPlaylist || videoPlaylist.privacy === VideoPlaylistPrivacy.PRIVATE) {
155 res.status(HttpStatusCode.NOT_FOUND_404)
159 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(videoPlaylist.name))
160 customHtml = ClientHtml.addDescriptionTag(customHtml, toPlainText(videoPlaylist.description))
162 const url = videoPlaylist.getWatchUrl()
163 const originUrl = videoPlaylist.url
164 const title = escapeHTML(videoPlaylist.name)
165 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
166 const description = toPlainText(videoPlaylist.description)
169 url: videoPlaylist.getThumbnailUrl()
173 url: WEBSERVER.URL + videoPlaylist.getEmbedStaticPath(),
174 createdAt: videoPlaylist.createdAt.toISOString()
178 numberOfItems: videoPlaylist.get('videosLength') as number
181 const ogType = 'video'
182 const twitterCard = CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary'
183 const schemaType = 'ItemList'
185 customHtml = ClientHtml.addTags(customHtml, {
202 static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
203 return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
206 static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
207 return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
210 static async getEmbedHTML () {
211 const path = ClientHtml.getEmbedPath()
213 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
215 const buffer = await readFile(path)
217 let html = buffer.toString()
218 html = await ClientHtml.addAsyncPluginCSS(html)
219 html = ClientHtml.addCustomCSS(html)
220 html = ClientHtml.addTitleTag(html)
222 ClientHtml.htmlCache[path] = html
227 private static async getAccountOrChannelHTMLPage (
228 loader: () => Promise<MAccountActor | MChannelActor>,
229 req: express.Request,
230 res: express.Response
232 const [ html, entity ] = await Promise.all([
233 ClientHtml.getIndexHTML(req, res),
237 // Let Angular application handle errors
239 res.status(HttpStatusCode.NOT_FOUND_404)
240 return ClientHtml.getIndexHTML(req, res)
243 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
244 customHtml = ClientHtml.addDescriptionTag(customHtml, toPlainText(entity.description))
246 const url = entity.getLocalUrl()
247 const originUrl = entity.Actor.url
248 const siteName = escapeHTML(CONFIG.INSTANCE.NAME)
249 const title = escapeHTML(entity.getDisplayName())
250 const description = toPlainText(entity.description)
253 url: entity.Actor.getAvatarUrl(),
254 width: ACTOR_IMAGES_SIZE.AVATARS.width,
255 height: ACTOR_IMAGES_SIZE.AVATARS.height
258 const ogType = 'website'
259 const twitterCard = 'summary'
260 const schemaType = 'ProfilePage'
262 customHtml = ClientHtml.addTags(customHtml, {
277 private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
278 const path = ClientHtml.getIndexPath(req, res, paramLang)
279 if (!isTestInstance() && ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
281 const buffer = await readFile(path)
283 let html = buffer.toString()
285 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
286 html = ClientHtml.addManifestContentHash(html)
287 html = ClientHtml.addFaviconContentHash(html)
288 html = ClientHtml.addLogoContentHash(html)
289 html = ClientHtml.addCustomCSS(html)
290 html = await ClientHtml.addAsyncPluginCSS(html)
292 ClientHtml.htmlCache[path] = html
297 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
300 // Check param lang validity
301 if (paramLang && is18nLocale(paramLang)) {
304 // Save locale in cookies
305 res.cookie('clientLanguage', lang, {
306 secure: WEBSERVER.SCHEME === 'https',
308 maxAge: 1000 * 3600 * 24 * 90 // 3 months
311 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
312 lang = req.cookies.clientLanguage
314 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
317 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
320 private static getEmbedPath () {
321 return join(__dirname, '../../../client/dist/standalone/videos/embed.html')
324 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
325 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
328 private static addManifestContentHash (htmlStringPage: string) {
329 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
332 private static addFaviconContentHash (htmlStringPage: string) {
333 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
336 private static addLogoContentHash (htmlStringPage: string) {
337 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
340 private static addTitleTag (htmlStringPage: string, title?: string) {
341 let text = title || CONFIG.INSTANCE.NAME
342 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
344 const titleTag = `<title>${text}</title>`
346 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
349 private static addDescriptionTag (htmlStringPage: string, description?: string) {
350 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
351 const descriptionTag = `<meta name="description" content="${content}" />`
353 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
356 private static addCustomCSS (htmlStringPage: string) {
357 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
359 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
362 private static async addAsyncPluginCSS (htmlStringPage: string) {
363 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
364 if (globalCSSContent.byteLength === 0) return htmlStringPage
366 const fileHash = sha256(globalCSSContent)
367 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
369 return htmlStringPage.replace('</head>', linkTag + '</head>')
372 private static generateOpenGraphMetaTags (tags: Tags) {
374 'og:type': tags.ogType,
375 'og:site_name': tags.siteName,
376 'og:title': tags.title,
377 'og:image': tags.image.url
380 if (tags.image.width && tags.image.height) {
381 metaTags['og:image:width'] = tags.image.width
382 metaTags['og:image:height'] = tags.image.height
385 metaTags['og:url'] = tags.url
386 metaTags['og:description'] = tags.description
389 metaTags['og:video:url'] = tags.embed.url
390 metaTags['og:video:secure_url'] = tags.embed.url
391 metaTags['og:video:type'] = 'text/html'
392 metaTags['og:video:width'] = EMBED_SIZE.width
393 metaTags['og:video:height'] = EMBED_SIZE.height
399 private static generateStandardMetaTags (tags: Tags) {
402 description: tags.description,
403 image: tags.image.url
407 private static generateTwitterCardMetaTags (tags: Tags) {
409 'twitter:card': tags.twitterCard,
410 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
411 'twitter:title': tags.title,
412 'twitter:description': tags.description,
413 'twitter:image': tags.image.url
416 if (tags.image.width && tags.image.height) {
417 metaTags['twitter:image:width'] = tags.image.width
418 metaTags['twitter:image:height'] = tags.image.height
421 if (tags.twitterCard === 'player') {
422 metaTags['twitter:player'] = tags.embed.url
423 metaTags['twitter:player:width'] = EMBED_SIZE.width
424 metaTags['twitter:player:height'] = EMBED_SIZE.height
430 private static generateSchemaTags (tags: Tags) {
432 '@context': 'http://schema.org',
433 '@type': tags.schemaType,
435 'description': tags.description,
436 'image': tags.image.url,
441 schema['numberOfItems'] = tags.list.numberOfItems
442 schema['thumbnailUrl'] = tags.image.url
446 schema['embedUrl'] = tags.embed.url
447 schema['uploadDate'] = tags.embed.createdAt
449 if (tags.embed.duration) schema['duration'] = tags.embed.duration
450 if (tags.embed.views) schema['iterationCount'] = tags.embed.views
452 schema['thumbnailUrl'] = tags.image.url
453 schema['contentUrl'] = tags.url
459 private static addTags (htmlStringPage: string, tagsValues: Tags) {
460 const openGraphMetaTags = this.generateOpenGraphMetaTags(tagsValues)
461 const standardMetaTags = this.generateStandardMetaTags(tagsValues)
462 const twitterCardMetaTags = this.generateTwitterCardMetaTags(tagsValues)
463 const schemaTags = this.generateSchemaTags(tagsValues)
465 const { url, title, embed, originUrl } = tagsValues
467 const oembedLinkTags: { type: string, href: string, title: string }[] = []
470 oembedLinkTags.push({
471 type: 'application/json+oembed',
472 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(url),
480 Object.keys(openGraphMetaTags).forEach(tagName => {
481 const tagValue = openGraphMetaTags[tagName]
483 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
487 Object.keys(standardMetaTags).forEach(tagName => {
488 const tagValue = standardMetaTags[tagName]
490 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
494 Object.keys(twitterCardMetaTags).forEach(tagName => {
495 const tagValue = twitterCardMetaTags[tagName]
497 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
501 for (const oembedLinkTag of oembedLinkTags) {
502 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
507 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
510 // SEO, use origin URL
511 tagsString += `<link rel="canonical" href="${originUrl}" />`
513 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, tagsString)
517 function sendHTML (html: string, res: express.Response) {
518 res.set('Content-Type', 'text/html; charset=UTF-8')
520 return res.send(html)
523 async function serveIndexHTML (req: express.Request, res: express.Response) {
524 if (req.accepts(ACCEPT_HEADERS) === 'html' ||
525 !req.headers.accept) {
527 await generateHTMLPage(req, res, req.params.language)
530 logger.error('Cannot generate HTML page.', err)
531 return res.sendStatus(HttpStatusCode.INTERNAL_SERVER_ERROR_500)
535 return res.sendStatus(HttpStatusCode.NOT_ACCEPTABLE_406)
538 // ---------------------------------------------------------------------------
546 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
547 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
549 return sendHTML(html, res)