]>
Commit | Line | Data |
---|---|---|
1 | import * as Bluebird from 'bluebird' | |
2 | import * as express from 'express' | |
3 | import * as helmet from 'helmet' | |
4 | import { join } from 'path' | |
5 | import * as validator from 'validator' | |
6 | import { escapeHTML, readFileBufferPromise, root } from '../helpers/core-utils' | |
7 | import { ACCEPT_HEADERS, CONFIG, EMBED_SIZE, OPENGRAPH_AND_OEMBED_COMMENT, STATIC_MAX_AGE, STATIC_PATHS } from '../initializers' | |
8 | import { asyncMiddleware } from '../middlewares' | |
9 | import { VideoModel } from '../models/video/video' | |
10 | import { VideoPrivacy } from '../../shared/models/videos' | |
11 | import { | |
12 | buildFileLocale, | |
13 | getCompleteLocale, | |
14 | getDefaultLocale, | |
15 | is18nLocale, | |
16 | LOCALE_FILES, | |
17 | POSSIBLE_LOCALES | |
18 | } from '../../shared/models/i18n/i18n' | |
19 | ||
20 | const clientsRouter = express.Router() | |
21 | ||
22 | const distPath = join(root(), 'client', 'dist') | |
23 | const assetsImagesPath = join(root(), 'client', 'dist', 'assets', 'images') | |
24 | const embedPath = join(distPath, 'standalone', 'videos', 'embed.html') | |
25 | const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html') | |
26 | ||
27 | // Special route that add OpenGraph and oEmbed tags | |
28 | // Do not use a template engine for a so little thing | |
29 | clientsRouter.use('/videos/watch/:id', | |
30 | asyncMiddleware(generateWatchHtmlPage) | |
31 | ) | |
32 | ||
33 | clientsRouter.use('' + | |
34 | '/videos/embed', | |
35 | (req: express.Request, res: express.Response, next: express.NextFunction) => { | |
36 | res.removeHeader('X-Frame-Options') | |
37 | res.sendFile(embedPath) | |
38 | } | |
39 | ) | |
40 | clientsRouter.use('' + | |
41 | '/videos/test-embed', (req: express.Request, res: express.Response, next: express.NextFunction) => { | |
42 | res.sendFile(testEmbedPath) | |
43 | }) | |
44 | ||
45 | // Static HTML/CSS/JS client files | |
46 | ||
47 | const staticClientFiles = [ | |
48 | 'manifest.json', | |
49 | 'ngsw-worker.js', | |
50 | 'ngsw.json' | |
51 | ] | |
52 | for (const staticClientFile of staticClientFiles) { | |
53 | const path = join(root(), 'client', 'dist', staticClientFile) | |
54 | clientsRouter.use('/' + staticClientFile, express.static(path, { maxAge: STATIC_MAX_AGE })) | |
55 | } | |
56 | ||
57 | clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE })) | |
58 | clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE })) | |
59 | ||
60 | clientsRouter.use('/client/locales/:locale/:file.json', function (req, res) { | |
61 | const locale = req.params.locale | |
62 | const file = req.params.file | |
63 | ||
64 | if (is18nLocale(locale) && LOCALE_FILES.indexOf(file) !== -1) { | |
65 | const completeLocale = getCompleteLocale(locale) | |
66 | const completeFileLocale = buildFileLocale(completeLocale) | |
67 | return res.sendFile(join(__dirname, `../../../client/dist/locale/${file}_${completeFileLocale}.json`)) | |
68 | } | |
69 | ||
70 | return res.sendStatus(404) | |
71 | }) | |
72 | ||
73 | // 404 for static files not found | |
74 | clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => { | |
75 | res.sendStatus(404) | |
76 | }) | |
77 | ||
78 | // Always serve index client page (the client is a single page application, let it handle routing) | |
79 | // Try to provide the right language index.html | |
80 | clientsRouter.use('/(:language)?', function (req, res) { | |
81 | if (req.accepts(ACCEPT_HEADERS) === 'html') { | |
82 | return res.sendFile(getIndexPath(req, res, req.params.language)) | |
83 | } | |
84 | ||
85 | return res.status(404).end() | |
86 | }) | |
87 | ||
88 | // --------------------------------------------------------------------------- | |
89 | ||
90 | export { | |
91 | clientsRouter | |
92 | } | |
93 | ||
94 | // --------------------------------------------------------------------------- | |
95 | ||
96 | function getIndexPath (req: express.Request, res: express.Response, paramLang?: string) { | |
97 | let lang: string | |
98 | ||
99 | // Check param lang validity | |
100 | if (paramLang && is18nLocale(paramLang)) { | |
101 | lang = paramLang | |
102 | ||
103 | // Save locale in cookies | |
104 | res.cookie('clientLanguage', lang, { | |
105 | secure: CONFIG.WEBSERVER.SCHEME === 'https', | |
106 | sameSite: true, | |
107 | maxAge: 1000 * 3600 * 24 * 90 // 3 months | |
108 | }) | |
109 | ||
110 | } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) { | |
111 | lang = req.cookies.clientLanguage | |
112 | } else { | |
113 | lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale() | |
114 | } | |
115 | ||
116 | return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html') | |
117 | } | |
118 | ||
119 | function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) { | |
120 | const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName() | |
121 | const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid | |
122 | ||
123 | const videoNameEscaped = escapeHTML(video.name) | |
124 | const videoDescriptionEscaped = escapeHTML(video.description) | |
125 | const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedStaticPath() | |
126 | ||
127 | const openGraphMetaTags = { | |
128 | 'og:type': 'video', | |
129 | 'og:title': videoNameEscaped, | |
130 | 'og:image': previewUrl, | |
131 | 'og:url': videoUrl, | |
132 | 'og:description': videoDescriptionEscaped, | |
133 | ||
134 | 'og:video:url': embedUrl, | |
135 | 'og:video:secure_url': embedUrl, | |
136 | 'og:video:type': 'text/html', | |
137 | 'og:video:width': EMBED_SIZE.width, | |
138 | 'og:video:height': EMBED_SIZE.height, | |
139 | ||
140 | 'name': videoNameEscaped, | |
141 | 'description': videoDescriptionEscaped, | |
142 | 'image': previewUrl, | |
143 | ||
144 | 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image', | |
145 | 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME, | |
146 | 'twitter:title': videoNameEscaped, | |
147 | 'twitter:description': videoDescriptionEscaped, | |
148 | 'twitter:image': previewUrl, | |
149 | 'twitter:player': embedUrl, | |
150 | 'twitter:player:width': EMBED_SIZE.width, | |
151 | 'twitter:player:height': EMBED_SIZE.height | |
152 | } | |
153 | ||
154 | const oembedLinkTags = [ | |
155 | { | |
156 | type: 'application/json+oembed', | |
157 | href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl), | |
158 | title: videoNameEscaped | |
159 | } | |
160 | ] | |
161 | ||
162 | const schemaTags = { | |
163 | '@context': 'http://schema.org', | |
164 | '@type': 'VideoObject', | |
165 | name: videoNameEscaped, | |
166 | description: videoDescriptionEscaped, | |
167 | thumbnailUrl: previewUrl, | |
168 | uploadDate: video.createdAt.toISOString(), | |
169 | duration: video.getActivityStreamDuration(), | |
170 | contentUrl: videoUrl, | |
171 | embedUrl: embedUrl, | |
172 | interactionCount: video.views | |
173 | } | |
174 | ||
175 | let tagsString = '' | |
176 | ||
177 | // Opengraph | |
178 | Object.keys(openGraphMetaTags).forEach(tagName => { | |
179 | const tagValue = openGraphMetaTags[tagName] | |
180 | ||
181 | tagsString += `<meta property="${tagName}" content="${tagValue}" />` | |
182 | }) | |
183 | ||
184 | // OEmbed | |
185 | for (const oembedLinkTag of oembedLinkTags) { | |
186 | tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />` | |
187 | } | |
188 | ||
189 | // Schema.org | |
190 | tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>` | |
191 | ||
192 | // SEO | |
193 | tagsString += `<link rel="canonical" href="${videoUrl}" />` | |
194 | ||
195 | return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString) | |
196 | } | |
197 | ||
198 | async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) { | |
199 | const videoId = '' + req.params.id | |
200 | let videoPromise: Bluebird<VideoModel> | |
201 | ||
202 | // Let Angular application handle errors | |
203 | if (validator.isUUID(videoId, 4)) { | |
204 | videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId) | |
205 | } else if (validator.isInt(videoId)) { | |
206 | videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId) | |
207 | } else { | |
208 | return res.sendFile(getIndexPath(req, res)) | |
209 | } | |
210 | ||
211 | let [ file, video ] = await Promise.all([ | |
212 | readFileBufferPromise(getIndexPath(req, res)), | |
213 | videoPromise | |
214 | ]) | |
215 | ||
216 | const html = file.toString() | |
217 | ||
218 | // Let Angular application handle errors | |
219 | if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req, res)) | |
220 | ||
221 | const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video) | |
222 | res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags) | |
223 | } |