]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Bumped to version v2.3.0-rc.1
[github/Chocobozzz/PeerTube.git] / server / lib / client-html.ts
CommitLineData
e032aec9 1import * as express from 'express'
e032aec9 2import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/models/i18n/i18n'
a8b666e9 3import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, PLUGIN_GLOBAL_CSS_PATH, WEBSERVER } from '../initializers/constants'
e032aec9 4import { join } from 'path'
a8b666e9 5import { escapeHTML, sha256 } from '../helpers/core-utils'
e032aec9 6import { VideoModel } from '../models/video/video'
7cde3b9c 7import validator from 'validator'
e032aec9 8import { VideoPrivacy } from '../../shared/models/videos'
62689b94 9import { readFile } from 'fs-extra'
098eb377 10import { getActivityStreamDuration } from '../models/video/video-format-utils'
92bf2f62
C
11import { AccountModel } from '../models/account/account'
12import { VideoChannelModel } from '../models/video/video-channel'
13import * as Bluebird from 'bluebird'
6dd9de95 14import { CONFIG } from '../initializers/config'
3e753302 15import { logger } from '../helpers/logger'
26d6bf65 16import { MAccountActor, MChannelActor, MVideo } from '../types/models'
e032aec9
C
17
18export class ClientHtml {
19
a1587156 20 private static htmlCache: { [path: string]: string } = {}
e032aec9
C
21
22 static invalidCache () {
3e753302
C
23 logger.info('Cleaning HTML cache.')
24
e032aec9
C
25 ClientHtml.htmlCache = {}
26 }
27
9aac4423 28 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
7738273b
RK
29 const html = paramLang
30 ? await ClientHtml.getIndexHTML(req, res, paramLang)
31 : await ClientHtml.getIndexHTML(req, res)
e032aec9 32
9aac4423
C
33 let customHtml = ClientHtml.addTitleTag(html)
34 customHtml = ClientHtml.addDescriptionTag(customHtml)
e032aec9 35
9aac4423 36 return customHtml
e032aec9
C
37 }
38
39 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
e032aec9 40 // Let Angular application handle errors
92bf2f62 41 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
c08579e1 42 res.status(404)
e032aec9
C
43 return ClientHtml.getIndexHTML(req, res)
44 }
45
46 const [ html, video ] = await Promise.all([
47 ClientHtml.getIndexHTML(req, res),
d636ab58 48 VideoModel.loadWithBlacklist(videoId)
e032aec9
C
49 ])
50
51 // Let Angular application handle errors
22a73cb8 52 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
c08579e1
C
53 res.status(404)
54 return html
e032aec9
C
55 }
56
9aac4423
C
57 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
58 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
92bf2f62
C
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 (
453e83ea 73 loader: () => Bluebird<MAccountActor | MChannelActor>,
92bf2f62
C
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) {
c08579e1 84 res.status(404)
92bf2f62
C
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)
9aac4423
C
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)
a1587156 97 if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
9aac4423
C
98
99 const buffer = await readFile(path)
100
101 let html = buffer.toString()
102
7738273b 103 if (paramLang) html = ClientHtml.addHtmlLang(html, paramLang)
9aac4423 104 html = ClientHtml.addCustomCSS(html)
a8b666e9 105 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 106
a1587156 107 ClientHtml.htmlCache[path] = html
9aac4423
C
108
109 return html
e032aec9
C
110 }
111
7738273b 112 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
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, {
6dd9de95 121 secure: WEBSERVER.SCHEME === 'https',
bc90883f 122 sameSite: 'none',
e032aec9
C
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
7738273b
RK
135 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
136 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
137 }
138
9aac4423
C
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>`
e032aec9
C
144
145 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
146 }
147
9aac4423
C
148 private static addDescriptionTag (htmlStringPage: string, description?: string) {
149 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
150 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
151
152 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
153 }
154
155 private static addCustomCSS (htmlStringPage: string) {
ffb321be 156 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
157
158 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
159 }
160
a8b666e9
C
161 private static async addAsyncPluginCSS (htmlStringPage: string) {
162 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 163 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
164
165 const fileHash = sha256(globalCSSContent)
166 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
167
168 return htmlStringPage.replace('</head>', linkTag + '</head>')
169 }
170
453e83ea 171 private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: MVideo) {
6dd9de95
C
172 const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
173 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
e032aec9
C
174
175 const videoNameEscaped = escapeHTML(video.name)
176 const videoDescriptionEscaped = escapeHTML(video.description)
6dd9de95 177 const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
e032aec9
C
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,
fb651cf2 188 'og:video:type': 'text/html',
e032aec9
C
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',
6dd9de95 209 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
e032aec9
C
210 title: videoNameEscaped
211 }
212 ]
213
214 const schemaTags = {
215 '@context': 'http://schema.org',
216 '@type': 'VideoObject',
a1587156
C
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
e032aec9
C
225 }
226
227 let tagsString = ''
228
229 // Opengraph
230 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 231 const tagValue = openGraphMetaTags[tagName]
e032aec9
C
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
c04eb647
C
244 // SEO, use origin video url so Google does not index remote videos
245 tagsString += `<link rel="canonical" href="${video.url}" />`
e032aec9 246
92bf2f62
C
247 return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
248 }
249
453e83ea 250 private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: MAccountActor | MChannelActor) {
92bf2f62
C
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)
e032aec9
C
259 }
260}