]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/client.ts
Improve tests when waiting pending jobs
[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'
74b7c6d4
C
10import { buildFileLocale, getCompleteLocale, getDefaultLocale, is18nLocale } from '../../shared/models'
11import { LOCALE_FILES } from '../../shared/models/i18n/i18n'
830bcd0f 12
65fcc311 13const clientsRouter = express.Router()
830bcd0f 14
e02643f3 15const distPath = join(root(), 'client', 'dist')
1f30a185 16const assetsImagesPath = join(root(), 'client', 'dist', 'assets', 'images')
e02643f3 17const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
830bcd0f 18
d8755eed 19// Special route that add OpenGraph and oEmbed tags
830bcd0f 20// Do not use a template engine for a so little thing
eb080476
C
21clientsRouter.use('/videos/watch/:id',
22 asyncMiddleware(generateWatchHtmlPage)
23)
830bcd0f 24
075f16ca 25clientsRouter.use('/videos/embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
830bcd0f
C
26 res.sendFile(embedPath)
27})
28
79530164 29// Static HTML/CSS/JS client files
78967fca
C
30
31const staticClientFiles = [
32 'manifest.json',
33 'ngsw-worker.js',
34 'ngsw.json'
35]
36for (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
65fcc311 41clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
6bafac54 42clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
79530164 43
e945b184 44clientsRouter.use('/client/locales/:locale/:file.json', function (req, res) {
7ce44a74
C
45 const locale = req.params.locale
46 const file = req.params.file
47
74b7c6d4
C
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`))
e945b184
C
52 }
53
54 return res.sendStatus(404)
55})
56
79530164 57// 404 for static files not found
075f16ca 58clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
79530164
C
59 res.sendStatus(404)
60})
61
989e526a
C
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
64clientsRouter.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
830bcd0f
C
72// ---------------------------------------------------------------------------
73
65fcc311
C
74export {
75 clientsRouter
76}
830bcd0f
C
77
78// ---------------------------------------------------------------------------
79
989e526a
C
80function 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 {
74b7c6d4 87 // lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
f8b44753
C
88 // Disable auto language for now
89 lang = getDefaultLocale()
989e526a
C
90 }
91
74b7c6d4 92 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
989e526a
C
93}
94
3fd3ab2d 95function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
d38309c3 96 const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
d8755eed 97 const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
830bcd0f 98
a434c465
C
99 const videoNameEscaped = escapeHTML(video.name)
100 const videoDescriptionEscaped = escapeHTML(video.description)
7ff7802a 101 const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
49347a0a 102
d8755eed 103 const openGraphMetaTags = {
830bcd0f 104 'og:type': 'video',
a434c465 105 'og:title': videoNameEscaped,
41b5da1d 106 'og:image': previewUrl,
830bcd0f 107 'og:url': videoUrl,
a434c465 108 'og:description': videoDescriptionEscaped,
830bcd0f 109
7ff7802a
C
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
a434c465
C
116 'name': videoNameEscaped,
117 'description': videoDescriptionEscaped,
41b5da1d 118 'image': previewUrl,
830bcd0f 119
8be1afa1
C
120 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
121 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
a434c465
C
122 'twitter:title': videoNameEscaped,
123 'twitter:description': videoDescriptionEscaped,
7ff7802a
C
124 'twitter:image': previewUrl,
125 'twitter:player': embedUrl,
126 'twitter:player:width': EMBED_SIZE.width,
127 'twitter:player:height': EMBED_SIZE.height
830bcd0f
C
128 }
129
d8755eed
C
130 const oembedLinkTags = [
131 {
132 type: 'application/json+oembed',
133 href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
a434c465 134 title: videoNameEscaped
d8755eed
C
135 }
136 ]
137
093237cf 138 const schemaTags = {
c7b1b92b
C
139 '@context': 'http://schema.org',
140 '@type': 'VideoObject',
093237cf
C
141 name: videoNameEscaped,
142 description: videoDescriptionEscaped,
acbffe9c
C
143 thumbnailUrl: previewUrl,
144 uploadDate: video.createdAt.toISOString(),
093237cf 145 duration: video.getActivityStreamDuration(),
acbffe9c
C
146 contentUrl: videoUrl,
147 embedUrl: embedUrl,
148 interactionCount: video.views
093237cf
C
149 }
150
830bcd0f 151 let tagsString = ''
c7b1b92b
C
152
153 // Opengraph
d8755eed
C
154 Object.keys(openGraphMetaTags).forEach(tagName => {
155 const tagValue = openGraphMetaTags[tagName]
830bcd0f 156
d8755eed 157 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
830bcd0f
C
158 })
159
c7b1b92b 160 // OEmbed
d8755eed
C
161 for (const oembedLinkTag of oembedLinkTags) {
162 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
163 }
164
c7b1b92b
C
165 // Schema.org
166 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
093237cf 167
acbffe9c
C
168 // SEO
169 tagsString += `<link rel="canonical" href="${videoUrl}" />`
170
d8755eed 171 return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
830bcd0f
C
172}
173
eb080476 174async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
69818c93 175 const videoId = '' + req.params.id
3fd3ab2d 176 let videoPromise: Bluebird<VideoModel>
73ce7f96
C
177
178 // Let Angular application handle errors
0a6658fd 179 if (validator.isUUID(videoId, 4)) {
3fd3ab2d 180 videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
0a6658fd 181 } else if (validator.isInt(videoId)) {
3fd3ab2d 182 videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
0a6658fd 183 } else {
989e526a 184 return res.sendFile(getIndexPath(req))
0a6658fd 185 }
73ce7f96 186
eb080476 187 let [ file, video ] = await Promise.all([
989e526a 188 readFileBufferPromise(getIndexPath(req)),
0a6658fd 189 videoPromise
6fcd19ba 190 ])
830bcd0f 191
eb080476 192 const html = file.toString()
73ce7f96 193
eb080476 194 // Let Angular application handle errors
989e526a 195 if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req))
eb080476
C
196
197 const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
198 res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
830bcd0f 199}