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