1 import * as cors from 'cors'
2 import * as express from 'express'
3 import { logger } from '@server/helpers/logger'
4 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
5 import { Hooks } from '@server/lib/plugins/hooks'
6 import { getVideoFilePath } from '@server/lib/video-paths'
7 import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
8 import { HttpStatusCode } from '@shared/core-utils/miscs/http-error-codes'
9 import { VideoStreamingPlaylistType } from '@shared/models'
10 import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants'
11 import { asyncMiddleware, videosDownloadValidator } from '../middlewares'
13 const downloadRouter = express.Router()
15 downloadRouter.use(cors())
18 STATIC_DOWNLOAD_PATHS.TORRENTS + ':filename',
19 asyncMiddleware(downloadTorrent)
23 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
24 asyncMiddleware(videosDownloadValidator),
25 asyncMiddleware(downloadVideoFile)
29 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
30 asyncMiddleware(videosDownloadValidator),
31 asyncMiddleware(downloadHLSVideoFile)
34 // ---------------------------------------------------------------------------
40 // ---------------------------------------------------------------------------
42 async function downloadTorrent (req: express.Request, res: express.Response) {
43 const result = await VideosTorrentCache.Instance.getFilePath(req.params.filename)
44 if (!result) return res.sendStatus(HttpStatusCode.NOT_FOUND_404)
46 const allowParameters = { torrentPath: result.path, downloadName: result.downloadName }
48 const allowedResult = await Hooks.wrapFun(
49 isTorrentDownloadAllowed,
51 'filter:api.download.torrent.allowed.result'
54 if (!checkAllowResult(res, allowParameters, allowedResult)) return
56 return res.download(result.path, result.downloadName)
59 async function downloadVideoFile (req: express.Request, res: express.Response) {
60 const video = res.locals.videoAll
62 const videoFile = getVideoFile(req, video.VideoFiles)
63 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
65 const allowParameters = { video, videoFile }
67 const allowedResult = await Hooks.wrapFun(
68 isVideoDownloadAllowed,
70 'filter:api.download.video.allowed.result'
73 if (!checkAllowResult(res, allowParameters, allowedResult)) return
75 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
78 async function downloadHLSVideoFile (req: express.Request, res: express.Response) {
79 const video = res.locals.videoAll
80 const streamingPlaylist = getHLSPlaylist(video)
81 if (!streamingPlaylist) return res.status(HttpStatusCode.NOT_FOUND_404).end
83 const videoFile = getVideoFile(req, streamingPlaylist.VideoFiles)
84 if (!videoFile) return res.status(HttpStatusCode.NOT_FOUND_404).end()
86 const allowParameters = { video, streamingPlaylist, videoFile }
88 const allowedResult = await Hooks.wrapFun(
89 isVideoDownloadAllowed,
91 'filter:api.download.video.allowed.result'
94 if (!checkAllowResult(res, allowParameters, allowedResult)) return
96 const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}`
97 return res.download(getVideoFilePath(streamingPlaylist, videoFile), filename)
100 function getVideoFile (req: express.Request, files: MVideoFile[]) {
101 const resolution = parseInt(req.params.resolution, 10)
102 return files.find(f => f.resolution === resolution)
105 function getHLSPlaylist (video: MVideoFullLight) {
106 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
107 if (!playlist) return undefined
109 return Object.assign(playlist, { Video: video })
112 type AllowedResult = {
114 errorMessage?: string
117 function isTorrentDownloadAllowed (_object: {
120 return { allowed: true }
123 function isVideoDownloadAllowed (_object: {
125 videoFile: MVideoFile
126 streamingPlaylist?: MStreamingPlaylist
128 return { allowed: true }
131 function checkAllowResult (res: express.Response, allowParameters: any, result?: AllowedResult) {
132 if (!result || result.allowed !== true) {
133 logger.info('Download is not allowed.', { result, allowParameters })
134 res.status(HttpStatusCode.FORBIDDEN_403)
135 .json({ error: result?.errorMessage || 'Refused download' })