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, sendReject } from '../send'
8 import { Notifier } from '../../notifier'
9 import { getAPId } from '../../../helpers/activitypub'
10 import { getServerActor } from '../../../helpers/utils'
11 import { CONFIG } from '../../../initializers/config'
12 import { APProcessorOptions } from '../../../typings/activitypub-processor.model'
14 async function processFollowActivity (options: APProcessorOptions<ActivityFollow>) {
15 const { activity, byActor } = options
16 const activityObject = getAPId(activity.object)
18 return retryTransactionWrapper(processFollow, byActor, activityObject)
21 // ---------------------------------------------------------------------------
27 // ---------------------------------------------------------------------------
29 async function processFollow (actor: ActorModel, targetActorURL: string) {
30 const { actorFollow, created, isFollowingInstance } = await sequelizeTypescript.transaction(async t => {
31 const targetActor = await ActorModel.loadByUrlAndPopulateAccountAndChannel(targetActorURL, t)
33 if (!targetActor) throw new Error('Unknown actor')
34 if (targetActor.isOwned() === false) throw new Error('This is not a local actor.')
36 const serverActor = await getServerActor()
37 const isFollowingInstance = targetActor.id === serverActor.id
39 if (isFollowingInstance && CONFIG.FOLLOWERS.INSTANCE.ENABLED === false) {
40 logger.info('Rejecting %s because instance followers are disabled.', targetActor.url)
42 await sendReject(actor, targetActor)
44 return { actorFollow: undefined }
47 const [ actorFollow, created ] = await ActorFollowModel.findOrCreate({
50 targetActorId: targetActor.id
54 targetActorId: targetActor.id,
55 state: CONFIG.FOLLOWERS.INSTANCE.MANUAL_APPROVAL ? 'pending' : 'accepted'
60 if (actorFollow.state !== 'accepted' && CONFIG.FOLLOWERS.INSTANCE.MANUAL_APPROVAL === false) {
61 actorFollow.state = 'accepted'
62 await actorFollow.save({ transaction: t })
65 actorFollow.ActorFollower = actor
66 actorFollow.ActorFollowing = targetActor
68 // Target sends to actor he accepted the follow request
69 if (actorFollow.state === 'accepted') await sendAccept(actorFollow)
71 return { actorFollow, created, isFollowingInstance }
75 if (!actorFollow) return
78 if (isFollowingInstance) Notifier.Instance.notifyOfNewInstanceFollow(actorFollow)
79 else Notifier.Instance.notifyOfNewUserFollow(actorFollow)
82 logger.info('Actor %s is followed by actor %s.', targetActorURL, actor.url)