Disable auto language
[oweals/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     // Disable auto language for now
82     lang = getDefaultLocale()
83   }
84
85   return join(__dirname, '../../../client/dist/' + lang + '/index.html')
86 }
87
88 function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
89   const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
90   const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
91
92   const videoNameEscaped = escapeHTML(video.name)
93   const videoDescriptionEscaped = escapeHTML(video.description)
94   const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
95
96   const openGraphMetaTags = {
97     'og:type': 'video',
98     'og:title': videoNameEscaped,
99     'og:image': previewUrl,
100     'og:url': videoUrl,
101     'og:description': videoDescriptionEscaped,
102
103     'og:video:url': embedUrl,
104     'og:video:secure_url': embedUrl,
105     'og:video:type': 'text/html',
106     'og:video:width': EMBED_SIZE.width,
107     'og:video:height': EMBED_SIZE.height,
108
109     'name': videoNameEscaped,
110     'description': videoDescriptionEscaped,
111     'image': previewUrl,
112
113     'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
114     'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
115     'twitter:title': videoNameEscaped,
116     'twitter:description': videoDescriptionEscaped,
117     'twitter:image': previewUrl,
118     'twitter:player': embedUrl,
119     'twitter:player:width': EMBED_SIZE.width,
120     'twitter:player:height': EMBED_SIZE.height
121   }
122
123   const oembedLinkTags = [
124     {
125       type: 'application/json+oembed',
126       href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
127       title: videoNameEscaped
128     }
129   ]
130
131   const schemaTags = {
132     '@context': 'http://schema.org',
133     '@type': 'VideoObject',
134     name: videoNameEscaped,
135     description: videoDescriptionEscaped,
136     thumbnailUrl: previewUrl,
137     uploadDate: video.createdAt.toISOString(),
138     duration: video.getActivityStreamDuration(),
139     contentUrl: videoUrl,
140     embedUrl: embedUrl,
141     interactionCount: video.views
142   }
143
144   let tagsString = ''
145
146   // Opengraph
147   Object.keys(openGraphMetaTags).forEach(tagName => {
148     const tagValue = openGraphMetaTags[tagName]
149
150     tagsString += `<meta property="${tagName}" content="${tagValue}" />`
151   })
152
153   // OEmbed
154   for (const oembedLinkTag of oembedLinkTags) {
155     tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
156   }
157
158   // Schema.org
159   tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
160
161   // SEO
162   tagsString += `<link rel="canonical" href="${videoUrl}" />`
163
164   return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
165 }
166
167 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
168   const videoId = '' + req.params.id
169   let videoPromise: Bluebird<VideoModel>
170
171   // Let Angular application handle errors
172   if (validator.isUUID(videoId, 4)) {
173     videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
174   } else if (validator.isInt(videoId)) {
175     videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
176   } else {
177     return res.sendFile(getIndexPath(req))
178   }
179
180   let [ file, video ] = await Promise.all([
181     readFileBufferPromise(getIndexPath(req)),
182     videoPromise
183   ])
184
185   const html = file.toString()
186
187   // Let Angular application handle errors
188   if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req))
189
190   const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
191   res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
192 }