33aed89279a216a4549e4fa0e36d2e5e07070c0e
[oweals/peertube.git] / server / controllers / static.ts
1 import * as express from 'express'
2 import * as cors from 'cors'
3 import {
4   CONFIG,
5   STATIC_MAX_AGE,
6   STATIC_PATHS
7 } from '../initializers'
8 import { VideosPreviewCache } from '../lib'
9 import { asyncMiddleware } from '../middlewares'
10
11 const staticRouter = express.Router()
12
13 /*
14   Cors is very important to let other servers access torrent and video files
15 */
16
17 const torrentsPhysicalPath = CONFIG.STORAGE.TORRENTS_DIR
18 staticRouter.use(
19   STATIC_PATHS.TORRENTS,
20   cors(),
21   express.static(torrentsPhysicalPath, { maxAge: 0 }) // Don't cache because we could regenerate the torrent file
22 )
23
24 // Videos path for webseeding
25 const videosPhysicalPath = CONFIG.STORAGE.VIDEOS_DIR
26 staticRouter.use(
27   STATIC_PATHS.WEBSEED,
28   cors(),
29   express.static(videosPhysicalPath, { maxAge: STATIC_MAX_AGE })
30 )
31
32 // Thumbnails path for express
33 const thumbnailsPhysicalPath = CONFIG.STORAGE.THUMBNAILS_DIR
34 staticRouter.use(
35   STATIC_PATHS.THUMBNAILS,
36   express.static(thumbnailsPhysicalPath, { maxAge: STATIC_MAX_AGE })
37 )
38
39 // Video previews path for express
40 staticRouter.use(
41   STATIC_PATHS.PREVIEWS + ':uuid.jpg',
42   asyncMiddleware(getPreview)
43 )
44
45 // ---------------------------------------------------------------------------
46
47 export {
48   staticRouter
49 }
50
51 // ---------------------------------------------------------------------------
52
53 async function getPreview (req: express.Request, res: express.Response, next: express.NextFunction) {
54   const path = await VideosPreviewCache.Instance.getPreviewPath(req.params.uuid)
55   if (!path) return res.sendStatus(404)
56
57   return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
58 }