Add commentsEnabled field to AS context
[oweals/peertube.git] / server / helpers / activitypub.ts
1 import { ResultList } from '../../shared/models'
2 import { Activity } from '../../shared/models/activitypub'
3 import { ACTIVITY_PUB } from '../initializers'
4 import { ActorModel } from '../models/activitypub/actor'
5 import { signObject } from './peertube-crypto'
6
7 function activityPubContextify <T> (data: T) {
8   return Object.assign(data,{
9     '@context': [
10       'https://www.w3.org/ns/activitystreams',
11       'https://w3id.org/security/v1',
12       {
13         'RsaSignature2017': 'https://w3id.org/security#RsaSignature2017',
14         'Hashtag': 'as:Hashtag',
15         'uuid': 'http://schema.org/identifier',
16         'category': 'http://schema.org/category',
17         'licence': 'http://schema.org/license',
18         'nsfw': 'as:sensitive',
19         'language': 'http://schema.org/inLanguage',
20         'views': 'http://schema.org/Number',
21         'size': 'http://schema.org/Number',
22         'commentsEnabled': 'http://schema.org/Boolean'
23       }
24     ]
25   })
26 }
27
28 function activityPubCollection (results: any[]) {
29   return {
30     type: 'OrderedCollection',
31     totalItems: results.length,
32     orderedItems: results
33   }
34 }
35
36 function activityPubCollectionPagination (url: string, page: any, result: ResultList<any>) {
37   let next: string
38   let prev: string
39
40   // Assert page is a number
41   page = parseInt(page, 10)
42
43   // There are more results
44   if (result.total > page * ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE) {
45     next = url + '?page=' + (page + 1)
46   }
47
48   if (page > 1) {
49     prev = url + '?page=' + (page - 1)
50   }
51
52   const orderedCollectionPagination = {
53     id: url + '?page=' + page,
54     type: 'OrderedCollectionPage',
55     prev,
56     next,
57     partOf: url,
58     orderedItems: result.data
59   }
60
61   if (page === 1) {
62     return activityPubContextify({
63       id: url,
64       type: 'OrderedCollection',
65       totalItems: result.total,
66       first: orderedCollectionPagination
67     })
68   } else {
69     orderedCollectionPagination['totalItems'] = result.total
70   }
71
72   return orderedCollectionPagination
73 }
74
75 function buildSignedActivity (byActor: ActorModel, data: Object) {
76   const activity = activityPubContextify(data)
77
78   return signObject(byActor, activity) as Promise<Activity>
79 }
80
81 // ---------------------------------------------------------------------------
82
83 export {
84   activityPubContextify,
85   activityPubCollectionPagination,
86   activityPubCollection,
87   buildSignedActivity
88 }