]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/controllers/download.ts
Fix player error modal size
[github/Chocobozzz/PeerTube.git] / server / controllers / download.ts
CommitLineData
41fb13c3
C
1import cors from 'cors'
2import express from 'express'
4bc45da3 3import { logger } from '@server/helpers/logger'
90a8bd30 4import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
4bc45da3 5import { Hooks } from '@server/lib/plugins/hooks'
0305db28 6import { VideoPathManager } from '@server/lib/video-path-manager'
4bc45da3 7import { MStreamingPlaylist, MVideo, MVideoFile, MVideoFullLight } from '@server/types/models'
4638cd71 8import { addQueryParams, forceNumber } from '@shared/core-utils'
0305db28 9import { HttpStatusCode, VideoStorage, VideoStreamingPlaylistType } from '@shared/models'
90a8bd30 10import { STATIC_DOWNLOAD_PATHS } from '../initializers/constants'
3545e72c 11import { asyncMiddleware, optionalAuthenticate, videosDownloadValidator } from '../middlewares'
90a8bd30
C
12
13const downloadRouter = express.Router()
14
15downloadRouter.use(cors())
16
17downloadRouter.use(
18 STATIC_DOWNLOAD_PATHS.TORRENTS + ':filename',
4bc45da3 19 asyncMiddleware(downloadTorrent)
90a8bd30
C
20)
21
22downloadRouter.use(
23 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
3545e72c 24 optionalAuthenticate,
90a8bd30 25 asyncMiddleware(videosDownloadValidator),
4bc45da3 26 asyncMiddleware(downloadVideoFile)
90a8bd30
C
27)
28
29downloadRouter.use(
30 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
3545e72c 31 optionalAuthenticate,
90a8bd30 32 asyncMiddleware(videosDownloadValidator),
4bc45da3 33 asyncMiddleware(downloadHLSVideoFile)
90a8bd30
C
34)
35
36// ---------------------------------------------------------------------------
37
38export {
39 downloadRouter
40}
41
42// ---------------------------------------------------------------------------
43
44async function downloadTorrent (req: express.Request, res: express.Response) {
45 const result = await VideosTorrentCache.Instance.getFilePath(req.params.filename)
76148b27
RK
46 if (!result) {
47 return res.fail({
48 status: HttpStatusCode.NOT_FOUND_404,
49 message: 'Torrent file not found'
50 })
51 }
90a8bd30 52
4bc45da3
C
53 const allowParameters = { torrentPath: result.path, downloadName: result.downloadName }
54
55 const allowedResult = await Hooks.wrapFun(
56 isTorrentDownloadAllowed,
57 allowParameters,
58 'filter:api.download.torrent.allowed.result'
59 )
60
61 if (!checkAllowResult(res, allowParameters, allowedResult)) return
62
90a8bd30
C
63 return res.download(result.path, result.downloadName)
64}
65
4bc45da3 66async function downloadVideoFile (req: express.Request, res: express.Response) {
90a8bd30
C
67 const video = res.locals.videoAll
68
69 const videoFile = getVideoFile(req, video.VideoFiles)
76148b27
RK
70 if (!videoFile) {
71 return res.fail({
72 status: HttpStatusCode.NOT_FOUND_404,
73 message: 'Video file not found'
74 })
75 }
90a8bd30 76
4bc45da3
C
77 const allowParameters = { video, videoFile }
78
79 const allowedResult = await Hooks.wrapFun(
80 isVideoDownloadAllowed,
81 allowParameters,
82 'filter:api.download.video.allowed.result'
83 )
84
85 if (!checkAllowResult(res, allowParameters, allowedResult)) return
86
0305db28 87 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
9ab330b9 88 return redirectToObjectStorage({ req, res, video, file: videoFile })
0305db28
JB
89 }
90
ad5db104 91 await VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(video), path => {
62f53731
C
92 // Express uses basename on filename parameter
93 const videoName = video.name.replace(/[/\\]/g, '_')
94 const filename = `${videoName}-${videoFile.resolution}p${videoFile.extname}`
0305db28
JB
95
96 return res.download(path, filename)
97 })
90a8bd30
C
98}
99
4bc45da3 100async function downloadHLSVideoFile (req: express.Request, res: express.Response) {
90a8bd30 101 const video = res.locals.videoAll
4bc45da3
C
102 const streamingPlaylist = getHLSPlaylist(video)
103 if (!streamingPlaylist) return res.status(HttpStatusCode.NOT_FOUND_404).end
90a8bd30 104
4bc45da3 105 const videoFile = getVideoFile(req, streamingPlaylist.VideoFiles)
76148b27
RK
106 if (!videoFile) {
107 return res.fail({
108 status: HttpStatusCode.NOT_FOUND_404,
109 message: 'Video file not found'
110 })
111 }
90a8bd30 112
4bc45da3
C
113 const allowParameters = { video, streamingPlaylist, videoFile }
114
115 const allowedResult = await Hooks.wrapFun(
116 isVideoDownloadAllowed,
117 allowParameters,
118 'filter:api.download.video.allowed.result'
119 )
120
121 if (!checkAllowResult(res, allowParameters, allowedResult)) return
122
0305db28 123 if (videoFile.storage === VideoStorage.OBJECT_STORAGE) {
9ab330b9 124 return redirectToObjectStorage({ req, res, video, file: videoFile })
0305db28
JB
125 }
126
ad5db104 127 await VideoPathManager.Instance.makeAvailableVideoFile(videoFile.withVideoOrPlaylist(streamingPlaylist), path => {
0305db28
JB
128 const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}`
129
130 return res.download(path, filename)
131 })
90a8bd30
C
132}
133
134function getVideoFile (req: express.Request, files: MVideoFile[]) {
4638cd71 135 const resolution = forceNumber(req.params.resolution)
90a8bd30
C
136 return files.find(f => f.resolution === resolution)
137}
138
139function getHLSPlaylist (video: MVideoFullLight) {
140 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
141 if (!playlist) return undefined
142
143 return Object.assign(playlist, { Video: video })
144}
4bc45da3
C
145
146type AllowedResult = {
147 allowed: boolean
148 errorMessage?: string
149}
150
151function isTorrentDownloadAllowed (_object: {
152 torrentPath: string
153}): AllowedResult {
154 return { allowed: true }
155}
156
157function isVideoDownloadAllowed (_object: {
158 video: MVideo
159 videoFile: MVideoFile
160 streamingPlaylist?: MStreamingPlaylist
161}): AllowedResult {
162 return { allowed: true }
163}
164
165function checkAllowResult (res: express.Response, allowParameters: any, result?: AllowedResult) {
166 if (!result || result.allowed !== true) {
167 logger.info('Download is not allowed.', { result, allowParameters })
4bc45da3 168
76148b27
RK
169 res.fail({
170 status: HttpStatusCode.FORBIDDEN_403,
171 message: result?.errorMessage || 'Refused download'
172 })
4bc45da3
C
173 return false
174 }
175
176 return true
177}
9ab330b9
C
178
179function redirectToObjectStorage (options: {
180 req: express.Request
181 res: express.Response
182 video: MVideo
183 file: MVideoFile
184}) {
185 const { req, res, video, file } = options
186
187 const baseUrl = file.getObjectStorageUrl(video)
188
189 const url = video.hasPrivateStaticPath() && req.query.videoFileToken
190 ? addQueryParams(baseUrl, { videoFileToken: req.query.videoFileToken })
191 : baseUrl
192
193 return res.redirect(url)
194}