]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/validators/videos/video-imports.ts
a3a5cc5315e5414de3da9b4e3b3c0cf00d6514dd
[github/Chocobozzz/PeerTube.git] / server / middlewares / validators / videos / video-imports.ts
1 import express from 'express'
2 import { body, param } from 'express-validator'
3 import { isValid as isIPValid, parse as parseIP } from 'ipaddr.js'
4 import { isPreImportVideoAccepted } from '@server/lib/moderation'
5 import { Hooks } from '@server/lib/plugins/hooks'
6 import { MUserAccountId, MVideoImport } from '@server/types/models'
7 import { HttpStatusCode, UserRight, VideoImportState } from '@shared/models'
8 import { VideoImportCreate } from '@shared/models/videos/import/video-import-create.model'
9 import { isIdValid, toIntOrNull } from '../../../helpers/custom-validators/misc'
10 import { isVideoImportTargetUrlValid, isVideoImportTorrentFile } from '../../../helpers/custom-validators/video-imports'
11 import { isVideoMagnetUriValid, isVideoNameValid } from '../../../helpers/custom-validators/videos'
12 import { cleanUpReqFiles } from '../../../helpers/express-utils'
13 import { logger } from '../../../helpers/logger'
14 import { CONFIG } from '../../../initializers/config'
15 import { CONSTRAINTS_FIELDS } from '../../../initializers/constants'
16 import { areValidationErrors, doesVideoChannelOfAccountExist, doesVideoImportExist } from '../shared'
17 import { getCommonVideoEditAttributes } from './videos'
18
19 const videoImportAddValidator = getCommonVideoEditAttributes().concat([
20 body('channelId')
21 .customSanitizer(toIntOrNull)
22 .custom(isIdValid).withMessage('Should have correct video channel id'),
23 body('targetUrl')
24 .optional()
25 .custom(isVideoImportTargetUrlValid).withMessage('Should have a valid video import target URL'),
26 body('magnetUri')
27 .optional()
28 .custom(isVideoMagnetUriValid).withMessage('Should have a valid video magnet URI'),
29 body('torrentfile')
30 .custom((value, { req }) => isVideoImportTorrentFile(req.files))
31 .withMessage(
32 'This torrent file is not supported or too large. Please, make sure it is of the following type: ' +
33 CONSTRAINTS_FIELDS.VIDEO_IMPORTS.TORRENT_FILE.EXTNAME.join(', ')
34 ),
35 body('name')
36 .optional()
37 .custom(isVideoNameValid).withMessage(
38 `Should have a video name between ${CONSTRAINTS_FIELDS.VIDEOS.NAME.min} and ${CONSTRAINTS_FIELDS.VIDEOS.NAME.max} characters long`
39 ),
40
41 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
42 logger.debug('Checking videoImportAddValidator parameters', { parameters: req.body })
43
44 const user = res.locals.oauth.token.User
45 const torrentFile = req.files?.['torrentfile'] ? req.files['torrentfile'][0] : undefined
46
47 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
48
49 if (CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true && req.body.targetUrl) {
50 cleanUpReqFiles(req)
51
52 return res.fail({
53 status: HttpStatusCode.CONFLICT_409,
54 message: 'HTTP import is not enabled on this instance.'
55 })
56 }
57
58 if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) {
59 cleanUpReqFiles(req)
60
61 return res.fail({
62 status: HttpStatusCode.CONFLICT_409,
63 message: 'Torrent/magnet URI import is not enabled on this instance.'
64 })
65 }
66
67 if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
68
69 // Check we have at least 1 required param
70 if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) {
71 cleanUpReqFiles(req)
72
73 return res.fail({ message: 'Should have a magnetUri or a targetUrl or a torrent file.' })
74 }
75
76 if (req.body.targetUrl) {
77 const hostname = new URL(req.body.targetUrl).hostname
78
79 if (isIPValid(hostname)) {
80 const parsed = parseIP(hostname)
81
82 if (parsed.range() !== 'unicast') {
83 cleanUpReqFiles(req)
84
85 return res.fail({
86 status: HttpStatusCode.FORBIDDEN_403,
87 message: 'Cannot use non unicast IP as targetUrl.'
88 })
89 }
90 }
91 }
92
93 if (!await isImportAccepted(req, res)) return cleanUpReqFiles(req)
94
95 return next()
96 }
97 ])
98
99 const videoImportDeleteValidator = [
100 param('id')
101 .custom(isIdValid).withMessage('Should have correct import id'),
102
103 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
104 logger.debug('Checking videoImportDeleteValidator parameters', { parameters: req.params })
105
106 if (areValidationErrors(req, res)) return
107
108 if (!await doesVideoImportExist(parseInt(req.params.id), res)) return
109 if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return
110
111 if (res.locals.videoImport.state === VideoImportState.PENDING) {
112 return res.fail({
113 status: HttpStatusCode.CONFLICT_409,
114 message: 'Cannot delete a pending video import. Cancel it or wait for the end of the import first.'
115 })
116 }
117
118 return next()
119 }
120 ]
121
122 const videoImportCancelValidator = [
123 param('id')
124 .custom(isIdValid).withMessage('Should have correct import id'),
125
126 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
127 logger.debug('Checking videoImportCancelValidator parameters', { parameters: req.params })
128
129 if (areValidationErrors(req, res)) return
130
131 if (!await doesVideoImportExist(parseInt(req.params.id), res)) return
132 if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return
133
134 if (res.locals.videoImport.state !== VideoImportState.PENDING) {
135 return res.fail({
136 status: HttpStatusCode.CONFLICT_409,
137 message: 'Cannot cancel a non pending video import.'
138 })
139 }
140
141 return next()
142 }
143 ]
144
145 // ---------------------------------------------------------------------------
146
147 export {
148 videoImportAddValidator,
149 videoImportCancelValidator,
150 videoImportDeleteValidator
151 }
152
153 // ---------------------------------------------------------------------------
154
155 async function isImportAccepted (req: express.Request, res: express.Response) {
156 const body: VideoImportCreate = req.body
157 const hookName = body.targetUrl
158 ? 'filter:api.video.pre-import-url.accept.result'
159 : 'filter:api.video.pre-import-torrent.accept.result'
160
161 // Check we accept this video
162 const acceptParameters = {
163 videoImportBody: body,
164 user: res.locals.oauth.token.User
165 }
166 const acceptedResult = await Hooks.wrapFun(
167 isPreImportVideoAccepted,
168 acceptParameters,
169 hookName
170 )
171
172 if (!acceptedResult || acceptedResult.accepted !== true) {
173 logger.info('Refused to import video.', { acceptedResult, acceptParameters })
174
175 res.fail({
176 status: HttpStatusCode.FORBIDDEN_403,
177 message: acceptedResult.errorMessage || 'Refused to import video'
178 })
179 return false
180 }
181
182 return true
183 }
184
185 function checkUserCanManageImport (user: MUserAccountId, videoImport: MVideoImport, res: express.Response) {
186 if (user.hasRight(UserRight.MANAGE_VIDEO_IMPORTS) === false && videoImport.userId !== user.id) {
187 res.fail({
188 status: HttpStatusCode.FORBIDDEN_403,
189 message: 'Cannot manage video import of another user'
190 })
191 return false
192 }
193
194 return true
195 }