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