]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/client.ts
Increase redundancy check params timeout
[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/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))
24
25 const embedCSPMiddleware = CONFIG.CSP.ENABLED
26 ? embedCSP
27 : (req: express.Request, res: express.Response, next: express.NextFunction) => next()
28
29 clientsRouter.use(
30 '/videos/embed',
31 embedCSPMiddleware,
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 })
36 }
37 )
38 clientsRouter.use(
39 '/videos/test-embed',
40 (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
41 )
42
43 // Static HTML/CSS/JS client files
44 const staticClientFiles = [
45 'ngsw-worker.js',
46 'ngsw.json'
47 ]
48
49 for (const staticClientFile of staticClientFiles) {
50 const path = join(root(), 'client', 'dist', staticClientFile)
51
52 clientsRouter.get(`/${staticClientFile}`, (req: express.Request, res: express.Response) => {
53 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
54 })
55 }
56
57 // Dynamic PWA manifest
58 clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
59
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'
71 ]
72
73 for (const staticClientOverride of staticClientOverrides) {
74 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
75 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
76 }
77
78 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
79 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
80
81 // 404 for static files not found
82 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
83 res.sendStatus(404)
84 })
85
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))
89
90 // ---------------------------------------------------------------------------
91
92 export {
93 clientsRouter
94 }
95
96 // ---------------------------------------------------------------------------
97
98 function serveServerTranslations (req: express.Request, res: express.Response) {
99 const locale = req.params.locale
100 const file = req.params.file
101
102 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
103 const completeLocale = getCompleteLocale(locale)
104 const completeFileLocale = buildFileLocale(completeLocale)
105
106 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
107 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
108 }
109
110 return res.sendStatus(404)
111 }
112
113 async function serveIndexHTML (req: express.Request, res: express.Response) {
114 if (req.accepts(ACCEPT_HEADERS) === 'html') {
115 try {
116 await generateHTMLPage(req, res, req.params.language)
117 return
118 } catch (err) {
119 logger.error('Cannot generate HTML page.', err)
120 }
121 }
122
123 return res.status(404).end()
124 }
125
126 async function generateHTMLPage (req: express.Request, res: express.Response, paramLang?: string) {
127 const html = await ClientHtml.getDefaultHTMLPage(req, res, paramLang)
128
129 return sendHTML(html, res)
130 }
131
132 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
133 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
134
135 return sendHTML(html, res)
136 }
137
138 async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
139 const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
140
141 return sendHTML(html, res)
142 }
143
144 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
145 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
146
147 return sendHTML(html, res)
148 }
149
150 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
151 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
152
153 return sendHTML(html, res)
154 }
155
156 function sendHTML (html: string, res: express.Response) {
157 res.set('Content-Type', 'text/html; charset=UTF-8')
158
159 return res.send(html)
160 }
161
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)
166
167 manifest.name = CONFIG.INSTANCE.NAME
168 manifest.short_name = CONFIG.INSTANCE.NAME
169 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
170
171 res.json(manifest)
172 }
173
174 function serveClientOverride (path: string) {
175 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
176 try {
177 await fs.access(path, constants.F_OK)
178 // Serve override client
179 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
180 } catch {
181 // Serve dist client
182 next()
183 }
184 }
185 }