video-imports.ts 6.8 KB

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