]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Update validator dependency
[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'
453e83ea 16import { MAccountActor, MChannelActor, MVideo } from '../typings/models'
e032aec9
C
17
18export class ClientHtml {
19
92bf2f62 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
C
28 static async getDefaultHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
29 const html = await ClientHtml.getIndexHTML(req, res, paramLang)
e032aec9 30
9aac4423
C
31 let customHtml = ClientHtml.addTitleTag(html)
32 customHtml = ClientHtml.addDescriptionTag(customHtml)
e032aec9 33
9aac4423 34 return customHtml
e032aec9
C
35 }
36
37 static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
e032aec9 38 // Let Angular application handle errors
92bf2f62 39 if (!validator.isInt(videoId) && !validator.isUUID(videoId, 4)) {
e032aec9
C
40 return ClientHtml.getIndexHTML(req, res)
41 }
42
43 const [ html, video ] = await Promise.all([
44 ClientHtml.getIndexHTML(req, res),
d636ab58 45 VideoModel.loadWithBlacklist(videoId)
e032aec9
C
46 ])
47
48 // Let Angular application handle errors
22a73cb8 49 if (!video || video.privacy === VideoPrivacy.PRIVATE || video.privacy === VideoPrivacy.INTERNAL || video.VideoBlacklist) {
e032aec9
C
50 return ClientHtml.getIndexHTML(req, res)
51 }
52
9aac4423
C
53 let customHtml = ClientHtml.addTitleTag(html, escapeHTML(video.name))
54 customHtml = ClientHtml.addDescriptionTag(customHtml, escapeHTML(video.description))
92bf2f62
C
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 (
453e83ea 69 loader: () => Bluebird<MAccountActor | MChannelActor>,
92bf2f62
C
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)
9aac4423
C
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)
92bf2f62 92 if (ClientHtml.htmlCache[ path ]) return ClientHtml.htmlCache[ path ]
9aac4423
C
93
94 const buffer = await readFile(path)
95
96 let html = buffer.toString()
97
98 html = ClientHtml.addCustomCSS(html)
a8b666e9 99 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 100
92bf2f62 101 ClientHtml.htmlCache[ path ] = html
9aac4423
C
102
103 return html
e032aec9
C
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, {
6dd9de95 115 secure: WEBSERVER.SCHEME === 'https',
e032aec9
C
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
9aac4423
C
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>`
e032aec9
C
134
135 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
136 }
137
9aac4423
C
138 private static addDescriptionTag (htmlStringPage: string, description?: string) {
139 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
140 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
141
142 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
143 }
144
145 private static addCustomCSS (htmlStringPage: string) {
ffb321be 146 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
147
148 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
149 }
150
a8b666e9
C
151 private static async addAsyncPluginCSS (htmlStringPage: string) {
152 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 153 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
154
155 const fileHash = sha256(globalCSSContent)
156 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
157
158 return htmlStringPage.replace('</head>', linkTag + '</head>')
159 }
160
453e83ea 161 private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: MVideo) {
6dd9de95
C
162 const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
163 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
e032aec9
C
164
165 const videoNameEscaped = escapeHTML(video.name)
166 const videoDescriptionEscaped = escapeHTML(video.description)
6dd9de95 167 const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
e032aec9
C
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,
fb651cf2 178 'og:video:type': 'text/html',
e032aec9
C
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',
6dd9de95 199 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
e032aec9
C
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(),
098eb377 211 duration: getActivityStreamDuration(video.duration),
e032aec9
C
212 contentUrl: videoUrl,
213 embedUrl: embedUrl,
214 interactionCount: video.views
215 }
216
217 let tagsString = ''
218
219 // Opengraph
220 Object.keys(openGraphMetaTags).forEach(tagName => {
92bf2f62 221 const tagValue = openGraphMetaTags[ tagName ]
e032aec9
C
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
c04eb647
C
234 // SEO, use origin video url so Google does not index remote videos
235 tagsString += `<link rel="canonical" href="${video.url}" />`
e032aec9 236
92bf2f62
C
237 return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
238 }
239
453e83ea 240 private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: MAccountActor | MChannelActor) {
92bf2f62
C
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)
e032aec9
C
249 }
250}