]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/job-queue/handlers/activitypub-follow.ts
Don't send follow request if the follow is already accepted
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / activitypub-follow.ts
CommitLineData
94831479 1import * as Bull from 'bull'
5350fd8e
C
2import { logger } from '../../../helpers/logger'
3import { getServerActor } from '../../../helpers/utils'
4import { REMOTE_SCHEME, sequelizeTypescript, SERVER_ACTOR_NAME } from '../../../initializers'
5import { sendFollow } from '../../activitypub/send'
6import { sanitizeHost } from '../../../helpers/core-utils'
7import { loadActorUrlOrGetFromWebfinger } from '../../../helpers/webfinger'
8import { getOrCreateActorAndServerAndModel } from '../../activitypub/actor'
9import { retryTransactionWrapper } from '../../../helpers/database-utils'
10import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
11import { ActorModel } from '../../../models/activitypub/actor'
12
13export type ActivitypubFollowPayload = {
14 host: string
15}
16
94831479 17async function processActivityPubFollow (job: Bull.Job) {
5350fd8e
C
18 const payload = job.data as ActivitypubFollowPayload
19 const host = payload.host
20
21 logger.info('Processing ActivityPub follow in job %d.', job.id)
22
23 const sanitizedHost = sanitizeHost(host, REMOTE_SCHEME.HTTP)
24
25 const actorUrl = await loadActorUrlOrGetFromWebfinger(SERVER_ACTOR_NAME, sanitizedHost)
26 const targetActor = await getOrCreateActorAndServerAndModel(actorUrl)
27
28 const fromActor = await getServerActor()
5350fd8e 29
90d4bb81 30 return retryTransactionWrapper(follow, fromActor, targetActor)
5350fd8e
C
31}
32// ---------------------------------------------------------------------------
33
34export {
35 processActivityPubFollow
36}
37
38// ---------------------------------------------------------------------------
39
40function follow (fromActor: ActorModel, targetActor: ActorModel) {
41 if (fromActor.id === targetActor.id) {
42 throw new Error('Follower is the same than target actor.')
43 }
44
45 return sequelizeTypescript.transaction(async t => {
46 const [ actorFollow ] = await ActorFollowModel.findOrCreate({
47 where: {
48 actorId: fromActor.id,
49 targetActorId: targetActor.id
50 },
51 defaults: {
52 state: 'pending',
53 actorId: fromActor.id,
54 targetActorId: targetActor.id
55 },
56 transaction: t
57 })
58 actorFollow.ActorFollowing = targetActor
59 actorFollow.ActorFollower = fromActor
60
6104adc3
C
61 // Send a notification to remote server if our follow is not already accepted
62 if (actorFollow.state !== 'accepted') await sendFollow(actorFollow)
5350fd8e
C
63 })
64}