Refactor middleware helpers
[oweals/peertube.git] / server / lib / client-html.ts
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
17 export class ClientHtml {
18
19   private static htmlCache: { [ path: string ]: string } = {}
20
21   static invalidCache () {
22     logger.info('Cleaning HTML cache.')
23
24     ClientHtml.htmlCache = {}
25   }
26
27   static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
28     const html = await ClientHtml.getIndexHTML(req, res, paramLang)
29
30     let customHtml = ClientHtml.addTitleTag(html)
31     customHtml = ClientHtml.addDescriptionTag(customHtml)
32
33     return customHtml
34   }
35
36   static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
37     // Let Angular application handle errors
38     if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
39       return ClientHtml.getIndexHTML(req, res)
40     }
41
42     const [ html, video ] = await Promise.all([
43       ClientHtml.getIndexHTML(req, res),
44       VideoModel.loadAndPopulateAccountAndServerAndTags(videoId)
45     ])
46
47     // Let Angular application handle errors
48     if (!video || video.privacy === VideoPrivacy.PRIVATE) {
49       return ClientHtml.getIndexHTML(req, res)
50     }
51
52     let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
53     customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
54     customHtml = ClientHtml.addVideoOpenGraphAndOEmbedTags(customHtml, video)
55
56     return customHtml
57   }
58
59   static async getAccountHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
60     return this.getAccountOrChannelHTMLPage(() => AccountModel.loadByNameWithHost(nameWithHost), req, res)
61   }
62
63   static async getVideoChannelHTMLPage (nameWithHost: string, req: express.Request, res: express.Response) {
64     return this.getAccountOrChannelHTMLPage(() => VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithHost), req, res)
65   }
66
67   private static async getAccountOrChannelHTMLPage (
68     loader: () => Bluebird<AccountModel | VideoChannelModel>,
69     req: express.Request,
70     res: express.Response
71   ) {
72     const [ html, entity ] = await Promise.all([
73       ClientHtml.getIndexHTML(req, res),
74       loader()
75     ])
76
77     // Let Angular application handle errors
78     if (!entity) {
79       return ClientHtml.getIndexHTML(req, res)
80     }
81
82     let customHtml = ClientHtml.addTitleTag(html, escapeHTML(entity.getDisplayName()))
83     customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(entity.description))
84     customHtml = ClientHtml.addAccountOrChannelMetaTags(customHtml, entity)
85
86     return customHtml
87   }
88
89   private static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
90     const path = ClientHtml.getIndexPath(req, res, paramLang)
91     if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
92
93     const buffer = await readFile(path)
94
95     let html = buffer.toString()
96
97     html = ClientHtml.addCustomCSS(html)
98     html = await ClientHtml.addAsyncPluginCSS(html)
99
100     ClientHtml.htmlCache[ path ] = html
101
102     return html
103   }
104
105   private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
106     let lang: string
107
108     // Check param lang validity
109     if (paramLang && is18nLocale(paramLang)) {
110       lang = paramLang
111
112       // Save locale in cookies
113       res.cookie('clientLanguage', lang, {
114         secure: WEBSERVER.SCHEME === 'https',
115         sameSite: true,
116         maxAge: 1000 * 3600 * 24 * 90 // 3 months
117       })
118
119     } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
120       lang = req.cookies.clientLanguage
121     } else {
122       lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
123     }
124
125     return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
126   }
127
128   private static addTitleTag (htmlStringPage: string, title?: string) {
129     let text = title || CONFIG.INSTANCE.NAME
130     if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
131
132     const titleTag = `<title>${text}</title>`
133
134     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
135   }
136
137   private static addDescriptionTag (htmlStringPage: string, description?: string) {
138     const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
139     const descriptionTag = `<meta name="description" content="${content}" />`
140
141     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
142   }
143
144   private static addCustomCSS (htmlStringPage: string) {
145     const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
146
147     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
148   }
149
150   private static async addAsyncPluginCSS (htmlStringPage: string) {
151     const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
152     if (globalCSSContent.byteLength === 0) return htmlStringPage
153
154     const fileHash = sha256(globalCSSContent)
155     const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
156
157     return htmlStringPage.replace('</head>', linkTag + '</head>')
158   }
159
160   private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
161     const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
162     const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
163
164     const videoNameEscaped = escapeHTML(video.name)
165     const videoDescriptionEscaped = escapeHTML(video.description)
166     const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
167
168     const openGraphMetaTags = {
169       'og:type': 'video',
170       'og:title': videoNameEscaped,
171       'og:image': previewUrl,
172       'og:url': videoUrl,
173       'og:description': videoDescriptionEscaped,
174
175       'og:video:url': embedUrl,
176       'og:video:secure_url': embedUrl,
177       'og:video:type': 'text/html',
178       'og:video:width': EMBED_SIZE.width,
179       'og:video:height': EMBED_SIZE.height,
180
181       'name': videoNameEscaped,
182       'description': videoDescriptionEscaped,
183       'image': previewUrl,
184
185       'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
186       'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
187       'twitter:title': videoNameEscaped,
188       'twitter:description': videoDescriptionEscaped,
189       'twitter:image': previewUrl,
190       'twitter:player': embedUrl,
191       'twitter:player:width': EMBED_SIZE.width,
192       'twitter:player:height': EMBED_SIZE.height
193     }
194
195     const oembedLinkTags = [
196       {
197         type: 'application/json+oembed',
198         href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
199         title: videoNameEscaped
200       }
201     ]
202
203     const schemaTags = {
204       '@context': 'http://schema.org',
205       '@type': 'VideoObject',
206       name: videoNameEscaped,
207       description: videoDescriptionEscaped,
208       thumbnailUrl: previewUrl,
209       uploadDate: video.createdAt.toISOString(),
210       duration: getActivityStreamDuration(video.duration),
211       contentUrl: videoUrl,
212       embedUrl: embedUrl,
213       interactionCount: video.views
214     }
215
216     let tagsString = ''
217
218     // Opengraph
219     Object.keys(openGraphMetaTags).forEach(tagName => {
220       const tagValue = openGraphMetaTags[ tagName ]
221
222       tagsString += `<meta property="${tagName}" content="${tagValue}" />`
223     })
224
225     // OEmbed
226     for (const oembedLinkTag of oembedLinkTags) {
227       tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
228     }
229
230     // Schema.org
231     tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
232
233     // SEO, use origin video url so Google does not index remote videos
234     tagsString += `<link rel="canonical" href="${video.url}" />`
235
236     return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
237   }
238
239   private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: AccountModel | VideoChannelModel) {
240     // SEO, use origin account or channel URL
241     const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
242
243     return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
244   }
245
246   private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
247     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)
248   }
249 }