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'
18 } from '../../shared/models/i18n/i18n'
20 const clientsRouter = express.Router()
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')
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)
33 clientsRouter.use('' +
35 (req: express.Request, res: express.Response, next: express.NextFunction) => {
36 res.removeHeader('X-Frame-Options')
37 res.sendFile(embedPath)
40 clientsRouter.use('' +
41 '/videos/test-embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
42 res.sendFile(testEmbedPath)
45 // Static HTML/CSS/JS client files
47 const staticClientFiles = [
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 }))
57 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
58 clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
60 clientsRouter.use('/client/locales/:locale/:file.json', function (req, res) {
61 const locale = req.params.locale
62 const file = req.params.file
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`))
70 return res.sendStatus(404)
73 // 404 for static files not found
74 clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
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))
85 return res.status(404).end()
88 // ---------------------------------------------------------------------------
94 // ---------------------------------------------------------------------------
96 function getIndexPath (req: express.Request, res: express.Response, paramLang?: string) {
99 // Check param lang validity
100 if (paramLang && is18nLocale(paramLang)) {
103 // Save locale in cookies
104 res.cookie('clientLanguage', lang, {
105 secure: CONFIG.WEBSERVER.SCHEME === 'https',
107 maxAge: 1000 * 3600 * 24 * 90 // 3 months
110 } else if (req.cookies.clientLanguage && is18nLocale(req.cookies.clientLanguage)) {
111 lang = req.cookies.clientLanguage
113 lang = req.acceptsLanguages(POSSIBLE_LOCALES) || getDefaultLocale()
116 return join(__dirname, '../../../client/dist/' + buildFileLocale(lang) + '/index.html')
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
123 const videoNameEscaped = escapeHTML(video.name)
124 const videoDescriptionEscaped = escapeHTML(video.description)
125 const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedStaticPath()
127 const openGraphMetaTags = {
129 'og:title': videoNameEscaped,
130 'og:image': previewUrl,
132 'og:description': videoDescriptionEscaped,
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,
140 'name': videoNameEscaped,
141 'description': videoDescriptionEscaped,
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
154 const oembedLinkTags = [
156 type: 'application/json+oembed',
157 href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
158 title: videoNameEscaped
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,
172 interactionCount: video.views
178 Object.keys(openGraphMetaTags).forEach(tagName => {
179 const tagValue = openGraphMetaTags[tagName]
181 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
185 for (const oembedLinkTag of oembedLinkTags) {
186 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
190 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
193 tagsString += `<link rel="canonical" href="${videoUrl}" />`
195 return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
198 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
199 const videoId = '' + req.params.id
200 let videoPromise: Bluebird<VideoModel>
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)
208 return res.sendFile(getIndexPath(req, res))
211 let [ file, video ] = await Promise.all([
212 readFileBufferPromise(getIndexPath(req, res)),
216 const html = file.toString()
218 // Let Angular application handle errors
219 if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req, res))
221 const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
222 res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)