1 import { constants, promises as fs } from 'fs'
2 import * as express from 'express'
3 import { join } from 'path'
4 import { root } from '../helpers/core-utils'
5 import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
6 import { asyncMiddleware, embedCSP } from '../middlewares'
7 import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '../../shared/models/i18n/i18n'
8 import { ClientHtml } from '../lib/client-html'
9 import { logger } from '../helpers/logger'
10 import { CONFIG } from '@server/initializers/config'
12 const clientsRouter = express.Router()
14 const distPath = join(root(), 'client', 'dist')
15 const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
16 const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
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/playlist/:id', asyncMiddleware(generateWatchPlaylistHtmlPage))
21 clientsRouter.use('/videos/watch/:id', asyncMiddleware(generateWatchHtmlPage))
22 clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
23 clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
25 const embedCSPMiddleware = CONFIG.CSP.ENABLED
27 : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
32 (req: express.Request, res: express.Response) => {
33 res.removeHeader('X-Frame-Options')
34 // Don't cache HTML file since it's an index to the immutable JS/CSS files
35 res.sendFile(embedPath, { maxAge: 0 })
40 (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
43 // Static HTML/CSS/JS client files
44 const staticClientFiles = [
49 for (const staticClientFile of staticClientFiles) {
50 const path = join(root(), 'client', 'dist', staticClientFile)
52 clientsRouter.get(`/${staticClientFile}`, (req: express.Request, res: express.Response) => {
53 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
57 // Dynamic PWA manifest
58 clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
60 // Static client overrides
61 const staticClientOverrides = [
62 'assets/images/logo.svg',
63 'assets/images/favicon.png',
64 'assets/images/icons/icon-36x36.png',
65 'assets/images/icons/icon-48x48.png',
66 'assets/images/icons/icon-72x72.png',
67 'assets/images/icons/icon-96x96.png',
68 'assets/images/icons/icon-144x144.png',
69 'assets/images/icons/icon-192x192.png',
70 'assets/images/icons/icon-512x512.png'
73 for (const staticClientOverride of staticClientOverrides) {
74 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
75 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
78 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
79 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
81 // 404 for static files not found
82 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
86 // Always serve index client page (the client is a single page application, let it handle routing)
87 // Try to provide the right language index.html
88 clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
90 // ---------------------------------------------------------------------------
96 // ---------------------------------------------------------------------------
98 function serveServerTranslations (req: express.Request, res: express.Response) {
99 const locale = req.params.locale
100 const file = req.params.file
102 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
103 const completeLocale = getCompleteLocale(locale)
104 const completeFileLocale = buildFileLocale(completeLocale)
106 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
107 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
110 return res.sendStatus(404)
113 async function serveIndexHTML (req: express.Request, res: express.Response) {
114 if (req.accepts(ACCEPT_HEADERS) === 'html') {
116 await generateHTMLPage(req, res, req.params.language)
119 logger.error('Cannot generate HTML page.', err)
123 return res.status(404).end()
126 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
127 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
129 return sendHTML(html, res)
132 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
133 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
135 return sendHTML(html, res)
138 async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
139 const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
141 return sendHTML(html, res)
144 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
145 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
147 return sendHTML(html, res)
150 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
151 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
153 return sendHTML(html, res)
156 function sendHTML (html: string, res: express.Response) {
157 res.set('Content-Type', 'text/html; charset=UTF-8')
159 return res.send(html)
162 async function generateManifest (req: express.Request, res: express.Response) {
163 const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
164 const manifestJson = await fs.readFile(manifestPhysicalPath, 'utf8')
165 const manifest = JSON.parse(manifestJson)
167 manifest.name = CONFIG.INSTANCE.NAME
168 manifest.short_name = CONFIG.INSTANCE.NAME
169 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
174 function serveClientOverride (path: string) {
175 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
177 await fs.access(path, constants.F_OK)
178 // Serve override client
179 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })