]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blobdiff - server/lib/client-html.ts
WIP plugins: load theme on client side
[github/Chocobozzz/PeerTube.git] / server / lib / client-html.ts
index 72984e7789863505519fa831bf35a39efc6d3ce8..ccc963514ac46acde0bda562ac93ff06d4895460 100644 (file)
@@ -1,53 +1,44 @@
 import * as express from 'express'
-import * as Bluebird from 'bluebird'
 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/models/i18n/i18n'
-import { CONFIG, EMBED_SIZE, CUSTOM_HTML_TAG_COMMENTS, STATIC_PATHS } from '../initializers'
+import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, WEBSERVER } from '../initializers/constants'
 import { join } from 'path'
-import { escapeHTML, readFileBufferPromise } from '../helpers/core-utils'
+import { escapeHTML } from '../helpers/core-utils'
 import { VideoModel } from '../models/video/video'
 import * as validator from 'validator'
 import { VideoPrivacy } from '../../shared/models/videos'
+import { readFile } from 'fs-extra'
+import { getActivityStreamDuration } from '../models/video/video-format-utils'
+import { AccountModel } from '../models/account/account'
+import { VideoChannelModel } from '../models/video/video-channel'
+import * as Bluebird from 'bluebird'
+import { CONFIG } from '../initializers/config'
 
 export class ClientHtml {
 
-  private static htmlCache: { [path: string]: string } = {}
+  private static htmlCache: { [ path: string ]: string } = {}
 
   static invalidCache () {
     ClientHtml.htmlCache = {}
   }
 
-  static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
-    const path = ClientHtml.getIndexPath(req, res, paramLang)
-    if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
-
-    const buffer = await readFileBufferPromise(path)
-
-    let html = buffer.toString()
-
-    html = ClientHtml.addTitleTag(html)
-    html = ClientHtml.addDescriptionTag(html)
-    html = ClientHtml.addCustomCSS(html)
+  static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
+    const html = await ClientHtml.getIndexHTML(req, res, paramLang)
 
-    ClientHtml.htmlCache[path] = html
+    let customHtml = ClientHtml.addTitleTag(html)
+    customHtml = ClientHtml.addDescriptionTag(customHtml)
 
-    return html
+    return customHtml
   }
 
   static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
-    let videoPromise: Bluebird<VideoModel>
-
     // Let Angular application handle errors
-    if (validator.isUUID(videoId, 4)) {
-      videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
-    } else if (validator.isInt(videoId)) {
-      videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
-    } else {
+    if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
       return ClientHtml.getIndexHTML(req, res)
     }
 
     const [ html, video ] = await Promise.all([
       ClientHtml.getIndexHTML(req, res),
-      videoPromise
+      VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
     ])
 
     // Let Angular application handle errors
@@ -55,7 +46,57 @@ export class ClientHtml {
       return ClientHtml.getIndexHTML(req, res)
     }
 
-    return ClientHtml.addOpenGraphAndOEmbedTags(html, video)
+    let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
+    customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
+    customHtml = ClientHtml.addVideoOpenGraphAndOEmbedTags(customHtml, video)
+
+    return customHtml
+  }
+
+  static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
+    return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
+  }
+
+  static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
+    return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
+  }
+
+  private static async getAccountOrChannelHTMLPage (
+    loader: () => Bluebird<AccountModel | VideoChannelModel>,
+    req: express.Request,
+    res: express.Response
+  ) {
+    const [ html, entity ] = await Promise.all([
+      ClientHtml.getIndexHTML(req, res),
+      loader()
+    ])
+
+    // Let Angular application handle errors
+    if (!entity) {
+      return ClientHtml.getIndexHTML(req, res)
+    }
+
+    let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
+    customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
+    customHtml = ClientHtml.addAccountOrChannelMetaTags(customHtml, entity)
+
+    return customHtml
+  }
+
+  private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
+    const path = ClientHtml.getIndexPath(req, res, paramLang)
+    if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
+
+    const buffer = await readFile(path)
+
+    let html = buffer.toString()
+
+    html = ClientHtml.addCustomCSS(html)
+    html = ClientHtml.addPluginCSS(html)
+
+    ClientHtml.htmlCache[ path ] = html
+
+    return html
   }
 
   private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
