]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/controllers/download.ts
refactor API errors to standard error format
[github/Chocobozzz/PeerTube.git] / server / controllers / download.ts
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'
12
13 const downloadRouter = express.Router()
14
15 downloadRouter.use(cors())
16
17 downloadRouter.use(
18 STATIC_DOWNLOAD_PATHS.TORRENTS + ':filename',
19 asyncMiddleware(downloadTorrent)
20 )
21
22 downloadRouter.use(
23 STATIC_DOWNLOAD_PATHS.VIDEOS + ':id-:resolution([0-9]+).:extension',
24 asyncMiddleware(videosDownloadValidator),
25 asyncMiddleware(downloadVideoFile)
26 )
27
28 downloadRouter.use(
29 STATIC_DOWNLOAD_PATHS.HLS_VIDEOS + ':id-:resolution([0-9]+)-fragmented.:extension',
30 asyncMiddleware(videosDownloadValidator),
31 asyncMiddleware(downloadHLSVideoFile)
32 )
33
34 // ---------------------------------------------------------------------------
35
36 export {
37 downloadRouter
38 }
39
40 // ---------------------------------------------------------------------------
41
42 async function downloadTorrent (req: express.Request, res: express.Response) {
43 const result = await VideosTorrentCache.Instance.getFilePath(req.params.filename)
44 if (!result) {
45 return res.fail({
46 status: HttpStatusCode.NOT_FOUND_404,
47 message: 'Torrent file not found'
48 })
49 }
50
51 const allowParameters = { torrentPath: result.path, downloadName: result.downloadName }
52
53 const allowedResult = await Hooks.wrapFun(
54 isTorrentDownloadAllowed,
55 allowParameters,
56 'filter:api.download.torrent.allowed.result'
57 )
58
59 if (!checkAllowResult(res, allowParameters, allowedResult)) return
60
61 return res.download(result.path, result.downloadName)
62 }
63
64 async function downloadVideoFile (req: express.Request, res: express.Response) {
65 const video = res.locals.videoAll
66
67 const videoFile = getVideoFile(req, video.VideoFiles)
68 if (!videoFile) {
69 return res.fail({
70 status: HttpStatusCode.NOT_FOUND_404,
71 message: 'Video file not found'
72 })
73 }
74
75 const allowParameters = { video, videoFile }
76
77 const allowedResult = await Hooks.wrapFun(
78 isVideoDownloadAllowed,
79 allowParameters,
80 'filter:api.download.video.allowed.result'
81 )
82
83 if (!checkAllowResult(res, allowParameters, allowedResult)) return
84
85 return res.download(getVideoFilePath(video, videoFile), `${video.name}-${videoFile.resolution}p${videoFile.extname}`)
86 }
87
88 async function downloadHLSVideoFile (req: express.Request, res: express.Response) {
89 const video = res.locals.videoAll
90 const streamingPlaylist = getHLSPlaylist(video)
91 if (!streamingPlaylist) return res.status(HttpStatusCode.NOT_FOUND_404).end
92
93 const videoFile = getVideoFile(req, streamingPlaylist.VideoFiles)
94 if (!videoFile) {
95 return res.fail({
96 status: HttpStatusCode.NOT_FOUND_404,
97 message: 'Video file not found'
98 })
99 }
100
101 const allowParameters = { video, streamingPlaylist, videoFile }
102
103 const allowedResult = await Hooks.wrapFun(
104 isVideoDownloadAllowed,
105 allowParameters,
106 'filter:api.download.video.allowed.result'
107 )
108
109 if (!checkAllowResult(res, allowParameters, allowedResult)) return
110
111 const filename = `${video.name}-${videoFile.resolution}p-${streamingPlaylist.getStringType()}${videoFile.extname}`
112 return res.download(getVideoFilePath(streamingPlaylist, videoFile), filename)
113 }
114
115 function getVideoFile (req: express.Request, files: MVideoFile[]) {
116 const resolution = parseInt(req.params.resolution, 10)
117 return files.find(f => f.resolution === resolution)
118 }
119
120 function getHLSPlaylist (video: MVideoFullLight) {
121 const playlist = video.VideoStreamingPlaylists.find(p => p.type === VideoStreamingPlaylistType.HLS)
122 if (!playlist) return undefined
123
124 return Object.assign(playlist, { Video: video })
125 }
126
127 type AllowedResult = {
128 allowed: boolean
129 errorMessage?: string
130 }
131
132 function isTorrentDownloadAllowed (_object: {
133 torrentPath: string
134 }): AllowedResult {
135 return { allowed: true }
136 }
137
138 function isVideoDownloadAllowed (_object: {
139 video: MVideo
140 videoFile: MVideoFile
141 streamingPlaylist?: MStreamingPlaylist
142 }): AllowedResult {
143 return { allowed: true }
144 }
145
146 function checkAllowResult (res: express.Response, allowParameters: any, result?: AllowedResult) {
147 if (!result || result.allowed !== true) {
148 logger.info('Download is not allowed.', { result, allowParameters })
149
150 res.fail({
151 status: HttpStatusCode.FORBIDDEN_403,
152 message: result?.errorMessage || 'Refused download'
153 })
154 return false
155 }
156
157 return true
158 }