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