House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
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:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -44,19 +44,13 @@ namespace PrivaPub.Domain.Social
|
||||
// followers, unfeaturing it Remove{Hashtag}, both with its `featured` collection (/trophies) as the target: that is how
|
||||
// Mastodon sends them (its AddHashtagSerializer), and the only target Mastodon takes a Hashtag from. Received the same
|
||||
// way, with either collection as the target, and read from an account's featuredTags collection with its counts.
|
||||
public class FeaturedTags : IFeaturedTags
|
||||
public class FeaturedTags(
|
||||
IDeliveryService delivery,
|
||||
IRemoteActorService remoteActors) : IFeaturedTags
|
||||
{
|
||||
public const int MaxFeatured = 10;//the instance API's max_featured_tags, Mastodon's FeaturedTag::LIMIT
|
||||
public const int MaxRemote = 20;//what we keep of an account elsewhere, whatever its server allows
|
||||
|
||||
readonly IDeliveryService _delivery;
|
||||
readonly IRemoteActorService _remoteActors;
|
||||
|
||||
public FeaturedTags(IDeliveryService delivery, IRemoteActorService remoteActors)
|
||||
{
|
||||
_delivery = delivery;
|
||||
_remoteActors = remoteActors;
|
||||
}
|
||||
|
||||
// a featured hashtag as Mastodon renders it (its HashtagSerializer): the link to this server's page of the tag, which
|
||||
// is what our posts' Hashtag tags link to, and the name as the persona wrote it
|
||||
@@ -119,7 +113,7 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
if (persona is not { IsFederated: true, Kind: Models.Federation.LocalActorKind.Person })
|
||||
return;
|
||||
await _delivery.EnqueueToFollowers(persona, new JsonObject
|
||||
await delivery.EnqueueToFollowers(persona, new JsonObject
|
||||
{
|
||||
["@context"] = ActivityPubRenderer.Context(),
|
||||
["id"] = persona.ActivityUri($"{(add ? "feature" : "unfeature")}-tag-{tag.ID}-{DateTime.UtcNow.Ticks}"),
|
||||
@@ -129,7 +123,7 @@ namespace PrivaPub.Domain.Social
|
||||
["target"] = persona.Featured,
|
||||
["to"] = new JsonArray(ActivityPubRenderer.Public),
|
||||
["cc"] = new JsonArray(persona.Followers)
|
||||
}, token);
|
||||
}, token: token);
|
||||
}
|
||||
|
||||
// what posts carry the tag: a persona's own public and unlisted posts, or the public and unlisted posts we hold of an
|
||||
@@ -257,7 +251,7 @@ namespace PrivaPub.Domain.Social
|
||||
|
||||
async Task<JsonObject> Fetch(string uri, CancellationToken token)
|
||||
{
|
||||
using var fetched = await _remoteActors.FetchObject(uri, token);
|
||||
using var fetched = await remoteActors.FetchObject(uri, token);
|
||||
return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? default : JsonNode.Parse(fetched.Root.GetRawText()) as JsonObject;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,25 +21,16 @@ namespace PrivaPub.Domain.Social
|
||||
// server's reader (LocalActorService.ReaderUserName) follows every community in the feeds anyone reads, as Lemmy's own
|
||||
// follower of multi-communities does, and stops following one no feed holds any more. What it follows arrives as any
|
||||
// community's posts do; nobody's home shows them, the feed's timeline does.
|
||||
public class FeedFollows : IFeedFollows
|
||||
public class FeedFollows(
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IRemoteActorService remoteActors,
|
||||
IFollowService followService,
|
||||
IJobQueue jobQueue) : IFeedFollows
|
||||
{
|
||||
public const int MaxCommunities = 500;
|
||||
static readonly TimeSpan Stale = TimeSpan.FromDays(1);
|
||||
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IRemoteActorService _remoteActors;
|
||||
readonly IFollowService _follows;
|
||||
readonly IJobQueue _jobs;
|
||||
|
||||
public FeedFollows(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IFollowService follows, IJobQueue jobs)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
_remoteActors = remoteActors;
|
||||
_follows = follows;
|
||||
_jobs = jobs;
|
||||
}
|
||||
|
||||
public static Task<bool> Sync(IJobQueue jobs, CancellationToken token) =>
|
||||
jobs.Enqueue(JobKind.SyncFeeds, string.Empty, default, $"feeds|{Guid.NewGuid():N}", token);
|
||||
@@ -59,7 +50,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
else if ((await DB.Default.DeleteAsync<FeedSubscription>(s => s.AvatarId == me.Id && s.FeedActorURI == feed.ActorURI)).DeletedCount == 0)
|
||||
return true;
|
||||
await Sync(_jobs, token);
|
||||
await Sync(jobQueue, token);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -69,26 +60,26 @@ namespace PrivaPub.Domain.Social
|
||||
public async Task Reconcile(CancellationToken token)
|
||||
{
|
||||
var read = (await DB.Default.Find<FeedSubscription, string>().Project(s => s.FeedActorURI).ExecuteAsync(token)).Distinct().ToList();
|
||||
var feeds = await _dbEntities.ForeignAvatars.Match(a => read.Contains(a.ActorURI) && a.AvatarType == AvatarType.Feed && !a.DeletionAt.HasValue)
|
||||
var feeds = await dbEntities.ForeignAvatars.Match(a => read.Contains(a.ActorURI) && a.AvatarType == AvatarType.Feed && !a.DeletionAt.HasValue)
|
||||
.ExecuteAsync(token);
|
||||
// a feed's communities are as its server listed them a day ago at most (AccountCountsJob reads them, then asks
|
||||
// for this again)
|
||||
foreach (var stale in feeds.Where(f => !(DateTime.UtcNow - f.CountedAt < Stale)))
|
||||
if (Uri.TryCreate(stale.ActorURI, UriKind.Absolute, out var uri))
|
||||
await _jobs.Enqueue(JobKind.CountAccount, stale.ActorURI, uri.Host.ToLowerInvariant(), AccountCountsJob.DedupeKey(stale.ActorURI, DateTime.UtcNow), token);
|
||||
await jobQueue.Enqueue(JobKind.CountAccount, stale.ActorURI, uri.Host.ToLowerInvariant(), AccountCountsJob.DedupeKey(stale.ActorURI, DateTime.UtcNow), token);
|
||||
|
||||
var ours = _localActors.BaseAddress + "/";
|
||||
var ours = localActors.BaseAddress + "/";
|
||||
var wanted = feeds.SelectMany(f => f.FeedCommunities).Where(c => !c.StartsWith(ours, StringComparison.Ordinal))
|
||||
.Distinct(StringComparer.Ordinal).Take(MaxCommunities).ToHashSet(StringComparer.Ordinal);
|
||||
var reader = await _localActors.GetReaderActor(token);
|
||||
var following = await _dbEntities.Followings.Match(f => f.AvatarId == reader.Id).ExecuteAsync(token);
|
||||
var reader = await localActors.GetReaderActor(token);
|
||||
var following = await dbEntities.Followings.Match(f => f.AvatarId == reader.Id).ExecuteAsync(token);
|
||||
foreach (var gone in following.Where(f => !wanted.Contains(f.TargetActorURI)))
|
||||
await _follows.UnfollowAs(reader, gone.TargetActorURI, token);
|
||||
await followService.UnfollowAs(reader, gone.TargetActorURI, token);
|
||||
var followed = following.Select(f => f.TargetActorURI).ToHashSet(StringComparer.Ordinal);
|
||||
foreach (var community in wanted.Where(c => !followed.Contains(c)))
|
||||
// only a community: a feed lists nothing else, and the reader follows nothing else
|
||||
if (await _remoteActors.GetActor(community, refresh: false, token) is { AvatarType: AvatarType.Group })
|
||||
await _follows.FollowAs(reader, community, showReblogs: false, token);
|
||||
if (await remoteActors.GetActor(community, refresh: false, token) is { AvatarType: AvatarType.Group })
|
||||
await followService.FollowAs(reader, community, showReblogs: false, token: token);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,8 +28,9 @@ namespace PrivaPub.Domain.Social
|
||||
Task<WebResult> Followings(string rootUserId, string avatarId, CancellationToken token);
|
||||
/// <summary>Follows an account, or changes how a follow already made shows it: notify and languages (R8) change only
|
||||
/// when given (languages empty: every language).</summary>
|
||||
Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default,
|
||||
IReadOnlyList<string> languages = default);
|
||||
Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
|
||||
IReadOnlyList<string> languages = default,
|
||||
CancellationToken token = default);
|
||||
Task UnfollowAs(LocalActor follower, string target, CancellationToken token);
|
||||
Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token);
|
||||
Task<int> ResendPending(DateTime now, CancellationToken token);
|
||||
@@ -37,26 +38,14 @@ namespace PrivaPub.Domain.Social
|
||||
Task<(LocalActor Local, ForeignAvatar Remote)> Resolve(string target, CancellationToken token);
|
||||
}
|
||||
|
||||
public class FollowService : IFollowService
|
||||
public class FollowService(
|
||||
DbEntities dbEntities,
|
||||
ILocalActorService localActors,
|
||||
IRemoteActorService remoteActors,
|
||||
IDeliveryService delivery,
|
||||
IStringLocalizer<GenericRes> localizer,
|
||||
ILogger<FollowService> logger) : IFollowService
|
||||
{
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IRemoteActorService _remoteActors;
|
||||
readonly IDeliveryService _delivery;
|
||||
readonly IStringLocalizer<GenericRes> _localizer;
|
||||
readonly ILogger<FollowService> _logger;
|
||||
|
||||
public FollowService(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery,
|
||||
IStringLocalizer<GenericRes> localizer, ILogger<FollowService> logger)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_localActors = localActors;
|
||||
_remoteActors = remoteActors;
|
||||
_delivery = delivery;
|
||||
_localizer = localizer;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<WebResult> Follow(string rootUserId, FollowForm form, CancellationToken token)
|
||||
{
|
||||
var result = new WebResult();
|
||||
@@ -64,17 +53,17 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (follower == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
var following = await FollowAs(follower, form.Target, true, token);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
var following = await FollowAs(follower, form.Target, true, token: token);
|
||||
if (following == default)
|
||||
return result.Invalidate(_localizer["Account not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Account not found."], StatusCodes.Status404NotFound);
|
||||
result.Data = ToView(following);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,14 +74,14 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
|
||||
if (follower == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
await UnfollowAs(follower, form.Target, token);
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}");
|
||||
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
|
||||
logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}");
|
||||
return result.Invalidate(localizer["Something went wrong."], exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,8 +95,9 @@ namespace PrivaPub.Domain.Social
|
||||
return kept.Count == 0 ? null : kept;
|
||||
}
|
||||
|
||||
public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default,
|
||||
IReadOnlyList<string> languages = default)
|
||||
public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
|
||||
IReadOnlyList<string> languages = default,
|
||||
CancellationToken token = default)
|
||||
{
|
||||
var (local, remote) = await ResolveTarget(target, token);
|
||||
if (local == default && remote == default)
|
||||
@@ -116,7 +106,7 @@ namespace PrivaPub.Domain.Social
|
||||
return default;
|
||||
|
||||
var targetUri = local?.Uri ?? remote.ActorURI;
|
||||
var existing = await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
var existing = await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
if (existing != default)
|
||||
{
|
||||
if (existing.ShowReblogs != showReblogs)
|
||||
@@ -136,8 +126,8 @@ namespace PrivaPub.Domain.Social
|
||||
// a request still unanswered is sent again, at most once an hour: a server can take a Follow (202) and
|
||||
// drop it later, as one that cannot yet read our actor does; one that holds it already ignores the copy
|
||||
if (existing.State == FollowState.Requested && remote != default)
|
||||
await _delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing), token,
|
||||
again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture));
|
||||
await delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing),
|
||||
again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture), token);
|
||||
return existing;
|
||||
}
|
||||
|
||||
@@ -162,7 +152,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
|
||||
{
|
||||
return await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
return await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
}
|
||||
//a new follow starts in no list, whatever lists the account was in before a follow that ended without passing here
|
||||
await DB.Default.DeleteAsync<PersonaListMember>(m => m.AvatarId == follower.Id && m.AccountId == following.TargetAccountId);
|
||||
@@ -170,7 +160,7 @@ namespace PrivaPub.Domain.Social
|
||||
if (local != default)
|
||||
await FollowLocally(follower, local, following, token);
|
||||
else
|
||||
await _delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, following), token);
|
||||
await delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, following), token: token);
|
||||
return following;
|
||||
}
|
||||
|
||||
@@ -178,7 +168,7 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
var (local, remote) = await ResolveTarget(target, token);
|
||||
var targetUri = local?.Uri ?? remote?.ActorURI ?? target;
|
||||
var following = await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
var following = await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
|
||||
if (following == default)
|
||||
return;
|
||||
|
||||
@@ -202,17 +192,17 @@ namespace PrivaPub.Domain.Social
|
||||
["actor"] = follower.Uri,
|
||||
["object"] = FollowActivity(follower, following)
|
||||
};
|
||||
await _delivery.Enqueue(follower, new[] { following.TargetInboxURL }, undo, token);
|
||||
await delivery.Enqueue(follower, new[] { following.TargetInboxURL }, undo, token: token);
|
||||
}
|
||||
|
||||
public async Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token)
|
||||
{
|
||||
var localFollower = await _localActors.FindById(LocalActorKind.Person, followerAccountId, token);
|
||||
var remoteFollower = localFollower == default ? await _dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default;
|
||||
var localFollower = await localActors.FindById(LocalActorKind.Person, followerAccountId, token);
|
||||
var remoteFollower = localFollower == default ? await dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default;
|
||||
var followerUri = localFollower?.Uri ?? remoteFollower?.ActorURI;
|
||||
if (followerUri == default)
|
||||
return false;
|
||||
var request = await _dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.LocalActorKind == me.Kind && f.ActorURI == followerUri && !f.IsAccepted)
|
||||
var request = await dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.LocalActorKind == me.Kind && f.ActorURI == followerUri && !f.IsAccepted)
|
||||
.ExecuteFirstAsync(token);
|
||||
if (request == default)
|
||||
return false;
|
||||
@@ -249,10 +239,10 @@ namespace PrivaPub.Domain.Social
|
||||
["actor"] = me.Uri,
|
||||
["object"] = follow
|
||||
};
|
||||
await _delivery.Enqueue(me, new[] { request.InboxURL }, answer, token);
|
||||
await delivery.Enqueue(me, new[] { request.InboxURL }, answer, token: token);
|
||||
}
|
||||
if (accept)
|
||||
await Notifications.Add(me.Id, NotificationType.Follow, followerAccountId, followerUri, default, token);
|
||||
await Notifications.Add(me.Id, NotificationType.Follow, followerAccountId, followerUri, default, token: token);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -261,8 +251,8 @@ namespace PrivaPub.Domain.Social
|
||||
var result = new WebResult();
|
||||
var follower = await OwnedAvatar(rootUserId, avatarId, token);
|
||||
if (follower == default)
|
||||
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
result.Data = (await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token))
|
||||
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
|
||||
result.Data = (await dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token))
|
||||
.Select(ToView).ToList();
|
||||
return result;
|
||||
}
|
||||
@@ -286,7 +276,7 @@ namespace PrivaPub.Domain.Social
|
||||
.ExecuteAsync(token);
|
||||
if (target.Kind == LocalActorKind.Person)
|
||||
await Notifications.Add(target.Id, following.State == FollowState.Accepted ? NotificationType.Follow : NotificationType.FollowRequest,
|
||||
follower.Id, follower.Uri, default, token);
|
||||
follower.Id, follower.Uri, default, token: token);
|
||||
}
|
||||
|
||||
public Task<(LocalActor Local, ForeignAvatar Remote)> Resolve(string target, CancellationToken token) => ResolveTarget(target, token);
|
||||
@@ -298,17 +288,17 @@ namespace PrivaPub.Domain.Social
|
||||
return default;
|
||||
if (target.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || target.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
var byUri = await _localActors.FindByUri(target, token);
|
||||
return byUri != default ? (byUri, default) : (default, await _remoteActors.GetActor(target, refresh: false, token));
|
||||
var byUri = await localActors.FindByUri(target, token);
|
||||
return byUri != default ? (byUri, default) : (default, await remoteActors.GetActor(target, refresh: false, token));
|
||||
}
|
||||
|
||||
var parts = target.TrimStart('@').Split('@');
|
||||
var localDomain = new Uri(_localActors.BaseAddress).Authority;
|
||||
var localDomain = new Uri(localActors.BaseAddress).Authority;
|
||||
if (parts.Length == 1 || parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase))
|
||||
return (await _localActors.FindByUserName(parts[0], token), default);
|
||||
return (await localActors.FindByUserName(parts[0], token), default);
|
||||
|
||||
var actorUri = await _remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
|
||||
return (default, actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token));
|
||||
var actorUri = await remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
|
||||
return (default, actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token));
|
||||
}
|
||||
|
||||
// how long after it was made, or last sent again, a request still unanswered is sent again: a server can take a Follow and
|
||||
@@ -324,19 +314,19 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
var sent = 0;
|
||||
// (a request older than the count has no Resent yet: "not at least" matches it, "less than" would not)
|
||||
var pending = await _dbEntities.Followings.Match(f => f.State == FollowState.Requested && !f.TargetIsLocal && !(f.Resent >= ResendAfter.Length))
|
||||
var pending = await dbEntities.Followings.Match(f => f.State == FollowState.Requested && !f.TargetIsLocal && !(f.Resent >= ResendAfter.Length))
|
||||
.ExecuteAsync(token);
|
||||
foreach (var following in pending.Where(f => (f.ResentAt ?? f.CreatedAt) + ResendAfter[f.Resent] <= now))
|
||||
{
|
||||
var follower = await _localActors.FindById(following.FollowerKind ?? LocalActorKind.Person, following.AvatarId, token);
|
||||
var inbox = following.TargetInboxURL ?? (await _remoteActors.GetActor(following.TargetActorURI, refresh: false, token))?.InboxURL;
|
||||
var follower = await localActors.FindById(following.FollowerKind ?? LocalActorKind.Person, following.AvatarId, token);
|
||||
var inbox = following.TargetInboxURL ?? (await remoteActors.GetActor(following.TargetActorURI, refresh: false, token))?.InboxURL;
|
||||
if (follower != default && !string.IsNullOrEmpty(inbox))
|
||||
{
|
||||
// under a new id each time: Lemmy keeps the ids it received and never answers one again
|
||||
var again = FollowActivity(follower, following);
|
||||
again["id"] = AgainId(following.FollowActivityURI, following.Resent + 1);
|
||||
await _delivery.Enqueue(follower, new[] { inbox }, again, token,
|
||||
again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture));
|
||||
await delivery.Enqueue(follower, new[] { inbox }, again,
|
||||
again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture), token);
|
||||
sent++;
|
||||
}
|
||||
await DB.Default.Update<Following>().MatchID(following.ID).Modify(b => b.Inc(f => f.Resent, 1)).Modify(f => f.ResentAt, now)
|
||||
@@ -363,10 +353,10 @@ namespace PrivaPub.Domain.Social
|
||||
{
|
||||
if (string.IsNullOrEmpty(rootUserId) || string.IsNullOrEmpty(avatarId))
|
||||
return default;
|
||||
if (!await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
|
||||
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
|
||||
return default;
|
||||
// a suspended persona does nothing through the client API either (R6)
|
||||
return await _localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
|
||||
return await localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
|
||||
}
|
||||
|
||||
static ViewFollowing ToView(Following following) => new()
|
||||
|
||||
@@ -26,8 +26,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task Add(string avatarId, NotificationType type, string fromAccountId, string fromActorUri, string postId,
|
||||
CancellationToken token, string emoji = default, string emojiUrl = default, string text = default)
|
||||
public static async Task Add(string avatarId, NotificationType type, string fromAccountId, string fromActorUri, string postId, string emoji = default, string emojiUrl = default, string text = default, CancellationToken token = default)
|
||||
{
|
||||
if (string.IsNullOrEmpty(avatarId) || avatarId == fromAccountId && type != NotificationType.Poll)
|
||||
return;
|
||||
|
||||
@@ -27,18 +27,12 @@ namespace PrivaPub.Domain.Social
|
||||
Task<bool> Unreact(LocalActor me, PostEntity post, string emoji, CancellationToken token);
|
||||
}
|
||||
|
||||
public class Reactions : IReactions
|
||||
public class Reactions(
|
||||
DbEntities dbEntities,
|
||||
IDeliveryService delivery) : IReactions
|
||||
{
|
||||
static readonly string[] Hearts = { "❤", "❤️", "♥", "♥️" };
|
||||
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IDeliveryService _delivery;
|
||||
|
||||
public Reactions(DbEntities dbEntities, IDeliveryService delivery)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_delivery = delivery;
|
||||
}
|
||||
|
||||
public static bool IsHeart(string content) => content == default || Hearts.Contains(content.Trim());
|
||||
|
||||
@@ -64,7 +58,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
Arrival.Accept("reaction");
|
||||
if (!post.IsFederatedCopy)
|
||||
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, actor.ID, actor.ActorURI, post.ID, token, emoji.Name, emoji.Url);
|
||||
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, actor.ID, actor.ActorURI, post.ID, emoji.Name, emoji.Url, token: token);
|
||||
}
|
||||
|
||||
public async Task<bool> Withdraw(ForeignAvatar actor, string activityId, string objectUri, string content, CancellationToken token)
|
||||
@@ -74,7 +68,7 @@ namespace PrivaPub.Domain.Social
|
||||
: await DB.Default.Find<Reaction>().Match(r => r.ActivityURI == activityId && r.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
|
||||
if (reaction == default && objectUri != default && Normalise(content, new()) is { } emoji)
|
||||
{
|
||||
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
|
||||
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
|
||||
reaction = post == default
|
||||
? default
|
||||
: await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID && r.ActorURI == actor.ActorURI && r.Emoji == emoji.Name).ExecuteFirstAsync(token);
|
||||
@@ -114,7 +108,7 @@ namespace PrivaPub.Domain.Social
|
||||
return true;
|
||||
}
|
||||
if (!post.IsFederatedCopy)
|
||||
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, me.Id, me.Uri, post.ID, token, picked.Name, picked.Url);
|
||||
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, me.Id, me.Uri, post.ID, picked.Name, picked.Url, token: token);
|
||||
else
|
||||
await Tell(me, post, Activity(me, post, reaction), token);
|
||||
return true;
|
||||
@@ -169,9 +163,9 @@ namespace PrivaPub.Domain.Social
|
||||
|
||||
async Task Tell(LocalActor me, PostEntity post, JsonObject activity, CancellationToken token)
|
||||
{
|
||||
var author = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
|
||||
var author = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
|
||||
if (!string.IsNullOrEmpty(author?.InboxURL))
|
||||
await _delivery.Enqueue(me, new[] { author.InboxURL }, activity, token);
|
||||
await delivery.Enqueue(me, new[] { author.InboxURL }, activity, token: token);
|
||||
}
|
||||
|
||||
public sealed record Picked(string Name, string Url);
|
||||
|
||||
@@ -13,26 +13,20 @@ namespace PrivaPub.Domain.Social
|
||||
// and fetch nothing). Hashtags and links rise with the number of different authors using them today against the
|
||||
// week before; posts with their favourites, boosts and replies, halving every twelve hours. A post trends only if its
|
||||
// author is discoverable, and nothing warned about (content warning) trends. Computed at most every ten minutes.
|
||||
public sealed class Trends
|
||||
public sealed class Trends(
|
||||
DbEntities dbEntities,
|
||||
IMemoryCache cache)
|
||||
{
|
||||
public static readonly TimeSpan Fresh = TimeSpan.FromMinutes(10);
|
||||
const int MinAuthors = 2;//one account alone never makes a trend
|
||||
const int Kept = 40;
|
||||
|
||||
readonly DbEntities _dbEntities;
|
||||
readonly IMemoryCache _cache;
|
||||
|
||||
public Trends(DbEntities dbEntities, IMemoryCache cache)
|
||||
{
|
||||
_dbEntities = dbEntities;
|
||||
_cache = cache;
|
||||
}
|
||||
|
||||
// what is computed is forgotten: the next read computes it again
|
||||
public void Forget()
|
||||
{
|
||||
foreach (var key in new[] { "trends:tags", "trends:links", "trends:statuses" })
|
||||
_cache.Remove(key);
|
||||
cache.Remove(key);
|
||||
}
|
||||
|
||||
public sealed record DayUse(DateTime Day, int Uses, int Accounts);
|
||||
@@ -40,7 +34,7 @@ namespace PrivaPub.Domain.Social
|
||||
public sealed record Trend(string Key, List<DayUse> History, string SamplePostId);
|
||||
|
||||
public Task<List<Trend>> Tags(CancellationToken token) =>
|
||||
_cache.GetOrCreateAsync("trends:tags", async entry =>
|
||||
cache.GetOrCreateAsync("trends:tags", async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = Fresh;
|
||||
var posts = await Week(p => p.Tags.Count > 0, token);
|
||||
@@ -48,7 +42,7 @@ namespace PrivaPub.Domain.Social
|
||||
});
|
||||
|
||||
public Task<List<Trend>> Links(CancellationToken token) =>
|
||||
_cache.GetOrCreateAsync("trends:links", async entry =>
|
||||
cache.GetOrCreateAsync("trends:links", async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = Fresh;
|
||||
var posts = await Week(p => p.Link != null, token);
|
||||
@@ -58,12 +52,12 @@ namespace PrivaPub.Domain.Social
|
||||
|
||||
// the ids of the trending posts, best first
|
||||
public Task<List<string>> Statuses(CancellationToken token) =>
|
||||
_cache.GetOrCreateAsync("trends:statuses", async entry =>
|
||||
cache.GetOrCreateAsync("trends:statuses", async entry =>
|
||||
{
|
||||
entry.AbsoluteExpirationRelativeToNow = Fresh;
|
||||
var now = DateTime.UtcNow;
|
||||
var since = now.AddHours(-48);
|
||||
var posts = await _dbEntities.Posts
|
||||
var posts = await dbEntities.Posts
|
||||
.Match(p => p.Visibility == PostVisibility.Public && !p.DeletedAt.HasValue && !p.AuthorGone && !p.HasContentWarning && !p.IsLocalOnly
|
||||
&& p.ReblogOfPostId == null && p.InReplyToURI == null && p.AnsweringToPostId == null && p.CreationDate >= since
|
||||
&& p.FavouritesCount + p.ReblogsCount + p.RepliesCount > 0)
|
||||
@@ -78,7 +72,7 @@ namespace PrivaPub.Domain.Social
|
||||
Task<List<Post>> Week(System.Linq.Expressions.Expression<Func<Post, bool>> with, CancellationToken token)
|
||||
{
|
||||
var since = DateTime.UtcNow.Date.AddDays(-6);
|
||||
return _dbEntities.Posts
|
||||
return dbEntities.Posts
|
||||
.Match(p => p.Visibility == PostVisibility.Public && !p.DeletedAt.HasValue && !p.AuthorGone && !p.HasContentWarning && !p.IsLocalOnly
|
||||
&& p.ReblogOfPostId == null && p.CreationDate >= since)
|
||||
.Match(Privacy.VisibilityPolicy.IsPublic).Match(Privacy.VisibilityPolicy.IsListed)
|
||||
|
||||
@@ -83,7 +83,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
|
||||
/// <summary>Every subscription of these personas goes (their tokens ended, or they did).</summary>
|
||||
public static async Task Forget(IReadOnlyCollection<string> avatarIds)
|
||||
public static async Task Forget(IReadOnlyCollection<string> avatarIds, CancellationToken token = default)
|
||||
{
|
||||
var ids = avatarIds?.Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList() ?? new List<string>();
|
||||
if (ids.Count > 0)
|
||||
@@ -91,7 +91,7 @@ namespace PrivaPub.Domain.Social
|
||||
}
|
||||
|
||||
/// <summary>The subscription made with this token goes (the token was revoked).</summary>
|
||||
public static async Task ForgetToken(string tokenId)
|
||||
public static async Task ForgetToken(string tokenId, CancellationToken token = default)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(tokenId))
|
||||
await DB.Default.DeleteAsync<PushSubscription>(s => s.TokenId == tokenId);
|
||||
@@ -100,17 +100,10 @@ namespace PrivaPub.Domain.Social
|
||||
|
||||
// Hangs on Notifications.Told while the host runs and queues one SendPush job per subscription the notification goes to
|
||||
// (WebPushJob sends it, encrypted). Queueing is a few indexed reads and inserts; nothing leaves the server here.
|
||||
public class WebPushDispatcher : IHostedService
|
||||
public class WebPushDispatcher(
|
||||
IJobQueue jobQueue,
|
||||
ILogger<WebPushDispatcher> logger) : IHostedService
|
||||
{
|
||||
readonly IJobQueue _jobs;
|
||||
readonly ILogger<WebPushDispatcher> _logger;
|
||||
|
||||
public WebPushDispatcher(IJobQueue jobs, ILogger<WebPushDispatcher> logger)
|
||||
{
|
||||
_jobs = jobs;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
Notifications.Told = Dispatch;
|
||||
@@ -145,11 +138,11 @@ namespace PrivaPub.Domain.Social
|
||||
DedupeKey = $"push|{subscription.ID}|{notification.ID}"
|
||||
});
|
||||
if (jobs.Count > 0)
|
||||
await _jobs.EnqueueMany(jobs, token);
|
||||
await jobQueue.EnqueueMany(jobs, token);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex, "{Service} could not queue the pushes of a notification", nameof(WebPushDispatcher));
|
||||
logger.LogWarning(ex, "{Service} could not queue the pushes of a notification", nameof(WebPushDispatcher));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user