]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/lib/job-queue/handlers/activitypub-follow.ts
Fix adding captions to a video
[github/Chocobozzz/PeerTube.git] / server / lib / job-queue / handlers / activitypub-follow.ts
1 import * as Bull from 'bull'
2 import { logger } from '../../../helpers/logger'
3 import { CONFIG, REMOTE_SCHEME, sequelizeTypescript } 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
12 export type ActivitypubFollowPayload = {
13 followerActorId: number
14 name: string
15 host: string
16 }
17
18 async function processActivityPubFollow (job: Bull.Job) {
19 const payload = job.data as ActivitypubFollowPayload
20 const host = payload.host
21
22 logger.info('Processing ActivityPub follow in job %d.', job.id)
23
24 let targetActor: ActorModel
25 if (!host || host === CONFIG.WEBSERVER.HOST) {
26 targetActor = await ActorModel.loadLocalByName(payload.name)
27 } else {
28 const sanitizedHost = sanitizeHost(host, REMOTE_SCHEME.HTTP)
29 const actorUrl = await loadActorUrlOrGetFromWebfinger(payload.name + '@' + sanitizedHost)
30 targetActor = await getOrCreateActorAndServerAndModel(actorUrl)
31 }
32
33 const fromActor = await ActorModel.load(payload.followerActorId)
34
35 return retryTransactionWrapper(follow, fromActor, targetActor)
36 }
37 // ---------------------------------------------------------------------------
38
39 export {
40 processActivityPubFollow
41 }
42
43 // ---------------------------------------------------------------------------
44
45 function follow (fromActor: ActorModel, targetActor: ActorModel) {
46 if (fromActor.id === targetActor.id) {
47 throw new Error('Follower is the same than target actor.')
48 }
49
50 // Same server, direct accept
51 const state = !fromActor.serverId && !targetActor.serverId ? 'accepted' : 'pending'
52
53 return sequelizeTypescript.transaction(async t => {
54 const [ actorFollow ] = await ActorFollowModel.findOrCreate({
55 where: {
56 actorId: fromActor.id,
57 targetActorId: targetActor.id
58 },
59 defaults: {
60 state,
61 actorId: fromActor.id,
62 targetActorId: targetActor.id
63 },
64 transaction: t
65 })
66 actorFollow.ActorFollowing = targetActor
67 actorFollow.ActorFollower = fromActor
68
69 // Send a notification to remote server if our follow is not already accepted
70 if (actorFollow.state !== 'accepted') await sendFollow(actorFollow)
71 })
72 }