Add videos list filters
[oweals/peertube.git] / server / helpers / custom-validators / activitypub / misc.ts
1 import * as validator from 'validator'
2 import { CONSTRAINTS_FIELDS } from '../../../initializers'
3 import { isTestInstance } from '../../core-utils'
4 import { exists } from '../misc'
5
6 function isActivityPubUrlValid (url: string) {
7   const isURLOptions = {
8     require_host: true,
9     require_tld: true,
10     require_protocol: true,
11     require_valid_protocol: true,
12     protocols: [ 'http', 'https' ]
13   }
14
15   // We validate 'localhost', so we don't have the top level domain
16   if (isTestInstance()) {
17     isURLOptions.require_tld = false
18   }
19
20   return exists(url) && validator.isURL('' + url, isURLOptions) && validator.isLength('' + url, CONSTRAINTS_FIELDS.ACTORS.URL)
21 }
22
23 function isBaseActivityValid (activity: any, type: string) {
24   return (activity['@context'] === undefined || Array.isArray(activity['@context'])) &&
25     activity.type === type &&
26     isActivityPubUrlValid(activity.id) &&
27     (isActivityPubUrlValid(activity.actor) || isActivityPubUrlValid(activity.actor.id)) &&
28     (
29       activity.to === undefined ||
30       (Array.isArray(activity.to) && activity.to.every(t => isActivityPubUrlValid(t)))
31     ) &&
32     (
33       activity.cc === undefined ||
34       (Array.isArray(activity.cc) && activity.cc.every(t => isActivityPubUrlValid(t)))
35     )
36 }
37
38 function setValidAttributedTo (obj: any) {
39   if (Array.isArray(obj.attributedTo) === false) {
40     obj.attributedTo = []
41     return true
42   }
43
44   const newAttributesTo = obj.attributedTo.filter(a => {
45     return (a.type === 'Group' || a.type === 'Person') && isActivityPubUrlValid(a.id)
46   })
47
48   obj.attributedTo = newAttributesTo
49
50   return true
51 }
52
53 export {
54   isActivityPubUrlValid,
55   isBaseActivityValid,
56   setValidAttributedTo
57 }