]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/client.ts
5413f61e8ba36acb33a23d2ea226024a283fde63
[github/Chocobozzz/PeerTube.git] / server / controllers / client.ts
1 import * as Bluebird from 'bluebird'
2 import * as express from 'express'
3 import { join } from 'path'
4 import * as validator from 'validator'
5 import { escapeHTML, readFileBufferPromise, root } from '../helpers/core-utils'
6 import { ACCEPT_HEADERS, CONFIG, EMBED_SIZE, OPENGRAPH_AND_OEMBED_COMMENT, STATIC_MAX_AGE, STATIC_PATHS } from '../initializers'
7 import { asyncMiddleware } from '../middlewares'
8 import { VideoModel } from '../models/video/video'
9 import { VideoPrivacy } from '../../shared/models/videos'
10 import {
11 buildFileLocale,
12 getCompleteLocale,
13 getDefaultLocale,
14 is18nLocale,
15 LOCALE_FILES,
16 POSSIBLE_LOCALES
17 } from '../../shared/models/i18n/i18n'
18
19 const clientsRouter = express.Router()
20
21 const distPath = join(root(), 'client', 'dist')
22 const assetsImagesPath = join(root(), 'client', 'dist', 'assets', 'images')
23 const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
24 const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
25
26 // Special route that add OpenGraph and oEmbed tags
27 // Do not use a template engine for a so little thing
28 clientsRouter.use('/videos/watch/:id',
29 asyncMiddleware(generateWatchHtmlPage)
30 )
31
32 clientsRouter.use('' +
33 '/videos/embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
34 res.sendFile(embedPath)
35 })
36 clientsRouter.use('' +
37 '/videos/test-embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
38 res.sendFile(testEmbedPath)
39 })
40
41 // Static HTML/CSS/JS client files
42
43 const staticClientFiles = [
44 'manifest.json',
45 'ngsw-worker.js',
46 'ngsw.json'
47 ]
48 for (const staticClientFile of staticClientFiles) {
49 const path = join(root(), 'client', 'dist', staticClientFile)
50 clientsRouter.use('/' + staticClientFile, express.static(path, { maxAge: STATIC_MAX_AGE }))
51 }
52
53 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
54 clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
55
56 clientsRouter.use('/client/locales/:locale/:file.json', function (req, res) {
57 const locale = req.params.locale
58 const file = req.params.file
59
60 if (is18nLocale(locale) && LOCALE_FILES.indexOf(file) !== -1) {
61 const completeLocale = getCompleteLocale(locale)
62 const completeFileLocale = buildFileLocale(completeLocale)
63 return res.sendFile(join(__dirname, `../../../client/dist/locale/${file}_${completeFileLocale}.json`))
64 }
65
66 return res.sendStatus(404)
67 })
68
69 // 404 for static files not found
70 clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
71 res.sendStatus(404)
72 })
73
74 // Always serve index client page (the client is a single page application, let it handle routing)
75 // Try to provide the right language index.html
76 clientsRouter.use('/(:language)?', function (req, res) {
77 if (req.accepts(ACCEPT_HEADERS) === 'html') {
78 return res.sendFile(getIndexPath(req, res, req.params.language))
79 }
80
81 return res.status(404).end()
82 })
83
84 // ---------------------------------------------------------------------------
85
86 export {
87 clientsRouter
88 }
89
90 // ---------------------------------------------------------------------------
91
92 function getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
93 let lang: string
94
95 // Check param lang validity
96 if (paramLang && is18nLocale(paramLang)) {
97 lang = paramLang
98
99 // Save locale in cookies
100 res.cookie('clientLanguage', lang, {
101 secure: CONFIG.WEBSERVER.SCHEME === 'https',
102 sameSite: true,
103 maxAge: 1000 * 3600 * 24 * 90 // 3 months
104 })
105
106 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
107 lang = req.cookies.clientLanguage
108 } else {
109 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
110 }
111
112 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
113 }
114
115 function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
116 const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
117 const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
118
119 const videoNameEscaped = escapeHTML(video.name)
120 const videoDescriptionEscaped = escapeHTML(video.description)
121 const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
122
123 const openGraphMetaTags = {
124 'og:type': 'video',
125 'og:title': videoNameEscaped,
126 'og:image': previewUrl,
127 'og:url': videoUrl,
128 'og:description': videoDescriptionEscaped,
129
130 'og:video:url': embedUrl,
131 'og:video:secure_url': embedUrl,
132 'og:video:type': 'text/html',
133 'og:video:width': EMBED_SIZE.width,
134 'og:video:height': EMBED_SIZE.height,
135
136 'name': videoNameEscaped,
137 'description': videoDescriptionEscaped,
138 'image': previewUrl,
139
140 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
141 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
142 'twitter:title': videoNameEscaped,
143 'twitter:description': videoDescriptionEscaped,
144 'twitter:image': previewUrl,
145 'twitter:player': embedUrl,
146 'twitter:player:width': EMBED_SIZE.width,
147 'twitter:player:height': EMBED_SIZE.height
148 }
149
150 const oembedLinkTags = [
151 {
152 type: 'application/json+oembed',
153 href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
154 title: videoNameEscaped
155 }
156 ]
157
158 const schemaTags = {
159 '@context': 'http://schema.org',
160 '@type': 'VideoObject',
161 name: videoNameEscaped,
162 description: videoDescriptionEscaped,
163 thumbnailUrl: previewUrl,
164 uploadDate: video.createdAt.toISOString(),
165 duration: video.getActivityStreamDuration(),
166 contentUrl: videoUrl,
167 embedUrl: embedUrl,
168 interactionCount: video.views
169 }
170
171 let tagsString = ''
172
173 // Opengraph
174 Object.keys(openGraphMetaTags).forEach(tagName => {
175 const tagValue = openGraphMetaTags[tagName]
176
177 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
178 })
179
180 // OEmbed
181 for (const oembedLinkTag of oembedLinkTags) {
182 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
183 }
184
185 // Schema.org
186 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
187
188 // SEO
189 tagsString += `<link rel="canonical" href="${videoUrl}" />`
190
191 return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
192 }
193
194 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
195 const videoId = '' + req.params.id
196 let videoPromise: Bluebird<VideoModel>
197
198 // Let Angular application handle errors
199 if (validator.isUUID(videoId, 4)) {
200 videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
201 } else if (validator.isInt(videoId)) {
202 videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
203 } else {
204 return res.sendFile(getIndexPath(req, res))
205 }
206
207 let [ file, video ] = await Promise.all([
208 readFileBufferPromise(getIndexPath(req, res)),
209 videoPromise
210 ])
211
212 const html = file.toString()
213
214 // Let Angular application handle errors
215 if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req, res))
216
217 const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
218 res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
219 }