1 import * as express from 'express'
2 import { constants, promises as fs } from 'fs'
3 import { join } from 'path'
4 import { CONFIG } from '@server/initializers/config'
5 import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '@shared/core-utils/i18n'
6 import { root } from '../helpers/core-utils'
7 import { logger } from '../helpers/logger'
8 import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
9 import { ClientHtml } from '../lib/client-html'
10 import { asyncMiddleware, embedCSP } from '../middlewares'
12 const clientsRouter = express.Router()
14 const distPath = join(root(), 'client', 'dist')
15 const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
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/playlist/:id', asyncMiddleware(generateWatchPlaylistHtmlPage))
20 clientsRouter.use('/videos/watch/:id', asyncMiddleware(generateWatchHtmlPage))
21 clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
22 clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
24 const embedMiddlewares = [
27 : (req: express.Request, res: express.Response, next: express.NextFunction) => next(),
29 (req: express.Request, res: express.Response, next: express.NextFunction) => {
30 res.removeHeader('X-Frame-Options')
32 // Don't cache HTML file since it's an index to the immutable JS/CSS files
33 res.setHeader('Cache-Control', 'public, max-age=0')
38 asyncMiddleware(generateEmbedHtmlPage)
41 clientsRouter.use('/videos/embed', ...embedMiddlewares)
42 clientsRouter.use('/video-playlists/embed', ...embedMiddlewares)
44 const testEmbedController = (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
46 clientsRouter.use('/videos/test-embed', testEmbedController)
47 clientsRouter.use('/video-playlists/test-embed', testEmbedController)
49 // Static HTML/CSS/JS client files
50 const staticClientFiles = [
55 for (const staticClientFile of staticClientFiles) {
56 const path = join(root(), 'client', 'dist', staticClientFile)
58 clientsRouter.get(`/${staticClientFile}`, (req: express.Request, res: express.Response) => {
59 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
63 // Dynamic PWA manifest
64 clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
66 // Static client overrides
67 const staticClientOverrides = [
68 'assets/images/logo.svg',
69 'assets/images/favicon.png',
70 'assets/images/icons/icon-36x36.png',
71 'assets/images/icons/icon-48x48.png',
72 'assets/images/icons/icon-72x72.png',
73 'assets/images/icons/icon-96x96.png',
74 'assets/images/icons/icon-144x144.png',
75 'assets/images/icons/icon-192x192.png',
76 'assets/images/icons/icon-512x512.png'
79 for (const staticClientOverride of staticClientOverrides) {
80 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
81 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
84 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
85 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
87 // 404 for static files not found
88 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
92 // Always serve index client page (the client is a single page application, let it handle routing)
93 // Try to provide the right language index.html
94 clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
96 // ---------------------------------------------------------------------------
102 // ---------------------------------------------------------------------------
104 function serveServerTranslations (req: express.Request, res: express.Response) {
105 const locale = req.params.locale
106 const file = req.params.file
108 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
109 const completeLocale = getCompleteLocale(locale)
110 const completeFileLocale = buildFileLocale(completeLocale)
112 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
113 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
116 return res.sendStatus(404)
119 async function serveIndexHTML (req: express.Request, res: express.Response) {
120 if (req.accepts(ACCEPT_HEADERS) === 'html') {
122 await generateHTMLPage(req, res, req.params.language)
125 logger.error('Cannot generate HTML page.', err)
129 return res.status(404).end()
132 async function generateEmbedHtmlPage (req: express.Request, res: express.Response) {
133 const html = await ClientHtml.getEmbedHTML()
135 return sendHTML(html, res)
138 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
139 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
141 return sendHTML(html, res)
144 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
145 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
147 return sendHTML(html, res)
150 async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
151 const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
153 return sendHTML(html, res)
156 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
157 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
159 return sendHTML(html, res)
162 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
163 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
165 return sendHTML(html, res)
168 function sendHTML (html: string, res: express.Response) {
169 res.set('Content-Type', 'text/html; charset=UTF-8')
171 return res.send(html)
174 async function generateManifest (req: express.Request, res: express.Response) {
175 const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
176 const manifestJson = await fs.readFile(manifestPhysicalPath, 'utf8')
177 const manifest = JSON.parse(manifestJson)
179 manifest.name = CONFIG.INSTANCE.NAME
180 manifest.short_name = CONFIG.INSTANCE.NAME
181 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
186 function serveClientOverride (path: string) {
187 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
189 await fs.access(path, constants.F_OK)
190 // Serve override client
191 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })