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