2026-10-01 11:39:10 +02:00
using MongoDB.Driver ;
using MongoDB.Entities ;
2026-10-03 11:15:21 +02:00
using PrivaPub.Domain.Statuses ;
2026-10-01 11:39:10 +02:00
using PrivaPub.Domain.Social ;
using PrivaPub.Domain.Timelines ;
using PrivaPub.Federation.Actors ;
using PrivaPub.Federation.Objects ;
using PrivaPub.Infrastructure.Ids ;
2026-10-05 06:10:25 +02:00
using PrivaPub.Models.Federation ;
2026-10-01 11:39:10 +02:00
using PrivaPub.Models.Post ;
using PrivaPub.Models.Social ;
using PrivaPub.Models.User ;
using PrivaPub.StaticServices ;
using System.Globalization ;
using System.Text.Json.Nodes ;
using static PrivaPub . Federation . Objects . ActivityJson ;
using PostEntity = PrivaPub . Models . Post . Post ;
namespace PrivaPub.Federation.Inbox.Handlers
{
2026-11-10 01:24:43 +01:00
public class AnnounceHandler (
DbEntities dbEntities ,
ILocalActorService localActors ,
IRemotePosts remotePosts ,
IFanout fanout ,
IRemoteActorService remoteActors ,
IObjectRecords records ,
IQuoteService quotes ,
IServiceProvider services = default ,
PrivaPub . Federation . Relays . IRelays relays = default ,
PrivaPub . Federation . Moderation . IDomainBlocks domainBlocks = default ) : IActivityHandler
2026-10-01 11:39:10 +02:00
{
2026-10-05 00:55:04 +02:00
// the handlers a community's relayed votes go to (Like, Dislike, Undo); resolved when first needed, since this
// handler is one of them; tests set it
2026-11-10 01:24:43 +01:00
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "Null until first needed: this handler is one of the relayed-vote handlers, so they cannot be injected into it.")]
2026-10-05 00:55:04 +02:00
public IEnumerable < IActivityHandler > Relays { get ; set ; }
2026-10-03 11:15:21 +02:00
2026-10-01 11:39:10 +02:00
public string Type => "Announce" ;
public async Task Handle ( JsonNode activity , ForeignAvatar actor , CancellationToken token )
{
var inner = activity [ "object" ];
2026-10-07 21:42:54 +02:00
if ( inner is JsonObject && Value ( inner , "type" ) is "Create" or "Update" or "Delete" or "Like" or "Dislike" or "Undo" or "Add" or "Remove" or "Block" or "Lock" or "Move" )
2026-10-01 12:30:57 +02:00
{
await GroupActivity ( inner , actor , token );
2026-10-01 11:39:10 +02:00
return ;
2026-10-01 12:30:57 +02:00
}
2026-10-01 11:39:10 +02:00
var objectUri = Id ( inner );
var announceId = Id ( activity );
if ( objectUri == default || announceId == default )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "unparseable" );
2026-10-01 11:39:10 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-11-10 01:24:43 +01:00
if ( await dbEntities . Posts . Match ( p => p . ObjectURI == announceId ). ExecuteAnyAsync ( token ))
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "duplicate" );
2026-10-01 11:39:10 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-10-01 11:39:10 +02:00
2026-11-10 01:24:43 +01:00
if ( relays != default && await relays . Passes ( actor . ActorURI , token ))
2026-10-05 23:11:59 +02:00
{
await FromRelay ( objectUri , token );
return ;
}
2026-11-10 01:24:43 +01:00
var isLocal = objectUri . StartsWith ( localActors . BaseAddress + "/" , StringComparison . OrdinalIgnoreCase );
var original = await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri && ! p . DeletedAt . HasValue && p . ReblogOfPostId == null ). ExecuteFirstAsync ( token );
var followed = await dbEntities . Followings . Match ( f => f . TargetActorURI == actor . ActorURI && f . State == FollowState . Accepted ). ExecuteAnyAsync ( token );
2026-10-01 11:39:10 +02:00
if ( original is not { IsFederatedCopy : false } && ! followed )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "not-followed" );
2026-10-01 11:39:10 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-10-01 11:39:10 +02:00
if ( original == default && ! isLocal )
2026-11-10 01:24:43 +01:00
original = await remotePosts . StoreContext ( objectUri , 0 , token );
2026-10-03 11:04:42 +02:00
if ( original == default )
{
Arrival . Drop ( "fetch-failed" );
2026-10-01 11:39:10 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
Arrival . About ( original . ObjectType ?? "Note" , original . Visibility , original . CreationDate );
if ( original . Visibility is not ( PostVisibility . Public or PostVisibility . Unlisted ))
{
Arrival . Drop ( "not-public" );
return ;
}
2026-10-01 11:39:10 +02:00
var to = Strings ( activity [ "to" ]);
var cc = Strings ( activity [ "cc" ]);
var published = DateTimeOffset . TryParse ( Value ( activity , "published" ), CultureInfo . InvariantCulture , DateTimeStyles . AssumeUniversal , out var at )
? at . UtcDateTime
: DateTime . UtcNow ;
var reblog = new PostEntity
{
2026-10-01 13:19:16 +02:00
ID = PrivacyIds . Arrived ( published ),
2026-10-01 11:39:10 +02:00
ObjectURI = announceId ,
ActivityURI = announceId ,
ActorURI = actor . ActorURI ,
AuthorAccountId = actor . ID ,
ReblogOfPostId = original . ID ,
Visibility = Addressing . Classify ( to , cc , actor . FollowersURL ),
To = to ,
Cc = cc ,
IsFederatedCopy = true ,
2026-10-17 05:23:45 +02:00
AuthorSuspended = actor . SuspendedAt . HasValue ,
2026-11-10 01:24:43 +01:00
AuthorLimited = RemotePosts . Limited ( actor , domainBlocks ),
2026-10-01 11:39:10 +02:00
CreationDate = published ,
UpdateDate = published
};
if ( reblog . Visibility == PostVisibility . Direct )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "not-public" );
2026-10-01 11:39:10 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-10-01 11:39:10 +02:00
try
{
await DB . Default . SaveAsync ( reblog , token );
}
catch ( MongoWriteException ex ) when ( ex . WriteError ?. Category == ServerErrorCategory . DuplicateKey )
{
2026-10-03 11:04:42 +02:00
Arrival . Drop ( "duplicate" );
2026-10-01 11:39:10 +02:00
return ;
}
2026-10-03 11:04:42 +02:00
Arrival . Accept ( "stored" );
2026-11-10 01:24:43 +01:00
Arrival . About ( local : original . IsFederatedCopy ? default : await localActors . FindById ( Models . Federation . LocalActorKind . Person , original . GroupUserId , token ));
2026-10-01 11:39:10 +02:00
await DB . Default . Update < PostEntity >(). MatchID ( original . ID ). Modify ( b => b . Inc ( p => p . ReblogsCount , 1 )). ExecuteAsync ( token );
if (! original . IsFederatedCopy )
2026-11-10 01:24:43 +01:00
await Notifications . Add ( original . GroupUserId , NotificationType . Reblog , actor . ID , actor . ActorURI , original . ID , token : token );
await fanout . Distribute ( reblog , token );
2026-10-01 11:39:10 +02:00
}
2026-10-05 23:11:59 +02:00
// a post a relay we subscribe to announces: kept as its author's, for the federated timeline, never as the relay's
// boost (Mastodon unwraps them the same way)
async Task FromRelay ( string objectUri , CancellationToken token )
{
2026-11-10 01:24:43 +01:00
var held = await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri ). ExecuteFirstAsync ( token );
var post = held ?? await remotePosts . StoreContext ( objectUri , 0 , token );
2026-10-05 23:11:59 +02:00
if ( post == default )
{
Arrival . Drop ( "fetch-failed" );
return ;
}
Arrival . About ( post . ObjectType ?? "Note" , post . Visibility , post . CreationDate );
if ( held != default )
{
Arrival . Drop ( "duplicate" );
return ;
}
Arrival . Accept ( "relayed" );
2026-11-10 01:24:43 +01:00
await fanout . Distribute ( post , token );
2026-10-05 23:11:59 +02:00
}
2026-10-01 12:30:57 +02:00
async Task GroupActivity ( JsonNode inner , ForeignAvatar group , CancellationToken token )
{
2026-10-03 11:04:42 +02:00
Arrival . About ( Value ( inner , "type" ));
2026-10-01 12:30:57 +02:00
if ( group . AvatarType != AvatarType . Group
2026-11-10 01:24:43 +01:00
|| ! await dbEntities . Followings . Match ( f => f . TargetActorURI == group . ActorURI && f . State == FollowState . Accepted ). ExecuteAnyAsync ( token )
2026-10-05 07:29:12 +02:00
&& ! await OurPostInItsThread ( inner , group , token ))
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "not-followed" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-10-01 12:30:57 +02:00
var objectUri = Id ( inner [ "object" ]);
switch ( Value ( inner , "type" ))
{
case "Create" when objectUri != default :
2026-11-10 01:24:43 +01:00
if ( await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri ). ExecuteAnyAsync ( token ))
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "duplicate" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-11-10 01:24:43 +01:00
var post = await remotePosts . StoreContext ( objectUri , 0 , token );
2026-10-01 12:30:57 +02:00
if ( post == default )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "fetch-failed" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
Arrival . Accept ( "stored" );
Arrival . About ( visibility : post . Visibility );
2026-10-01 12:30:57 +02:00
await DB . Default . Update < PostEntity >(). MatchID ( post . ID ). Modify ( p => p . AudienceURI , group . ActorURI ). ExecuteAsync ( token );
post . AudienceURI = group . ActorURI ;
2026-11-10 01:24:43 +01:00
await fanout . Distribute ( post , token );
2026-10-01 12:30:57 +02:00
break ;
case "Update" when objectUri != default :
2026-11-10 01:24:43 +01:00
var stored = await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri && p . AudienceURI == group . ActorURI && ! p . DeletedAt . HasValue )
2026-10-01 12:30:57 +02:00
. ExecuteFirstAsync ( token );
if ( stored == default )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "unknown-object" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
Arrival . About ( visibility : stored . Visibility , created : stored . CreationDate );
2026-11-10 01:24:43 +01:00
using ( var fetched = await remoteActors . FetchObject ( objectUri , token ))
2026-10-01 12:30:57 +02:00
{
var note = fetched == default ? default : NoteParser . Parse ( System . Text . Json . Nodes . JsonNode . Parse ( fetched . Root . GetRawText ()));
if ( note == default || note . AttributedTo != stored . ActorURI )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( note == default ? "fetch-failed" : "misattributed" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
2026-11-10 01:24:43 +01:00
Arrival . Accept ( await RemoteEdits . Apply ( stored , note , Id ( inner ), localActors , records , quotes , token ) ? "edit" : "refresh" );
2026-10-01 12:30:57 +02:00
}
break ;
case "Delete" when objectUri != default :
2026-11-10 01:24:43 +01:00
var deleted = await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri && p . AudienceURI == group . ActorURI ). ExecuteFirstAsync ( token );
2026-10-01 12:30:57 +02:00
if ( deleted == default )
2026-10-03 11:04:42 +02:00
{
Arrival . Drop ( "unknown-object" );
2026-10-01 12:30:57 +02:00
return ;
2026-10-03 11:04:42 +02:00
}
Arrival . About ( visibility : deleted . Visibility , created : deleted . CreationDate );
2026-10-05 15:44:13 +02:00
// a community on the post's own server speaks for it: PieFed keeps serving a thread its moderator removed.
// One elsewhere is believed once the post's server says it is gone
if (! Origin . Same ( objectUri , group . ActorURI ))
2026-11-10 01:24:43 +01:00
using ( var check = await remoteActors . FetchObject ( objectUri , token ))
2026-10-05 15:44:13 +02:00
if ( check != default && Value ( System . Text . Json . Nodes . JsonNode . Parse ( check . Root . GetRawText ()), "type" ) != "Tombstone" )
{
Arrival . Drop ( "not-deleted" );
return ;
}
2026-10-03 11:04:42 +02:00
Arrival . Accept ( "removed" );
2026-10-03 11:15:21 +02:00
await RemoteDeletes . Remove ( deleted , objectUri , token );
2026-10-01 12:30:57 +02:00
break ;
2026-10-05 06:10:25 +02:00
case "Lock" when objectUri != default :
await Lock ( objectUri , group , true , token );
break ;
2026-10-07 21:42:54 +02:00
case "Move" when objectUri != default && Id ( inner [ "origin" ]) == group . ActorURI :
await Move ( objectUri , Id ( inner [ "target" ]), group , token );
break ;
2026-10-05 06:10:25 +02:00
case "Undo" when Value ( inner [ "object" ], "type" ) == "Lock" :
await Lock ( Id ( inner [ "object" ]?[ "object" ]), group , false , token );
break ;
case "Block" when Id ( inner [ "target" ]) == group . ActorURI :
await Ban ( inner , group , token );
break ;
case "Undo" when Value ( inner [ "object" ], "type" ) == "Block" && Id ( inner [ "object" ]?[ "target" ]) == group . ActorURI :
2026-11-10 01:24:43 +01:00
if ( await BlockHandler . Undo ( inner [ "object" ], Id ( inner [ "object" ]), group , localActors , token ))
2026-10-05 06:10:25 +02:00
Arrival . Accept ( "unbanned" );
else
Arrival . Drop ( "unknown-object" );
break ;
2026-10-05 00:55:04 +02:00
case "Like" or "Dislike" or "Undo" :
await Relayed ( inner , group , token );
break ;
2026-10-05 22:48:57 +02:00
// a moderator features a post in the community, or no longer: the community's own pins
case "Add" or "Remove" when Id ( inner [ "target" ]) is { } target && target == group . FeaturedURL :
2026-11-10 01:24:43 +01:00
var featured = ( Relays ?? services ?. GetService ( typeof ( IEnumerable < IActivityHandler >)) as IEnumerable < IActivityHandler >)
2026-10-05 22:48:57 +02:00
?. FirstOrDefault ( h => h . Type == Value ( inner , "type" ));
if ( featured == default )
Arrival . Drop ( "unsupported" );
else
await featured . Handle ( inner , group , token );
break ;
2026-10-03 11:04:42 +02:00
default :
Arrival . Drop ( "unsupported" );
break ;
2026-10-01 12:30:57 +02:00
}
}
2026-10-05 07:29:12 +02:00
// A vote (or its undoing) on one of our posts in a thread the community holds: the community relays it to the post's
// server whether or not anyone here follows the community (Lemmy sends a vote to the community alone)
async Task < bool > OurPostInItsThread ( JsonNode inner , ForeignAvatar group , CancellationToken token )
{
var target = Value ( inner , "type" ) switch
{
"Like" or "Dislike" => Id ( inner [ "object" ]),
"Undo" when ( inner [ "object" ] as JsonObject )?[ "type" ]?. GetValue < string >() is "Like" or "Dislike" => Id ( inner [ "object" ]?[ "object" ]),
_ => default
};
var post = target == default
? default
2026-11-10 01:24:43 +01:00
: await dbEntities . Posts . Match ( p => p . ObjectURI == target && ! p . IsFederatedCopy && ! p . DeletedAt . HasValue ). ExecuteFirstAsync ( token );
return post != default && await Communities . Of ( post , dbEntities , token ) == group . ActorURI ;
2026-10-05 07:29:12 +02:00
}
2026-10-05 06:10:25 +02:00
// A community's moderators lock one of its posts, or unlock it: no more replies, ours included. The community vouches
// for what is done to its own posts.
async Task Lock ( string objectUri , ForeignAvatar group , bool locked , CancellationToken token )
{
var post = objectUri == default
? default
2026-11-10 01:24:43 +01:00
: await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri && p . AudienceURI == group . ActorURI ). ExecuteFirstAsync ( token );
2026-10-05 06:10:25 +02:00
if ( post == default )
{
Arrival . Drop ( "unknown-object" );
return ;
}
Arrival . About ( visibility : post . Visibility , created : post . CreationDate );
await DB . Default . Update < PostEntity >(). MatchID ( post . ID ). Modify ( p => p . LockedAt , locked ? DateTime . UtcNow : null ). ExecuteAsync ( token );
Arrival . Accept ( locked ? "locked" : "unlocked" );
}
2026-10-07 21:42:54 +02:00
// A post moved to another community (PieFed's Move{object: post, origin, target}), relayed by the community it leaves,
// which vouches for what is done to its own posts as for a lock; its thread goes with it. A move into a community we
// host is not taken: it would be ours to announce.
async Task Move ( string objectUri , string targetUri , ForeignAvatar group , CancellationToken token )
{
2026-11-10 01:24:43 +01:00
var post = await dbEntities . Posts . Match ( p => p . ObjectURI == objectUri && p . AudienceURI == group . ActorURI && ! p . DeletedAt . HasValue )
2026-10-07 21:42:54 +02:00
. ExecuteFirstAsync ( token );
if ( post == default )
{
Arrival . Drop ( "unknown-object" );
return ;
}
Arrival . About ( visibility : post . Visibility , created : post . CreationDate );
2026-11-10 01:24:43 +01:00
var target = targetUri == default || targetUri == group . ActorURI || await localActors . FindByUri ( targetUri , token ) != default
2026-10-07 21:42:54 +02:00
? default
2026-11-10 01:24:43 +01:00
: await remoteActors . GetActor ( targetUri , refresh : false , token );
2026-10-07 21:42:54 +02:00
if ( target is not { AvatarType : AvatarType . Group })
{
Arrival . Drop ( "unknown-target" );
return ;
}
var thread = new List < string > { post . ID };
var level = thread . ToList ();
while ( level . Count > 0 && thread . Count < MaxMoved )
{
var parents = level ;
2026-11-10 01:24:43 +01:00
level = ( await dbEntities . Posts . Match ( p => parents . Contains ( p . AnsweringToPostId ) && p . AudienceURI == group . ActorURI )
2026-10-07 21:42:54 +02:00
. Project ( p => new PostEntity { ID = p . ID }). ExecuteAsync ( token )). Select ( p => p . ID ). ToList ();
thread . AddRange ( level );
}
await DB . Default . Update < PostEntity >(). Match ( p => thread . Contains ( p . ID )). Modify ( p => p . AudienceURI , target . ActorURI ). ExecuteAsync ( token );
Arrival . Accept ( "moved" );
}
const int MaxMoved = 1000 ;
2026-10-05 06:10:25 +02:00
// A community bans one of our personas (Lemmy's Block with the community as its target): kept as the community
// blocking the persona, so its relationship says blocked_by and nothing of the persona's is posted there until the
// Undo. A ban of someone from another server is no business of ours.
async Task Ban ( JsonNode inner , ForeignAvatar group , CancellationToken token )
{
2026-11-10 01:24:43 +01:00
if ( Id ( inner [ "object" ]) is not { } uri || await localActors . FindByUri ( uri , token ) is not { Kind : LocalActorKind . Person } persona )
2026-10-05 06:10:25 +02:00
{
Arrival . Drop ( "not-ours" );
return ;
}
try
{
await DB . Default . SaveAsync ( new BlockedBy { AvatarId = persona . Id , ActorURI = group . ActorURI , AccountId = group . ID , ActivityURI = Id ( inner ) }, token );
Arrival . Accept ( "banned" );
}
catch ( MongoWriteException ex ) when ( ex . WriteError ?. Category == ServerErrorCategory . DuplicateKey )
{
Arrival . Drop ( "duplicate" );
}
}
2026-10-05 00:55:04 +02:00
// A vote, or its undoing, that a community relays (Lemmy, PieFed and Mbin send them so). The community vouches for
// what accounts on its own server do and for what is done to its own posts, as Lemmy trusts it (refetching every vote
// would not scale); anything else is believed only once fetched from its own origin. It is then handled as if its
// actor had delivered it.
async Task Relayed ( JsonNode inner , ForeignAvatar group , CancellationToken token )
{
var actorUri = Id ( inner [ "actor" ]);
var type = Value ( inner , "type" );
2026-11-10 01:24:43 +01:00
var handlers = Relays ?? services ?. GetService ( typeof ( IEnumerable < IActivityHandler >)) as IEnumerable < IActivityHandler >;
2026-10-05 00:55:04 +02:00
var handler = handlers ?. FirstOrDefault ( h => h . Type == type );
if ( actorUri == default || handler == default )
{
Arrival . Drop ( "unparseable" );
return ;
}
var activity = inner ;
var target = Id ( Value ( inner , "type" ) == "Undo" ? ( inner [ "object" ] as JsonObject )?[ "object" ] : inner [ "object" ]);
var ownPost = target != default
2026-11-10 01:24:43 +01:00
&& await dbEntities . Posts . Match ( p => p . ObjectURI == target && p . AudienceURI == group . ActorURI ). ExecuteAnyAsync ( token );
2026-10-05 00:55:04 +02:00
if (! Origin . Same ( actorUri , group . ActorURI ) && ! ownPost )
{
var id = Id ( inner );
if ( id == default || ! Origin . Same ( id , actorUri ))
{
Arrival . Drop ( "misattributed" );
return ;
}
2026-11-10 01:24:43 +01:00
using var fetched = await remoteActors . FetchObject ( id , token );
2026-10-05 00:55:04 +02:00
activity = fetched == default ? default : JsonNode . Parse ( fetched . Root . GetRawText ());
if ( activity == default || Value ( activity , "type" ) != type || Id ( activity [ "actor" ]) != actorUri )
{
Arrival . Drop ( activity == default ? "fetch-failed" : "misattributed" );
return ;
}
}
2026-11-10 01:24:43 +01:00
var actor = await remoteActors . GetActor ( actorUri , refresh : false , token );
2026-10-05 00:55:04 +02:00
if ( actor == default )
{
Arrival . Drop ( "unknown-actor" );
return ;
}
await handler . Handle ( activity , actor , token );
}
2026-10-01 11:39:10 +02:00
static List < string > Strings ( JsonNode node ) => node switch
{
JsonArray array => array . Select ( Id ). Where ( id => id != default ). ToList (),
JsonNode single when Id ( single ) is { } id => new List < string > { id },
_ => new List < string >()
};
}
}