bb02f5075e1a6af3b8bc5147988c2e2ea82b461f
[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', 'client', '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 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
29 clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
30
31 // 404 for static files not found
32 clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
33   res.sendStatus(404)
34 })
35
36 // ---------------------------------------------------------------------------
37
38 export {
39   clientsRouter
40 }
41
42 // ---------------------------------------------------------------------------
43
44 function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
45   const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
46   const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
47
48   const videoNameEscaped = escapeHTML(video.name)
49   const videoDescriptionEscaped = escapeHTML(video.description)
50   const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
51
52   const openGraphMetaTags = {
53     'og:type': 'video',
54     'og:title': videoNameEscaped,
55     'og:image': previewUrl,
56     'og:url': videoUrl,
57     'og:description': videoDescriptionEscaped,
58
59     'og:video:url': embedUrl,
60     'og:video:secure_url': embedUrl,
61     'og:video:type': 'text/html',
62     'og:video:width': EMBED_SIZE.width,
63     'og:video:height': EMBED_SIZE.height,
64
65     'name': videoNameEscaped,
66     'description': videoDescriptionEscaped,
67     'image': previewUrl,
68
69     'twitter:card': 'summary_large_image',
70     'twitter:site': '@Chocobozzz',
71     'twitter:title': videoNameEscaped,
72     'twitter:description': videoDescriptionEscaped,
73     'twitter:image': previewUrl,
74     'twitter:player': embedUrl,
75     'twitter:player:width': EMBED_SIZE.width,
76     'twitter:player:height': EMBED_SIZE.height
77   }
78
79   const oembedLinkTags = [
80     {
81       type: 'application/json+oembed',
82       href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
83       title: videoNameEscaped
84     }
85   ]
86
87   const schemaTags = {
88     name: videoNameEscaped,
89     description: videoDescriptionEscaped,
90     duration: video.getActivityStreamDuration(),
91     thumbnailURL: previewUrl,
92     contentURL: videoUrl,
93     embedURL: embedUrl,
94     uploadDate: video.createdAt
95   }
96
97   let tagsString = ''
98   Object.keys(openGraphMetaTags).forEach(tagName => {
99     const tagValue = openGraphMetaTags[tagName]
100
101     tagsString += `<meta property="${tagName}" content="${tagValue}" />`
102   })
103
104   for (const oembedLinkTag of oembedLinkTags) {
105     tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
106   }
107
108   tagsString += '<div itemprop="video" itemscope itemtype="http://schema.org/VideoObject">'
109   tagsString += '<h2>Video: <span itemprop="name">' + schemaTags.name + '</span></h2>'
110
111   Object.keys(schemaTags).forEach(tagName => {
112     const tagValue = schemaTags[tagName]
113     tagsString += `<meta itemprop="${tagName}" content="${tagValue}" />`
114   })
115
116   tagsString += '</div>'
117
118   return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
119 }
120
121 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
122   const videoId = '' + req.params.id
123   let videoPromise: Bluebird<VideoModel>
124
125   // Let Angular application handle errors
126   if (validator.isUUID(videoId, 4)) {
127     videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
128   } else if (validator.isInt(videoId)) {
129     videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
130   } else {
131     return res.sendFile(indexPath)
132   }
133
134   let [ file, video ] = await Promise.all([
135     readFileBufferPromise(indexPath),
136     videoPromise
137   ])
138
139   const html = file.toString()
140
141   // Let Angular application handle errors
142   if (!video) return res.sendFile(indexPath)
143
144   const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
145   res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
146 }