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