1 import * as cors from 'cors'
2 import * as express from 'express'
3 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
4 import { getVideoFilePath } from '@server/lib/video-paths'
5 import { MVideoFile, MVideoFullLight } from '@server/types/models'
6 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
7 import { VideoStreamingPlaylistType } from '@shared/models'
8 import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants'
9 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
11 const downloadRouter = express.Router()
13 downloadRouter.use(cors())
16 STATIC_DOWNLOAD_PATHS.TORRENTS + ':filename',
21 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
22 asyncMiddleware(videosDownloadValidator),
27 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
28 asyncMiddleware(videosDownloadValidator),
32 // ---------------------------------------------------------------------------
38 // ---------------------------------------------------------------------------
40 async function downloadTorrent (req: express.Request, res: express.Response) {
41 const result = await VideosTorrentCache.Instance.getFilePath(req.params.filename)
42 if (!result) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
44 return res.download(result.path, result.downloadName)
47 function downloadVideoFile (req: express.Request, res: express.Response) {
48 const video = res.locals.videoAll
50 const videoFile = getVideoFile(req, video.VideoFiles)
51 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
53 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
56 function downloadHLSVideoFile (req: express.Request, res: express.Response) {
57 const video = res.locals.videoAll
58 const playlist = getHLSPlaylist(video)
59 if (!playlist) return res.status(HttpStatusCode.NOT_FOUND_404).end
61 const videoFile = getVideoFile(req, playlist.VideoFiles)
62 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
64 const filename = `${video.name}-${videoFile.resolution}p-${playlist.getStringType()}${videoFile.extname}`
65 return res.download(getVideoFilePath(playlist, videoFile), filename)
68 function getVideoFile (req: express.Request, files: MVideoFile[]) {
69 const resolution = parseInt(req.params.resolution, 10)
70 return files.find(f => f.resolution === resolution)
73 function getHLSPlaylist (video: MVideoFullLight) {
74 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
75 if (!playlist) return undefined
77 return Object.assign(playlist, { Video: video })