1 import * as kue from 'kue'
2 import { logger } from '../../../helpers/logger'
3 import { getServerActor } from '../../../helpers/utils'
4 import { REMOTE_SCHEME, sequelizeTypescript, SERVER_ACTOR_NAME } from '../../../initializers'
5 import { sendFollow } from '../../activitypub/send'
6 import { sanitizeHost } from '../../../helpers/core-utils'
7 import { loadActorUrlOrGetFromWebfinger } from '../../../helpers/webfinger'
8 import { getOrCreateActorAndServerAndModel } from '../../activitypub/actor'
9 import { retryTransactionWrapper } from '../../../helpers/database-utils'
10 import { ActorFollowModel } from '../../../models/activitypub/actor-follow'
11 import { ActorModel } from '../../../models/activitypub/actor'
13 export type ActivitypubFollowPayload = {
17 async function processActivityPubFollow (job: kue.Job) {
18 const payload = job.data as ActivitypubFollowPayload
19 const host = payload.host
21 logger.info('Processing ActivityPub follow in job %d.', job.id)
23 const sanitizedHost = sanitizeHost(host, REMOTE_SCHEME.HTTP)
25 const actorUrl = await loadActorUrlOrGetFromWebfinger(SERVER_ACTOR_NAME, sanitizedHost)
26 const targetActor = await getOrCreateActorAndServerAndModel(actorUrl)
28 const fromActor = await getServerActor()
30 arguments: [ fromActor, targetActor ],
31 errorMessage: 'Cannot follow with many retries.'
34 return retryTransactionWrapper(follow, options)
36 // ---------------------------------------------------------------------------
39 processActivityPubFollow
42 // ---------------------------------------------------------------------------
44 function follow (fromActor: ActorModel, targetActor: ActorModel) {
45 if (fromActor.id === targetActor.id) {
46 throw new Error('Follower is the same than target actor.')
49 return sequelizeTypescript.transaction(async t => {
50 const [ actorFollow ] = await ActorFollowModel.findOrCreate({
52 actorId: fromActor.id,
53 targetActorId: targetActor.id
57 actorId: fromActor.id,
58 targetActorId: targetActor.id
62 actorFollow.ActorFollowing = targetActor
63 actorFollow.ActorFollower = fromActor
65 // Send a notification to remote server
66 await sendFollow(actorFollow)