]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/client-html.ts
Translated using Weblate (Chinese (Traditional))
[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'
caf2aaf4 3import { CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, PLUGIN_GLOBAL_CSS_PATH, WEBSERVER, FILES_CONTENT_HASH } 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)
caf2aaf4
K
104 html = ClientHtml.addManifestContentHash(html)
105 html = ClientHtml.addFaviconContentHash(html)
106 html = ClientHtml.addLogoContentHash(html)
9aac4423 107 html = ClientHtml.addCustomCSS(html)
a8b666e9 108 html = await ClientHtml.addAsyncPluginCSS(html)
9aac4423 109
a1587156 110 ClientHtml.htmlCache[path] = html
9aac4423
C
111
112 return html
e032aec9
C
113 }
114
7738273b 115 private static getIndexPath (req: express.Request, res: express.Response, paramLang: string) {
e032aec9
C
116 let lang: string
117
118 // Check param lang validity
119 if (paramLang && is18nLocale(paramLang)) {
120 lang = paramLang
121
122 // Save locale in cookies
123 res.cookie('clientLanguage', lang, {
6dd9de95 124 secure: WEBSERVER.SCHEME === 'https',
bc90883f 125 sameSite: 'none',
e032aec9
C
126 maxAge: 1000 * 3600 * 24 * 90 // 3 months
127 })
128
129 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
130 lang = req.cookies.clientLanguage
131 } else {
132 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
133 }
134
135 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
136 }
137
7738273b
RK
138 private static addHtmlLang (htmlStringPage: string, paramLang: string) {
139 return htmlStringPage.replace('<html>', `<html lang="${paramLang}">`)
140 }
141
caf2aaf4
K
142 private static addManifestContentHash (htmlStringPage: string) {
143 return htmlStringPage.replace('[manifestContentHash]', FILES_CONTENT_HASH.MANIFEST)
144 }
145
146 private static addFaviconContentHash(htmlStringPage: string) {
147 return htmlStringPage.replace('[faviconContentHash]', FILES_CONTENT_HASH.FAVICON)
148 }
149
150 private static addLogoContentHash(htmlStringPage: string) {
151 return htmlStringPage.replace('[logoContentHash]', FILES_CONTENT_HASH.LOGO)
152 }
153
9aac4423
C
154 private static addTitleTag (htmlStringPage: string, title?: string) {
155 let text = title || CONFIG.INSTANCE.NAME
156 if (title) text += ` - ${CONFIG.INSTANCE.NAME}`
157
158 const titleTag = `<title>${text}</title>`
e032aec9
C
159
160 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
161 }
162
9aac4423
C
163 private static addDescriptionTag (htmlStringPage: string, description?: string) {
164 const content = description || CONFIG.INSTANCE.SHORT_DESCRIPTION
165 const descriptionTag = `<meta name="description" content="${content}" />`
e032aec9
C
166
167 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
168 }
169
170 private static addCustomCSS (htmlStringPage: string) {
ffb321be 171 const styleTag = `<style class="custom-css-style">${CONFIG.INSTANCE.CUSTOMIZATIONS.CSS}</style>`
e032aec9
C
172
173 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
174 }
175
a8b666e9
C
176 private static async addAsyncPluginCSS (htmlStringPage: string) {
177 const globalCSSContent = await readFile(PLUGIN_GLOBAL_CSS_PATH)
3e753302 178 if (globalCSSContent.byteLength === 0) return htmlStringPage
a8b666e9
C
179
180 const fileHash = sha256(globalCSSContent)
181 const linkTag = `<link rel="stylesheet" href="/plugins/global.css?hash=${fileHash}" />`
ffb321be
C
182
183 return htmlStringPage.replace('</head>', linkTag + '</head>')
184 }
185
453e83ea 186 private static addVideoOpenGraphAndOEmbedTags (htmlStringPage: string, video: MVideo) {
6dd9de95
C
187 const previewUrl = WEBSERVER.URL + video.getPreviewStaticPath()
188 const videoUrl = WEBSERVER.URL + video.getWatchStaticPath()
e032aec9
C
189
190 const videoNameEscaped = escapeHTML(video.name)
191 const videoDescriptionEscaped = escapeHTML(video.description)
6dd9de95 192 const embedUrl = WEBSERVER.URL + video.getEmbedStaticPath()
e032aec9
C
193
194 const openGraphMetaTags = {
195 'og:type': 'video',
196 'og:title': videoNameEscaped,
197 'og:image': previewUrl,
198 'og:url': videoUrl,
199 'og:description': videoDescriptionEscaped,
200
201 'og:video:url': embedUrl,
202 'og:video:secure_url': embedUrl,
fb651cf2 203 'og:video:type': 'text/html',
e032aec9
C
204 'og:video:width': EMBED_SIZE.width,
205 'og:video:height': EMBED_SIZE.height,
206
207 'name': videoNameEscaped,
208 'description': videoDescriptionEscaped,
209 'image': previewUrl,
210
211 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
212 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
213 'twitter:title': videoNameEscaped,
214 'twitter:description': videoDescriptionEscaped,
215 'twitter:image': previewUrl,
216 'twitter:player': embedUrl,
217 'twitter:player:width': EMBED_SIZE.width,
218 'twitter:player:height': EMBED_SIZE.height
219 }
220
221 const oembedLinkTags = [
222 {
223 type: 'application/json+oembed',
6dd9de95 224 href: WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
e032aec9
C
225 title: videoNameEscaped
226 }
227 ]
228
229 const schemaTags = {
230 '@context': 'http://schema.org',
231 '@type': 'VideoObject',
a1587156
C
232 'name': videoNameEscaped,
233 'description': videoDescriptionEscaped,
234 'thumbnailUrl': previewUrl,
235 'uploadDate': video.createdAt.toISOString(),
236 'duration': getActivityStreamDuration(video.duration),
237 'contentUrl': videoUrl,
238 'embedUrl': embedUrl,
239 'interactionCount': video.views
e032aec9
C
240 }
241
242 let tagsString = ''
243
244 // Opengraph
245 Object.keys(openGraphMetaTags).forEach(tagName => {
a1587156 246 const tagValue = openGraphMetaTags[tagName]
e032aec9
C
247
248 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
249 })
250
251 // OEmbed
252 for (const oembedLinkTag of oembedLinkTags) {
253 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
254 }
255
256 // Schema.org
257 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
258
c04eb647
C
259 // SEO, use origin video url so Google does not index remote videos
260 tagsString += `<link rel="canonical" href="${video.url}" />`
e032aec9 261
92bf2f62
C
262 return this.addOpenGraphAndOEmbedTags(htmlStringPage, tagsString)
263 }
264
453e83ea 265 private static addAccountOrChannelMetaTags (htmlStringPage: string, entity: MAccountActor | MChannelActor) {
92bf2f62
C
266 // SEO, use origin account or channel URL
267 const metaTags = `<link rel="canonical" href="${entity.Actor.url}" />`
268
269 return this.addOpenGraphAndOEmbedTags(htmlStringPage, metaTags)
270 }
271
272 private static addOpenGraphAndOEmbedTags (htmlStringPage: string, metaTags: string) {
273 return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.META_TAGS, metaTags)
e032aec9
C
274 }
275}