]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/client.ts
df2eee9c987278711ffc3f1f1ce85668441a390b
[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', '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 duration: video.getActivityStreamDuration(),
104 thumbnailURL: previewUrl,
105 contentURL: videoUrl,
106 embedURL: embedUrl,
107 uploadDate: video.createdAt
108 }
109
110 let tagsString = ''
111
112 // Opengraph
113 Object.keys(openGraphMetaTags).forEach(tagName => {
114 const tagValue = openGraphMetaTags[tagName]
115
116 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
117 })
118
119 // OEmbed
120 for (const oembedLinkTag of oembedLinkTags) {
121 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
122 }
123
124 // Schema.org
125 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
126
127 return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
128 }
129
130 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
131 const videoId = '' + req.params.id
132 let videoPromise: Bluebird<VideoModel>
133
134 // Let Angular application handle errors
135 if (validator.isUUID(videoId, 4)) {
136 videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
137 } else if (validator.isInt(videoId)) {
138 videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
139 } else {
140 return res.sendFile(indexPath)
141 }
142
143 let [ file, video ] = await Promise.all([
144 readFileBufferPromise(indexPath),
145 videoPromise
146 ])
147
148 const html = file.toString()
149
150 // Let Angular application handle errors
151 if (!video) return res.sendFile(indexPath)
152
153 const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
154 res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)
155 }