1 import cors from 'cors'
2 import 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 { VideoPathManager } from '@server/lib/video-path-manager'
7 import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
8 import { HttpStatusCode, VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
9 import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants'
10 import { asyncMiddleware, optionalAuthenticate, videosDownloadValidator } from '../middlewares'
12 const downloadRouter = express.Router()
14 downloadRouter.use(cors())
17 STATIC_DOWNLOAD_PATHS.TORRENTS + ':filename',
18 asyncMiddleware(downloadTorrent)
22 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',
31 asyncMiddleware(videosDownloadValidator),
32 asyncMiddleware(downloadHLSVideoFile)
35 // ---------------------------------------------------------------------------
41 // ---------------------------------------------------------------------------
43 async function downloadTorrent (req: express.Request, res: express.Response) {
44 const result = await VideosTorrentCache.Instance.getFilePath(req.params.filename)
47 status: HttpStatusCode.NOT_FOUND_404,
48 message: 'Torrent file not found'
52 const allowParameters = { torrentPath: result.path, downloadName: result.downloadName }
54 const allowedResult = await Hooks.wrapFun(
55 isTorrentDownloadAllowed,
57 'filter:api.download.torrent.allowed.result'
60 if (!checkAllowResult(res, allowParameters, allowedResult)) return
62 return res.download(result.path, result.downloadName)
65 async function downloadVideoFile (req: express.Request, res: express.Response) {
66 const video = res.locals.videoAll
68 const videoFile = getVideoFile(req, video.VideoFiles)
71 status: HttpStatusCode.NOT_FOUND_404,
72 message: 'Video file not found'
76 const allowParameters = { video, videoFile }
78 const allowedResult = await Hooks.wrapFun(
79 isVideoDownloadAllowed,
81 'filter:api.download.video.allowed.result'
84 if (!checkAllowResult(res, allowParameters, allowedResult)) return
86 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
87 return res.redirect(videoFile.getObjectStorageUrl())
90 await VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(video), path => {
91 // Express uses basename on filename parameter
92 const videoName = video.name.replace(/[/\\]/g, '_')
93 const filename = `${videoName}-${videoFile.resolution}p${videoFile.extname}`
95 return res.download(path, filename)
99 async function downloadHLSVideoFile (req: express.Request, res: express.Response) {
100 const video = res.locals.videoAll
101 const streamingPlaylist = getHLSPlaylist(video)
102 if (!streamingPlaylist) return res.status(HttpStatusCode.NOT_FOUND_404).end
104 const videoFile = getVideoFile(req, streamingPlaylist.VideoFiles)
107 status: HttpStatusCode.NOT_FOUND_404,
108 message: 'Video file not found'
112 const allowParameters = { video, streamingPlaylist, videoFile }
114 const allowedResult = await Hooks.wrapFun(
115 isVideoDownloadAllowed,
117 'filter:api.download.video.allowed.result'
120 if (!checkAllowResult(res, allowParameters, allowedResult)) return
122 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
123 return res.redirect(videoFile.getObjectStorageUrl())
126 await VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(streamingPlaylist), path => {
127 const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}`
129 return res.download(path, filename)
133 function getVideoFile (req: express.Request, files: MVideoFile[]) {
134 const resolution = parseInt(req.params.resolution, 10)
135 return files.find(f => f.resolution === resolution)
138 function getHLSPlaylist (video: MVideoFullLight) {
139 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
140 if (!playlist) return undefined
142 return Object.assign(playlist, { Video: video })
145 type AllowedResult = {
147 errorMessage?: string
150 function isTorrentDownloadAllowed (_object: {
153 return { allowed: true }
156 function isVideoDownloadAllowed (_object: {
158 videoFile: MVideoFile
159 streamingPlaylist?: MStreamingPlaylist
161 return { allowed: true }
164 function checkAllowResult (res: express.Response, allowParameters: any, result?: AllowedResult) {
165 if (!result || result.allowed !== true) {
166 logger.info('Download is not allowed.', { result, allowParameters })
169 status: HttpStatusCode.FORBIDDEN_403,
170 message: result?.errorMessage || 'Refused download'