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