House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s

- Services, controllers and jobs take their dependencies through primary
  constructors and use them directly; where a method already named a local
  after a dependency, the dependency takes its type's name.
- Every async method takes a CancellationToken last and passes it down to
  MongoDB, HTTP and the job queue. The setup claim is still given back when
  a request is cancelled.
- The federation and media options are read through IOptionsMonitor.
- The Mastodon entities keep sending "" for empty strings, and every model
  field where null means something says so.
- The inbox's 503 with Retry-After, which other servers retry, is the one
  server error left, and says why.
- Arasaka.HouseRules.Analyzers checks all of this in every build, here and in
  PrivaPub.ClientModels as decePubClient builds it.

Checked against GoToSocial in the pasture: 64 passed, 0 failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-11-10 01:24:43 +01:00
1 parent f0a14c737f
commit 0f73f69239
176 files changed
+2789 -3974

No files matched your search

@@ -12,53 +12,40 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class AcceptHandler : IActivityHandler
public class AcceptHandler(
DbEntities db,
ILocalActorService localActorService,
IQuoteService quotes,
IInteractionApprovals approvals = default,
IParticipations participations = default,
Relays.IRelays relays = default,
Infrastructure.Jobs.IJobQueue queue = default) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IQuoteService _quotes;
readonly IInteractionApprovals _approvals;
readonly IParticipations _participations;
readonly Relays.IRelays _relays;
readonly Infrastructure.Jobs.IJobQueue _queue;
public AcceptHandler(DbEntities dbEntities, ILocalActorService localActors, IQuoteService quotes, IInteractionApprovals approvals = default,
IParticipations participations = default, Relays.IRelays relays = default, Infrastructure.Jobs.IJobQueue queue = default)
{
_queue = queue;
_relays = relays;
_participations = participations;
_dbEntities = dbEntities;
_localActors = localActors;
_quotes = quotes;
_approvals = approvals;
}
public virtual string Type => "Accept";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
{
if (await _quotes.Answered(activity, actor, accepted: Type == "Accept", token))
if (await quotes.Answered(activity, actor, accepted: Type == "Accept", token))
{
Arrival.Accept("quote-answer");
return;
}
if (_approvals != default && await _approvals.Answered(activity, actor, accepted: Type == "Accept", token))
if (approvals != default && await approvals.Answered(activity, actor, accepted: Type == "Accept", token))
{
Arrival.Accept("interaction-answer");
return;
}
if (_participations != default && await _participations.Answered(activity, actor, accepted: Type == "Accept", token))
if (participations != default && await participations.Answered(activity, actor, accepted: Type == "Accept", token))
{
Arrival.Accept("participation-answer");
return;
}
if (_relays != default && await _relays.Answered(activity, actor, accepted: Type == "Accept", token))
if (relays != default && await relays.Answered(activity, actor, accepted: Type == "Accept", token))
{
Arrival.Accept("relay-answer");
return;
}
var following = await FindFollowing(activity["object"], actor, _dbEntities, _localActors, token);
var following = await FindFollowing(activity["object"], actor, db, localActorService, token);
if (following == default)
{
Arrival.Drop("unknown-object");
@@ -73,8 +60,8 @@ namespace PrivaPub.Federation.Inbox.Handlers
protected virtual async Task Apply(Following following, CancellationToken token)
{
await DB.Default.Update<Following>().MatchID(following.ID).Modify(f => f.State, FollowState.Accepted).ExecuteAsync(token);
if (_queue != default)
await _queue.Enqueue(Models.Jobs.JobKind.BackfillOutbox, following.TargetActorURI, new Uri(following.TargetActorURI).Host,
if (queue != default)
await queue.Enqueue(Models.Jobs.JobKind.BackfillOutbox, following.TargetActorURI, new Uri(following.TargetActorURI).Host,
Actors.OutboxBackfill.DedupeKey(following.TargetActorURI, DateTime.UtcNow), token);
}
@@ -22,40 +22,23 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class AnnounceHandler : IActivityHandler
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
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemotePosts _remotePosts;
readonly IFanout _fanout;
readonly IRemoteActorService _remoteActors;
readonly IObjectRecords _records;
readonly IQuoteService _quotes;
readonly IServiceProvider _services;
// 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
[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.")]
public IEnumerable<IActivityHandler> Relays { get; set; }
readonly PrivaPub.Federation.Relays.IRelays _relayService;
readonly PrivaPub.Federation.Moderation.IDomainBlocks _domainBlocks;
public 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)
{
_domainBlocks = domainBlocks;
_relayService = relays;
_services = services;
_records = records;
_quotes = quotes;
_remoteActors = remoteActors;
_dbEntities = dbEntities;
_localActors = localActors;
_remotePosts = remotePosts;
_fanout = fanout;
}
public string Type => "Announce";
@@ -74,27 +57,27 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop("unparseable");
return;
}
if (await _dbEntities.Posts.Match(p => p.ObjectURI == announceId).ExecuteAnyAsync(token))
if (await dbEntities.Posts.Match(p => p.ObjectURI == announceId).ExecuteAnyAsync(token))
{
Arrival.Drop("duplicate");
return;
}
if (_relayService != default && await _relayService.Passes(actor.ActorURI, token))
if (relays != default && await relays.Passes(actor.ActorURI, token))
{
await FromRelay(objectUri, token);
return;
}
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);
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);
if (original is not { IsFederatedCopy: false } && !followed)
{
Arrival.Drop("not-followed");
return;
}
if (original == default && !isLocal)
original = await _remotePosts.StoreContext(objectUri, 0, token);
original = await remotePosts.StoreContext(objectUri, 0, token);
if (original == default)
{
Arrival.Drop("fetch-failed");
@@ -125,7 +108,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
Cc = cc,
IsFederatedCopy = true,
AuthorSuspended = actor.SuspendedAt.HasValue,
AuthorLimited = RemotePosts.Limited(actor, _domainBlocks),
AuthorLimited = RemotePosts.Limited(actor, domainBlocks),
CreationDate = published,
UpdateDate = published
};
@@ -144,20 +127,20 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
Arrival.Accept("stored");
Arrival.About(local: original.IsFederatedCopy ? default : await _localActors.FindById(Models.Federation.LocalActorKind.Person, original.GroupUserId, token));
Arrival.About(local: original.IsFederatedCopy ? default : await localActors.FindById(Models.Federation.LocalActorKind.Person, original.GroupUserId, token));
await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, 1)).ExecuteAsync(token);
if (!original.IsFederatedCopy)
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, actor.ID, actor.ActorURI, original.ID, token);
await _fanout.Distribute(reblog, token);
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, actor.ID, actor.ActorURI, original.ID, token: token);
await fanout.Distribute(reblog, token);
}
// 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)
{
var held = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = held ?? await _remotePosts.StoreContext(objectUri, 0, token);
var held = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = held ?? await remotePosts.StoreContext(objectUri, 0, token);
if (post == default)
{
Arrival.Drop("fetch-failed");
@@ -170,14 +153,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
Arrival.Accept("relayed");
await _fanout.Distribute(post, token);
await fanout.Distribute(post, token);
}
async Task GroupActivity(JsonNode inner, ForeignAvatar group, CancellationToken token)
{
Arrival.About(Value(inner, "type"));
if (group.AvatarType != AvatarType.Group
|| !await _dbEntities.Followings.Match(f => f.TargetActorURI == group.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token)
|| !await dbEntities.Followings.Match(f => f.TargetActorURI == group.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token)
&& !await OurPostInItsThread(inner, group, token))
{
Arrival.Drop("not-followed");
@@ -187,12 +170,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
switch (Value(inner, "type"))
{
case "Create" when objectUri != default:
if (await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteAnyAsync(token))
if (await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteAnyAsync(token))
{
Arrival.Drop("duplicate");
return;
}
var post = await _remotePosts.StoreContext(objectUri, 0, token);
var post = await remotePosts.StoreContext(objectUri, 0, token);
if (post == default)
{
Arrival.Drop("fetch-failed");
@@ -202,10 +185,10 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.About(visibility: post.Visibility);
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.AudienceURI, group.ActorURI).ExecuteAsync(token);
post.AudienceURI = group.ActorURI;
await _fanout.Distribute(post, token);
await fanout.Distribute(post, token);
break;
case "Update" when objectUri != default:
var stored = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI && !p.DeletedAt.HasValue)
var stored = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI && !p.DeletedAt.HasValue)
.ExecuteFirstAsync(token);
if (stored == default)
{
@@ -213,7 +196,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
Arrival.About(visibility: stored.Visibility, created: stored.CreationDate);
using (var fetched = await _remoteActors.FetchObject(objectUri, token))
using (var fetched = await remoteActors.FetchObject(objectUri, token))
{
var note = fetched == default ? default : NoteParser.Parse(System.Text.Json.Nodes.JsonNode.Parse(fetched.Root.GetRawText()));
if (note == default || note.AttributedTo != stored.ActorURI)
@@ -221,11 +204,11 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop(note == default ? "fetch-failed" : "misattributed");
return;
}
Arrival.Accept(await RemoteEdits.Apply(stored, note, Id(inner), _localActors, _records, _quotes, token) ? "edit" : "refresh");
Arrival.Accept(await RemoteEdits.Apply(stored, note, Id(inner), localActors, records, quotes, token) ? "edit" : "refresh");
}
break;
case "Delete" when objectUri != default:
var deleted = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI).ExecuteFirstAsync(token);
var deleted = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI).ExecuteFirstAsync(token);
if (deleted == default)
{
Arrival.Drop("unknown-object");
@@ -235,7 +218,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
// 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))
using (var check = await _remoteActors.FetchObject(objectUri, token))
using (var check = await remoteActors.FetchObject(objectUri, token))
if (check != default && Value(System.Text.Json.Nodes.JsonNode.Parse(check.Root.GetRawText()), "type") != "Tombstone")
{
Arrival.Drop("not-deleted");
@@ -257,7 +240,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
await Ban(inner, group, token);
break;
case "Undo" when Value(inner["object"], "type") == "Block" && Id(inner["object"]?["target"]) == group.ActorURI:
if (await BlockHandler.Undo(inner["object"], Id(inner["object"]), group, _localActors, token))
if (await BlockHandler.Undo(inner["object"], Id(inner["object"]), group, localActors, token))
Arrival.Accept("unbanned");
else
Arrival.Drop("unknown-object");
@@ -267,7 +250,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
break;
// 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:
var featured = (Relays ?? _services?.GetService(typeof(IEnumerable<IActivityHandler>)) as IEnumerable<IActivityHandler>)
var featured = (Relays ?? services?.GetService(typeof(IEnumerable<IActivityHandler>)) as IEnumerable<IActivityHandler>)
?.FirstOrDefault(h => h.Type == Value(inner, "type"));
if (featured == default)
Arrival.Drop("unsupported");
@@ -292,8 +275,8 @@ namespace PrivaPub.Federation.Inbox.Handlers
};
var post = target == default
? default
: 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;
: 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;
}
// A community's moderators lock one of its posts, or unlock it: no more replies, ours included. The community vouches
@@ -302,7 +285,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
var post = objectUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI).ExecuteFirstAsync(token);
if (post == default)
{
Arrival.Drop("unknown-object");
@@ -318,7 +301,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
// host is not taken: it would be ours to announce.
async Task Move(string objectUri, string targetUri, ForeignAvatar group, CancellationToken token)
{
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI && !p.DeletedAt.HasValue)
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.AudienceURI == group.ActorURI && !p.DeletedAt.HasValue)
.ExecuteFirstAsync(token);
if (post == default)
{
@@ -326,9 +309,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
Arrival.About(visibility: post.Visibility, created: post.CreationDate);
var target = targetUri == default || targetUri == group.ActorURI || await _localActors.FindByUri(targetUri, token) != default
var target = targetUri == default || targetUri == group.ActorURI || await localActors.FindByUri(targetUri, token) != default
? default
: await _remoteActors.GetActor(targetUri, refresh: false, token);
: await remoteActors.GetActor(targetUri, refresh: false, token);
if (target is not { AvatarType: AvatarType.Group })
{
Arrival.Drop("unknown-target");
@@ -339,7 +322,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
while (level.Count > 0 && thread.Count < MaxMoved)
{
var parents = level;
level = (await _dbEntities.Posts.Match(p => parents.Contains(p.AnsweringToPostId) && p.AudienceURI == group.ActorURI)
level = (await dbEntities.Posts.Match(p => parents.Contains(p.AnsweringToPostId) && p.AudienceURI == group.ActorURI)
.Project(p => new PostEntity { ID = p.ID }).ExecuteAsync(token)).Select(p => p.ID).ToList();
thread.AddRange(level);
}
@@ -354,7 +337,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
// Undo. A ban of someone from another server is no business of ours.
async Task Ban(JsonNode inner, ForeignAvatar group, CancellationToken token)
{
if (Id(inner["object"]) is not { } uri || await _localActors.FindByUri(uri, token) is not { Kind: LocalActorKind.Person } persona)
if (Id(inner["object"]) is not { } uri || await localActors.FindByUri(uri, token) is not { Kind: LocalActorKind.Person } persona)
{
Arrival.Drop("not-ours");
return;
@@ -378,7 +361,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
var actorUri = Id(inner["actor"]);
var type = Value(inner, "type");
var handlers = Relays ?? _services?.GetService(typeof(IEnumerable<IActivityHandler>)) as IEnumerable<IActivityHandler>;
var handlers = Relays ?? services?.GetService(typeof(IEnumerable<IActivityHandler>)) as IEnumerable<IActivityHandler>;
var handler = handlers?.FirstOrDefault(h => h.Type == type);
if (actorUri == default || handler == default)
{
@@ -388,7 +371,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var activity = inner;
var target = Id(Value(inner, "type") == "Undo" ? (inner["object"] as JsonObject)?["object"] : inner["object"]);
var ownPost = target != default
&& await _dbEntities.Posts.Match(p => p.ObjectURI == target && p.AudienceURI == group.ActorURI).ExecuteAnyAsync(token);
&& await dbEntities.Posts.Match(p => p.ObjectURI == target && p.AudienceURI == group.ActorURI).ExecuteAnyAsync(token);
if (!Origin.Same(actorUri, group.ActorURI) && !ownPost)
{
var id = Id(inner);
@@ -397,7 +380,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop("misattributed");
return;
}
using var fetched = await _remoteActors.FetchObject(id, token);
using var fetched = await remoteActors.FetchObject(id, token);
activity = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
if (activity == default || Value(activity, "type") != type || Id(activity["actor"]) != actorUri)
{
@@ -405,7 +388,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
}
var actor = await _remoteActors.GetActor(actorUri, refresh: false, token);
var actor = await remoteActors.GetActor(actorUri, refresh: false, token);
if (actor == default)
{
Arrival.Drop("unknown-actor");
@@ -17,22 +17,15 @@ namespace PrivaPub.Federation.Inbox.Handlers
// A remote account blocks one of our personas, as Mastodon does it: the follows between them end here too (the blocker
// already ended its side, so nothing is sent back), the persona stops seeing the blocker's posts and notifications, the
// relationship says blocked_by, and nothing of the persona's is addressed to the blocker any more. Undo{Block} lifts it.
public class BlockHandler : IActivityHandler
public class BlockHandler(
DbEntities dbEntities,
ILocalActorService localActorService) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public BlockHandler(DbEntities dbEntities, ILocalActorService localActors)
{
_dbEntities = dbEntities;
_localActors = localActors;
}
public string Type => "Block";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
{
var target = Id(activity["object"]) is { } uri ? await _localActors.FindByUri(uri, token) : default;
var target = Id(activity["object"]) is { } uri ? await localActorService.FindByUri(uri, token) : default;
if (target is not { Kind: LocalActorKind.Person })
{
Arrival.Drop("unknown-object");
@@ -70,7 +63,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
async Task Ban(JsonNode activity, LocalActor persona, string communityUri, CancellationToken token)
{
var community = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == communityUri && f.AvatarType == AvatarType.Group).ExecuteFirstAsync(token);
var community = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == communityUri && f.AvatarType == AvatarType.Group).ExecuteFirstAsync(token);
if (community == default)
{
Arrival.Drop("unknown-community");
@@ -26,45 +26,22 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class CreateHandler : IActivityHandler
public class CreateHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IDeliveryService delivery,
IFanout fanout,
IRemotePosts remotePosts,
IGroupDistributor groups,
IObjectRecords records,
IPollService polls,
ILinkPreviews previews,
IQuoteService quotes,
IInteractionApprovals approvals = default,
Relays.IRelays relays = default,
IWalls walls = default) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDeliveryService _delivery;
readonly IDomainBlocks _domainBlocks;
readonly IFanout _fanout;
readonly IRemotePosts _remotePosts;
readonly IGroupDistributor _groups;
readonly IObjectRecords _records;
readonly IPollService _polls;
readonly ILinkPreviews _previews;
readonly IQuoteService _quotes;
readonly IInteractionApprovals _approvals;
readonly Relays.IRelays _relays;
readonly IWalls _walls;
public CreateHandler(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery,
IDomainBlocks domainBlocks, IFanout fanout, IRemotePosts remotePosts, IGroupDistributor groups, IObjectRecords records, IPollService polls, ILinkPreviews previews, IQuoteService quotes,
IInteractionApprovals approvals = default, Relays.IRelays relays = default, IWalls walls = default)
{
_walls = walls;
_relays = relays;
_approvals = approvals;
_quotes = quotes;
_previews = previews;
_records = records;
_polls = polls;
_groups = groups;
_fanout = fanout;
_remotePosts = remotePosts;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_delivery = delivery;
_domainBlocks = domainBlocks;
}
public string Type => "Create";
public async Task Handle(JsonNode activity, ForeignAvatar author, CancellationToken token)
@@ -73,7 +50,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var refetched = node is not JsonObject || !Origin.Same(Id(node), author.ActorURI);
if (refetched)
{
using var fetched = await _remoteActors.FetchObject(Id(node), token);
using var fetched = await remoteActors.FetchObject(Id(node), token);
node = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
if (node == default)
Arrival.Drop("fetch-failed");
@@ -85,11 +62,11 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
if (!refetched)
{
using var fetched = await _remoteActors.FetchObject(note.Id, token);
using var fetched = await remoteActors.FetchObject(note.Id, token);
note = fetched == default ? default : NoteParser.Parse(JsonNode.Parse(fetched.Root.GetRawText()));
refetched = true;
}
author = note == default ? default : await _remoteActors.GetActor(note.AttributedTo, refresh: false, token);
author = note == default ? default : await remoteActors.GetActor(note.AttributedTo, refresh: false, token);
if (author == default)
{
Arrival.Drop(note == default ? "fetch-failed" : "author-unavailable");
@@ -104,16 +81,16 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.About(note.Type);
if (note.Title != default && note.InReplyTo != default && ObjectShapes.Text(note.ContentHtml, 1) == default)
{
var question = await _dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && p.Poll != null).ExecuteFirstAsync(token);
var question = await dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && p.Poll != null).ExecuteFirstAsync(token);
if (question != default)
{
await _polls.Receive(question, author, note.Title, Id(activity), token);
await polls.Receive(question, author, note.Title, Id(activity), token);
Arrival.Accept("poll-vote");
Arrival.About(visibility: question.Visibility);
return;
}
}
if (await _dbEntities.Posts.Match(p => p.ObjectURI == note.Id).ExecuteAnyAsync(token))
if (await dbEntities.Posts.Match(p => p.ObjectURI == note.Id).ExecuteAnyAsync(token))
{
Arrival.Drop("duplicate");
return;
@@ -146,7 +123,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var localTargets = new List<LocalActor>();
for (var i = 0; i < addressed.Count; i++)
{
var local = await _localActors.FindByAddress(addressed[i], token);
var local = await localActors.FindByAddress(addressed[i], token);
if (local == default)
continue;
addressed[i] = local.Uri;
@@ -158,9 +135,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
var parent = string.IsNullOrEmpty(note.InReplyTo)
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
// a reply its parent's author has not let in (GoToSocial's canReply), which a third party must not show
if (_approvals != default && parent != default && !await _approvals.MayReply(note, author, parent, token))
if (approvals != default && parent != default && !await approvals.MayReply(note, author, parent, token))
{
Arrival.Drop("reply-not-authorized");
return;
@@ -183,26 +160,26 @@ namespace PrivaPub.Federation.Inbox.Handlers
group = default;
var repliesToLocal = parent is { IsFederatedCopy: false } && visibility != PostVisibility.Direct;
var followed = visibility != PostVisibility.Direct && await _dbEntities.Followings
var followed = visibility != PostVisibility.Direct && await dbEntities.Followings
.Match(f => f.TargetActorURI == author.ActorURI && f.State == FollowState.Accepted)
.ExecuteAnyAsync(token);
// a reply in the thread of someone followed here, as Mastodon keeps them: what the thread's server forwards
var repliesToFollowed = !followed && parent is { IsFederatedCopy: true } && visibility is PostVisibility.Public or PostVisibility.Unlisted
&& await _dbEntities.Followings.Match(f => f.TargetActorURI == parent.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
&& await dbEntities.Followings.Match(f => f.TargetActorURI == parent.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
// a post in a remote group followed here that the group's own server sends itself rather than announcing it (Mbin
// delivers a magazine's threads to its subscribers as their author's Create): the group's server speaks for it
var inFollowedGroup = !followed && visibility is PostVisibility.Public or PostVisibility.Unlisted && note.Audience != default
&& Origin.Same(note.Audience, author.ActorURI) && Origin.Same(note.Id, note.Audience)
&& await _dbEntities.Followings.Match(f => f.TargetActorURI == note.Audience && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
&& await dbEntities.Followings.Match(f => f.TargetActorURI == note.Audience && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
// a public post a relay we subscribe to passes on, for the federated timeline (read again from its origin, as any
// forwarded post)
var relayed = !followed && visibility == PostVisibility.Public && _relays != default
&& await _relays.Passes(Arrival.Current?.ForwardedBy, token);
var relayed = !followed && visibility == PostVisibility.Public && relays != default
&& await relays.Passes(Arrival.Current?.ForwardedBy, token);
// written on a persona's wall (FEP-400e): public, not a reply, by an account following the persona, as its actor
// tells Smithereen
var wall = _walls == default || note.Wall == default ? default : await _walls.OwnerOf(note.Wall, token);
var wall = walls == default || note.Wall == default ? default : await walls.OwnerOf(note.Wall, token);
if (wall != default && (visibility is not (PostVisibility.Public or PostVisibility.Unlisted) || !string.IsNullOrEmpty(note.InReplyTo)
|| note.WallOwner != default && note.WallOwner != wall.Uri || !await _walls.MayWrite(wall, author, token)))
|| note.WallOwner != default && note.WallOwner != wall.Uri || !await walls.MayWrite(wall, author, token)))
{
Arrival.Drop("wall-refused");
return;
@@ -214,7 +191,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
if (parent == default && visibility != PostVisibility.Direct)
parent = await _remotePosts.Parent(note.InReplyTo, 1, token);
parent = await remotePosts.Parent(note.InReplyTo, 1, token);
DmGroup conversation = default;
if (visibility == PostVisibility.Direct)
@@ -226,7 +203,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
conversation = await FindOrCreateConversation(participants, Origin.Same(note.Context, author.ActorURI) ? note.Context : default, token);
}
var post = await _remotePosts.Build(note, author, visibility, to, cc, parent, token);
var post = await remotePosts.Build(note, author, visibility, to, cc, parent, token);
post.ActivityURI = Id(activity);
post.GroupId = group?.Id;
post.ConversationId = conversation?.ID;
@@ -247,31 +224,31 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
Arrival.Accept("stored");
Arrival.About(local: group ?? persons.FirstOrDefault());
await _records.Record(note, post, ObjectPath.Delivered, refetched, token);
await _previews.Wanted(post, token);
await _quotes.Resolve(post, note, token);
await records.Record(note, post, ObjectPath.Delivered, refetched, token);
await previews.Wanted(post, token);
await quotes.Resolve(post, note, token);
if (parent != default && Domain.Privacy.Counted.Reply(post))
await DB.Default.Update<PostEntity>().MatchID(parent.ID).Modify(b => b.Inc(p => p.RepliesCount, 1)).ExecuteAsync(token);
await _fanout.Distribute(post, token);
await ReplyRelay.Pass(post, _dbEntities, _localActors, _delivery, token);
await fanout.Distribute(post, token);
await ReplyRelay.Pass(post, dbEntities, localActors, delivery, token);
if (conversation != default)
{
await Domain.Statuses.ConversationStates.Posted(conversation.ID, post.ID, default, token);
await Domain.Timelines.Fanout.Conversation(conversation.ID, token);//the `direct` streams (R8), once it is the newest
}
if (group is { IsCircle: false })
await _groups.Announce(group, activity.AsObject(), note.Id, isNewPost: true, token);
await groups.Announce(group, activity.AsObject(), note.Id, isNewPost: true, token);
if (wall != default)
await _walls.Hosted(post, wall, token);
await walls.Hosted(post, wall, token);
}
async Task<bool> IsCircleMember(LocalActor circle, string actorUri, CancellationToken token) =>
await _dbEntities.Groups.Match(g => g.ID == circle.Id && g.Members.Any(m => m.IsForeign && m.AvatarId == actorUri)).ExecuteAnyAsync(token);
await dbEntities.Groups.Match(g => g.ID == circle.Id && g.Members.Any(m => m.IsForeign && m.AvatarId == actorUri)).ExecuteAnyAsync(token);
async Task<bool> MayPost(LocalActor community, string actorUri, CancellationToken token)
{
var entity = await _dbEntities.Groups.MatchID(community.Id).ExecuteFirstAsync(token);
var entity = await dbEntities.Groups.MatchID(community.Id).ExecuteFirstAsync(token);
return entity?.PostingPolicy switch
{
PostingPolicy.Anyone => true,
@@ -285,7 +262,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var members = new List<GroupMember>();
foreach (var uri in participantUris.Distinct(StringComparer.Ordinal))
{
var local = await _localActors.FindByUri(uri, token);
var local = await localActors.FindByUri(uri, token);
var member = local != default && local.Kind == LocalActorKind.Person
? new GroupMember { AvatarId = local.Id }
: new GroupMember { AvatarId = uri, IsForeign = true };
@@ -294,7 +271,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
var key = DmGroup.KeyOf(members);
var match = await _dbEntities.DmGroups.Match(g => g.ParticipantsKey == key && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
var match = await dbEntities.DmGroups.Match(g => g.ParticipantsKey == key && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (match != default)
return match;
@@ -21,26 +21,14 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class DeleteHandler : IActivityHandler
public class DeleteHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IDeliveryService delivery,
IGroupDistributor groups,
IQuoteService quotes) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDeliveryService _delivery;
readonly IGroupDistributor _groups;
readonly IQuoteService _quotes;
public DeleteHandler(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery,
IGroupDistributor groups, IQuoteService quotes)
{
_quotes = quotes;
_groups = groups;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_delivery = delivery;
}
public string Type => "Delete";
const int MaxObjects = 50;
@@ -70,7 +58,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
actor.DeletionAt = DateTime.UtcNow;
actor.AccountState = AvatarAccountState.Deleted;
await DB.Default.SaveAsync(actor, token);
var followers = await _dbEntities.Followers.Match(f => f.ActorURI == actor.ActorURI).ExecuteAsync(token);
var followers = await dbEntities.Followers.Match(f => f.ActorURI == actor.ActorURI).ExecuteAsync(token);
foreach (var follower in followers)
{
await DB.Default.DeleteAsync<Follower>(follower.ID);
@@ -85,24 +73,24 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
await RemoteDeletes.Tombstone(objectUri, token);
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
// deleted by another account of its author's server (Mobilizon's organiser deletes the group's event): once
// that server says it is gone
if (post == default && await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token) is { } held
&& held.ActorURI != actor.ActorURI && Origin.Same(held.ActorURI, actor.ActorURI) && await _remoteActors.IsGone(objectUri, token))
if (post == default && await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token) is { } held
&& held.ActorURI != actor.ActorURI && Origin.Same(held.ActorURI, actor.ActorURI) && await remoteActors.IsGone(objectUri, token))
post = held;
if (post == default)
{
Arrival.Accept("tombstone-only");
await _quotes.Revoke(objectUri, token);
await quotes.Revoke(objectUri, token);
return;
}
Arrival.Accept("removed");
Arrival.About(post.ObjectType, post.Visibility, post.CreationDate);
await ReplyRelay.Pass(post, _dbEntities, _localActors, _delivery, token);
await ReplyRelay.Pass(post, dbEntities, localActors, delivery, token);
await RemoteDeletes.Remove(post, objectUri, token);
if (!string.IsNullOrEmpty(post.GroupId) && await _localActors.FindById(LocalActorKind.Group, post.GroupId, token) is { IsCircle: false } community)
await _groups.Announce(community, activity.AsObject(), post.ObjectURI, isNewPost: false, token);
if (!string.IsNullOrEmpty(post.GroupId) && await localActors.FindById(LocalActorKind.Group, post.GroupId, token) is { IsCircle: false } community)
await groups.Announce(community, activity.AsObject(), post.ObjectURI, isNewPost: false, token);
}
}
}
@@ -14,15 +14,9 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class DislikeHandler : IActivityHandler
public class DislikeHandler(
DbEntities dbEntities) : IActivityHandler
{
readonly DbEntities _dbEntities;
public DislikeHandler(DbEntities dbEntities)
{
_dbEntities = dbEntities;
}
public string Type => "Dislike";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -30,7 +24,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var objectUri = Id(activity["object"]);
var post = objectUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
if (post == default || !await VisibilityPolicy.RemoteCanSee(post, actor, token))
{
Arrival.Drop(post == default ? "unknown-object" : "not-visible");
@@ -8,17 +8,10 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class EmojiReactHandler : IActivityHandler
public class EmojiReactHandler(
DbEntities dbEntities,
IReactions reactions) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly IReactions _reactions;
public EmojiReactHandler(DbEntities dbEntities, IReactions reactions)
{
_dbEntities = dbEntities;
_reactions = reactions;
}
public string Type => "EmojiReact";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -26,14 +19,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
var objectUri = Id(activity["object"]);
var post = objectUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
if (post == default)
{
Arrival.Drop("unknown-object");
return;
}
Arrival.About(post.ObjectType ?? "Note", post.Visibility, post.CreationDate);
await _reactions.Receive(post, actor, Value(activity, "content"), activity["tag"], Id(activity), token);
await reactions.Receive(post, actor, Value(activity, "content"), activity["tag"], Id(activity), token);
}
}
}
@@ -10,51 +10,39 @@ namespace PrivaPub.Federation.Inbox.Handlers
// its `featured` collection (as Mastodon sends it) or its `featuredTags` is a featured tag (R8). On its wall
// (Smithereen's, FEP-400e) it tells of a post someone wrote there, or takes it off. Any other target (a community's
// moderators) is not ours to keep.
public class FeaturedHandler : IActivityHandler
public class FeaturedHandler(
IFeaturedPosts featuredPosts,
bool add,
IWalls walls = default,
IRemoteActorService remoteActors = default,
Infrastructure.Jobs.IJobQueue queue = default,
Domain.Social.IFeaturedTags tags = default) : IActivityHandler
{
readonly IFeaturedPosts _featured;
readonly IWalls _walls;
readonly IRemoteActorService _remoteActors;
readonly Infrastructure.Jobs.IJobQueue _queue;
readonly Domain.Social.IFeaturedTags _tags;
readonly bool _add;
public FeaturedHandler(IFeaturedPosts featured, bool add, IWalls walls = default, IRemoteActorService remoteActors = default,
Infrastructure.Jobs.IJobQueue queue = default, Domain.Social.IFeaturedTags tags = default)
{
_tags = tags;
_featured = featured;
_walls = walls;
_remoteActors = remoteActors;
_queue = queue;
_add = add;
}
public string Type => _add ? "Add" : "Remove";
public string Type => add ? "Add" : "Remove";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
{
if (_add && _queue != default && await ConversationContainers.Unwrap(activity, actor, _queue, token))
if (add && queue != default && await ConversationContainers.Unwrap(activity, actor, queue, token))
return;
var target = Objects.ActivityJson.Id(activity["target"]);
// a collection of its own we do not know of: its document read again, at most hourly, in case it was kept before
// we read that collection (a wall)
if (_remoteActors != default && target != default && target != actor.FeaturedURL && target != actor.WallURL && target != actor.FeaturedTagsURL
if (remoteActors != default && target != default && target != actor.FeaturedURL && target != actor.WallURL && target != actor.FeaturedTagsURL
&& Objects.Origin.Same(target, actor.ActorURI) && actor.UpdatedAt < DateTime.UtcNow.AddHours(-1))
actor = await _remoteActors.GetActor(actor.ActorURI, refresh: true, token) ?? actor;
actor = await remoteActors.GetActor(actor.ActorURI, refresh: true, token) ?? actor;
// a featured hashtag: an object of its own, with no id (its href is no post), so before anything reads it as one
if (Objects.ActivityJson.Value(activity["object"], "type") == "Hashtag")
{
if (_tags != default && target != default && (target == actor.FeaturedURL || target == actor.FeaturedTagsURL))
await _tags.Receive(activity, actor, _add, token);
if (tags != default && target != default && (target == actor.FeaturedURL || target == actor.FeaturedTagsURL))
await tags.Receive(activity, actor, add, token);
else
Arrival.Drop("unknown-target");
return;
}
if (_walls != default && !string.IsNullOrEmpty(actor.WallURL) && target == actor.WallURL)
await _walls.Receive(activity, actor, _add, token);
if (walls != default && !string.IsNullOrEmpty(actor.WallURL) && target == actor.WallURL)
await walls.Receive(activity, actor, add, token);
else
await _featured.Receive(activity, actor, _add, token);
await featuredPosts.Receive(activity, actor, add, token);
}
}
}
@@ -12,17 +12,10 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class FlagHandler : IActivityHandler
public class FlagHandler(
DbEntities dbEntities,
ILocalActorService localActors) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public FlagHandler(DbEntities dbEntities, ILocalActorService localActors)
{
_dbEntities = dbEntities;
_localActors = localActors;
}
public string Type => "Flag";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -38,7 +31,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var postUris = new List<string>();
foreach (var uri in objects.Take(50))
{
var local = await _localActors.FindByUri(uri, token);
var local = await localActors.FindByUri(uri, token);
if (local is { Kind: LocalActorKind.Person } && uri.TrimEnd('/') == local.Uri)
target ??= local;
else
@@ -46,9 +39,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
var posts = postUris.Count == 0
? new List<Models.Post.Post>()
: await _dbEntities.Posts.Match(p => postUris.Contains(p.ObjectURI) && !p.IsFederatedCopy).ExecuteAsync(token);
: await dbEntities.Posts.Match(p => postUris.Contains(p.ObjectURI) && !p.IsFederatedCopy).ExecuteAsync(token);
if (target == default && posts.Count > 0)
target = await _localActors.FindById(LocalActorKind.Person, posts[0].GroupUserId, token);
target = await localActors.FindById(LocalActorKind.Person, posts[0].GroupUserId, token);
if (target == default)
{
Arrival.Drop("unknown-object");
@@ -21,21 +21,11 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class FollowHandler : IActivityHandler
public class FollowHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDeliveryService _delivery;
public FollowHandler(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_delivery = delivery;
}
public string Type => "Follow";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -43,7 +33,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var follow = activity;
var follower = actor;
var target = await _localActors.FindByAddress(Id(follow["object"]), token);
var target = await localActors.FindByAddress(Id(follow["object"]), token);
if (target is not { IsFederated: true } || target.IsServerActor)
{
Arrival.Drop("unknown-recipient");
@@ -67,12 +57,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
["actor"] = target.Uri,
["object"] = follow.DeepClone()
};
await _delivery.Enqueue(target, new[] { follower.InboxURL }, reject, token);
await delivery.Enqueue(target, new[] { follower.InboxURL }, reject, token: token);
Arrival.Reject("blocked");
return;
}
var existing = await _dbEntities.Followers
var existing = await dbEntities.Followers
.Match(f => f.LocalActorId == target.Id && f.LocalActorKind == target.Kind && f.ActorURI == follower.ActorURI)
.ExecuteFirstAsync(token);
var record = existing ?? new Follower
@@ -90,7 +80,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
if (target.Kind == LocalActorKind.Person)
await Notifications.Add(target.Id, record.IsAccepted ? NotificationType.Follow : NotificationType.FollowRequest,
follower.ID, follower.ActorURI, default, token);
follower.ID, follower.ActorURI, default, token: token);
if (!record.IsAccepted)
return;
@@ -98,7 +88,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
await AddForeignMember(target.Id, follower.ActorURI, token);
var accept = ActivityPubRenderer.Accept(target, follow, $"accept-{record.ID}-{DateTime.UtcNow.Ticks}");
await _delivery.Enqueue(target, new[] { follower.InboxURL }, accept, token);
await delivery.Enqueue(target, new[] { follower.InboxURL }, accept, token: token);
return;
}
}
@@ -11,31 +11,23 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class JoinHandler : IActivityHandler
public class JoinHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
public JoinHandler(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery)
{
_dbEntities = dbEntities;
_localActors = localActors;
_delivery = delivery;
}
public string Type => "Join";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
{
var objectUri = Id(activity["object"]);
if (objectUri == default || !objectUri.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
if (objectUri == default || !objectUri.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
{
Arrival.Drop("unknown-object");
return;
}
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var owner = post == default ? default : await _localActors.FindById(LocalActorKind.Person, post.GroupUserId, token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var owner = post == default ? default : await localActors.FindById(LocalActorKind.Person, post.GroupUserId, token);
if (owner == default || string.IsNullOrEmpty(actor.InboxURL))
{
Arrival.Drop("unknown-object");
@@ -43,14 +35,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
Arrival.About(post.ObjectType ?? "Note", post.Visibility, post.CreationDate);
Arrival.Reject("ignored");
await _delivery.Enqueue(owner, new[] { actor.InboxURL }, new JsonObject
await delivery.Enqueue(owner, new[] { actor.InboxURL }, new JsonObject
{
["@context"] = ActivityPubRenderer.ActivityStreams,
["id"] = owner.ActivityUri($"ignore-{Guid.NewGuid():N}"),
["type"] = "Ignore",
["actor"] = owner.Uri,
["object"] = activity.DeepClone()
}, token);
}, token: token);
}
}
}
@@ -16,17 +16,10 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class LikeHandler : IActivityHandler
public class LikeHandler(
DbEntities dbEntities,
IReactions reactions) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly IReactions _reactions;
public LikeHandler(DbEntities dbEntities, IReactions reactions)
{
_dbEntities = dbEntities;
_reactions = reactions;
}
public string Type => "Like";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -34,7 +27,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var objectUri = Id(activity["object"]);
var post = objectUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
if (post == default || !await VisibilityPolicy.RemoteCanSee(post, actor, token))
{
Arrival.Drop(post == default ? "unknown-object" : "not-visible");
@@ -44,7 +37,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var content = Value(activity, "_misskey_reaction") ?? Value(activity, "content");
if (!Reactions.IsHeart(content))
{
await _reactions.Receive(post, actor, content, activity["tag"], Id(activity), token);
await reactions.Receive(post, actor, content, activity["tag"], Id(activity), token);
return;
}
@@ -64,7 +57,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
&& (await DB.Default.DeleteAsync<Downvote>(downvoted.ID)).DeletedCount > 0)
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(b => b.Inc(p => p.DownvotesCount, -1)).ExecuteAsync(token);
if (!post.IsFederatedCopy)
await Notifications.Add(post.GroupUserId, NotificationType.Favourite, actor.ID, actor.ActorURI, post.ID, token);
await Notifications.Add(post.GroupUserId, NotificationType.Favourite, actor.ID, actor.ActorURI, post.ID, token: token);
}
}
}
@@ -15,20 +15,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
// A moderator's lock of a thread sent as it is, not inside its community's announce (Mbin sends it to the magazine's
// subscribers itself): taken only from the post's own server, which speaks for it. Replies are refused until the
// Undo{Lock}, as for a lock a community announces.
public class LockHandler : IActivityHandler
public class LockHandler(
DbEntities db) : IActivityHandler
{
readonly DbEntities _dbEntities;
public LockHandler(DbEntities dbEntities)
{
_dbEntities = dbEntities;
}
public string Type => "Lock";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
{
if (await Set(_dbEntities, Id(activity["object"]), actor, locked: true, token))
if (await Set(db, Id(activity["object"]), actor, locked: true, token))
Arrival.Accept("locked");
else
Arrival.Drop("unknown-object");
@@ -20,24 +20,13 @@ namespace PrivaPub.Federation.Inbox.Handlers
// it among its alsoKnownAs. The old account then shows where it went (`moved`), and, as Mastodon does it (owner
// decision 2026-10-05), the personas following it follow the new one instead, in the same lists, and those that
// muted or blocked it mute or block the new one too.
public class MoveHandler : IActivityHandler
public class MoveHandler(
IRemoteActorService remoteActors,
DbEntities dbEntities,
ILocalActorService localActors,
IFollowService follows,
IRelationshipService relationships) : IActivityHandler
{
readonly IRemoteActorService _remoteActors;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IFollowService _follows;
readonly IRelationshipService _relationships;
public MoveHandler(IRemoteActorService remoteActors, DbEntities dbEntities, ILocalActorService localActors, IFollowService follows,
IRelationshipService relationships)
{
_remoteActors = remoteActors;
_dbEntities = dbEntities;
_localActors = localActors;
_follows = follows;
_relationships = relationships;
}
public string Type => "Move";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -48,7 +37,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop("not-self");
return;
}
var moved = await _remoteActors.GetActor(target, refresh: true, token);
var moved = await remoteActors.GetActor(target, refresh: true, token);
if (moved == default)
{
Arrival.Drop("target-unavailable");
@@ -67,15 +56,15 @@ namespace PrivaPub.Federation.Inbox.Handlers
async Task MoveFollows(ForeignAvatar old, ForeignAvatar moved, CancellationToken token)
{
foreach (var following in await _dbEntities.Followings.Match(f => f.TargetActorURI == old.ActorURI).ExecuteAsync(token))
foreach (var following in await dbEntities.Followings.Match(f => f.TargetActorURI == old.ActorURI).ExecuteAsync(token))
{
var persona = await _localActors.FindById(LocalActorKind.Person, following.AvatarId, token);
var persona = await localActors.FindById(LocalActorKind.Person, following.AvatarId, token);
if (persona == default)
continue;
var lists = await DB.Default.Find<PersonaListMember>().Match(m => m.AvatarId == persona.Id && m.AccountId == old.ID).ExecuteAsync(token);
var endorsed = await DB.Default.Find<Endorsement>().Match(e => e.AvatarId == persona.Id && e.TargetActorURI == old.ActorURI).ExecuteAnyAsync(token);
var followed = await _follows.FollowAs(persona, moved.ActorURI, following.ShowReblogs, token, following.Notify, following.Languages ?? new List<string>());
await _follows.UnfollowAs(persona, old.ActorURI, token);
var followed = await follows.FollowAs(persona, moved.ActorURI, following.ShowReblogs, following.Notify, following.Languages ?? new List<string>(), token);
await follows.UnfollowAs(persona, old.ActorURI, token);
if (followed == default)
continue;
// the persona's endorsement and private note go with the follow, as Mastodon carries them over (R8)
@@ -100,14 +89,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
async Task CarryOver(ForeignAvatar old, ForeignAvatar moved, CancellationToken token)
{
foreach (var mute in await DB.Default.Find<Mute>().Match(m => m.TargetActorURI == old.ActorURI).ExecuteAsync(token))
if (await _localActors.FindById(LocalActorKind.Person, mute.AvatarId, token) is { } persona
if (await localActors.FindById(LocalActorKind.Person, mute.AvatarId, token) is { } persona
&& !await DB.Default.Find<Mute>().Match(m => m.AvatarId == persona.Id && m.TargetActorURI == moved.ActorURI).ExecuteAnyAsync(token))
await _relationships.Mute(persona, moved.ActorURI, moved.ID, mute.HideNotifications,
await relationships.Mute(persona, moved.ActorURI, moved.ID, mute.HideNotifications,
mute.ExpiresAt is { } expires ? expires - DateTime.UtcNow : default(TimeSpan?), token);
foreach (var block in await DB.Default.Find<Block>().Match(b => b.TargetActorURI == old.ActorURI).ExecuteAsync(token))
if (await _localActors.FindById(LocalActorKind.Person, block.AvatarId, token) is { } persona
if (await localActors.FindById(LocalActorKind.Person, block.AvatarId, token) is { } persona
&& !await DB.Default.Find<Block>().Match(b => b.AvatarId == persona.Id && b.TargetActorURI == moved.ActorURI).ExecuteAnyAsync(token))
await _relationships.Block(persona, moved.ActorURI, moved.ID, token);
await relationships.Block(persona, moved.ActorURI, moved.ID, token);
}
}
}
@@ -5,17 +5,11 @@ using System.Text.Json.Nodes;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class QuoteRequestHandler : IActivityHandler
public class QuoteRequestHandler(
IQuoteService quotes) : IActivityHandler
{
readonly IQuoteService _quotes;
public QuoteRequestHandler(IQuoteService quotes)
{
_quotes = quotes;
}
public string Type => "QuoteRequest";
public Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) => _quotes.ReceiveRequest(activity, actor, token);
public Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) => quotes.ReceiveRequest(activity, actor, token);
}
}
@@ -7,18 +7,15 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
// FEP-5624 (PeerTube): the author of a post whose canReply asks it to approve each reply lets one of ours in, which then
// goes to its audience carrying the approval (replyApproval)
public class ReplyApprovalHandler : IActivityHandler
public class ReplyApprovalHandler(
IInteractionApprovals approvals) : IActivityHandler
{
readonly IInteractionApprovals _approvals;
public ReplyApprovalHandler(IInteractionApprovals approvals) => _approvals = approvals;
public virtual string Type => "ApproveReply";
protected virtual bool Approves => true;
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) =>
await _approvals.Answered(activity, actor, Approves, token);
await approvals.Answered(activity, actor, Approves, token);
}
// and refuses one, which stays ours alone
@@ -15,18 +15,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
// Lemmy 1.0 tells a report's sender that it was dealt with: Resolve{Flag}, the Flag being one we sent
// (`/grunts/flag-<report id>`). It is believed from the server holding what was reported, or the community it was
// reported to, and kept on the report beside our own moderators' resolution, which it never replaces.
public class ResolveHandler : IActivityHandler
public class ResolveHandler(
DbEntities dbEntities,
ILocalActorService localActors) : IActivityHandler
{
const string FlagMarker = "/grunts/flag-";
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public ResolveHandler(DbEntities dbEntities, ILocalActorService localActors)
{
_dbEntities = dbEntities;
_localActors = localActors;
}
public string Type => "Resolve";
@@ -36,7 +30,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var flagId = Id(flag);
var marker = flagId?.IndexOf(FlagMarker, StringComparison.Ordinal) ?? -1;
if (flag is JsonObject && Value(flag, "type") != "Flag" || marker < 0
|| !flagId.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
|| !flagId.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
{
Arrival.Drop("not-ours");
return;
@@ -49,8 +43,8 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
var concerned = new List<string>(report.ObjectURIs) { report.TargetActorURI };
foreach (var post in report.PostIds.Count == 0 ? new List<Models.Post.Post>() : await _dbEntities.Posts.Match(p => report.PostIds.Contains(p.ID)).ExecuteAsync(token))
concerned.Add(await Communities.Of(post, _dbEntities, token));
foreach (var post in report.PostIds.Count == 0 ? new List<Models.Post.Post>() : await dbEntities.Posts.Match(p => report.PostIds.Contains(p.ID)).ExecuteAsync(token))
concerned.Add(await Communities.Of(post, dbEntities, token));
if (!concerned.Any(uri => Origin.Same(uri, actor.ActorURI)))
{
Arrival.Drop("misattributed");
@@ -16,19 +16,11 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class UndoHandler : IActivityHandler
public class UndoHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IReactions reactions) : IActivityHandler
{
readonly IReactions _reactions;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public UndoHandler(DbEntities dbEntities, ILocalActorService localActors, IReactions reactions)
{
_reactions = reactions;
_dbEntities = dbEntities;
_localActors = localActors;
}
public string Type => "Undo";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -48,11 +40,11 @@ namespace PrivaPub.Federation.Inbox.Handlers
if (innerType is null or "Dislike")
undone |= await UndoDislike(inner, innerId, actor, token);
if (innerType is null or "Block")
undone |= await BlockHandler.Undo(inner, innerId, actor, _localActors, token);
undone |= await BlockHandler.Undo(inner, innerId, actor, localActors, token);
if (innerType == "Lock")
undone |= await LockHandler.Set(_dbEntities, Id(inner["object"]), actor, locked: false, token);
undone |= await LockHandler.Set(dbEntities, Id(inner["object"]), actor, locked: false, token);
if (innerType is null or "Like" or "EmojiReact")
undone |= await _reactions.Withdraw(actor, innerId, inner is JsonObject ? Id(inner["object"]) : default,
undone |= await reactions.Withdraw(actor, innerId, inner is JsonObject ? Id(inner["object"]) : default,
inner is JsonObject ? Value(inner, "_misskey_reaction") ?? Value(inner, "content") : default, token);
if (undone)
Arrival.Accept("undone");
@@ -67,7 +59,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
: await DB.Default.Find<Downvote>().Match(d => d.ActivityURI == innerId && d.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
if (downvote == default && inner is JsonObject && Id(inner["object"]) is { } objectUri)
{
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
downvote = post == default
? default
: await DB.Default.Find<Downvote>().Match(d => d.PostId == post.ID && d.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
@@ -81,9 +73,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
async Task<bool> UndoFollow(JsonNode inner, string innerId, ForeignAvatar actor, CancellationToken token)
{
var followers = await _dbEntities.Followers.Match(f => f.ActorURI == actor.ActorURI).ExecuteAsync(token);
var followers = await dbEntities.Followers.Match(f => f.ActorURI == actor.ActorURI).ExecuteAsync(token);
var targetUri = inner is JsonObject ? Id(inner["object"]) : default;
var target = targetUri == default ? default : await _localActors.FindByAddress(targetUri, token);
var target = targetUri == default ? default : await localActors.FindByAddress(targetUri, token);
var undone = false;
foreach (var follower in followers)
{
@@ -104,13 +96,13 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
var favourite = innerId == default
? default
: await _dbEntities.Favourites.Match(f => f.ActivityURI == innerId && f.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
: await dbEntities.Favourites.Match(f => f.ActivityURI == innerId && f.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
if (favourite == default && inner is JsonObject && Id(inner["object"]) is { } objectUri)
{
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
favourite = post == default
? default
: await _dbEntities.Favourites.Match(f => f.PostId == post.ID && f.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
: await dbEntities.Favourites.Match(f => f.PostId == post.ID && f.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
}
if (favourite == default)
return false;
@@ -123,7 +115,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
if (innerId == default)
return false;
var reblog = await _dbEntities.Posts
var reblog = await dbEntities.Posts
.Match(p => p.ObjectURI == innerId && p.ActorURI == actor.ActorURI && p.ReblogOfPostId != null)
.ExecuteFirstAsync(token);
if (reblog == default)
@@ -16,29 +16,15 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers
{
public class UpdateHandler : IActivityHandler
public class UpdateHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IGroupDistributor groups,
IObjectRecords records,
IQuoteService quotes,
IDeliveryService delivery = default) : IActivityHandler
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IGroupDistributor _groups;
readonly IObjectRecords _records;
readonly IQuoteService _quotes;
readonly IDeliveryService _delivery;
public UpdateHandler(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IGroupDistributor groups,
IObjectRecords records, IQuoteService quotes, IDeliveryService delivery = default)
{
_delivery = delivery;
_quotes = quotes;
_records = records;
_groups = groups;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
}
public string Type => "Update";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -46,7 +32,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var inner = activity["object"];
if (Id(inner) == actor.ActorURI)
{
await _remoteActors.GetActor(actor.ActorURI, refresh: true, token);
await remoteActors.GetActor(actor.ActorURI, refresh: true, token);
Arrival.Accept("actor-refresh");
Arrival.About(actor.AvatarType.ToString());
return;
@@ -61,7 +47,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
// as that server has it now
if (note != default && note.AttributedTo != actor.ActorURI && Origin.Same(note.AttributedTo, actor.ActorURI))
{
using var fetched = await _remoteActors.FetchObject(note.Id, token);
using var fetched = await remoteActors.FetchObject(note.Id, token);
var current = fetched == default ? default : NoteParser.Parse(JsonNode.Parse(fetched.Root.GetRawText()));
if (current == default || current.Id != note.Id || current.AttributedTo != note.AttributedTo)
{
@@ -69,7 +55,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
note = current;
actor = await _remoteActors.GetActor(note.AttributedTo, refresh: false, token);
actor = await remoteActors.GetActor(note.AttributedTo, refresh: false, token);
if (actor == default)
{
Arrival.Drop("author-unavailable");
@@ -82,7 +68,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == note.Id && p.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == note.Id && p.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
if (post == default || post.DeletedAt.HasValue)
{
Arrival.Drop("unknown-object");
@@ -90,12 +76,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
}
Arrival.About(note.Type, post.Visibility, post.CreationDate);
var edited = await RemoteEdits.Apply(post, note, Id(activity), _localActors, _records, _quotes, token);
var edited = await RemoteEdits.Apply(post, note, Id(activity), localActors, records, quotes, token);
Arrival.Accept(edited ? "edit" : "refresh");
if (edited)
await ReplyRelay.Pass(post, _dbEntities, _localActors, _delivery, token);
if (edited && !string.IsNullOrEmpty(post.GroupId) && await _localActors.FindById(Models.Federation.LocalActorKind.Group, post.GroupId, token) is { IsCircle: false } community)
await _groups.Announce(community, activity.AsObject(), post.ObjectURI, isNewPost: false, token);
await ReplyRelay.Pass(post, dbEntities, localActors, delivery, token);
if (edited && !string.IsNullOrEmpty(post.GroupId) && await localActors.FindById(Models.Federation.LocalActorKind.Group, post.GroupId, token) is { IsCircle: false } community)
await groups.Announce(community, activity.AsObject(), post.ObjectURI, isNewPost: false, token);
}
}
}
@@ -17,20 +17,13 @@ namespace PrivaPub.Federation.Inbox.Handlers
// [persona], object: post, summary: reason, audience: community}), sent to the persona's inbox alone. It becomes the
// persona's moderation_warning notification, once the sender is shown to moderate that community and the post is the
// persona's own, in it.
public class WarnHandler : IActivityHandler
public class WarnHandler(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors) : IActivityHandler
{
const int MaxReason = 1000;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
public WarnHandler(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
}
public string Type => "Warn";
@@ -38,7 +31,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
{
LocalActor persona = default;
foreach (var uri in Recipients(activity["to"]))
if (await _localActors.FindByUri(uri, token) is { Kind: LocalActorKind.Person } found)
if (await localActors.FindByUri(uri, token) is { Kind: LocalActorKind.Person } found)
{
persona = found;
break;
@@ -49,7 +42,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return;
}
var communityUri = Id(activity["audience"]);
var community = communityUri == default ? default : await _remoteActors.GetActor(communityUri, refresh: false, token);
var community = communityUri == default ? default : await remoteActors.GetActor(communityUri, refresh: false, token);
if (community is not { AvatarType: AvatarType.Group })
{
Arrival.Drop("unknown-community");
@@ -58,21 +51,21 @@ namespace PrivaPub.Federation.Inbox.Handlers
var objectUri = Id(activity["object"]);
var post = objectUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.GroupUserId == persona.Id && !p.IsFederatedCopy).ExecuteFirstAsync(token);
if (post == default || await Communities.Of(post, _dbEntities, token) != community.ActorURI)
: await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.GroupUserId == persona.Id && !p.IsFederatedCopy).ExecuteFirstAsync(token);
if (post == default || await Communities.Of(post, dbEntities, token) != community.ActorURI)
{
Arrival.Drop("unknown-object");
return;
}
Arrival.About(visibility: post.Visibility, created: post.CreationDate, local: persona);
if (!await Communities.Moderates(community, actor.ActorURI, _remoteActors, token))
if (!await Communities.Moderates(community, actor.ActorURI, remoteActors, token))
{
Arrival.Drop("not-moderator");
return;
}
var reason = Value(activity, "summary") ?? Value(activity, "content");
await Notifications.Add(persona.Id, NotificationType.ModerationWarning, community.ID, community.ActorURI, post.ID, token,
text: string.IsNullOrWhiteSpace(reason) ? default : reason.Trim().Length <= MaxReason ? reason.Trim() : reason.Trim()[..MaxReason]);
await Notifications.Add(persona.Id, NotificationType.ModerationWarning, community.ID, community.ActorURI, post.ID,
text: string.IsNullOrWhiteSpace(reason) ? default : reason.Trim().Length <= MaxReason ? reason.Trim() : reason.Trim()[..MaxReason], token: token);
Arrival.Accept("warned");
}
+16 -26
View File
@@ -20,27 +20,17 @@ namespace PrivaPub.Federation.Inbox
Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token);
}
public class InboxProcessor : IJobHandler
public class InboxProcessor(
IRemoteActorService remoteActors,
IEnumerable<IActivityHandler> handlers,
ILogger<InboxProcessor> logger,
IInteractionLedger ledger = default,
ILocalActorService localActors = default,
Microsoft.Extensions.Options.IOptionsMonitor<Infrastructure.Http.FederationOptions> federation = default) : IJobHandler
{
readonly IRemoteActorService _remoteActors;
readonly IReadOnlyDictionary<string, IActivityHandler> _handlers;
readonly ILogger<InboxProcessor> _logger;
readonly IInteractionLedger _ledger;
readonly ILocalActorService _localActors;
readonly IReadOnlyDictionary<string, IActivityHandler> _handlers = handlers.ToDictionary(h => h.Type, StringComparer.Ordinal);
readonly int _concurrency = Math.Max(1, federation?.CurrentValue.InboxConcurrency ?? 8);
readonly int _concurrency;
public InboxProcessor(IRemoteActorService remoteActors, IEnumerable<IActivityHandler> handlers, ILogger<InboxProcessor> logger,
IInteractionLedger ledger = default, ILocalActorService localActors = default,
Microsoft.Extensions.Options.IOptions<Infrastructure.Http.FederationOptions> federation = default)
{
_concurrency = Math.Max(1, federation?.Value.InboxConcurrency ?? 8);
_localActors = localActors;
_remoteActors = remoteActors;
_handlers = handlers.ToDictionary(h => h.Type, StringComparer.Ordinal);
_logger = logger;
_ledger = ledger;
}
public JobKind Kind => JobKind.ProcessInbox;
public int Concurrency => _concurrency;
@@ -59,7 +49,7 @@ namespace PrivaPub.Federation.Inbox
return JobOutcome.Done;
}
var actor = await _remoteActors.GetActor(payload.ActorURI, refresh: false, token);
var actor = await remoteActors.GetActor(payload.ActorURI, refresh: false, token);
if (actor == default)
{
Record(job, payload, activity, type, started, new ArrivalVerdict(), Interactions.Deferred, "actor-unavailable");
@@ -73,10 +63,10 @@ namespace PrivaPub.Federation.Inbox
return JobOutcome.Done;
}
if (payload.ForwardedBy != default && Forwarded.NamesUnknownKey(activity, actor))
actor = await _remoteActors.GetActor(actor.ActorURI, refresh: true, token) ?? actor;
actor = await remoteActors.GetActor(actor.ActorURI, refresh: true, token) ?? actor;
if (payload.ForwardedBy != default && !Forwarded.Proven(activity, actor))
{
var (confirmed, drop) = await Forwarded.Confirm(activity, type, actor.ActorURI, _remoteActors, token);
var (confirmed, drop) = await Forwarded.Confirm(activity, type, actor.ActorURI, remoteActors, token);
if (drop != default)
{
Record(job, payload, activity, type, started, new ArrivalVerdict(), Interactions.Dropped, drop);
@@ -91,7 +81,7 @@ namespace PrivaPub.Federation.Inbox
Arrival.Current = arrival;
try
{
await LocalReferences.Canonicalise(activity, _localActors?.BaseAddress, token);
await LocalReferences.Canonicalise(activity, localActors?.BaseAddress, token);
await handler.Handle(activity, actor, token);
}
catch (Exception ex) when (ex is not OperationCanceledException)
@@ -104,16 +94,16 @@ namespace PrivaPub.Federation.Inbox
Arrival.Current = default;
}
Record(job, payload, activity, type, started, arrival.Verdict, default, default);
_logger.LogInformation("Processed {Type} {Id} from {Actor}", type, Id(activity), actor.ActorURI);
logger.LogInformation("Processed {Type} {Id} from {Actor}", type, Id(activity), actor.ActorURI);
return JobOutcome.Done;
}
void Record(Job job, InboxPayload payload, JsonNode activity, string type, long started, ArrivalVerdict verdict, string outcome, string reason)
{
if (_ledger == default || payload == default)
if (ledger == default || payload == default)
return;
var embedded = activity?["object"] as JsonObject;
_ledger.Record(new InteractionEvent
ledger.Record(new InteractionEvent
{
Channel = Interactions.In,
Host = Interactions.HostOf(payload.ActorURI),
+27 -37
View File
@@ -28,29 +28,18 @@ namespace PrivaPub.Federation.Inbox
InboxResult NoSuchRecipient(HttpRequest request);
}
public class InboxReceiver : IInboxReceiver
public class InboxReceiver(
ILocalActorService localActors,
IRemoteActorService remoteActors,
IJobQueue queue,
IDomainBlocks domainBlocks,
ILogger<InboxReceiver> logger,
IInteractionLedger ledger = default) : IInboxReceiver
{
const int KeyRetrySeconds = 300;
const int MaxBodyBytes = 1024 * 1024;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IJobQueue _queue;
readonly IDomainBlocks _domainBlocks;
readonly ILogger<InboxReceiver> _logger;
readonly IInteractionLedger _ledger;
public InboxReceiver(ILocalActorService localActors, IRemoteActorService remoteActors, IJobQueue queue, IDomainBlocks domainBlocks,
ILogger<InboxReceiver> logger, IInteractionLedger ledger = default)
{
_localActors = localActors;
_remoteActors = remoteActors;
_queue = queue;
_domainBlocks = domainBlocks;
_logger = logger;
_ledger = ledger;
}
sealed class Receipt
{
@@ -91,10 +80,10 @@ namespace PrivaPub.Federation.Inbox
void Record(Receipt receipt, InboxResult result, int latencyMs)
{
if (_ledger == default || result == default)
if (ledger == default || result == default)
return;
var verified = receipt.VerifiedActor != default;
_ledger.Record(new InteractionEvent
ledger.Record(new InteractionEvent
{
Channel = Interactions.Receive,
Host = verified ? Interactions.HostOf(receipt.VerifiedActor) : receipt.ClaimedHost,
@@ -111,6 +100,7 @@ namespace PrivaPub.Federation.Inbox
}, verified ? receipt.VerifiedActor : default, hostClaimed: !verified && !receipt.Blocked);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0007", Justification = "ActivityPub servers retry a 503 with Retry-After when the signing key cannot be fetched yet; a 4XX would make them drop the activity.")]
async Task<InboxResult> Receive(HttpRequest request, LocalActor recipient, Receipt receipt, CancellationToken token)
{
if (request.ContentLength > MaxBodyBytes)
@@ -123,7 +113,7 @@ namespace PrivaPub.Federation.Inbox
var body = buffer.ToArray();
receipt.Bytes = body.Length;
JsonNode activity;
var activity = default(JsonNode);
try
{
activity = JsonNode.Parse(body);
@@ -149,10 +139,10 @@ namespace PrivaPub.Federation.Inbox
return new(StatusCodes.Status401Unauthorized, "missing or unreadable Signature header", Reason: "no-signature");
receipt.Signature = signature.Scheme;
receipt.ClaimedHost ??= HostOf(signature.KeyId);
if (_domainBlocks.IsSuspended(HostOf(signature.KeyId)) || _domainBlocks.IsSuspended(HostOf(actorUri)))
if (domainBlocks.IsSuspended(HostOf(signature.KeyId)) || domainBlocks.IsSuspended(HostOf(actorUri)))
{
receipt.Blocked = true;
receipt.ClaimedHost = _domainBlocks.IsSuspended(HostOf(actorUri)) ? HostOf(actorUri) : HostOf(signature.KeyId);
receipt.ClaimedHost = domainBlocks.IsSuspended(HostOf(actorUri)) ? HostOf(actorUri) : HostOf(signature.KeyId);
return new(StatusCodes.Status202Accepted, Reason: "suspended");
}
@@ -160,14 +150,14 @@ namespace PrivaPub.Federation.Inbox
if (requestProblem != default)
return new(StatusCodes.Status401Unauthorized, requestProblem, Reason: HttpSignatures.ProblemCode(requestProblem));
var signed = signature.Signed(request, _localActors.BaseAddress);
var keyOwner = await _remoteActors.GetActorByKeyId(signature.KeyId, refresh: false, token);
var signed = signature.Signed(request, localActors.BaseAddress);
var keyOwner = await remoteActors.GetActorByKeyId(signature.KeyId, refresh: false, token);
if (keyOwner == default && type == "Delete" && Id(activity["object"]) == actorUri)
return new(StatusCodes.Status202Accepted, Reason: "self-delete-unknown-key");
if (keyOwner == default || !signature.VerifiedBy(keyOwner.PublicKey, signed))
{
keyOwner = await _remoteActors.GetActorByKeyId(signature.KeyId, refresh: true, token);
if (keyOwner == default && _remoteActors.KeyTemporarilyUnavailable(signature.KeyId))
keyOwner = await remoteActors.GetActorByKeyId(signature.KeyId, refresh: true, token);
if (keyOwner == default && remoteActors.KeyTemporarilyUnavailable(signature.KeyId))
return new(StatusCodes.Status503ServiceUnavailable, "the signing key could not be fetched; try again later", KeyRetrySeconds, "key-unavailable");
if (keyOwner == default || !signature.VerifiedBy(keyOwner.PublicKey, signed))
return new(StatusCodes.Status401Unauthorized, "the signature does not verify", Reason: "signature-invalid");
@@ -178,7 +168,7 @@ namespace PrivaPub.Federation.Inbox
receipt.VerifiedActor = keyOwner.ActorURI;
var forwardedBy = string.Equals(keyOwner.ActorURI, actorUri, StringComparison.Ordinal) ? default : keyOwner.ActorURI;
// (ours come back too, Friendica forwarding our comments in its threads: we know them already)
if (forwardedBy != default && (!Forwarded.Takeable(type, activity, actorUri) || Origin.Same(actorUri, _localActors.BaseAddress)))
if (forwardedBy != default && (!Forwarded.Takeable(type, activity, actorUri) || Origin.Same(actorUri, localActors.BaseAddress)))
return new(StatusCodes.Status202Accepted, Reason: "forwarded-ignored");
var shapeProblem = await ShapeProblem(type, activity, actorUri, token);
@@ -193,21 +183,21 @@ namespace PrivaPub.Federation.Inbox
var dedupe = activityId == default ? default : (forwardedBy == default ? "inbox|" : "inbox|forwarded|") + activityId;
var queuedPayload = JsonSerializer.Serialize(payload);
var host = new Uri(actorUri).Host.ToLowerInvariant();
var queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, dedupe, token);
var queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, dedupe, token);
// one id its sender gave two activities is no duplicate (Friendica's ids are uniqid(), a prefix and the
// microsecond, which two of its processes answering at once share): what each carries tells them apart, and a
// true copy carries the same
if (!queued && dedupe != default && CarriesOther(await _queue.Payload(dedupe, token), activity))
queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}", token);
if (!queued && dedupe != default && CarriesOther(await queue.Payload(dedupe, token), activity))
queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}", token);
// an Undo of a Follow that comes again while the follow it ends exists again is meant for that follow: Mastodon
// gives every Undo it sends after reading a roll-call (FEP-8fcf) one id, `{actor}#follows//undo`. It is kept
// once per follow, so a retry still counts as a copy
if (!queued && dedupe != default && type == "Undo" && await FollowAgain(activity, actorUri, token) is { } follow)
queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}|{follow}", token);
queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}|{follow}", token);
// FEP-8fcf: what the sender says of its followers here (FollowingSynchronization)
if (queued && forwardedBy == default && FollowersSynchronization.Claim(actorUri, request.Headers[FollowersSynchronization.Header].ToString()) is { } claim)
await _queue.Enqueue(JobKind.SynchronizeFollowing, JsonSerializer.Serialize(claim), host, FollowingSynchronization.DedupeKey(claim, activityId), token);
_logger.LogInformation("Inbox {Recipient}: {Type} from {Actor} queued", recipient?.Handle ?? "shared", type, actorUri);
await queue.Enqueue(JobKind.SynchronizeFollowing, JsonSerializer.Serialize(claim), host, FollowingSynchronization.DedupeKey(claim, activityId), token);
logger.LogInformation("Inbox {Recipient}: {Type} from {Actor} queued", recipient?.Handle ?? "shared", type, actorUri);
return new(StatusCodes.Status202Accepted, Reason: !queued ? "duplicate" : forwardedBy != default ? "forwarded" : "queued");
}
@@ -215,7 +205,7 @@ namespace PrivaPub.Federation.Inbox
async Task<string> FollowAgain(JsonNode activity, string actorUri, CancellationToken token)
{
if (activity["object"] is not JsonObject inner || Value(inner, "type") != "Follow" || Id(inner["object"]) is not { } targetUri
|| await _localActors.FindByUri(targetUri, token) is not { } target)
|| await localActors.FindByUri(targetUri, token) is not { } target)
return default;
var follower = await MongoDB.Entities.DB.Default.Find<Follower>()
.Match(f => f.ActorURI == actorUri && f.LocalActorId == target.Id && f.LocalActorKind == target.Kind)
@@ -244,7 +234,7 @@ namespace PrivaPub.Federation.Inbox
var activityId = Id(activity);
// (Funkwhale names its answer after the activity it answers: `<our Follow's id>/accept`)
if (activityId != default && !Origin.Same(activityId, actorUri)
&& !(type is "Accept" or "Reject" && Id(activity["object"]) is { } answered && Origin.Same(answered, _localActors.BaseAddress)
&& !(type is "Accept" or "Reject" && Id(activity["object"]) is { } answered && Origin.Same(answered, localActors.BaseAddress)
&& activityId.StartsWith(answered + "/", StringComparison.Ordinal)))
return new(StatusCodes.Status400BadRequest, "the activity's id is not on its actor's origin", Reason: "id-cross-origin");
@@ -253,7 +243,7 @@ namespace PrivaPub.Federation.Inbox
{
case "Follow":
// (by its actor's id, or the profile page Forte names instead)
var target = await _localActors.FindByAddress(Id(inner), token);
var target = await localActors.FindByAddress(Id(inner), token);
if (target is not { IsFederated: true } || target.IsServerActor)
return new(StatusCodes.Status404NotFound, "no such local actor", Reason: "unknown-recipient");
break;
+27 -46
View File
@@ -31,29 +31,17 @@ namespace PrivaPub.Federation.Inbox
Task<PostEntity> StoreContext(string objectUri, int depth, CancellationToken token);
}
public class RemotePosts : IRemotePosts
public class RemotePosts(
DbEntities dbEntities,
ILocalActorService localActorService,
IRemoteActorService remoteActors,
IDomainBlocks domainBlockList,
IJobQueue queue,
IObjectRecords records,
ILinkPreviews previews) : IRemotePosts
{
public const int MaxDepth = 10;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDomainBlocks _domainBlocks;
readonly IJobQueue _queue;
readonly IObjectRecords _records;
readonly ILinkPreviews _previews;
public RemotePosts(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDomainBlocks domainBlocks,
IJobQueue queue, IObjectRecords records, ILinkPreviews previews)
{
_previews = previews;
_records = records;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_domainBlocks = domainBlocks;
_queue = queue;
}
// The accounts a remote post names (its Mention tags), plus our personas it is addressed to without naming them: Mastodon
// keeps those as silent mentions, and Akkoma's to[], or an edit that dropped the @name, address someone that way. A
@@ -81,7 +69,7 @@ namespace PrivaPub.Federation.Inbox
public async Task<PostEntity> Build(NoteDocument note, ForeignAvatar author, PostVisibility visibility, IReadOnlyList<string> to,
IReadOnlyList<string> cc, PostEntity parent, CancellationToken token)
{
var mentions = await Mentions(note, to.Concat(cc), _localActors, token);
var mentions = await Mentions(note, to.Concat(cc), localActorService, token);
var post = new PostEntity
{
@@ -127,7 +115,7 @@ namespace PrivaPub.Federation.Inbox
Language = note.Language,
Mentions = mentions,
Tags = note.Tags.ToList(),
Media = _domainBlocks.Find(new Uri(author.ActorURI).Host)?.RejectMedia == true ? new() : note.Attachments.ToList(),
Media = domainBlockList.Find(new Uri(author.ActorURI).Host)?.RejectMedia == true ? new() : note.Attachments.ToList(),
InReplyToURI = note.InReplyTo,
AnsweringToPostId = parent?.ID,
InReplyToAccountId = parent?.AuthorAccountId ?? parent?.GroupUserId,
@@ -135,7 +123,7 @@ namespace PrivaPub.Federation.Inbox
AuthorGone = author.AccountState == AvatarAccountState.Deleted,
// the staff's moderation of its author or its server (R6), as AccountModeration sets it on what came before
AuthorSuspended = author.SuspendedAt.HasValue,
AuthorLimited = Limited(author, _domainBlocks),
AuthorLimited = Limited(author, domainBlockList),
CreationDate = note.Published,
UpdateDate = note.Updated ?? note.Published,
EditedAt = note.Updated,
@@ -172,7 +160,7 @@ namespace PrivaPub.Federation.Inbox
if (links.Count != 1 || links[0] == note.Id || !Origin.Same(links[0], author.ActorURI))
return;
using var scope = HttpScope.For("object");
using var fetched = await _remoteActors.FetchObject(links[0], token);
using var fetched = await remoteActors.FetchObject(links[0], token);
var episode = fetched == default ? default : NoteParser.Parse(JsonNode.Parse(fetched.Root.GetRawText()));
if (episode is not { Type: "PodcastEpisode" } || episode.AttributedTo != author.ActorURI)
return;
@@ -187,33 +175,33 @@ namespace PrivaPub.Federation.Inbox
{
if (string.IsNullOrEmpty(inReplyTo))
return default;
var known = await _dbEntities.Posts.Match(p => p.ObjectURI == inReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (known != default || inReplyTo.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
var known = await dbEntities.Posts.Match(p => p.ObjectURI == inReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (known != default || inReplyTo.StartsWith(localActorService.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return known;
return await StoreContext(inReplyTo, depth, token);
}
public async Task<PostEntity> StoreContext(string objectUri, int depth, CancellationToken token)
{
var existing = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var existing = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
if (existing != default || depth > MaxDepth || await DB.Default.Find<DeletedObject>().Match(d => d.ObjectURI == objectUri).ExecuteAnyAsync(token))
return existing;
using var scope = HttpScope.For("context");
using var fetched = await _remoteActors.FetchObject(objectUri, token);
using var fetched = await remoteActors.FetchObject(objectUri, token);
var note = fetched == default ? default : NoteParser.Parse(JsonNode.Parse(fetched.Root.GetRawText()));
if (note == default || !Origin.Same(note.Id, note.AttributedTo))
return default;
var visibility = Addressing.Classify(note.To, note.Cc, default);
if (visibility is not (PostVisibility.Public or PostVisibility.Unlisted))
return default;
var author = await _remoteActors.GetActor(note.AttributedTo, refresh: false, token);
var author = await remoteActors.GetActor(note.AttributedTo, refresh: false, token);
if (author == default)
return default;
var grandparent = string.IsNullOrEmpty(note.InReplyTo)
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
: await dbEntities.Posts.Match(p => p.ObjectURI == note.InReplyTo && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var post = await Build(note, author, visibility, note.To, note.Cc, grandparent, token);
try
{
@@ -221,29 +209,22 @@ namespace PrivaPub.Federation.Inbox
}
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
{
return await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
return await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
}
await _records.Record(note, post, ObjectPath.Fetched, refetched: false, token);
await _previews.Wanted(post, token);
await records.Record(note, post, ObjectPath.Fetched, refetched: false, token);
await previews.Wanted(post, token);
if (grandparent == default && !string.IsNullOrEmpty(note.InReplyTo) && depth < MaxDepth)
await _queue.Enqueue(JobKind.FetchAncestors, JsonSerializer.Serialize(new AncestorsPayload(post.ID, depth + 1)), new Uri(note.InReplyTo).Host,
await queue.Enqueue(JobKind.FetchAncestors, JsonSerializer.Serialize(new AncestorsPayload(post.ID, depth + 1)), new Uri(note.InReplyTo).Host,
"ancestors|" + post.ID, token);
return post;
}
}
public class AncestorsJobHandler : IJobHandler
public class AncestorsJobHandler(
DbEntities dbEntities,
IRemotePosts remotePosts) : IJobHandler
{
readonly DbEntities _dbEntities;
readonly IRemotePosts _remotePosts;
public AncestorsJobHandler(DbEntities dbEntities, IRemotePosts remotePosts)
{
_dbEntities = dbEntities;
_remotePosts = remotePosts;
}
public JobKind Kind => JobKind.FetchAncestors;
public int Concurrency => 1;
public int MaxAttempts => 3;
@@ -252,11 +233,11 @@ namespace PrivaPub.Federation.Inbox
public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{
var payload = JsonSerializer.Deserialize<AncestorsPayload>(job.Payload);
var child = await _dbEntities.Posts.MatchID(payload.PostId).ExecuteFirstAsync(token);
var child = await dbEntities.Posts.MatchID(payload.PostId).ExecuteFirstAsync(token);
if (child == default || string.IsNullOrEmpty(child.InReplyToURI) || !string.IsNullOrEmpty(child.AnsweringToPostId))
return JobOutcome.Done;
var parent = await _remotePosts.Parent(child.InReplyToURI, payload.Depth, token);
var parent = await remotePosts.Parent(child.InReplyToURI, payload.Depth, token);
if (parent == default)
return JobOutcome.Done;
await DB.Default.Update<PostEntity>().MatchID(child.ID)
+13 -21
View File
@@ -27,7 +27,11 @@ namespace PrivaPub.Federation.Inbox
// replies' own, two levels down. Read with the instance actor's signature, never a persona's, a few pages and at most
// MaxItems posts a job; each one is fetched from its own server and stored like any post fetched for a thread
// (RemotePosts.StoreContext: public and unlisted only, its author checked against its origin).
public class RepliesJobHandler : IJobHandler
public class RepliesJobHandler(
DbEntities dbEntities,
IRemoteActorService remoteActors,
IRemotePosts remotePosts,
IJobQueue queue) : IJobHandler
{
public const int MaxPages = 5;
public const int MaxItems = 100;
@@ -39,18 +43,6 @@ namespace PrivaPub.Federation.Inbox
"Collection", "OrderedCollection", "CollectionPage", "OrderedCollectionPage"
};
readonly DbEntities _dbEntities;
readonly IRemoteActorService _remoteActors;
readonly IRemotePosts _remotePosts;
readonly IJobQueue _queue;
public RepliesJobHandler(DbEntities dbEntities, IRemoteActorService remoteActors, IRemotePosts remotePosts, IJobQueue queue)
{
_dbEntities = dbEntities;
_remoteActors = remoteActors;
_remotePosts = remotePosts;
_queue = queue;
}
public JobKind Kind => JobKind.FetchReplies;
public int Concurrency => 2;
@@ -69,7 +61,7 @@ namespace PrivaPub.Federation.Inbox
public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{
var payload = JsonSerializer.Deserialize<RepliesPayload>(job.Payload);
var post = await _dbEntities.Posts.MatchID(payload.PostId).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.MatchID(payload.PostId).ExecuteFirstAsync(token);
if (post is not { IsFederatedCopy: true, Visibility: PostVisibility.Public or PostVisibility.Unlisted } || post.DeletedAt.HasValue
|| string.IsNullOrEmpty(post.ObjectURI))
return JobOutcome.Done;
@@ -80,7 +72,7 @@ namespace PrivaPub.Federation.Inbox
{
var uri = Id(document[name]);
// Forte's `context` is the thread's first post
if (uri != default && await _dbEntities.Posts.Match(p => p.ObjectURI == uri).ExecuteAnyAsync(token))
if (uri != default && await dbEntities.Posts.Match(p => p.ObjectURI == uri).ExecuteAnyAsync(token))
continue;
var known = uri == default ? default : await DB.Default.Find<ThreadCollection>().Match(c => c.URI == uri).ExecuteFirstAsync(token);
var (thread, etag, unchanged) = await Collection(document[name], known?.ETag, token);
@@ -106,7 +98,7 @@ namespace PrivaPub.Federation.Inbox
return JobOutcome.Done;
var (answers, _) = await StoreAll(replies, false, token);
if (payload.Depth < MaxDepth)
await _queue.EnqueueMany(answers.Where(a => a.IsFederatedCopy && a.AnsweringToPostId == post.ID).Take(MaxBranches)
await queue.EnqueueMany(answers.Where(a => a.IsFederatedCopy && a.AnsweringToPostId == post.ID).Take(MaxBranches)
.Select(a => For(a, payload.Depth + 1)), token);
return JobOutcome.Done;
}
@@ -119,7 +111,7 @@ namespace PrivaPub.Federation.Inbox
if (record != default)
return JsonNode.Parse(record.Raw) as JsonObject;
using var scope = HttpScope.For("replies");
using var fetched = await _remoteActors.FetchObject(post.ObjectURI, token);
using var fetched = await remoteActors.FetchObject(post.ObjectURI, token);
return fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText()) as JsonObject;
}
@@ -133,7 +125,7 @@ namespace PrivaPub.Federation.Inbox
if (uri != default && Uri.TryCreate(uri, UriKind.Absolute, out var parsed) && (parsed.Scheme == Uri.UriSchemeHttps || parsed.Scheme == Uri.UriSchemeHttp))
{
using var scope = HttpScope.For("replies");
using var fetched = await _remoteActors.FetchObject(uri, etag, token);
using var fetched = await remoteActors.FetchObject(uri, etag, token);
if (fetched?.NotModified == true)
return (default, etag, true);
node = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
@@ -160,8 +152,8 @@ namespace PrivaPub.Federation.Inbox
var id = activities ? await Added(item, token) : PostId(item);
if (id == default)
continue;
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await _remotePosts.StoreContext(id, 0, token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await remotePosts.StoreContext(id, 0, token);
if (post != default)
posts.Add(post);
}
@@ -200,7 +192,7 @@ namespace PrivaPub.Federation.Inbox
if (node is JsonValue && Id(node) is { } uri)
{
using var scope = HttpScope.For("replies");
using var fetched = await _remoteActors.FetchObject(uri, token);
using var fetched = await remoteActors.FetchObject(uri, token);
node = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
}
return node as JsonObject;
+1 -1
View File
@@ -37,7 +37,7 @@ namespace PrivaPub.Federation.Inbox
var replier = Interactions.HostOf(reply.ActorURI);
var inboxes = (await delivery.FollowerInboxes(owner, token)).Where(i => Interactions.HostOf(i) != replier).ToList();
if (inboxes.Count > 0)
await delivery.Enqueue(owner, inboxes, activity, token);
await delivery.Enqueue(owner, inboxes, activity, token: token);
}
}
}