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