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