aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/middlewares/validators/videos/video-channel-sync.ts
blob: b184982431c6efe3c5851f4038ddc994a19b474f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import * as express from 'express'
import { body, param } from 'express-validator'
import { isUrlValid } from '@server/helpers/custom-validators/activitypub/misc'
import { logger } from '@server/helpers/logger'
import { CONFIG } from '@server/initializers/config'
import { VideoChannelModel } from '@server/models/video/video-channel'
import { VideoChannelSyncModel } from '@server/models/video/video-channel-sync'
import { HttpStatusCode, VideoChannelSyncCreate } from '@shared/models'
import { areValidationErrors, doesVideoChannelIdExist } from '../shared'

export const ensureSyncIsEnabled = (req: express.Request, res: express.Response, next: express.NextFunction) => {
  if (!CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.ENABLED) {
    return res.fail({
      status: HttpStatusCode.FORBIDDEN_403,
      message: 'Synchronization is impossible as video channel synchronization is not enabled on the server'
    })
  }

  return next()
}

export const videoChannelSyncValidator = [
  body('externalChannelUrl').custom(isUrlValid).withMessage('Should have a valid channel url'),
  body('videoChannelId').isInt().withMessage('Should have a valid video channel id'),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    logger.debug('Checking videoChannelSync parameters', { parameters: req.body })

    if (areValidationErrors(req, res)) return

    const body: VideoChannelSyncCreate = req.body
    if (!await doesVideoChannelIdExist(body.videoChannelId, res)) return

    const count = await VideoChannelSyncModel.countByAccount(res.locals.videoChannel.accountId)
    if (count >= CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.MAX_PER_USER) {
      return res.fail({
        message: `You cannot create more than ${CONFIG.IMPORT.VIDEO_CHANNEL_SYNCHRONIZATION.MAX_PER_USER} channel synchronizations`
      })
    }

    return next()
  }
]

export const ensureSyncExists = [
  param('id').exists().isInt().withMessage('Should have an sync id'),

  async (req: express.Request, res: express.Response, next: express.NextFunction) => {
    if (areValidationErrors(req, res)) return

    const syncId = parseInt(req.params.id, 10)
    const sync = await VideoChannelSyncModel.loadWithChannel(syncId)

    if (!sync) {
      return res.fail({
        status: HttpStatusCode.NOT_FOUND_404,
        message: 'Synchronization not found'
      })
    }

    res.locals.videoChannelSync = sync
    res.locals.videoChannel = await VideoChannelModel.loadAndPopulateAccount(sync.videoChannelId)

    return next()
  }
]