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