@@ -67,7 +108,7 @@ export class ClientHtml {
 
       // Save locale in cookies
       res.cookie('clientLanguage', lang, {
-        secure: CONFIG.WEBSERVER.SCHEME === 'https',
+        secure: WEBSERVER.SCHEME === 'https',
         sameSite: true,
         maxAge: 1000 * 3600 * 24 * 90 // 3 months
       })
@@ -81,31 +122,41 @@ export class ClientHtml {
     return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
   }
 
-  private static addTitleTag (htmlStringPage: string) {
-    const titleTag = '<title>' + CONFIG.INSTANCE.NAME + '</title>'
+  private static addTitleTag (htmlStringPage: string, title?: string) {
+    let text = title || CONFIG.INSTANCE.NAME
+    if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
+
+    const titleTag = `<title>${text}</title>`
 
     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
   }
 
-  private static addDescriptionTag (htmlStringPage: string) {
-    const descriptionTag = `<meta name="description" content="${CONFIG.INSTANCE.SHORT_DESCRIPTION}" />`
+  private static addDescriptionTag (htmlStringPage: string, description?: string) {
+    const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
+    const descriptionTag = `<meta name="description" content="${content}" />`
 
     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
   }
 
   private static addCustomCSS (htmlStringPage: string) {
-    const styleTag = '<style class="custom-css-style">' + CONFIG.INSTANCE.CUSTOMIZATIONS.CSS + '</style>'
+    const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
 
     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
   }
 
-  private static addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
-    const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
-    const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
+  private static addPluginCSS (htmlStringPage: string) {
+    const linkTag = `<link rel="stylesheet" href="/plugins/global.css" />`
+
+    return htmlStringPage.replace('</head>', linkTag + '</head>')
+  }
+
+  private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
+    const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
+    const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
 
     const videoNameEscaped = escapeHTML(video.name)
     const videoDescriptionEscaped = escapeHTML(video.description)
-    const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedStaticPath()
+    const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
 
     const openGraphMetaTags = {
       'og:type': 'video',
@@ -137,7 +188,7 @@ export class ClientHtml {
     const oembedLinkTags = [
       {
         type: 'application/json+oembed',
-        href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
+        href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
         title: videoNameEscaped
       }
     ]
@@ -149,7 +200,7 @@ export class ClientHtml {
       description: videoDescriptionEscaped,
       thumbnailUrl: previewUrl,
       uploadDate: video.createdAt.toISOString(),
-      duration: video.getActivityStreamDuration(),
+      duration: getActivityStreamDuration(video.duration),
       contentUrl: videoUrl,
       embedUrl: embedUrl,
       interactionCount: video.views
@@ -159,7 +210,7 @@ export class ClientHtml {
 
     // Opengraph
     Object.keys(openGraphMetaTags).forEach(tagName => {
-      const tagValue = openGraphMetaTags[tagName]
+      const tagValue = openGraphMetaTags[ tagName ]
 
       tagsString += `<meta property="${tagName}" content="${tagValue}" />`
     })
@@ -172,9 +223,20 @@ export class ClientHtml {
     // Schema.org
     tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
 
-    // SEO
-    tagsString += `<link rel="canonical" href="${videoUrl}" />`
+    // SEO, use origin video url so Google does not index remote videos
+    tagsString += `<link rel="canonical" href="${video.url}" />`
+
+    return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
+  }
+
+  private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: AccountModel | VideoChannelModel) {
+    // SEO, use origin account or channel URL
+    const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
+
+    return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
+  }
 
-    return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.OPENGRAPH_AND_OEMBED, tagsString)
+  private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
+    return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)
   }
 }