]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/client.ts
Add ability to override client assets : logo - favicon - PWA icons - PWA manifest...
[github/Chocobozzz/PeerTube.git] / server / controllers / client.ts
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'
11
12 const clientsRouter = express.Router()
13
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')
17
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/:id', asyncMiddleware(generateWatchHtmlPage))
21 clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
22 clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
23
24 const embedCSPMiddleware = CONFIG.CSP.ENABLED
25 ? embedCSP
26 : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
27
28 clientsRouter.use(
29 '/videos/embed',
30 embedCSPMiddleware,
31 (req: express.Request, res: express.Response) => {
32 res.removeHeader('X-Frame-Options')
33 // Don't cache HTML file since it's an index to the immutable JS/CSS files
34 res.sendFile(embedPath, { maxAge: 0 })
35 }
36 )
37 clientsRouter.use(
38 '/videos/test-embed',
39 (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
40 )
41
42 // Static HTML/CSS/JS client files
43 const staticClientFiles = [
44 'ngsw-worker.js',
45 'ngsw.json'
46 ]
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 // Dynamic PWA manifest
57 clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
58
59 // Static client overrides
60 const staticClientOverrides = [
61 'assets/images/logo.svg',
62 'assets/images/favicon.png',
63 'assets/images/icons/icon-36x36.png',
64 'assets/images/icons/icon-48x48.png',
65 'assets/images/icons/icon-72x72.png',
66 'assets/images/icons/icon-96x96.png',
67 'assets/images/icons/icon-144x144.png',
68 'assets/images/icons/icon-192x192.png',
69 'assets/images/icons/icon-512x512.png'
70 ]
71
72 for (const staticClientOverride of staticClientOverrides) {
73 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
74 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
75 }
76
77 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
78 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
79
80 // 404 for static files not found
81 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
82 res.sendStatus(404)
83 })
84
85 // Always serve index client page (the client is a single page application, let it handle routing)
86 // Try to provide the right language index.html
87 clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
88
89 // ---------------------------------------------------------------------------
90
91 export {
92 clientsRouter
93 }
94
95 // ---------------------------------------------------------------------------
96
97 function serveServerTranslations (req: express.Request, res: express.Response) {
98 const locale = req.params.locale
99 const file = req.params.file
100
101 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
102 const completeLocale = getCompleteLocale(locale)
103 const completeFileLocale = buildFileLocale(completeLocale)
104
105 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
106 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
107 }
108
109 return res.sendStatus(404)
110 }
111
112 async function serveIndexHTML (req: express.Request, res: express.Response) {
113 if (req.accepts(ACCEPT_HEADERS) === 'html') {
114 try {
115 await generateHTMLPage(req, res, req.params.language)
116 return
117 } catch (err) {
118 logger.error('Cannot generate HTML page.', err)
119 }
120 }
121
122 return res.status(404).end()
123 }
124
125 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
126 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
127
128 return sendHTML(html, res)
129 }
130
131 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
132 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
133
134 return sendHTML(html, res)
135 }
136
137 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
138 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
139
140 return sendHTML(html, res)
141 }
142
143 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
144 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
145
146 return sendHTML(html, res)
147 }
148
149 function sendHTML (html: string, res: express.Response) {
150 res.set('Content-Type', 'text/html; charset=UTF-8')
151
152 return res.send(html)
153 }
154
155 async function generateManifest (req: express.Request, res: express.Response) {
156 const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
157 const manifestJson = await fs.readFile(manifestPhysicalPath, 'utf8')
158 const manifest = JSON.parse(manifestJson)
159
160 manifest.name = CONFIG.INSTANCE.NAME
161 manifest.short_name = CONFIG.INSTANCE.NAME
162 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
163
164 res.json(manifest)
165 }
166
167 function serveClientOverride (path: string) {
168 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
169 try {
170 await fs.access(path, constants.F_OK)
171 // Serve override client
172 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
173 } catch {
174 // Serve dist client
175 next()
176 }
177 }
178 }