1 import * as Bull from 'bull'
2 import { logger } from '../../../helpers/logger'
3 import { REMOTE_SCHEME, sequelizeTypescript, WEBSERVER } from '../../../initializers'
4 import { sendFollow } from '../../activitypub/send'
5 import { sanitizeHost } from '../../../helpers/core-utils'
6 import { loadActorUrlOrGetFromWebfinger } from '../../../helpers/webfinger'
7 import { getOrCreateActorAndServerAndModel } from '../../activitypub/actor'
8 import { retryTransactionWrapper } from '../../../helpers/database-utils'
9 import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
10 import { ActorModel } from '../../../models/activitypub/actor'
11 import { Notifier } from '../../notifier'
13 export type ActivitypubFollowPayload = {
14 followerActorId: number
19 async function processActivityPubFollow (job: Bull.Job) {
20 const payload = job.data as ActivitypubFollowPayload
21 const host = payload.host
23 logger.info('Processing ActivityPub follow in job %d.', job.id)
25 let targetActor: ActorModel
26 if (!host || host === WEBSERVER.HOST) {
27 targetActor = await ActorModel.loadLocalByName(payload.name)
29 const sanitizedHost = sanitizeHost(host, REMOTE_SCHEME.HTTP)
30 const actorUrl = await loadActorUrlOrGetFromWebfinger(payload.name + '@' + sanitizedHost)
31 targetActor = await getOrCreateActorAndServerAndModel(actorUrl)
34 const fromActor = await ActorModel.load(payload.followerActorId)
36 return retryTransactionWrapper(follow, fromActor, targetActor)
38 // ---------------------------------------------------------------------------
41 processActivityPubFollow
44 // ---------------------------------------------------------------------------
46 async function follow (fromActor: ActorModel, targetActor: ActorModel) {
47 if (fromActor.id === targetActor.id) {
48 throw new Error('Follower is the same than target actor.')
51 // Same server, direct accept
52 const state = !fromActor.serverId && !targetActor.serverId ? 'accepted' : 'pending'
54 const actorFollow = await sequelizeTypescript.transaction(async t => {
55 const [ actorFollow ] = await ActorFollowModel.findOrCreate({
57 actorId: fromActor.id,
58 targetActorId: targetActor.id
62 actorId: fromActor.id,
63 targetActorId: targetActor.id
67 actorFollow.ActorFollowing = targetActor
68 actorFollow.ActorFollower = fromActor
70 // Send a notification to remote server if our follow is not already accepted
71 if (actorFollow.state !== 'accepted') await sendFollow(actorFollow)
76 if (actorFollow.state === 'accepted') Notifier.Instance.notifyOfNewUserFollow(actorFollow)