Fix oauth server module
[oweals/peertube.git] / server / lib / client-html.ts
1 import * as express from 'express'
2 import * as Bluebird from 'bluebird'
3 import { buildFileLocale, getDefaultLocale, is18nLocale, POSSIBLE_LOCALES } from '../../shared/models/i18n/i18n'
4 import { CONFIG, CUSTOM_HTML_TAG_COMMENTS, EMBED_SIZE, STATIC_PATHS } from '../initializers'
5 import { join } from 'path'
6 import { escapeHTML } from '../helpers/core-utils'
7 import { VideoModel } from '../models/video/video'
8 import * as validator from 'validator'
9 import { VideoPrivacy } from '../../shared/models/videos'
10 import { readFile } from 'fs-extra'
11
12 export class ClientHtml {
13
14   private static htmlCache: { [path: string]: string } = {}
15
16   static invalidCache () {
17     ClientHtml.htmlCache = {}
18   }
19
20   static async getIndexHTML (req: express.Request, res: express.Response, paramLang?: string) {
21     const path = ClientHtml.getIndexPath(req, res, paramLang)
22     if (ClientHtml.htmlCache[path]) return ClientHtml.htmlCache[path]
23
24     const buffer = await readFile(path)
25
26     let html = buffer.toString()
27
28     html = ClientHtml.addTitleTag(html)
29     html = ClientHtml.addDescriptionTag(html)
30     html = ClientHtml.addCustomCSS(html)
31
32     ClientHtml.htmlCache[path] = html
33
34     return html
35   }
36
37   static async getWatchHTMLPage (videoId: string, req: express.Request, res: express.Response) {
38     let videoPromise: Bluebird<VideoModel>
39
40     // Let Angular application handle errors
41     if (validator.isUUID(videoId, 4)) {
42       videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
43     } else if (validator.isInt(videoId)) {
44       videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
45     } else {
46       return ClientHtml.getIndexHTML(req, res)
47     }
48
49     const [ html, video ] = await Promise.all([
50       ClientHtml.getIndexHTML(req, res),
51       videoPromise
52     ])
53
54     // Let Angular application handle errors
55     if (!video || video.privacy === VideoPrivacy.PRIVATE) {
56       return ClientHtml.getIndexHTML(req, res)
57     }
58
59     return ClientHtml.addOpenGraphAndOEmbedTags(html, video)
60   }
61
62   private static getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
63     let lang: string
64
65     // Check param lang validity
66     if (paramLang && is18nLocale(paramLang)) {
67       lang = paramLang
68
69       // Save locale in cookies
70       res.cookie('clientLanguage', lang, {
71         secure: CONFIG.WEBSERVER.SCHEME === 'https',
72         sameSite: true,
73         maxAge: 1000 * 3600 * 24 * 90 // 3 months
74       })
75
76     } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
77       lang = req.cookies.clientLanguage
78     } else {
79       lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
80     }
81
82     return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
83   }
84
85   private static addTitleTag (htmlStringPage: string) {
86     const titleTag = '<title>' + CONFIG.INSTANCE.NAME + '</title>'
87
88     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.TITLE, titleTag)
89   }
90
91   private static addDescriptionTag (htmlStringPage: string) {
92     const descriptionTag = `<meta name="description" content="${CONFIG.INSTANCE.SHORT_DESCRIPTION}" />`
93
94     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.DESCRIPTION, descriptionTag)
95   }
96
97   private static addCustomCSS (htmlStringPage: string) {
98     const styleTag = '<style class="custom-css-style">' + CONFIG.INSTANCE.CUSTOMIZATIONS.CSS + '</style>'
99
100     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.CUSTOM_CSS, styleTag)
101   }
102
103   private static addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
104     const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
105     const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
106
107     const videoNameEscaped = escapeHTML(video.name)
108     const videoDescriptionEscaped = escapeHTML(video.description)
109     const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedStaticPath()
110
111     const openGraphMetaTags = {
112       'og:type': 'video',
113       'og:title': videoNameEscaped,
114       'og:image': previewUrl,
115       'og:url': videoUrl,
116       'og:description': videoDescriptionEscaped,
117
118       'og:video:url': embedUrl,
119       'og:video:secure_url': embedUrl,
120       'og:video:type': 'text/html',
121       'og:video:width': EMBED_SIZE.width,
122       'og:video:height': EMBED_SIZE.height,
123
124       'name': videoNameEscaped,
125       'description': videoDescriptionEscaped,
126       'image': previewUrl,
127
128       'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
129       'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
130       'twitter:title': videoNameEscaped,
131       'twitter:description': videoDescriptionEscaped,
132       'twitter:image': previewUrl,
133       'twitter:player': embedUrl,
134       'twitter:player:width': EMBED_SIZE.width,
135       'twitter:player:height': EMBED_SIZE.height
136     }
137
138     const oembedLinkTags = [
139       {
140         type: 'application/json+oembed',
141         href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
142         title: videoNameEscaped
143       }
144     ]
145
146     const schemaTags = {
147       '@context': 'http://schema.org',
148       '@type': 'VideoObject',
149       name: videoNameEscaped,
150       description: videoDescriptionEscaped,
151       thumbnailUrl: previewUrl,
152       uploadDate: video.createdAt.toISOString(),
153       duration: video.getActivityStreamDuration(),
154       contentUrl: videoUrl,
155       embedUrl: embedUrl,
156       interactionCount: video.views
157     }
158
159     let tagsString = ''
160
161     // Opengraph
162     Object.keys(openGraphMetaTags).forEach(tagName => {
163       const tagValue = openGraphMetaTags[tagName]
164
165       tagsString += `<meta property="${tagName}" content="${tagValue}" />`
166     })
167
168     // OEmbed
169     for (const oembedLinkTag of oembedLinkTags) {
170       tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
171     }
172
173     // Schema.org
174     tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
175
176     // SEO
177     tagsString += `<link rel="canonical" href="${videoUrl}" />`
178
179     return htmlStringPage.replace(CUSTOM_HTML_TAG_COMMENTS.OPENGRAPH_AND_OEMBED, tagsString)
180   }
181 }