1 import express from 'express'
2 import { constants, promises as fs } from 'fs'
3 import { readFile } from 'fs-extra'
4 import { join } from 'path'
5 import { logger } from '@server/helpers/logger'
6 import { CONFIG } from '@server/initializers/config'
7 import { Hooks } from '@server/lib/plugins/hooks'
8 import { buildFileLocale, getCompleteLocale, is18nLocale, LOCALE_FILES } from '@shared/core-utils/i18n'
9 import { HttpStatusCode } from '@shared/models'
10 import { root } from '../helpers/core-utils'
11 import { STATIC_MAX_AGE } from '../initializers/constants'
12 import { ClientHtml, sendHTML, serveIndexHTML } from '../lib/client-html'
13 import { asyncMiddleware, disableRobots, embedCSP } from '../middlewares'
15 const clientsRouter = express.Router()
17 const distPath = join(root(), 'client', 'dist')
18 const testEmbedPath = join(distPath, 'standalone', 'videos', 'test-embed.html')
20 // Special route that add OpenGraph and oEmbed tags
21 // Do not use a template engine for a so little thing
22 clientsRouter.use([ '/w/p/:id', '/videos/watch/playlist/:id' ], asyncMiddleware(generateWatchPlaylistHtmlPage))
23 clientsRouter.use([ '/w/:id', '/videos/watch/:id' ], asyncMiddleware(generateWatchHtmlPage))
24 clientsRouter.use([ '/accounts/:nameWithHost', '/a/:nameWithHost' ], asyncMiddleware(generateAccountHtmlPage))
25 clientsRouter.use([ '/video-channels/:nameWithHost', '/c/:nameWithHost' ], asyncMiddleware(generateVideoChannelHtmlPage))
26 clientsRouter.use('/@:nameWithHost', asyncMiddleware(generateActorHtmlPage))
28 const embedMiddlewares = [
31 : (req: express.Request, res: express.Response, next: express.NextFunction) => next(),
34 (req: express.Request, res: express.Response, next: express.NextFunction) => {
35 res.removeHeader('X-Frame-Options')
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')
43 asyncMiddleware(generateEmbedHtmlPage)
46 clientsRouter.use('/videos/embed', ...embedMiddlewares)
47 clientsRouter.use('/video-playlists/embed', ...embedMiddlewares)
49 const testEmbedController = (req: express.Request, res: express.Response) => res.sendFile(testEmbedPath)
51 clientsRouter.use('/videos/test-embed', testEmbedController)
52 clientsRouter.use('/video-playlists/test-embed', testEmbedController)
54 // Dynamic PWA manifest
55 clientsRouter.get('/manifest.webmanifest', asyncMiddleware(generateManifest))
57 // Static client overrides
58 // Must be consistent with static client overrides redirections in /support/nginx/peertube
59 const 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'
71 for (const staticClientOverride of staticClientOverrides) {
72 const overridePhysicalPath = join(CONFIG.STORAGE.CLIENT_OVERRIDES_DIR, staticClientOverride)
73 clientsRouter.use(`/client/${staticClientOverride}`, asyncMiddleware(serveClientOverride(overridePhysicalPath)))
76 clientsRouter.use('/client/locales/:locale/:file.json', serveServerTranslations)
77 clientsRouter.use('/client', express.static(distPath, { maxAge: STATIC_MAX_AGE.CLIENT }))
79 // 404 for static files not found
80 clientsRouter.use('/client/*', (req: express.Request, res: express.Response) => {
81 res.status(HttpStatusCode.NOT_FOUND_404).end()
84 // No index exceptions
85 clientsRouter.all('/about/peertube',
87 asyncMiddleware(serveIndexHTML)
90 // Always serve index client page (the client is a single page application, let it handle routing)
91 // Try to provide the right language index.html
92 clientsRouter.use('/(:language)?', asyncMiddleware(serveIndexHTML))
94 // ---------------------------------------------------------------------------
100 // ---------------------------------------------------------------------------
102 function serveServerTranslations (req: express.Request, res: express.Response) {
103 const locale = req.params.locale
104 const file = req.params.file
106 if (is18nLocale(locale) && LOCALE_FILES.includes(file)) {
107 const completeLocale = getCompleteLocale(locale)
108 const completeFileLocale = buildFileLocale(completeLocale)
110 const path = join(__dirname, `../../../client/dist/locale/${file}.${completeFileLocale}.json`)
111 return res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
114 return res.status(HttpStatusCode.NOT_FOUND_404).end()
117 async function generateEmbedHtmlPage (req: express.Request, res: express.Response) {
118 const hookName = req.originalUrl.startsWith('/video-playlists/')
119 ? 'filter:html.embed.video-playlist.allowed.result'
120 : 'filter:html.embed.video.allowed.result'
122 const allowParameters = { req }
124 const allowedResult = await Hooks.wrapFun(
130 if (!allowedResult || allowedResult.allowed !== true) {
131 logger.info('Embed is not allowed.', { allowedResult })
133 return sendHTML(allowedResult?.html || '', res)
136 const html = await ClientHtml.getEmbedHTML()
138 return sendHTML(html, res)
141 async function generateWatchHtmlPage (req: express.Request, res: express.Response) {
142 const html = await ClientHtml.getWatchHTMLPage(req.params.id + '', req, res)
144 return sendHTML(html, res)
147 async function generateWatchPlaylistHtmlPage (req: express.Request, res: express.Response) {
148 const html = await ClientHtml.getWatchPlaylistHTMLPage(req.params.id + '', req, res)
150 return sendHTML(html, res)
153 async function generateAccountHtmlPage (req: express.Request, res: express.Response) {
154 const html = await ClientHtml.getAccountHTMLPage(req.params.nameWithHost, req, res)
156 return sendHTML(html, res)
159 async function generateVideoChannelHtmlPage (req: express.Request, res: express.Response) {
160 const html = await ClientHtml.getVideoChannelHTMLPage(req.params.nameWithHost, req, res)
162 return sendHTML(html, res)
165 async function generateActorHtmlPage (req: express.Request, res: express.Response) {
166 const html = await ClientHtml.getActorHTMLPage(req.params.nameWithHost, req, res)
168 return sendHTML(html, res)
171 async function generateManifest (req: express.Request, res: express.Response) {
172 const manifestPhysicalPath = join(root(), 'client', 'dist', 'manifest.webmanifest')
173 const manifestJson = await readFile(manifestPhysicalPath, 'utf8')
174 const manifest = JSON.parse(manifestJson)
176 manifest.name = CONFIG.INSTANCE.NAME
177 manifest.short_name = CONFIG.INSTANCE.NAME
178 manifest.description = CONFIG.INSTANCE.SHORT_DESCRIPTION
183 function serveClientOverride (path: string) {
184 return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
186 await fs.access(path, constants.F_OK)
187 // Serve override client
188 res.sendFile(path, { maxAge: STATIC_MAX_AGE.SERVER })
196 type AllowedResult = { allowed: boolean, html?: string }
197 function isEmbedAllowed (_object: {
200 return { allowed: true }