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