1 import * as Bluebird from 'bluebird'
2 import * as validator from 'validator'
3 import { ResultList } from '../../shared/models'
4 import { Activity } from '../../shared/models/activitypub'
5 import { ACTIVITY_PUB } from '../initializers'
6 import { ActorModel } from '../models/activitypub/actor'
7 import { signJsonLDObject } from './peertube-crypto'
8 import { pageToStartAndCount } from './core-utils'
9 import { parse } from 'url'
11 function activityPubContextify <T> (data: T) {
12 return Object.assign(data, {
14 'https://www.w3.org/ns/activitystreams',
15 'https://w3id.org/security/v1',
17 RsaSignature2017: 'https://w3id.org/security#RsaSignature2017',
18 pt: 'https://joinpeertube.org/ns',
19 sc: 'http://schema.org#',
20 Hashtag: 'as:Hashtag',
21 uuid: 'sc:identifier',
22 category: 'sc:category',
23 licence: 'sc:license',
24 subtitleLanguage: 'sc:subtitleLanguage',
25 sensitive: 'as:sensitive',
26 language: 'sc:inLanguage',
31 commentsEnabled: 'sc:Boolean',
32 waitTranscoding: 'sc:Boolean',
33 expires: 'sc:expires',
35 CacheFile: 'pt:CacheFile'
59 type ActivityPubCollectionPaginationHandler = (start: number, count: number) => Bluebird<ResultList<any>> | Promise<ResultList<any>>
60 async function activityPubCollectionPagination (baseUrl: string, handler: ActivityPubCollectionPaginationHandler, page?: any) {
61 if (!page || !validator.isInt(page)) {
62 // We just display the first page URL, we only need the total items
63 const result = await handler(0, 1)
67 type: 'OrderedCollection',
68 totalItems: result.total,
69 first: baseUrl + '?page=1'
73 const { start, count } = pageToStartAndCount(page, ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE)
74 const result = await handler(start, count)
76 let next: string | undefined
77 let prev: string | undefined
79 // Assert page is a number
80 page = parseInt(page, 10)
82 // There are more results
83 if (result.total > page * ACTIVITY_PUB.COLLECTION_ITEMS_PER_PAGE) {
84 next = baseUrl + '?page=' + (page + 1)
88 prev = baseUrl + '?page=' + (page - 1)
92 id: baseUrl + '?page=' + page,
93 type: 'OrderedCollectionPage',
97 orderedItems: result.data,
98 totalItems: result.total
103 function buildSignedActivity (byActor: ActorModel, data: Object) {
104 const activity = activityPubContextify(data)
106 return signJsonLDObject(byActor, activity) as Promise<Activity>
109 function getAPUrl (activity: string | { id: string }) {
110 if (typeof activity === 'string') return activity
115 function checkUrlsSameHost (url1: string, url2: string) {
116 const idHost = parse(url1).host
117 const actorHost = parse(url2).host
119 return idHost && actorHost && idHost.toLowerCase() === actorHost.toLowerCase()
122 // ---------------------------------------------------------------------------
127 activityPubContextify,
128 activityPubCollectionPagination,