]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/activitypub/process/process-follow.ts
a678924403fa41e56d7dfa0dc42d8d865d2ace52
[github/Chocobozzz/PeerTube.git] / server / lib / activitypub / process / process-follow.ts
1 import { ActivityFollow } from '../../../../shared/models/activitypub'
2 import { retryTransactionWrapper } from '../../../helpers/database-utils'
3 import { logger } from '../../../helpers/logger'
4 import { sequelizeTypescript } from '../../../initializers'
5 import { ActorModel } from '../../../models/activitypub/actor'
6 import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
7 import { sendAccept } from '../send'
8 import { Notifier } from '../../notifier'
9
10 async function processFollowActivity (activity: ActivityFollow, byActor: ActorModel) {
11 const activityObject = activity.object
12
13 return retryTransactionWrapper(processFollow, byActor, activityObject)
14 }
15
16 // ---------------------------------------------------------------------------
17
18 export {
19 processFollowActivity
20 }
21
22 // ---------------------------------------------------------------------------
23
24 async function processFollow (actor: ActorModel, targetActorURL: string) {
25 const { actorFollow, created } = await sequelizeTypescript.transaction(async t => {
26 const targetActor = await ActorModel.loadByUrlAndPopulateAccountAndChannel(targetActorURL, t)
27
28 if (!targetActor) throw new Error('Unknown actor')
29 if (targetActor.isOwned() === false) throw new Error('This is not a local actor.')
30
31 const [ actorFollow, created ] = await ActorFollowModel.findOrCreate({
32 where: {
33 actorId: actor.id,
34 targetActorId: targetActor.id
35 },
36 defaults: {
37 actorId: actor.id,
38 targetActorId: targetActor.id,
39 state: 'accepted'
40 },
41 transaction: t
42 })
43
44 actorFollow.ActorFollower = actor
45 actorFollow.ActorFollowing = targetActor
46
47 if (actorFollow.state !== 'accepted') {
48 actorFollow.state = 'accepted'
49 await actorFollow.save({ transaction: t })
50 }
51
52 actorFollow.ActorFollower = actor
53 actorFollow.ActorFollowing = targetActor
54
55 // Target sends to actor he accepted the follow request
56 await sendAccept(actorFollow)
57
58 return { actorFollow, created }
59 })
60
61 if (created) Notifier.Instance.notifyOfNewFollow(actorFollow)
62
63 logger.info('Actor %s is followed by actor %s.', targetActorURL, actor.url)
64 }