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