Update server dependencies
[oweals/peertube.git] / server / controllers / client.ts
1 import * as express from 'express'
2 import { join } from 'path'
3 import { root } from '../helpers/core-utils'
4 import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
5 import { asyncMiddleware, embedCSP } from '../middlewares'
6 import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '../../shared/models/i18n/i18n'
7 import { ClientHtml } from '../lib/client-html'
8 import { logger } from '../helpers/logger'
9 import { CONFIG } from '@server/initializers/config'
10
11 const clientsRouter = express.Router()
12
13 const distPath = join(root(), 'client', 'dist')
14 const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
15 const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
16
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/:id', asyncMiddleware(generateWatchHtmlPage))
20 clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
21 clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
22
23 const embedCSPMiddleware = CONFIG.CSP.ENABLED
24   ? embedCSP
25   : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
26
27 clientsRouter.use(
28   '/videos/embed',
29   embedCSPMiddleware,
30   (req: express.Request, res: express.Response) => {
31     res.removeHeader('X-Frame-Options')
32     // Don't cache HTML file since it's an index to the immutable JS/CSS files
33     res.sendFile(embedPath, { maxAge: 0 })
34   }
35 )
36 clientsRouter.use(
37   '/videos/test-embed',
38   (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
39 )
40
41 // Static HTML/CSS/JS client files
42
43 const staticClientFiles = [
44   'manifest.webmanifest',
45   'ngsw-worker.js',
46   'ngsw.json'
47 ]
48 for (const staticClientFile of staticClientFiles) {
49   const path = join(root(), 'client', 'dist', staticClientFile)
50
51   clientsRouter.get('/' + staticClientFile, (req: express.Request, res: express.Response) => {
52     res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
53   })
54 }
55
56 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
57 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
58
59 // 404 for static files not found
60 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
61   res.sendStatus(404)
62 })
63
64 // Always serve index client page (the client is a single page application, let it handle routing)
65 // Try to provide the right language index.html
66 clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
67
68 // ---------------------------------------------------------------------------
69
70 export {
71   clientsRouter
72 }
73
74 // ---------------------------------------------------------------------------
75
76 function serveServerTranslations (req: express.Request, res: express.Response) {
77   const locale = req.params.locale
78   const file = req.params.file
79
80   if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
81     const completeLocale = getCompleteLocale(locale)
82     const completeFileLocale = buildFileLocale(completeLocale)
83
84     const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
85     return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
86   }
87
88   return res.sendStatus(404)
89 }
90
91 async function serveIndexHTML (req: express.Request, res: express.Response) {
92   if (req.accepts(ACCEPT_HEADERS) === 'html') {
93     try {
94       await generateHTMLPage(req, res, req.params.language)
95       return
96     } catch (err) {
97       logger.error('Cannot generate HTML page.', err)
98     }
99   }
100
101   return res.status(404).end()
102 }
103
104 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
105   const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
106
107   return sendHTML(html, res)
108 }
109
110 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
111   const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
112
113   return sendHTML(html, res)
114 }
115
116 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
117   const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
118
119   return sendHTML(html, res)
120 }
121
122 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
123   const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
124
125   return sendHTML(html, res)
126 }
127
128 function sendHTML (html: string, res: express.Response) {
129   res.set('Content-Type', 'text/html; charset=UTF-8')
130
131   return res.send(html)
132 }