]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/client.ts
Update my-account sub-menus icons (#2977)
[github/Chocobozzz/PeerTube.git] / server / controllers / client.ts
... / ...
CommitLineData
1import { constants, promises as fs } from 'fs'
2import * as express from 'express'
3import { join } from 'path'
4import { root } from '../helpers/core-utils'
5import { ACCEPT_HEADERS, STATIC_MAX_AGE } from '../initializers/constants'
6import { asyncMiddleware, embedCSP } from '../middlewares'
7import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '../../shared/models/i18n/i18n'
8import { ClientHtml } from '../lib/client-html'
9import { logger } from '../helpers/logger'
10import { CONFIG } from '@server/initializers/config'
11
12const clientsRouter = express.Router()
13
14const distPath = join(root(), 'client', 'dist')
15const embedPath = join(distPath, 'standalone', 'videos', 'embed.html')
16const 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
20clientsRouter.use('/videos/watch/:id', asyncMiddleware(generateWatchHtmlPage))
21clientsRouter.use('/accounts/:nameWithHost', asyncMiddleware(generateAccountHtmlPage))
22clientsRouter.use('/video-channels/:nameWithHost', asyncMiddleware(generateVideoChannelHtmlPage))
23
24const embedCSPMiddleware = CONFIG.CSP.ENABLED
25 ? embedCSP
26 : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
27
28clientsRouter.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)
37clientsRouter.use(
38 '/videos/test-embed',
39 (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
40)
41
42// Static HTML/CSS/JS client files
43const staticClientFiles = [
44 'ngsw-worker.js',
45 'ngsw.json'
46]
47
48for (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
57clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
58
59// Static client overrides
60const 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
72for (const staticClientOverride of staticClientOverrides) {
73 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
74 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
75}
76
77clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
78clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
79
80// 404 for static files not found
81clientsRouter.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
87clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
88
89// ---------------------------------------------------------------------------
90
91export {
92 clientsRouter
93}
94
95// ---------------------------------------------------------------------------
96
97function 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
112async 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
125async 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
131async 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
137async 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
143async 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
149function sendHTML (html: string, res: express.Response) {
150 res.set('Content-Type', 'text/html; charset=UTF-8')
151
152 return res.send(html)
153}
154
155async 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
167function 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}