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