b20bafc76d6cbf8152960671afe031246eb9c59e
[oweals/peertube.git] / server / controllers / static.ts
1 import * as express from 'express'
2 import * as cors from 'cors'
3
4 import {
5   CONFIG,
6   STATIC_MAX_AGE,
7   STATIC_PATHS
8 } from '../initializers'
9 import { VideosPreviewCache } from '../lib'
10
11 const staticRouter = express.Router()
12
13 /*
14   Cors is very important to let other pods 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: STATIC_MAX_AGE })
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   getPreview
43 )
44
45 // ---------------------------------------------------------------------------
46
47 export {
48   staticRouter
49 }
50
51 // ---------------------------------------------------------------------------
52
53 function getPreview (req: express.Request, res: express.Response, next: express.NextFunction) {
54   VideosPreviewCache.Instance.getPreviewPath(req.params.uuid)
55     .then(path => {
56       if (!path) return res.sendStatus(404)
57
58       return res.sendFile(path, { maxAge: STATIC_MAX_AGE })
59     })
60 }