1 import { Transaction } from 'sequelize'
2 import { ActorFollowHealthCache } from '@server/lib/actor-follow-health-cache'
3 import { getServerActor } from '@server/models/application/application'
4 import { Activity, ActivityAudience, ActivitypubHttpBroadcastPayload } from '@shared/models'
5 import { ContextType } from '@shared/models/activitypub/context'
6 import { afterCommitIfTransaction } from '../../../../helpers/database-utils'
7 import { logger } from '../../../../helpers/logger'
8 import { ActorModel } from '../../../../models/actor/actor'
9 import { ActorFollowModel } from '../../../../models/actor/actor-follow'
10 import { MActor, MActorId, MActorLight, MActorWithInboxes, MVideoAccountLight, MVideoId, MVideoImmutable } from '../../../../types/models'
11 import { JobQueue } from '../../../job-queue'
12 import { getActorsInvolvedInVideo, getAudienceFromFollowersOf, getOriginVideoAudience } from './audience-utils'
14 async function sendVideoRelatedActivity (activityBuilder: (audience: ActivityAudience) => Activity, options: {
16 video: MVideoImmutable | MVideoAccountLight
17 contextType: ContextType
18 transaction?: Transaction
20 const { byActor, video, transaction, contextType } = options
22 const actorsInvolvedInVideo = await getActorsInvolvedInVideo(video, transaction)
25 if (video.isOwned() === false) {
26 return sendVideoActivityToOrigin(activityBuilder, options)
30 const audience = getAudienceFromFollowersOf(actorsInvolvedInVideo)
31 const activity = activityBuilder(audience)
33 const actorsException = [ byActor ]
35 return broadcastToFollowers({
38 toFollowersOf: actorsInvolvedInVideo,
45 async function sendVideoActivityToOrigin (activityBuilder: (audience: ActivityAudience) => Activity, options: {
47 video: MVideoImmutable | MVideoAccountLight
48 contextType: ContextType
50 actorsInvolvedInVideo?: MActorLight[]
51 transaction?: Transaction
53 const { byActor, video, actorsInvolvedInVideo, transaction, contextType } = options
55 if (video.isOwned()) throw new Error('Cannot send activity to owned video origin ' + video.url)
57 let accountActor: MActorLight = (video as MVideoAccountLight).VideoChannel?.Account?.Actor
58 if (!accountActor) accountActor = await ActorModel.loadAccountActorByVideoId(video.id, transaction)
60 const audience = getOriginVideoAudience(accountActor, actorsInvolvedInVideo)
61 const activity = activityBuilder(audience)
63 return afterCommitIfTransaction(transaction, () => {
67 toActorUrl: accountActor.getSharedInbox(),
73 // ---------------------------------------------------------------------------
75 async function forwardVideoRelatedActivity (
78 followersException: MActorWithInboxes[],
81 // Mastodon does not add our announces in audience, so we forward to them manually
82 const additionalActors = await getActorsInvolvedInVideo(video, t)
83 const additionalFollowerUrls = additionalActors.map(a => a.followersUrl)
85 return forwardActivity(activity, t, followersException, additionalFollowerUrls)
88 async function forwardActivity (
91 followersException: MActorWithInboxes[] = [],
92 additionalFollowerUrls: string[] = []
94 logger.info('Forwarding activity %s.', activity.id)
96 const to = activity.to || []
97 const cc = activity.cc || []
99 const followersUrls = additionalFollowerUrls
100 for (const dest of to.concat(cc)) {
101 if (dest.endsWith('/followers')) {
102 followersUrls.push(dest)
106 const toActorFollowers = await ActorModel.listByFollowersUrls(followersUrls, t)
107 const uris = await computeFollowerUris(toActorFollowers, followersException, t)
109 if (uris.length === 0) {
110 logger.info('0 followers for %s, no forwarding.', toActorFollowers.map(a => a.id).join(', '))
114 logger.debug('Creating forwarding job.', { uris })
116 const payload: ActivitypubHttpBroadcastPayload = {
121 return afterCommitIfTransaction(t, () => JobQueue.Instance.createJob({ type: 'activitypub-http-broadcast', payload }))
124 // ---------------------------------------------------------------------------
126 async function broadcastToFollowers (options: {
129 toFollowersOf: MActorId[]
130 transaction: Transaction
131 contextType: ContextType
133 actorsException?: MActorWithInboxes[]
135 const { data, byActor, toFollowersOf, transaction, contextType, actorsException = [] } = options
137 const uris = await computeFollowerUris(toFollowersOf, actorsException, transaction)
139 return afterCommitIfTransaction(transaction, () => {
149 async function broadcastToActors (options: {
153 transaction: Transaction
154 contextType: ContextType
155 actorsException?: MActorWithInboxes[]
157 const { data, byActor, toActors, transaction, contextType, actorsException = [] } = options
159 const uris = await computeUris(toActors, actorsException)
161 return afterCommitIfTransaction(transaction, () => {
171 function broadcastTo (options: {
175 contextType: ContextType
177 const { uris, data, byActor, contextType } = options
179 if (uris.length === 0) return undefined
181 const broadcastUris: string[] = []
182 const unicastUris: string[] = []
184 // Bad URIs could be slow to respond, prefer to process them in a dedicated queue
185 for (const uri of uris) {
186 if (ActorFollowHealthCache.Instance.isBadInbox(uri)) {
187 unicastUris.push(uri)
189 broadcastUris.push(uri)
193 logger.debug('Creating broadcast job.', { broadcastUris, unicastUris })
195 if (broadcastUris.length !== 0) {
198 signatureActorId: byActor.id,
203 JobQueue.Instance.createJob({ type: 'activitypub-http-broadcast', payload })
206 for (const unicastUri of unicastUris) {
209 signatureActorId: byActor.id,
214 JobQueue.Instance.createJob({ type: 'activitypub-http-unicast', payload })
218 function unicastTo (options: {
222 contextType: ContextType
224 const { data, byActor, toActorUrl, contextType } = options
226 logger.debug('Creating unicast job.', { uri: toActorUrl })
230 signatureActorId: byActor.id,
235 JobQueue.Instance.createJob({ type: 'activitypub-http-unicast', payload })
238 // ---------------------------------------------------------------------------
241 broadcastToFollowers,
245 sendVideoActivityToOrigin,
246 forwardVideoRelatedActivity,
247 sendVideoRelatedActivity
250 // ---------------------------------------------------------------------------
252 async function computeFollowerUris (toFollowersOf: MActorId[], actorsException: MActorWithInboxes[], t: Transaction) {
253 const toActorFollowerIds = toFollowersOf.map(a => a.id)
255 const result = await ActorFollowModel.listAcceptedFollowerSharedInboxUrls(toActorFollowerIds, t)
256 const sharedInboxesException = await buildSharedInboxesException(actorsException)
258 return result.data.filter(sharedInbox => sharedInboxesException.includes(sharedInbox) === false)
261 async function computeUris (toActors: MActor[], actorsException: MActorWithInboxes[] = []) {
262 const serverActor = await getServerActor()
263 const targetUrls = toActors
264 .filter(a => a.id !== serverActor.id) // Don't send to ourselves
265 .map(a => a.getSharedInbox())
267 const toActorSharedInboxesSet = new Set(targetUrls)
269 const sharedInboxesException = await buildSharedInboxesException(actorsException)
270 return Array.from(toActorSharedInboxesSet)
271 .filter(sharedInbox => sharedInboxesException.includes(sharedInbox) === false)
274 async function buildSharedInboxesException (actorsException: MActorWithInboxes[]) {
275 const serverActor = await getServerActor()
277 return actorsException
278 .map(f => f.getSharedInbox())
279 .concat([ serverActor.sharedInboxUrl ])