]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server/controllers/client.ts
Move test functions outside extra-utils
[github/Chocobozzz/PeerTube.git] / server / controllers / client.ts
... / ...
CommitLineData
1import express from 'express'
2import { constants, promises as fs } from 'fs'
3import { readFile } from 'fs-extra'
4import { join } from 'path'
5import { logger } from '@server/helpers/logger'
6import { CONFIG } from '@server/initializers/config'
7import { Hooks } from '@server/lib/plugins/hooks'
8import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '@shared/core-utils/i18n'
9import { HttpStatusCode } from '@shared/models'
10import { root } from '@shared/core-utils'
11import { STATIC_MAX_AGE } from '../initializers/constants'
12import { ClientHtml, sendHTML, serveIndexHTML } from '../lib/client-html'
13import { asyncMiddleware, embedCSP } from '../middlewares'
14
15const clientsRouter = express.Router()
16
17const distPath = join(root(), 'client', 'dist')
18const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
19
20// Special route that add OpenGraph and oEmbed tags
21// Do not use a template engine for a so little thing
22clientsRouter.use([ '/w/p/:id', '/videos/watch/playlist/:id' ], asyncMiddleware(generateWatchPlaylistHtmlPage))
23clientsRouter.use([ '/w/:id', '/videos/watch/:id' ], asyncMiddleware(generateWatchHtmlPage))
24clientsRouter.use([ '/accounts/:nameWithHost', '/a/:nameWithHost' ], asyncMiddleware(generateAccountHtmlPage))
25clientsRouter.use([ '/video-channels/:nameWithHost', '/c/:nameWithHost' ], asyncMiddleware(generateVideoChannelHtmlPage))
26clientsRouter.use('/@:nameWithHost', asyncMiddleware(generateActorHtmlPage))
27
28const embedMiddlewares = [
29 CONFIG.CSP.ENABLED
30 ? embedCSP
31 : (req: express.Request, res: express.Response, next: express.NextFunction) => next(),
32
33 // Set headers
34 (req: express.Request, res: express.Response, next: express.NextFunction) => {
35 res.removeHeader('X-Frame-Options')
36
37 // Don't cache HTML file since it's an index to the immutable JS/CSS files
38 res.setHeader('Cache-Control', 'public, max-age=0')
39
40 next()
41 },
42
43 asyncMiddleware(generateEmbedHtmlPage)
44]
45
46clientsRouter.use('/videos/embed', ...embedMiddlewares)
47clientsRouter.use('/video-playlists/embed', ...embedMiddlewares)
48
49const testEmbedController = (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
50
51clientsRouter.use('/videos/test-embed', testEmbedController)
52clientsRouter.use('/video-playlists/test-embed', testEmbedController)
53
54// Dynamic PWA manifest
55clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
56
57// Static client overrides
58// Must be consistent with static client overrides redirections in /support/nginx/peertube
59const staticClientOverrides = [
60 'assets/images/logo.svg',
61 'assets/images/favicon.png',
62 'assets/images/icons/icon-36x36.png',
63 'assets/images/icons/icon-48x48.png',
64 'assets/images/icons/icon-72x72.png',
65 'assets/images/icons/icon-96x96.png',
66 'assets/images/icons/icon-144x144.png',
67 'assets/images/icons/icon-192x192.png',
68 'assets/images/icons/icon-512x512.png',
69 'assets/images/default-playlist.jpg',
70 'assets/images/default-avatar-account.png',
71 'assets/images/default-avatar-video-channel.png'
72]
73
74for (const staticClientOverride of staticClientOverrides) {
75 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
76 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
77}
78
79clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
80clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
81
82// 404 for static files not found
83clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
84 res.status(HttpStatusCode.NOT_FOUND_404).end()
85})
86
87// Always serve index client page (the client is a single page application, let it handle routing)
88// Try to provide the right language index.html
89clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
90
91// ---------------------------------------------------------------------------
92
93export {
94 clientsRouter
95}
96
97// ---------------------------------------------------------------------------
98
99function serveServerTranslations (req: express.Request, res: express.Response) {
100 const locale = req.params.locale
101 const file = req.params.file
102
103 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
104 const completeLocale = getCompleteLocale(locale)
105 const completeFileLocale = buildFileLocale(completeLocale)
106
107 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
108 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
109 }
110
111 return res.status(HttpStatusCode.NOT_FOUND_404).end()
112}
113
114async function generateEmbedHtmlPage (req: express.Request, res: express.Response) {
115 const hookName = req.originalUrl.startsWith('/video-playlists/')
116 ? 'filter:html.embed.video-playlist.allowed.result'
117 : 'filter:html.embed.video.allowed.result'
118
119 const allowParameters = { req }
120
121 const allowedResult = await Hooks.wrapFun(
122 isEmbedAllowed,
123 allowParameters,
124 hookName
125 )
126
127 if (!allowedResult || allowedResult.allowed !== true) {
128 logger.info('Embed is not allowed.', { allowedResult })
129
130 return sendHTML(allowedResult?.html || '', res)
131 }
132
133 const html = await ClientHtml.getEmbedHTML()
134
135 return sendHTML(html, res)
136}
137
138async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
139 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
140
141 return sendHTML(html, res, true)
142}
143
144async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
145 const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
146
147 return sendHTML(html, res, true)
148}
149
150async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
151 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
152
153 return sendHTML(html, res, true)
154}
155
156async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
157 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
158
159 return sendHTML(html, res, true)
160}
161
162async function generateActorHtmlPage (req: express.Request, res: express.Response) {
163 const html = await ClientHtml.getActorHTMLPage(req.params.nameWithHost, req, res)
164
165 return sendHTML(html, res, true)
166}
167
168async function generateManifest (req: express.Request, res: express.Response) {
169 const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
170 const manifestJson = await readFile(manifestPhysicalPath, 'utf8')
171 const manifest = JSON.parse(manifestJson)
172
173 manifest.name = CONFIG.INSTANCE.NAME
174 manifest.short_name = CONFIG.INSTANCE.NAME
175 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
176
177 res.json(manifest)
178}
179
180function serveClientOverride (path: string) {
181 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
182 try {
183 await fs.access(path, constants.F_OK)
184 // Serve override client
185 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
186 } catch {
187 // Serve dist client
188 next()
189 }
190 }
191}
192
193type AllowedResult = { allowed: boolean, html?: string }
194function isEmbedAllowed (_object: {
195 req: express.Request
196}): AllowedResult {
197 return { allowed: true }
198}