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
294 lines
12 KiB
C#
294 lines
12 KiB
C#
using MongoDB.Driver;
|
|
using MongoDB.Entities;
|
|
|
|
using PrivaPub.Domain.Timelines;
|
|
using PrivaPub.Federation.Actors;
|
|
using PrivaPub.Federation.Moderation;
|
|
using PrivaPub.Domain.Content;
|
|
using PrivaPub.Domain.Statuses;
|
|
using PrivaPub.Federation.Objects;
|
|
using PrivaPub.Federation.Outbox;
|
|
using PrivaPub.Infrastructure.Ids;
|
|
using PrivaPub.Federation.Rendering;
|
|
using PrivaPub.Models.Federation;
|
|
using PrivaPub.Models.Group;
|
|
using PrivaPub.Models.Post;
|
|
using PrivaPub.Models.Social;
|
|
using PrivaPub.Models.User;
|
|
using PrivaPub.StaticServices;
|
|
|
|
using System.Text.Json.Nodes;
|
|
|
|
using static PrivaPub.Federation.Inbox.ForeignMembers;
|
|
using static PrivaPub.Federation.Objects.ActivityJson;
|
|
|
|
using PostEntity = PrivaPub.Models.Post.Post;
|
|
|
|
namespace PrivaPub.Federation.Inbox.Handlers
|
|
{
|
|
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
|
|
{
|
|
public string Type => "Create";
|
|
|
|
public async Task Handle(JsonNode activity, ForeignAvatar author, CancellationToken token)
|
|
{
|
|
var node = activity["object"];
|
|
var refetched = node is not JsonObject || !Origin.Same(Id(node), author.ActorURI);
|
|
if (refetched)
|
|
{
|
|
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");
|
|
}
|
|
var note = NoteParser.Parse(node);
|
|
// made by another account of the author's own server (Mobilizon's organiser creates the group's event): taken
|
|
// as that server has it, under the account it is attributed to
|
|
if (note != default && note.AttributedTo != author.ActorURI && Origin.Same(note.AttributedTo, author.ActorURI))
|
|
{
|
|
if (!refetched)
|
|
{
|
|
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);
|
|
if (author == default)
|
|
{
|
|
Arrival.Drop(note == default ? "fetch-failed" : "author-unavailable");
|
|
return;
|
|
}
|
|
}
|
|
if (note == default || note.AttributedTo != author.ActorURI)
|
|
{
|
|
Arrival.Drop(note == default ? "unparseable" : "misattributed");
|
|
return;
|
|
}
|
|
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);
|
|
if (question != default)
|
|
{
|
|
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))
|
|
{
|
|
Arrival.Drop("duplicate");
|
|
return;
|
|
}
|
|
// a deleted post stays deleted however late or often its Create comes; but an id its server gives a new post again
|
|
// (Gancio numbers an event after the last one it keeps, so a deleted last event's id comes back), published after
|
|
// the deletion, is that new post
|
|
if (await DB.Default.Find<DeletedObject>().Match(d => d.ObjectURI == note.Id).ExecuteFirstAsync(token) is { } tombstone)
|
|
{
|
|
if (Value(note.Raw, "published") == default || note.Published <= tombstone.DeletedAt)
|
|
{
|
|
Arrival.Drop("deleted");
|
|
return;
|
|
}
|
|
await DB.Default.DeleteAsync<DeletedObject>(tombstone.ID);
|
|
}
|
|
|
|
var to = note.To.Concat(Strings(activity["to"])).Distinct(StringComparer.Ordinal).ToList();
|
|
var cc = note.Cc.Concat(Strings(activity["cc"])).Distinct(StringComparer.Ordinal).ToList();
|
|
var visibility = Addressing.Classify(to, cc, author.FollowersURL);
|
|
Arrival.About(visibility: visibility);
|
|
|
|
var addressed = to.Concat(cc)
|
|
.Concat(Addresses(activity))
|
|
.Concat(note.Mentions.Select(m => m.ActorURI))
|
|
.Append(note.Audience)
|
|
.Where(a => a != default && !Addressing.IsPublic(a) && a != author.FollowersURL)
|
|
.Distinct(StringComparer.Ordinal)
|
|
.ToList();
|
|
var localTargets = new List<LocalActor>();
|
|
for (var i = 0; i < addressed.Count; i++)
|
|
{
|
|
var local = await localActors.FindByAddress(addressed[i], token);
|
|
if (local == default)
|
|
continue;
|
|
addressed[i] = local.Uri;
|
|
if (local.IsFederated && localTargets.All(l => l.Id != local.Id))
|
|
localTargets.Add(local);
|
|
}
|
|
addressed = addressed.Distinct(StringComparer.Ordinal).ToList();
|
|
var persons = localTargets.Where(t => t.Kind == LocalActorKind.Person).ToList();
|
|
|
|
var parent = string.IsNullOrEmpty(note.InReplyTo)
|
|
? default
|
|
: 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))
|
|
{
|
|
Arrival.Drop("reply-not-authorized");
|
|
return;
|
|
}
|
|
var circle = localTargets.FirstOrDefault(t => t is { Kind: LocalActorKind.Group, IsCircle: true });
|
|
if (circle != default)
|
|
{
|
|
visibility = PostVisibility.Circle;
|
|
Arrival.About(visibility: visibility);
|
|
if (!await IsCircleMember(circle, author.ActorURI, token))
|
|
{
|
|
Arrival.Drop("not-addressed");
|
|
return;
|
|
}
|
|
}
|
|
var group = circle ?? (visibility is PostVisibility.Public or PostVisibility.Unlisted
|
|
? localTargets.FirstOrDefault(t => t is { Kind: LocalActorKind.Group, IsCircle: false })
|
|
: default);
|
|
if (group is { IsCircle: false } && !await MayPost(group, author.ActorURI, token))
|
|
group = default;
|
|
|
|
var repliesToLocal = parent is { IsFederatedCopy: false } && visibility != PostVisibility.Direct;
|
|
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);
|
|
// 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);
|
|
// 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);
|
|
// 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);
|
|
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)))
|
|
{
|
|
Arrival.Drop("wall-refused");
|
|
return;
|
|
}
|
|
if (visibility == PostVisibility.Direct ? persons.Count == 0
|
|
: group == default && wall == default && persons.Count == 0 && !repliesToLocal && !followed && !repliesToFollowed && !inFollowedGroup && !relayed)
|
|
{
|
|
Arrival.Drop("not-addressed");
|
|
return;
|
|
}
|
|
if (parent == default && visibility != PostVisibility.Direct)
|
|
parent = await remotePosts.Parent(note.InReplyTo, 1, token);
|
|
|
|
DmGroup conversation = default;
|
|
if (visibility == PostVisibility.Direct)
|
|
{
|
|
var participants = persons.Select(p => p.Uri)
|
|
.Concat(addressed.Where(a => !IsCollection(a)))
|
|
.Append(author.ActorURI)
|
|
.ToList();
|
|
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);
|
|
post.ActivityURI = Id(activity);
|
|
post.GroupId = group?.Id;
|
|
post.ConversationId = conversation?.ID;
|
|
if (wall != default)
|
|
{
|
|
post.WallURI = wall.Wall;
|
|
post.WallOwnerURI = wall.Uri;
|
|
post.WallOwnerAccountId = wall.Id;
|
|
}
|
|
try
|
|
{
|
|
await DB.Default.SaveAsync(post, token);
|
|
}
|
|
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
|
{
|
|
Arrival.Drop("duplicate");
|
|
return;
|
|
}
|
|
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);
|
|
|
|
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);
|
|
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);
|
|
if (wall != default)
|
|
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);
|
|
|
|
async Task<bool> MayPost(LocalActor community, string actorUri, CancellationToken token)
|
|
{
|
|
var entity = await dbEntities.Groups.MatchID(community.Id).ExecuteFirstAsync(token);
|
|
return entity?.PostingPolicy switch
|
|
{
|
|
PostingPolicy.Anyone => true,
|
|
PostingPolicy.Followers => await IsAcceptedFollower(community, actorUri, token),
|
|
_ => false
|
|
};
|
|
}
|
|
|
|
async Task<DmGroup> FindOrCreateConversation(List<string> participantUris, string context, CancellationToken token)
|
|
{
|
|
var members = new List<GroupMember>();
|
|
foreach (var uri in participantUris.Distinct(StringComparer.Ordinal))
|
|
{
|
|
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 };
|
|
if (members.All(m => m.AvatarId != member.AvatarId || m.IsForeign != member.IsForeign))
|
|
members.Add(member);
|
|
}
|
|
|
|
var key = DmGroup.KeyOf(members);
|
|
var match = await dbEntities.DmGroups.Match(g => g.ParticipantsKey == key && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
|
if (match != default)
|
|
return match;
|
|
|
|
var conversation = new DmGroup { Members = members, ConversationURI = context, ParticipantsKey = key };
|
|
await DB.Default.SaveAsync(conversation, token);
|
|
return conversation;
|
|
}
|
|
|
|
static bool IsCollection(string uri) =>
|
|
uri.EndsWith("/followers", StringComparison.Ordinal) || uri.EndsWith("/following", StringComparison.Ordinal);
|
|
|
|
static IEnumerable<string> Strings(JsonNode node) => node switch
|
|
{
|
|
JsonArray array => array.Select(Id).Where(id => id != default),
|
|
JsonNode single when Id(single) is { } id => new[] { id },
|
|
_ => Enumerable.Empty<string>()
|
|
};
|
|
}
|
|
}
|