aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/activitypub/activity.ts
blob: 391bcd9c6f85d069a4e6e16ef3d7d8d2df134e73 (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
67
68
69
70
71
72
73
74
import { doJSONRequest, PeerTubeRequestOptions } from '@server/helpers/requests'
import { CONFIG } from '@server/initializers/config'
import { ActivityObject, ActivityPubActor, ActivityType, APObjectId } from '@shared/models'
import { buildSignedRequestOptions } from './send'

export function getAPId (object: string | { id: string }) {
  if (typeof object === 'string') return object

  return object.id
}

export function getActivityStreamDuration (duration: number) {
  // https://www.w3.org/TR/activitystreams-vocabulary/#dfn-duration
  return 'PT' + duration + 'S'
}

export function getDurationFromActivityStream (duration: string) {
  return parseInt(duration.replace(/[^\d]+/, ''))
}

// ---------------------------------------------------------------------------

export function buildAvailableActivities (): ActivityType[] {
  return [
    'Create',
    'Update',
    'Delete',
    'Follow',
    'Accept',
    'Announce',
    'Undo',
    'Like',
    'Reject',
    'View',
    'Dislike',
    'Flag'
  ]
}

// ---------------------------------------------------------------------------

export async function fetchAP <T> (url: string, moreOptions: PeerTubeRequestOptions = {}) {
  const options = {
    activityPub: true,

    httpSignature: CONFIG.FEDERATION.SIGN_FEDERATED_FETCHES
      ? await buildSignedRequestOptions({ hasPayload: false })
      : undefined,

    ...moreOptions
  }

  return doJSONRequest<T>(url, options)
}

export async function fetchAPObjectIfNeeded <T extends (ActivityObject | ActivityPubActor)> (object: APObjectId) {
  if (typeof object === 'string') {
    const { body } = await fetchAP<Exclude<T, string>>(object)

    return body
  }

  return object as Exclude<T, string>
}

export async function findLatestAPRedirection (url: string, iteration = 1) {
  if (iteration > 10) throw new Error('Too much iterations to find final URL ' + url)

  const { headers } = await fetchAP(url, { followRedirect: false })

  if (headers.location) return findLatestAPRedirection(headers.location, iteration + 1)

  return url
}