b5dc7b7eddf13d9ca2cc121dfa16ff065852e8f8
[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 { CONFIG, EMBED_SIZE, OPENGRAPH_AND_OEMBED_COMMENT, STATIC_MAX_AGE, STATIC_PATHS } from '../initializers'
7 import { asyncMiddleware } from '../middlewares'
8 import { VideoModel } from '../models/video/video'
9
10 const clientsRouter = express.Router()
11
12 const distPath = join(root(), 'client', 'dist')
13 const assetsImagesPath = join(root(), 'client', 'dist', 'assets', 'images')
14 const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
15 const indexPath = join(distPath, 'index.html')
16
17 // Special route that add OpenGraph and oEmbed tags
18 // Do not use a template engine for a so little thing
19 clientsRouter.use('/videos/watch/:id',
20   asyncMiddleware(generateWatchHtmlPage)
21 )
22
23 clientsRouter.use('/videos/embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
24   res.sendFile(embedPath)
25 })
26
27 // Static HTML/CSS/JS client files
28
29 const staticClientFiles = [
30   'manifest.json',
31   'ngsw-worker.js',
32   'ngsw.json'
33 ]
34 for (const staticClientFile of staticClientFiles) {
35   const path = join(root(), 'client', 'dist', staticClientFile)
36   clientsRouter.use('/' + staticClientFile, express.static(path, { maxAge: STATIC_MAX_AGE }))
37 }
38
39 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
40 clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
41
42 // 404 for static files not found
43 clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
44   res.sendStatus(404)
45 })
46
47 // ---------------------------------------------------------------------------
48
49 export {
50   clientsRouter
51 }
52
53 // ---------------------------------------------------------------------------
54
55 function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
56   const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
57   const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
58
59   const videoNameEscaped = escapeHTML(video.name)
60   const videoDescriptionEscaped = escapeHTML(video.description)
61   const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
62
63   const openGraphMetaTags = {
64     'og:type': 'video',
65     'og:title': videoNameEscaped,
66     'og:image': previewUrl,
67     'og:url': videoUrl,
68     'og:description': videoDescriptionEscaped,
69
70     'og:video:url': embedUrl,
71     'og:video:secure_url': embedUrl,
72     'og:video:type': 'text/html',
73     'og:video:width': EMBED_SIZE.width,
74     'og:video:height': EMBED_SIZE.height,
75
76     'name': videoNameEscaped,
77     'description': videoDescriptionEscaped,
78     'image': previewUrl,
79
80     'twitter:card': 'summary_large_image',
81     'twitter:site': '@Chocobozzz',
82     'twitter:title': videoNameEscaped,
83     'twitter:description': videoDescriptionEscaped,
84     'twitter:image': previewUrl,
85     'twitter:player': embedUrl,
86     'twitter:player:width': EMBED_SIZE.width,
87     'twitter:player:height': EMBED_SIZE.height
88   }
89
90   const oembedLinkTags = [
91     {
92       type: 'application/json+oembed',
93       href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
94       title: videoNameEscaped
95     }
96   ]
97
98   const schemaTags = {
99     '@context': 'http://schema.org',
100     '@type': 'VideoObject',
101     name: videoNameEscaped,
102     description: videoDescriptionEscaped,
103     thumbnailUrl: previewUrl,
104     uploadDate: video.createdAt.toISOString(),
105     duration: video.getActivityStreamDuration(),
106     contentUrl: videoUrl,
107     embedUrl: embedUrl,
108     interactionCount: video.views
109   }
110
111   let tagsString = ''
112
113   // Opengraph
114   Object.keys(openGraphMetaTags).forEach(tagName => {
115     const tagValue = openGraphMetaTags[tagName]
116
117     tagsString += `<meta property="${tagName}" content="${tagValue}" />`
118   })
119
120   // OEmbed
121   for (const oembedLinkTag of oembedLinkTags) {
122     tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
123   }
124
125   // Schema.org
126   tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
127
128   // SEO
129   tagsString += `<link rel="canonical" href="${videoUrl}" />`
130
131   return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
132 }
133
134 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
135   const videoId = '' + req.params.id
136   let videoPromise: Bluebird<VideoModel>
137
138   // Let Angular application handle errors
139   if (validator.isUUID(videoId, 4)) {
140     videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
141   } else if (validator.isInt(videoId)) {
142     videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
143   } else {
144     return res.sendFile(indexPath)
145   }
146
147   let [ file, video ] = await Promise.all([
148     readFileBufferPromise(indexPath),
149     videoPromise
150   ])
151
152   const html = file.toString()
153
154   // Let Angular application handle errors
155   if (!video) return res.sendFile(indexPath)
156
157   const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
158   res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
159 }