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'
10 OPENGRAPH_AND_OEMBED_COMMENT,
13 } from '../initializers'
14 import { asyncMiddleware } from '../middlewares'
15 import { VideoModel } from '../models/video/video'
16 import { VideoPrivacy } from '../../shared/models/videos'
17 import { I18N_LOCALES, is18nLocale, getDefaultLocale } from '../../shared/models'
19 const clientsRouter = express.Router()
21 const distPath = join(root(), 'client', 'dist')
22 const assetsImagesPath = join(root(), 'client', 'dist', 'assets', 'images')
23 const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
25 // Special route that add OpenGraph and oEmbed tags
26 // Do not use a template engine for a so little thing
27 clientsRouter.use('/videos/watch/:id',
28 asyncMiddleware(generateWatchHtmlPage)
31 clientsRouter.use('/videos/embed', (req: express.Request, res: express.Response, next: express.NextFunction) => {
32 res.sendFile(embedPath)
35 // Static HTML/CSS/JS client files
37 const staticClientFiles = [
42 for (const staticClientFile of staticClientFiles) {
43 const path = join(root(), 'client', 'dist', staticClientFile)
44 clientsRouter.use('/' + staticClientFile, express.static(path, { maxAge: STATIC_MAX_AGE }))
47 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE }))
48 clientsRouter.use('/client/assets/images', express.static(assetsImagesPath, { maxAge: STATIC_MAX_AGE }))
50 // 404 for static files not found
51 clientsRouter.use('/client/*', (req: express.Request, res: express.Response, next: express.NextFunction) => {
55 // Always serve index client page (the client is a single page application, let it handle routing)
56 // Try to provide the right language index.html
57 clientsRouter.use('/(:language)?', function (req, res) {
58 if (req.accepts(ACCEPT_HEADERS) === 'html') {
59 return res.sendFile(getIndexPath(req, req.params.language))
62 return res.status(404).end()
65 // ---------------------------------------------------------------------------
71 // ---------------------------------------------------------------------------
73 function getIndexPath (req: express.Request, paramLang?: string) {
76 // Check param lang validity
77 if (paramLang && is18nLocale(paramLang)) {
80 // lang = req.acceptsLanguages(Object.keys(I18N_LOCALES)) || getDefaultLocale()
81 // Disable auto language for now
82 lang = getDefaultLocale()
85 return join(__dirname, '../../../client/dist/' + lang + '/index.html')
88 function addOpenGraphAndOEmbedTags (htmlStringPage: string, video: VideoModel) {
89 const previewUrl = CONFIG.WEBSERVER.URL + STATIC_PATHS.PREVIEWS + video.getPreviewName()
90 const videoUrl = CONFIG.WEBSERVER.URL + '/videos/watch/' + video.uuid
92 const videoNameEscaped = escapeHTML(video.name)
93 const videoDescriptionEscaped = escapeHTML(video.description)
94 const embedUrl = CONFIG.WEBSERVER.URL + video.getEmbedPath()
96 const openGraphMetaTags = {
98 'og:title': videoNameEscaped,
99 'og:image': previewUrl,
101 'og:description': videoDescriptionEscaped,
103 'og:video:url': embedUrl,
104 'og:video:secure_url': embedUrl,
105 'og:video:type': 'text/html',
106 'og:video:width': EMBED_SIZE.width,
107 'og:video:height': EMBED_SIZE.height,
109 'name': videoNameEscaped,
110 'description': videoDescriptionEscaped,
113 'twitter:card': CONFIG.SERVICES.TWITTER.WHITELISTED ? 'player' : 'summary_large_image',
114 'twitter:site': CONFIG.SERVICES.TWITTER.USERNAME,
115 'twitter:title': videoNameEscaped,
116 'twitter:description': videoDescriptionEscaped,
117 'twitter:image': previewUrl,
118 'twitter:player': embedUrl,
119 'twitter:player:width': EMBED_SIZE.width,
120 'twitter:player:height': EMBED_SIZE.height
123 const oembedLinkTags = [
125 type: 'application/json+oembed',
126 href: CONFIG.WEBSERVER.URL + '/services/oembed?url=' + encodeURIComponent(videoUrl),
127 title: videoNameEscaped
132 '@context': 'http://schema.org',
133 '@type': 'VideoObject',
134 name: videoNameEscaped,
135 description: videoDescriptionEscaped,
136 thumbnailUrl: previewUrl,
137 uploadDate: video.createdAt.toISOString(),
138 duration: video.getActivityStreamDuration(),
139 contentUrl: videoUrl,
141 interactionCount: video.views
147 Object.keys(openGraphMetaTags).forEach(tagName => {
148 const tagValue = openGraphMetaTags[tagName]
150 tagsString += `<meta property="${tagName}" content="${tagValue}" />`
154 for (const oembedLinkTag of oembedLinkTags) {
155 tagsString += `<link rel="alternate" type="${oembedLinkTag.type}" href="${oembedLinkTag.href}" title="${oembedLinkTag.title}" />`
159 tagsString += `<script type="application/ld+json">${JSON.stringify(schemaTags)}</script>`
162 tagsString += `<link rel="canonical" href="${videoUrl}" />`
164 return htmlStringPage.replace(OPENGRAPH_AND_OEMBED_COMMENT, tagsString)
167 async function generateWatchHtmlPage (req: express.Request, res: express.Response, next: express.NextFunction) {
168 const videoId = '' + req.params.id
169 let videoPromise: Bluebird<VideoModel>
171 // Let Angular application handle errors
172 if (validator.isUUID(videoId, 4)) {
173 videoPromise = VideoModel.loadByUUIDAndPopulateAccountAndServerAndTags(videoId)
174 } else if (validator.isInt(videoId)) {
175 videoPromise = VideoModel.loadAndPopulateAccountAndServerAndTags(+videoId)
177 return res.sendFile(getIndexPath(req))
180 let [ file, video ] = await Promise.all([
181 readFileBufferPromise(getIndexPath(req)),
185 const html = file.toString()
187 // Let Angular application handle errors
188 if (!video || video.privacy === VideoPrivacy.PRIVATE) return res.sendFile(getIndexPath(req))
190 const htmlStringPageWithTags = addOpenGraphAndOEmbedTags(html, video)
191 res.set('Content-Type', 'text/html; charset=UTF-8').send(htmlStringPageWithTags)