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 { 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'
19 const videoImportAddValidator = getCommonVideoEditAttributes().concat([
21 .customSanitizer(toIntOrNull)
25 .custom(isVideoImportTargetUrlValid),
28 .custom(isVideoMagnetUriValid),
30 .custom((value, { req }) => isVideoImportTorrentFile(req.files))
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(', ')
37 .custom(isVideoNameValid).withMessage(
38 `Should have a video name between ${CONSTRAINTS_FIELDS.VIDEOS.NAME.min} and ${CONSTRAINTS_FIELDS.VIDEOS.NAME.max} characters long`
41 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
42 const user = res.locals.oauth.token.User
43 const torrentFile = req.files?.['torrentfile'] ? req.files['torrentfile'][0] : undefined
45 if (areValidationErrors(req, res)) return cleanUpReqFiles(req)
47 if (CONFIG.IMPORT.VIDEOS.HTTP.ENABLED !== true && req.body.targetUrl) {
51 status: HttpStatusCode.CONFLICT_409,
52 message: 'HTTP import is not enabled on this instance.'
56 if (CONFIG.IMPORT.VIDEOS.TORRENT.ENABLED !== true && (req.body.magnetUri || torrentFile)) {
60 status: HttpStatusCode.CONFLICT_409,
61 message: 'Torrent/magnet URI import is not enabled on this instance.'
65 if (!await doesVideoChannelOfAccountExist(req.body.channelId, user, res)) return cleanUpReqFiles(req)
67 // Check we have at least 1 required param
68 if (!req.body.targetUrl && !req.body.magnetUri && !torrentFile) {
71 return res.fail({ message: 'Should have a magnetUri or a targetUrl or a torrent file.' })
74 if (req.body.targetUrl) {
75 const hostname = new URL(req.body.targetUrl).hostname
77 if (await isResolvingToUnicastOnly(hostname) !== true) {
81 status: HttpStatusCode.FORBIDDEN_403,
82 message: 'Cannot use non unicast IP as targetUrl.'
87 if (!await isImportAccepted(req, res)) return cleanUpReqFiles(req)
93 const getMyVideoImportsValidator = [
94 query('videoChannelSyncId')
98 (req: express.Request, res: express.Response, next: express.NextFunction) => {
99 if (areValidationErrors(req, res)) return
105 const videoImportDeleteValidator = [
109 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
110 if (areValidationErrors(req, res)) return
112 if (!await doesVideoImportExist(parseInt(req.params.id), res)) return
113 if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return
115 if (res.locals.videoImport.state === VideoImportState.PENDING) {
117 status: HttpStatusCode.CONFLICT_409,
118 message: 'Cannot delete a pending video import. Cancel it or wait for the end of the import first.'
126 const videoImportCancelValidator = [
130 async (req: express.Request, res: express.Response, next: express.NextFunction) => {
131 if (areValidationErrors(req, res)) return
133 if (!await doesVideoImportExist(parseInt(req.params.id), res)) return
134 if (!checkUserCanManageImport(res.locals.oauth.token.user, res.locals.videoImport, res)) return
136 if (res.locals.videoImport.state !== VideoImportState.PENDING) {
138 status: HttpStatusCode.CONFLICT_409,
139 message: 'Cannot cancel a non pending video import.'
147 // ---------------------------------------------------------------------------
150 videoImportAddValidator,
151 videoImportCancelValidator,
152 videoImportDeleteValidator,
153 getMyVideoImportsValidator
156 // ---------------------------------------------------------------------------
158 async function isImportAccepted (req: express.Request, res: express.Response) {
159 const body: VideoImportCreate = req.body
160 const hookName = body.targetUrl
161 ? 'filter:api.video.pre-import-url.accept.result'
162 : 'filter:api.video.pre-import-torrent.accept.result'
164 // Check we accept this video
165 const acceptParameters = {
166 videoImportBody: body,
167 user: res.locals.oauth.token.User
169 const acceptedResult = await Hooks.wrapFun(
170 isPreImportVideoAccepted,
175 if (!acceptedResult || acceptedResult.accepted !== true) {
176 logger.info('Refused to import video.', { acceptedResult, acceptParameters })
179 status: HttpStatusCode.FORBIDDEN_403,
180 message: acceptedResult.errorMessage || 'Refused to import video'
188 function checkUserCanManageImport (user: MUserAccountId, videoImport: MVideoImport, res: express.Response) {
189 if (user.hasRight(UserRight.MANAGE_VIDEO_IMPORTS) === false && videoImport.userId !== user.id) {
191 status: HttpStatusCode.FORBIDDEN_403,
192 message: 'Cannot manage video import of another user'