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