Add user adminFlags
[oweals/peertube.git] / server / helpers / custom-validators / video-channels.ts
1 import * as express from 'express'
2 import 'express-validator'
3 import 'multer'
4 import * as validator from 'validator'
5 import { CONSTRAINTS_FIELDS } from '../../initializers/constants'
6 import { VideoChannelModel } from '../../models/video/video-channel'
7 import { exists } from './misc'
8
9 const VIDEO_CHANNELS_CONSTRAINTS_FIELDS = CONSTRAINTS_FIELDS.VIDEO_CHANNELS
10
11 function isVideoChannelDescriptionValid (value: string) {
12   return value === null || validator.isLength(value, VIDEO_CHANNELS_CONSTRAINTS_FIELDS.DESCRIPTION)
13 }
14
15 function isVideoChannelNameValid (value: string) {
16   return exists(value) && validator.isLength(value, VIDEO_CHANNELS_CONSTRAINTS_FIELDS.NAME)
17 }
18
19 function isVideoChannelSupportValid (value: string) {
20   return value === null || (exists(value) && validator.isLength(value, VIDEO_CHANNELS_CONSTRAINTS_FIELDS.SUPPORT))
21 }
22
23 async function doesLocalVideoChannelNameExist (name: string, res: express.Response) {
24   const videoChannel = await VideoChannelModel.loadLocalByNameAndPopulateAccount(name)
25
26   return processVideoChannelExist(videoChannel, res)
27 }
28
29 async function doesVideoChannelIdExist (id: number | string, res: express.Response) {
30   let videoChannel: VideoChannelModel
31   if (validator.isInt('' + id)) {
32     videoChannel = await VideoChannelModel.loadAndPopulateAccount(+id)
33   } else { // UUID
34     videoChannel = await VideoChannelModel.loadByUUIDAndPopulateAccount('' + id)
35   }
36
37   return processVideoChannelExist(videoChannel, res)
38 }
39
40 async function doesVideoChannelNameWithHostExist (nameWithDomain: string, res: express.Response) {
41   const videoChannel = await VideoChannelModel.loadByNameWithHostAndPopulateAccount(nameWithDomain)
42
43   return processVideoChannelExist(videoChannel, res)
44 }
45
46 // ---------------------------------------------------------------------------
47
48 export {
49   doesVideoChannelNameWithHostExist,
50   doesLocalVideoChannelNameExist,
51   isVideoChannelDescriptionValid,
52   isVideoChannelNameValid,
53   isVideoChannelSupportValid,
54   doesVideoChannelIdExist
55 }
56
57 function processVideoChannelExist (videoChannel: VideoChannelModel, res: express.Response) {
58   if (!videoChannel) {
59     res.status(404)
60        .json({ error: 'Video channel not found' })
61        .end()
62
63     return false
64   }
65
66   res.locals.videoChannel = videoChannel
67   return true
68 }