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

+40 -2
View File
@@ -1045,8 +1045,7 @@ client's role route never does.
## Code style ## Code style
- Tabs, block-scoped namespaces, Allman braces. - Tabs, block-scoped namespaces, Allman braces.
- New services use `readonly _camel` fields and constructor injection. Older services use PascalCase fields; leave - Dependencies come in through primary constructors and are used as parameters (House rules, HR0004).
them.
- Services return `WebResult` (`PrivaPub.ClientModels/WebResult.cs`): `result.Invalidate(localizer[...], status)`. - Services return `WebResult` (`PrivaPub.ClientModels/WebResult.cs`): `result.Invalidate(localizer[...], status)`.
Controllers turn it into a status code. Controllers turn it into a status code.
- Localised strings go through `IStringLocalizer<GenericRes>`. - Localised strings go through `IStringLocalizer<GenericRes>`.
@@ -1060,6 +1059,45 @@ client's role route never does.
- Libraries chosen for the roadmap: HtmlSanitizer, Markdig (`DisableHtml`), NSign (RFC 9421 inbound), OpenIddict + - Libraries chosen for the roadmap: HtmlSanitizer, Markdig (`DisableHtml`), NSign (RFC 9421 inbound), OpenIddict +
OpenIddict.MongoDb, NetVips, Blurhash.Core, FFMpegCore. No ImageSharp (licence key enforced), no MassTransit. OpenIddict.MongoDb, NetVips, Blurhash.Core, FFMpegCore. No ImageSharp (licence key enforced), no MassTransit.
## House rules
The owner's rules for every .NET project (`~/RiderProjects/HouseRules/RULES.md`, repo `Arasaka/HouseRules`) apply
here and win over anything else in this file. `Arasaka.HouseRules.Analyzers` (`Directory.Build.props`) reports the
checkable ones as `HRxxxx` errors in every build and in Rider; decePubClient builds `PrivaPub.ClientModels` under the
same rules. Applied to PrivaPub:
- **Coding style:**
- `var x = default(T)` for a local without a value yet (HR0001).
- `IOptionsMonitor<T>.CurrentValue`, never `IOptions<T>` (HR0002).
- Primary constructors, using the parameters directly (HR0004). Where a method already names a local after the
parameter (`media`, `statuses`, `settings`), the parameter takes its type's name (`IMediaService mediaService`).
A private constructor behind static factories stays as it is (`RobotsTxt`, `RequestSignature`, `SafeArchive`).
- A `CancellationToken token` last on every async method, passed down to MongoDB, HTTP and the job queue (HR0003).
A write that must happen even when the request is cancelled passes `CancellationToken.None` on purpose (the
setup claim and its release, the lease renewal). Exempt, with a reason on each: OpenIddict inline handlers (their
signature is fixed), `Indexes.Plain` (a `params` array comes last), `JobWorker.KeepLease` (it takes the source it
cancels).
- **Models:**
- Collections start as `= []` (HR0006) and strings have no `= string.Empty` (HR0005), unless null means something.
Each exception carries a `[SuppressMessage("HouseRules", …, Justification = …)]` that says what: the Mastodon
entities' strings (the API sends `""`, never null), "not stated" (`SearchableBy`, `RemoteInstance.Languages`),
"every language" (`Following.Languages`), "fall back" (`Notification.StatusIds`, `ObjectRecord.Extensions`,
`ObjectRecord.ContextNamespaces`), "keep the media" (`StatusDraft.MediaIds`), "no focal point" (`Focus`), and the
Mastodon fields the API sends as null (`FilterResult` matches, `Poll.OwnVotes`, `Relationship.Languages`).
- Request and response types in `PrivaPub.ClientModels` are `View*`, `*Request` and `*Form` (HR0010). The Mastodon
entities and ActivityPub documents keep their names and JSON shapes: they are other software's contract.
- **APIs:**
- **No 5XX** (HR0007). The one exception: the inbox answers 503 with `Retry-After` while a signing key cannot be
fetched yet, because ActivityPub servers retry it (`InboxReceiver.Receive`). The Mastodon API's own 4XX codes
(422 for a request it refuses, 429 for the rate limits) are part of that API and stay.
- Services take the user's id from the controller, never `IHttpContextAccessor` (HR0008).
- Services return `WebResult`; a `LocalizedString` stored in it is cast, `(string)localizer[key]`, never `.Value`
(HR0009).
- Numbers shown to a reader go through formatting helpers (HR0011). The ISO week key (`InstanceDescriber.Week`)
and the six-digit email code (`EmailVerificationJob.NewCode`) are identifiers, and say so.
- **Still open:** route constants shared with decePubClient (HR0305; the frozen literals above stay their values)
and source-generated JSON contexts (HR0306).
## Verifying ## Verifying
There is no test project (owner decision 2026-10-17: `PrivaPub.Tests` was removed, with the CI and deploy steps that There is no test project (owner decision 2026-10-17: `PrivaPub.Tests` was removed, with the CI and deploy steps that
+10
View File
@@ -6,4 +6,14 @@
<BuildTimeUtc Condition="'$(BuildTimeUtc)' == ''"></BuildTimeUtc> <BuildTimeUtc Condition="'$(BuildTimeUtc)' == ''"></BuildTimeUtc>
</PropertyGroup> </PropertyGroup>
<PropertyGroup>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<HouseRulesDtoNamespaces>PrivaPub.ClientModels</HouseRulesDtoNamespaces>
<WarningsAsErrors>$(WarningsAsErrors);HR0001;HR0002;HR0003;HR0004;HR0005;HR0006;HR0007;HR0008;HR0009;HR0010;HR0011;HR0101;HR0102;HR0103;HR0104;HR0105;HR0106;HR0201</WarningsAsErrors>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Arasaka.HouseRules.Analyzers" Version="1.0.4" PrivateAssets="all" />
</ItemGroup>
</Project> </Project>
@@ -1,18 +1,10 @@
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace PrivaPub.ClientModels namespace PrivaPub.ClientModels
{ {
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class AtLeastOnePropertyAttribute : ValidationAttribute public class AtLeastOnePropertyAttribute(params string[] propertyList) : ValidationAttribute
{ {
private string[] PropertyList { get; set; }
public AtLeastOnePropertyAttribute(params string[] propertyList)
{
PropertyList = propertyList;
}
public override object TypeId public override object TypeId
{ {
get get
@@ -23,10 +15,9 @@ namespace PrivaPub.ClientModels
public override bool IsValid(object value) public override bool IsValid(object value)
{ {
PropertyInfo propertyInfo; foreach (var propertyName in propertyList)
foreach (string propertyName in PropertyList)
{ {
propertyInfo = value.GetType().GetProperty(propertyName); var propertyInfo = value.GetType().GetProperty(propertyName);
if (propertyInfo != null && propertyInfo.GetValue(value, null) != null) if (propertyInfo != null && propertyInfo.GetValue(value, null) != null)
return true; return true;
+6 -12
View File
@@ -2,19 +2,13 @@ using OpenIddict.Abstractions;
namespace PrivaPub.Api.Mastodon.Auth namespace PrivaPub.Api.Mastodon.Auth
{ {
public class OAuthPruner : BackgroundService public class OAuthPruner(
IServiceProvider services,
ILogger<OAuthPruner> logger) : BackgroundService
{ {
static readonly TimeSpan Interval = TimeSpan.FromHours(6); static readonly TimeSpan Interval = TimeSpan.FromHours(6);
static readonly TimeSpan Threshold = TimeSpan.FromDays(14); static readonly TimeSpan Threshold = TimeSpan.FromDays(14);
readonly IServiceProvider _services;
readonly ILogger<OAuthPruner> _logger;
public OAuthPruner(IServiceProvider services, ILogger<OAuthPruner> logger)
{
_services = services;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
@@ -25,7 +19,7 @@ namespace PrivaPub.Api.Mastodon.Auth
await Task.Delay(Interval, stoppingToken); await Task.Delay(Interval, stoppingToken);
var (tokens, authorizations) = await Prune(DateTimeOffset.UtcNow - Threshold, stoppingToken); var (tokens, authorizations) = await Prune(DateTimeOffset.UtcNow - Threshold, stoppingToken);
if (tokens + authorizations > 0) if (tokens + authorizations > 0)
_logger.LogInformation("{Service} removed {Tokens} tokens and {Authorizations} authorizations", nameof(OAuthPruner), tokens, authorizations); logger.LogInformation("{Service} removed {Tokens} tokens and {Authorizations} authorizations", nameof(OAuthPruner), tokens, authorizations);
} }
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{ {
@@ -33,7 +27,7 @@ namespace PrivaPub.Api.Mastodon.Auth
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, "{Service} pass failed", nameof(OAuthPruner)); logger.LogWarning(ex, "{Service} pass failed", nameof(OAuthPruner));
} }
} }
} }
@@ -41,7 +35,7 @@ namespace PrivaPub.Api.Mastodon.Auth
//one pass: tokens and authorizations created before the threshold that are no longer valid //one pass: tokens and authorizations created before the threshold that are no longer valid
public async Task<(long Tokens, long Authorizations)> Prune(DateTimeOffset threshold, CancellationToken token) public async Task<(long Tokens, long Authorizations)> Prune(DateTimeOffset threshold, CancellationToken token)
{ {
using var scope = _services.CreateScope(); using var scope = services.CreateScope();
var tokens = await scope.ServiceProvider.GetRequiredService<IOpenIddictTokenManager>().PruneAsync(threshold, token); var tokens = await scope.ServiceProvider.GetRequiredService<IOpenIddictTokenManager>().PruneAsync(threshold, token);
var authorizations = await scope.ServiceProvider.GetRequiredService<IOpenIddictAuthorizationManager>().PruneAsync(threshold, token); var authorizations = await scope.ServiceProvider.GetRequiredService<IOpenIddictAuthorizationManager>().PruneAsync(threshold, token);
return (tokens, authorizations); return (tokens, authorizations);
+1
View File
@@ -112,6 +112,7 @@ namespace PrivaPub.Api.Mastodon.Auth
return services; return services;
} }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0003", Justification = "An OpenIddict inline handler: its signature is fixed and the request's token travels on the context.")]
static async ValueTask OutOfBandCode(ApplyAuthorizationResponseContext context) static async ValueTask OutOfBandCode(ApplyAuthorizationResponseContext context)
{ {
if (context.RedirectUri != OutOfBand || context.Response.Code == default) if (context.RedirectUri != OutOfBand || context.Response.Code == default)
+4 -10
View File
@@ -66,7 +66,9 @@ namespace PrivaPub.Api.Mastodon.Auth
// Validates a root JWT given as a token exchange subject token, before OpenIddict tries it as one of its own tokens. // Validates a root JWT given as a token exchange subject token, before OpenIddict tries it as one of its own tokens.
// The principal it builds names the root under PersonaExchange.RootClaim for TokenController, which signs in a fresh // The principal it builds names the root under PersonaExchange.RootClaim for TokenController, which signs in a fresh
// identity for the avatar. // identity for the avatar.
public sealed class RootJwtSubjectToken : IOpenIddictServerHandler<ValidateTokenContext> public sealed class RootJwtSubjectToken(
IConfiguration configuration,
DbEntities dbEntities) : IOpenIddictServerHandler<ValidateTokenContext>
{ {
public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>() public static OpenIddictServerHandlerDescriptor Descriptor { get; } = OpenIddictServerHandlerDescriptor.CreateBuilder<ValidateTokenContext>()
.UseScopedHandler<RootJwtSubjectToken>() .UseScopedHandler<RootJwtSubjectToken>()
@@ -74,21 +76,13 @@ namespace PrivaPub.Api.Mastodon.Auth
.SetType(OpenIddictServerHandlerType.Custom) .SetType(OpenIddictServerHandlerType.Custom)
.Build(); .Build();
readonly IConfiguration _configuration;
readonly DbEntities _dbEntities;
public RootJwtSubjectToken(IConfiguration configuration, DbEntities dbEntities)
{
_configuration = configuration;
_dbEntities = dbEntities;
}
public async ValueTask HandleAsync(ValidateTokenContext context) public async ValueTask HandleAsync(ValidateTokenContext context)
{ {
if (context.ValidTokenTypes.Count != 1 || !context.ValidTokenTypes.Contains(PersonaExchange.SubjectTokenType)) if (context.ValidTokenTypes.Count != 1 || !context.ValidTokenTypes.Contains(PersonaExchange.SubjectTokenType))
return; return;
var root = await RootJwt.Root(context.Token, _configuration, _dbEntities, context.Transaction.CancellationToken); var root = await RootJwt.Root(context.Token, configuration, dbEntities, context.Transaction.CancellationToken);
if (root == default) if (root == default)
{ {
context.Reject(Errors.InvalidGrant, "The session token is not valid."); context.Reject(Errors.InvalidGrant, "The session token is not valid.");
+7 -13
View File
@@ -15,15 +15,9 @@ using static OpenIddict.Abstractions.OpenIddictConstants;
namespace PrivaPub.Api.Mastodon.Auth namespace PrivaPub.Api.Mastodon.Auth
{ {
[ApiController] [ApiController]
public class TokenController : ControllerBase public class TokenController(
DbEntities dbEntities) : ControllerBase
{ {
readonly DbEntities _dbEntities;
public TokenController(DbEntities dbEntities)
{
_dbEntities = dbEntities;
}
[HttpPost("/oauth/token"), IgnoreAntiforgeryToken, Produces("application/json")] [HttpPost("/oauth/token"), IgnoreAntiforgeryToken, Produces("application/json")]
public async Task<IActionResult> Exchange(CancellationToken token) public async Task<IActionResult> Exchange(CancellationToken token)
{ {
@@ -62,8 +56,8 @@ namespace PrivaPub.Api.Mastodon.Auth
var avatarId = (string)request[PersonaExchange.AvatarParameter]; var avatarId = (string)request[PersonaExchange.AvatarParameter];
if (string.IsNullOrEmpty(rootId) || string.IsNullOrEmpty(avatarId)) if (string.IsNullOrEmpty(rootId) || string.IsNullOrEmpty(avatarId))
return Refuse(Errors.InvalidGrant, "The persona can no longer be used."); return Refuse(Errors.InvalidGrant, "The persona can no longer be used.");
var owns = await _dbEntities.RootToAvatars.Match(r => r.RootId == rootId && r.AvatarId == avatarId).ExecuteAnyAsync(token); var owns = await dbEntities.RootToAvatars.Match(r => r.RootId == rootId && r.AvatarId == avatarId).ExecuteAnyAsync(token);
var avatar = owns ? await _dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token) : default; var avatar = owns ? await dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token) : default;
if (avatar == default || !await Usable(avatarId, token)) if (avatar == default || !await Usable(avatarId, token))
return Refuse(Errors.InvalidGrant, "The persona can no longer be used."); return Refuse(Errors.InvalidGrant, "The persona can no longer be used.");
@@ -79,9 +73,9 @@ namespace PrivaPub.Api.Mastodon.Auth
{ {
if (string.IsNullOrEmpty(avatarId)) if (string.IsNullOrEmpty(avatarId))
return false; return false;
var link = await _dbEntities.RootToAvatars.Match(r => r.AvatarId == avatarId).ExecuteFirstAsync(token); var link = await dbEntities.RootToAvatars.Match(r => r.AvatarId == avatarId).ExecuteFirstAsync(token);
var root = link == default ? default : await _dbEntities.RootUsers.MatchID(link.RootId).ExecuteFirstAsync(token); var root = link == default ? default : await dbEntities.RootUsers.MatchID(link.RootId).ExecuteFirstAsync(token);
var avatar = await _dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(avatarId).ExecuteFirstAsync(token);
// a suspended persona gets no token (R6), as its tokens were revoked when it was suspended // a suspended persona gets no token (R6), as its tokens were revoked when it was suspended
return root is { IsBanned: false, DeletedAt: null } && avatar is { DeletionAt: null, SuspendedAt: null }; return root is { IsBanned: false, DeletedAt: null } && avatar is { DeletionAt: null, SuspendedAt: null };
} }
@@ -23,39 +23,24 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class AccountsController : MastodonController public class AccountsController(
MastodonMapper mapper,
DbEntities dbEntities,
ILocalActorService localActors,
IFollowService followService,
IOutboxPublisher outbox,
IRelationshipService relationshipService,
IFeedFollows feedFollows) : MastodonController
{ {
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IFollowService _follows;
readonly IOutboxPublisher _outbox;
readonly IRelationshipService _relationships;
readonly IFeedFollows _feeds;
public AccountsController(MastodonMapper mapper, DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors,
IFollowService follows, IOutboxPublisher outbox, IRelationshipService relationships, IFeedFollows feeds)
{
_feeds = feeds;
_relationships = relationships;
_mapper = mapper;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_follows = follows;
_outbox = outbox;
}
// Mastodon 4.4: a token with the profile scope alone may read it too // Mastodon 4.4: a token with the profile scope alone may read it too
[HttpGet("/api/v1/accounts/verify_credentials"), Scope("read:accounts|profile")] [HttpGet("/api/v1/accounts/verify_credentials"), Scope("read:accounts|profile")]
public async Task<IActionResult> VerifyCredentials(CancellationToken token) => Json(await _mapper.Local(Me, withSource: true, token)); public async Task<IActionResult> VerifyCredentials(CancellationToken token) => Json(await mapper.Local(Me, withSource: true, token));
[HttpPatch("/api/v1/accounts/update_credentials"), Scope("write:accounts"), EnableRateLimiting(RateLimiting.Uploads), RequestSizeLimit(20 * 1024 * 1024), [HttpPatch("/api/v1/accounts/update_credentials"), Scope("write:accounts"), EnableRateLimiting(RateLimiting.Uploads), RequestSizeLimit(20 * 1024 * 1024),
RequestFormLimits(MultipartBodyLengthLimit = 20 * 1024 * 1024)] RequestFormLimits(MultipartBodyLengthLimit = 20 * 1024 * 1024)]
public async Task<IActionResult> UpdateCredentials([FromServices] IMediaService media, CancellationToken token) public async Task<IActionResult> UpdateCredentials([FromServices] IMediaService media, CancellationToken token)
{ {
var avatar = await _dbEntities.Avatars.MatchID(Me.Id).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(Me.Id).ExecuteFirstAsync(token);
// a new picture is a row of its own; the one it replaces goes to the trash once the profile is saved // a new picture is a row of its own; the one it replaces goes to the trash once the profile is saved
var replaced = new List<Models.Media.MediaAttachment>(); var replaced = new List<Models.Media.MediaAttachment>();
if (Request.HasFormContentType) if (Request.HasFormContentType)
@@ -122,9 +107,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
foreach (var made in replaced) foreach (var made in replaced)
await media.Trash(m => m.ProfileOfAvatarId == avatar.ID && m.Kind == made.Kind && m.ID != made.ID, "replaced", token); await media.Trash(m => m.ProfileOfAvatarId == avatar.ID && m.Kind == made.Kind && m.ID != made.ID, "replaced", token);
var actor = _localActors.FromAvatar(avatar); var actor = localActors.FromAvatar(avatar);
await _outbox.PublishProfile(actor, token); await outbox.PublishProfile(actor, token);
return Json(await _mapper.Local(actor, withSource: true, token)); return Json(await mapper.Local(actor, withSource: true, token));
} }
// Mastodon's: the picture goes (to the trash), the profile shows the default again, and followers are told // Mastodon's: the picture goes (to the trash), the profile shows the default again, and followers are told
@@ -136,7 +121,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<IActionResult> DeletePicture(IMediaService media, string kind, CancellationToken token) async Task<IActionResult> DeletePicture(IMediaService media, string kind, CancellationToken token)
{ {
var avatar = await _dbEntities.Avatars.MatchID(Me.Id).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(Me.Id).ExecuteFirstAsync(token);
if (kind == "avatar") if (kind == "avatar")
avatar.PictureURL = default; avatar.PictureURL = default;
else else
@@ -144,9 +129,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
avatar.UpdatedAt = DateTime.UtcNow; avatar.UpdatedAt = DateTime.UtcNow;
await DB.Default.SaveAsync(avatar, token); await DB.Default.SaveAsync(avatar, token);
await media.Trash(m => m.ProfileOfAvatarId == avatar.ID && m.Kind == kind, "removed", token); await media.Trash(m => m.ProfileOfAvatarId == avatar.ID && m.Kind == kind, "removed", token);
var actor = _localActors.FromAvatar(avatar); var actor = localActors.FromAvatar(avatar);
await _outbox.PublishProfile(actor, token); await outbox.PublishProfile(actor, token);
return Json(await _mapper.Local(actor, withSource: true, token)); return Json(await mapper.Local(actor, withSource: true, token));
} }
[HttpGet("/api/v1/accounts/lookup"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/accounts/lookup"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
@@ -156,17 +141,17 @@ namespace PrivaPub.Api.Mastodon.Controllers
var parts = acct?.Split('@'); var parts = acct?.Split('@');
if (parts is not { Length: 1 or 2 } || string.IsNullOrEmpty(parts[0])) if (parts is not { Length: 1 or 2 } || string.IsNullOrEmpty(parts[0]))
return NotFoundError(); return NotFoundError();
var localDomain = new Uri(_localActors.BaseAddress).Authority; var localDomain = new Uri(localActors.BaseAddress).Authority;
if (parts.Length == 1 || parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase)) if (parts.Length == 1 || parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase))
{ {
var local = await _localActors.FindByUserName(parts[0], token); var local = await localActors.FindByUserName(parts[0], token);
return local is { IsFederated: true, IsCircle: false, IsServerActor: false, Suspended: false } ? Json(await _mapper.Local(local, false, token)) : NotFoundError(); return local is { IsFederated: true, IsCircle: false, IsServerActor: false, Suspended: false } ? Json(await mapper.Local(local, false, token)) : NotFoundError();
} }
var userName = parts[0]; var userName = parts[0];
var domain = parts[1].ToLowerInvariant(); var domain = parts[1].ToLowerInvariant();
var foreign = await _dbEntities.ForeignAvatars.Match(f => f.UserName == userName && f.Domain == domain && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue) var foreign = await dbEntities.ForeignAvatars.Match(f => f.UserName == userName && f.Domain == domain && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
return foreign == default ? NotFoundError() : Json(_mapper.Foreign(foreign)); return foreign == default ? NotFoundError() : Json(mapper.Foreign(foreign));
} }
[HttpGet("/api/v1/accounts/relationships"), Scope("read:follows")] [HttpGet("/api/v1/accounts/relationships"), Scope("read:follows")]
@@ -190,7 +175,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var accounts = new List<object>(); var accounts = new List<object>();
foreach (var id in Params.List("id").Distinct().Take(40)) foreach (var id in Params.List("id").Distinct().Take(40))
if (await _mapper.Account(id, token) is { } account) if (await mapper.Account(id, token) is { } account)
accounts.Add(account); accounts.Add(account);
return Json(accounts); return Json(accounts);
} }
@@ -198,7 +183,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/accounts/{id}"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/accounts/{id}"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Get(string id, CancellationToken token) public async Task<IActionResult> Get(string id, CancellationToken token)
{ {
var account = await _mapper.Account(id, token); var account = await mapper.Account(id, token);
return account == default ? NotFoundError() : Json(account); return account == default ? NotFoundError() : Json(account);
} }
@@ -215,22 +200,22 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var featured = (await DB.Default.Find<RemoteFeatured>().Match(f => f.ActorURI == remote.ActorURI).Sort(f => f.Position, Order.Ascending) var featured = (await DB.Default.Find<RemoteFeatured>().Match(f => f.ActorURI == remote.ActorURI).Sort(f => f.Position, Order.Ascending)
.Limit(Federation.Actors.FeaturedPosts.MaxFeatured).ExecuteAsync(token)).Select(f => f.PostId).ToList(); .Limit(Federation.Actors.FeaturedPosts.MaxFeatured).ExecuteAsync(token)).Select(f => f.PostId).ToList();
var featuredPosts = await _dbEntities.Posts.Match(p => featured.Contains(p.ID) && !p.DeletedAt.HasValue).Match(VisibilityPolicy.IsPublic).ExecuteAsync(token); var featuredPosts = await dbEntities.Posts.Match(p => featured.Contains(p.ID) && !p.DeletedAt.HasValue).Match(VisibilityPolicy.IsPublic).ExecuteAsync(token);
return Json(await _mapper.Statuses(featured.Select(id => featuredPosts.FirstOrDefault(p => p.ID == id)).Where(p => p != default).ToList(), MyId, token)); return Json(await mapper.Statuses(featured.Select(id => featuredPosts.FirstOrDefault(p => p.ID == id)).Where(p => p != default).ToList(), MyId, token));
} }
var pinIds = (await DB.Default.Find<Pin>().Match(p => p.AvatarId == local.Id).Sort(p => p.ID, Order.Descending).ExecuteAsync(token)).Select(p => p.PostId).ToList(); var pinIds = (await DB.Default.Find<Pin>().Match(p => p.AvatarId == local.Id).Sort(p => p.ID, Order.Descending).ExecuteAsync(token)).Select(p => p.PostId).ToList();
var pinnedPosts = await _dbEntities.Posts.Match(p => pinIds.Contains(p.ID)).Match(VisibilityPolicy.IsPublic).ExecuteAsync(token); var pinnedPosts = await dbEntities.Posts.Match(p => pinIds.Contains(p.ID)).Match(VisibilityPolicy.IsPublic).ExecuteAsync(token);
return Json(await _mapper.Statuses(pinIds.Select(id => pinnedPosts.FirstOrDefault(p => p.ID == id)).Where(p => p != default).ToList(), MyId, token)); return Json(await mapper.Statuses(pinIds.Select(id => pinnedPosts.FirstOrDefault(p => p.ID == id)).Where(p => p != default).ToList(), MyId, token));
} }
var query = local is { Kind: LocalActorKind.Group } var query = local is { Kind: LocalActorKind.Group }
? _dbEntities.Posts.Match(p => p.GroupId == local.Id).Match(VisibilityPolicy.IsShown) ? dbEntities.Posts.Match(p => p.GroupId == local.Id).Match(VisibilityPolicy.IsShown)
: local != default : local != default
? _dbEntities.Posts.Match(p => p.GroupUserId == local.Id && !p.IsFederatedCopy).Match(VisibilityPolicy.IsShown) ? dbEntities.Posts.Match(p => p.GroupUserId == local.Id && !p.IsFederatedCopy).Match(VisibilityPolicy.IsShown)
: _dbEntities.Posts.Match(p => p.ActorURI == remote.ActorURI && p.IsFederatedCopy).Match(VisibilityPolicy.IsShown); : dbEntities.Posts.Match(p => p.ActorURI == remote.ActorURI && p.IsFederatedCopy).Match(VisibilityPolicy.IsShown);
var viewerFollows = MyId != default && (local != default var viewerFollows = MyId != default && (local != default
? await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetAccountId == local.Id && f.State == FollowState.Accepted).ExecuteAnyAsync(token) ? await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetAccountId == local.Id && f.State == FollowState.Accepted).ExecuteAnyAsync(token)
: await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == remote.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token)); : await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == remote.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token));
if (MyId != id) if (MyId != id)
query.Match(viewerFollows query.Match(viewerFollows
? p => p.Visibility == PostVisibility.Public || p.Visibility == PostVisibility.Unlisted || p.Visibility == PostVisibility.FollowersOnly ? p => p.Visibility == PostVisibility.Public || p.Visibility == PostVisibility.Unlisted || p.Visibility == PostVisibility.FollowersOnly
@@ -250,7 +235,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
query.Match(p => p.Tags.Contains(tag.ToLowerInvariant())); query.Match(p => p.Tags.Contains(tag.ToLowerInvariant()));
var posts = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token); var posts = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token);
var statuses = await _mapper.Statuses(posts, MyId, token); var statuses = await mapper.Statuses(posts, MyId, token);
Link($"/api/v1/accounts/{id}/statuses", posts.LastOrDefault()?.ID, posts.FirstOrDefault()?.ID); Link($"/api/v1/accounts/{id}/statuses", posts.LastOrDefault()?.ID, posts.FirstOrDefault()?.ID);
return Json(statuses); return Json(statuses);
} }
@@ -262,7 +247,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (local == default || local.Id != MyId) if (local == default || local.Id != MyId)
return Json(Array.Empty<Account>()); return Json(Array.Empty<Account>());
var followers = await Page.From(Params, Limit(40, 80)) var followers = await Page.From(Params, Limit(40, 80))
.Fetch(_dbEntities.Followers.Match(f => f.LocalActorId == local.Id && f.LocalActorKind == local.Kind && f.IsAccepted), f => f.ID, token); .Fetch(dbEntities.Followers.Match(f => f.LocalActorId == local.Id && f.LocalActorKind == local.Kind && f.IsAccepted), f => f.ID, token);
Link($"/api/v1/accounts/{id}/followers", followers.LastOrDefault()?.ID, followers.FirstOrDefault()?.ID); Link($"/api/v1/accounts/{id}/followers", followers.LastOrDefault()?.ID, followers.FirstOrDefault()?.ID);
return Json(await AccountsFor(followers.Select(f => f.ActorURI), token)); return Json(await AccountsFor(followers.Select(f => f.ActorURI), token));
} }
@@ -277,9 +262,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (local == default || local.Id != MyId) if (local == default || local.Id != MyId)
return Json(Array.Empty<Account>()); return Json(Array.Empty<Account>());
var following = await Page.From(Params, Limit(40, 80)) var following = await Page.From(Params, Limit(40, 80))
.Fetch(_dbEntities.Followings.Match(f => f.AvatarId == local.Id && f.State == FollowState.Accepted), f => f.ID, token); .Fetch(dbEntities.Followings.Match(f => f.AvatarId == local.Id && f.State == FollowState.Accepted), f => f.ID, token);
Link($"/api/v1/accounts/{id}/following", following.LastOrDefault()?.ID, following.FirstOrDefault()?.ID); Link($"/api/v1/accounts/{id}/following", following.LastOrDefault()?.ID, following.FirstOrDefault()?.ID);
var accounts = await _mapper.Accounts(following.Select(f => f.TargetAccountId), token); var accounts = await mapper.Accounts(following.Select(f => f.TargetAccountId), token);
return Json(following.Select(f => accounts.GetValueOrDefault(f.TargetAccountId)).Where(a => a != default).ToList()); return Json(following.Select(f => accounts.GetValueOrDefault(f.TargetAccountId)).Where(a => a != default).ToList());
} }
@@ -288,7 +273,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Feeds(CancellationToken token) public async Task<IActionResult> Feeds(CancellationToken token)
{ {
var read = await DB.Default.Find<FeedSubscription>().Match(s => s.AvatarId == MyId).Sort(s => s.ID, MongoDB.Entities.Order.Descending).ExecuteAsync(token); var read = await DB.Default.Find<FeedSubscription>().Match(s => s.AvatarId == MyId).Sort(s => s.ID, MongoDB.Entities.Order.Descending).ExecuteAsync(token);
var accounts = await _mapper.Accounts(read.Select(s => s.FeedAccountId), token); var accounts = await mapper.Accounts(read.Select(s => s.FeedAccountId), token);
return Json(read.Select(s => accounts.GetValueOrDefault(s.FeedAccountId)).Where(a => a != default).ToList()); return Json(read.Select(s => accounts.GetValueOrDefault(s.FeedAccountId)).Where(a => a != default).ToList());
} }
@@ -302,13 +287,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
// a feed is read through the server, whose reader follows its communities; the persona follows nothing // a feed is read through the server, whose reader follows its communities; the persona follows nothing
if (remote is { AvatarType: AvatarType.Feed }) if (remote is { AvatarType: AvatarType.Feed })
{ {
await _feeds.Subscribe(Me, remote, true, token); await feedFollows.Subscribe(Me, remote, true, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
// notify: a `status` notification for each of its new posts; languages: only its posts in those reach the home (R8). // notify: a `status` notification for each of its new posts; languages: only its posts in those reach the home (R8).
// Either changes only when given, as on Mastodon // Either changes only when given, as on Mastodon
var following = await _follows.FollowAs(Me, local?.Uri ?? remote.ActorURI, Params.Bool("reblogs") != false, token, Params.Bool("notify"), var following = await followService.FollowAs(Me, local?.Uri ?? remote.ActorURI, Params.Bool("reblogs") != false, Params.Bool("notify"),
Params.Has("languages") ? Params.List("languages") : default); Params.Has("languages") ? Params.List("languages") : default, token);
return following == default ? Error(StatusCodes.Status403Forbidden, "This action is not allowed") : Json(await Relationship(id, token)); return following == default ? Error(StatusCodes.Status403Forbidden, "This action is not allowed") : Json(await Relationship(id, token));
} }
@@ -319,9 +304,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (local == default && remote == default) if (local == default && remote == default)
return NotFoundError(); return NotFoundError();
if (remote is { AvatarType: AvatarType.Feed }) if (remote is { AvatarType: AvatarType.Feed })
await _feeds.Subscribe(Me, remote, false, token); await feedFollows.Subscribe(Me, remote, false, token);
else else
await _follows.UnfollowAs(Me, local?.Uri ?? remote.ActorURI, token); await followService.UnfollowAs(Me, local?.Uri ?? remote.ActorURI, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -332,7 +317,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var uri = local?.Uri ?? remote?.ActorURI; var uri = local?.Uri ?? remote?.ActorURI;
if (uri == default) if (uri == default)
return NotFoundError(); return NotFoundError();
await _relationships.RemoveFollower(Me, uri, id, token); await relationshipService.RemoveFollower(Me, uri, id, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -342,7 +327,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var (local, remote) = await Find(id, token); var (local, remote) = await Find(id, token);
if (local == default && remote == default || local?.Id == MyId) if (local == default && remote == default || local?.Id == MyId)
return NotFoundError(); return NotFoundError();
await _relationships.Block(Me, local?.Uri ?? remote.ActorURI, id, token); await relationshipService.Block(Me, local?.Uri ?? remote.ActorURI, id, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -352,7 +337,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var (local, remote) = await Find(id, token); var (local, remote) = await Find(id, token);
if (local == default && remote == default) if (local == default && remote == default)
return NotFoundError(); return NotFoundError();
await _relationships.Unblock(Me, local?.Uri ?? remote.ActorURI, token); await relationshipService.Unblock(Me, local?.Uri ?? remote.ActorURI, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -363,7 +348,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (local == default && remote == default || local?.Id == MyId) if (local == default && remote == default || local?.Id == MyId)
return NotFoundError(); return NotFoundError();
var duration = Params.Int("duration") is { } seconds and > 0 ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null; var duration = Params.Int("duration") is { } seconds and > 0 ? TimeSpan.FromSeconds(seconds) : (TimeSpan?)null;
await _relationships.Mute(Me, local?.Uri ?? remote.ActorURI, id, Params.Bool("notifications") != false, duration, token); await relationshipService.Mute(Me, local?.Uri ?? remote.ActorURI, id, Params.Bool("notifications") != false, duration, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -373,7 +358,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var (local, remote) = await Find(id, token); var (local, remote) = await Find(id, token);
if (local == default && remote == default) if (local == default && remote == default)
return NotFoundError(); return NotFoundError();
await _relationships.Unmute(Me, local?.Uri ?? remote.ActorURI, token); await relationshipService.Unmute(Me, local?.Uri ?? remote.ActorURI, token);
return Json(await Relationship(id, token)); return Json(await Relationship(id, token));
} }
@@ -381,7 +366,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Blocks(CancellationToken token) public async Task<IActionResult> Blocks(CancellationToken token)
{ {
var blocks = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<Block>().Match(b => b.AvatarId == MyId), b => b.ID, token); var blocks = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<Block>().Match(b => b.AvatarId == MyId), b => b.ID, token);
var accounts = await _mapper.Accounts(blocks.Select(b => b.TargetAccountId), token); var accounts = await mapper.Accounts(blocks.Select(b => b.TargetAccountId), token);
Link("/api/v1/blocks", blocks.LastOrDefault()?.ID, blocks.FirstOrDefault()?.ID); Link("/api/v1/blocks", blocks.LastOrDefault()?.ID, blocks.FirstOrDefault()?.ID);
return Json(blocks.Select(b => accounts.GetValueOrDefault(b.TargetAccountId)).Where(a => a != default).ToList()); return Json(blocks.Select(b => accounts.GetValueOrDefault(b.TargetAccountId)).Where(a => a != default).ToList());
} }
@@ -390,7 +375,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Mutes(CancellationToken token) public async Task<IActionResult> Mutes(CancellationToken token)
{ {
var mutes = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<Mute>().Match(m => m.AvatarId == MyId), m => m.ID, token); var mutes = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<Mute>().Match(m => m.AvatarId == MyId), m => m.ID, token);
var accounts = await _mapper.Accounts(mutes.Select(m => m.TargetAccountId), token); var accounts = await mapper.Accounts(mutes.Select(m => m.TargetAccountId), token);
Link("/api/v1/mutes", mutes.LastOrDefault()?.ID, mutes.FirstOrDefault()?.ID); Link("/api/v1/mutes", mutes.LastOrDefault()?.ID, mutes.FirstOrDefault()?.ID);
return Json(mutes.Select(m => accounts.GetValueOrDefault(m.TargetAccountId)).Where(a => a != default).ToList()); return Json(mutes.Select(m => accounts.GetValueOrDefault(m.TargetAccountId)).Where(a => a != default).ToList());
} }
@@ -410,9 +395,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: domain"); return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: domain");
if (Uri.CheckHostName(domain) != UriHostNameType.Dns) if (Uri.CheckHostName(domain) != UriHostNameType.Dns)
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Domain is invalid"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Domain is invalid");
var followings = await _dbEntities.Followings.Match(f => f.AvatarId == MyId && !f.TargetIsLocal && f.State == FollowState.Accepted) var followings = await dbEntities.Followings.Match(f => f.AvatarId == MyId && !f.TargetIsLocal && f.State == FollowState.Accepted)
.ExecuteAsync(token); .ExecuteAsync(token);
var followers = await _dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.IsAccepted).ExecuteAsync(token); var followers = await dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.IsAccepted).ExecuteAsync(token);
var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token); var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token);
return Json(new return Json(new
{ {
@@ -424,32 +409,32 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpPost("/api/v1/domain_blocks"), Scope("write:blocks")] [HttpPost("/api/v1/domain_blocks"), Scope("write:blocks")]
public async Task<IActionResult> BlockDomain(CancellationToken token) public async Task<IActionResult> BlockDomain(CancellationToken token)
{ {
await _relationships.BlockDomain(Me, Params.Get("domain"), token); await relationshipService.BlockDomain(Me, Params.Get("domain"), token);
return Json(new { }); return Json(new { });
} }
[HttpDelete("/api/v1/domain_blocks"), Scope("write:blocks")] [HttpDelete("/api/v1/domain_blocks"), Scope("write:blocks")]
public async Task<IActionResult> UnblockDomain(CancellationToken token) public async Task<IActionResult> UnblockDomain(CancellationToken token)
{ {
await _relationships.UnblockDomain(Me, Params.Get("domain"), token); await relationshipService.UnblockDomain(Me, Params.Get("domain"), token);
return Json(new { }); return Json(new { });
} }
[HttpGet("/api/v1/follow_requests"), Scope("read:follows")] [HttpGet("/api/v1/follow_requests"), Scope("read:follows")]
public async Task<IActionResult> FollowRequests(CancellationToken token) public async Task<IActionResult> FollowRequests(CancellationToken token)
{ {
var requests = await _dbEntities.Followers.Match(f => f.LocalActorId == Me.Id && f.LocalActorKind == LocalActorKind.Person && !f.IsAccepted) var requests = await dbEntities.Followers.Match(f => f.LocalActorId == Me.Id && f.LocalActorKind == LocalActorKind.Person && !f.IsAccepted)
.Sort(f => f.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token); .Sort(f => f.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token);
return Json(await AccountsFor(requests.Select(r => r.ActorURI), token)); return Json(await AccountsFor(requests.Select(r => r.ActorURI), token));
} }
[HttpPost("/api/v1/follow_requests/{id}/authorize"), Scope("write:follows")] [HttpPost("/api/v1/follow_requests/{id}/authorize"), Scope("write:follows")]
public async Task<IActionResult> Authorize(string id, CancellationToken token) => public async Task<IActionResult> Authorize(string id, CancellationToken token) =>
await _follows.Decide(Me, id, accept: true, token) ? Json(await Relationship(id, token)) : NotFoundError(); await followService.Decide(Me, id, accept: true, token) ? Json(await Relationship(id, token)) : NotFoundError();
[HttpPost("/api/v1/follow_requests/{id}/reject"), Scope("write:follows")] [HttpPost("/api/v1/follow_requests/{id}/reject"), Scope("write:follows")]
public async Task<IActionResult> Reject(string id, CancellationToken token) => public async Task<IActionResult> Reject(string id, CancellationToken token) =>
await _follows.Decide(Me, id, accept: false, token) ? Json(await Relationship(id, token)) : NotFoundError(); await followService.Decide(Me, id, accept: false, token) ? Json(await Relationship(id, token)) : NotFoundError();
// Familiar followers stay empty by design: which of the accounts the persona follows also follow another account would // Familiar followers stay empty by design: which of the accounts the persona follows also follow another account would
// tell who follows whom among the personas here (and their followers lists are never shown, hide_collections), so // tell who follows whom among the personas here (and their followers lists are never shown, hide_collections), so
@@ -507,12 +492,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<IActionResult> EndorsementsOf(string path, CancellationToken token) async Task<IActionResult> EndorsementsOf(string path, CancellationToken token)
{ {
var followed = (await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && f.FollowerKind == null) var followed = (await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && f.FollowerKind == null)
.Project(f => f.Include(x => x.TargetActorURI)).ExecuteAsync(token)).Select(f => f.TargetActorURI).ToList(); .Project(f => f.Include(x => x.TargetActorURI)).ExecuteAsync(token)).Select(f => f.TargetActorURI).ToList();
var page = await Page.From(Params, Limit(40, 80)) var page = await Page.From(Params, Limit(40, 80))
.Fetch(DB.Default.Find<Endorsement>().Match(e => e.AvatarId == MyId && followed.Contains(e.TargetActorURI)), e => e.ID, token); .Fetch(DB.Default.Find<Endorsement>().Match(e => e.AvatarId == MyId && followed.Contains(e.TargetActorURI)), e => e.ID, token);
Link(path, page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID); Link(path, page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID);
var accounts = await _mapper.Accounts(page.Select(e => e.TargetAccountId), token); var accounts = await mapper.Accounts(page.Select(e => e.TargetAccountId), token);
return Json(page.Select(e => accounts.GetValueOrDefault(e.TargetAccountId)).Where(a => a != default).ToList()); return Json(page.Select(e => accounts.GetValueOrDefault(e.TargetAccountId)).Where(a => a != default).ToList());
} }
@@ -554,7 +539,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
const int MaxEndorsements = 500; const int MaxEndorsements = 500;
async Task<bool> Follows(string uri, CancellationToken token) => async Task<bool> Follows(string uri, CancellationToken token) =>
await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == uri && f.State == FollowState.Accepted && f.FollowerKind == null) await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == uri && f.State == FollowState.Accepted && f.FollowerKind == null)
.ExecuteAnyAsync(token); .ExecuteAnyAsync(token);
async Task<List<Account>> AccountsFor(IEnumerable<string> actorUris, CancellationToken token) async Task<List<Account>> AccountsFor(IEnumerable<string> actorUris, CancellationToken token)
@@ -562,37 +547,37 @@ namespace PrivaPub.Api.Mastodon.Controllers
var accounts = new List<Account>(); var accounts = new List<Account>();
foreach (var uri in actorUris) foreach (var uri in actorUris)
{ {
var local = await _localActors.FindByUri(uri, token); var local = await localActors.FindByUri(uri, token);
if (local != default) if (local != default)
{ {
accounts.Add(await _mapper.Local(local, false, token)); accounts.Add(await mapper.Local(local, false, token));
continue; continue;
} }
var foreign = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == uri).ExecuteFirstAsync(token); var foreign = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == uri).ExecuteFirstAsync(token);
if (foreign != default) if (foreign != default)
accounts.Add(_mapper.Foreign(foreign)); accounts.Add(mapper.Foreign(foreign));
} }
return accounts; return accounts;
} }
async Task<(LocalActor Local, ForeignAvatar Remote)> Find(string id, CancellationToken token) async Task<(LocalActor Local, ForeignAvatar Remote)> Find(string id, CancellationToken token)
{ {
var avatar = await _dbEntities.Avatars.MatchID(id).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(id).ExecuteFirstAsync(token);
if (avatar is { DeletionAt: null }) if (avatar is { DeletionAt: null })
return (_localActors.FromAvatar(avatar), default); return (localActors.FromAvatar(avatar), default);
var group = await _dbEntities.Groups.MatchID(id).ExecuteFirstAsync(token); var group = await dbEntities.Groups.MatchID(id).ExecuteFirstAsync(token);
if (group is { DeletionAt: null } && _localActors.FromGroup(group) is { IsFederated: true, IsCircle: false } community) if (group is { DeletionAt: null } && localActors.FromGroup(group) is { IsFederated: true, IsCircle: false } community)
return (community, default); return (community, default);
return (default, await _dbEntities.ForeignAvatars.MatchID(id).ExecuteFirstAsync(token)); return (default, await dbEntities.ForeignAvatars.MatchID(id).ExecuteFirstAsync(token));
} }
async Task<Relationship> Relationship(string id, CancellationToken token) async Task<Relationship> Relationship(string id, CancellationToken token)
{ {
var (local, remote) = await Find(id, token); var (local, remote) = await Find(id, token);
var uri = local?.Uri ?? remote?.ActorURI; var uri = local?.Uri ?? remote?.ActorURI;
var following = uri == default ? default : await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == uri).ExecuteFirstAsync(token); var following = uri == default ? default : await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.TargetActorURI == uri).ExecuteFirstAsync(token);
var reading = remote is { AvatarType: AvatarType.Feed } && await _feeds.IsSubscribed(MyId, remote.ActorURI, token); var reading = remote is { AvatarType: AvatarType.Feed } && await feedFollows.IsSubscribed(MyId, remote.ActorURI, token);
var followedBy = uri == default ? default : await _dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.ActorURI == uri).ExecuteFirstAsync(token); var followedBy = uri == default ? default : await dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.ActorURI == uri).ExecuteFirstAsync(token);
var blocking = uri != default && await DB.Default.Find<Block>().Match(b => b.AvatarId == MyId && b.TargetActorURI == uri).ExecuteAnyAsync(token); var blocking = uri != default && await DB.Default.Find<Block>().Match(b => b.AvatarId == MyId && b.TargetActorURI == uri).ExecuteAnyAsync(token);
var mute = uri == default ? default : await DB.Default.Find<Mute>().Match(m => m.AvatarId == MyId && m.TargetActorURI == uri).ExecuteFirstAsync(token); var mute = uri == default ? default : await DB.Default.Find<Mute>().Match(m => m.AvatarId == MyId && m.TargetActorURI == uri).ExecuteFirstAsync(token);
var blockedBy = local != default var blockedBy = local != default
@@ -12,22 +12,16 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// Mastodon's announcements: the administrators' (Domain/Social/Announcements.cs), each persona's dismissals and // Mastodon's announcements: the administrators' (Domain/Social/Announcements.cs), each persona's dismissals and
// reactions its own. Anonymous readers get the list without `read` or `me`. // reactions its own. Anonymous readers get the list without `read` or `me`.
public class AnnouncementsController : MastodonController public class AnnouncementsController(
IAnnouncements announcementService) : MastodonController
{ {
readonly IAnnouncements _announcements;
public AnnouncementsController(IAnnouncements announcements)
{
_announcements = announcements;
}
[HttpGet("/api/v1/announcements"), Scope("read", requiresUser: false), AllowAnonymous] [HttpGet("/api/v1/announcements"), Scope("read", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> List(CancellationToken token) => public async Task<IActionResult> List(CancellationToken token) =>
Json(await Map(await _announcements.Shown(token), MyId, token)); Json(await Map(await announcementService.Shown(token), MyId, token));
[HttpPost("/api/v1/announcements/{id}/dismiss"), Scope("write:accounts")] [HttpPost("/api/v1/announcements/{id}/dismiss"), Scope("write:accounts")]
public async Task<IActionResult> Dismiss(string id, CancellationToken token) => public async Task<IActionResult> Dismiss(string id, CancellationToken token) =>
await _announcements.Dismiss(id, MyId, token) ? Json(new { }) : NotFoundError(); await announcementService.Dismiss(id, MyId, token) ? Json(new { }) : NotFoundError();
[HttpPut("/api/v1/announcements/{id}/reactions/{name}"), Scope("write:favourites")] [HttpPut("/api/v1/announcements/{id}/reactions/{name}"), Scope("write:favourites")]
public Task<IActionResult> React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token); public Task<IActionResult> React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token);
@@ -37,7 +31,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<IActionResult> Reaction(string id, string name, bool add, CancellationToken token) async Task<IActionResult> Reaction(string id, string name, bool add, CancellationToken token)
{ {
var (status, error) = await _announcements.React(id, MyId, name, add, token); var (status, error) = await announcementService.React(id, MyId, name, add, token);
return error == default ? Json(new { }) : Error(status, error); return error == default ? Json(new { }) : Error(status, error);
} }
@@ -13,17 +13,10 @@ using static OpenIddict.Abstractions.OpenIddictConstants;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class AppsController : MastodonController public class AppsController(
IOpenIddictApplicationManager applications,
PrivaPub.Infrastructure.Push.IVapid vapid) : MastodonController
{ {
readonly IOpenIddictApplicationManager _applications;
readonly PrivaPub.Infrastructure.Push.IVapid _vapid;
public AppsController(IOpenIddictApplicationManager applications, PrivaPub.Infrastructure.Push.IVapid vapid)
{
_applications = applications;
_vapid = vapid;
}
[HttpPost("/api/v1/apps"), AllowAnonymous] [HttpPost("/api/v1/apps"), AllowAnonymous]
public async Task<IActionResult> Create(CancellationToken token) public async Task<IActionResult> Create(CancellationToken token)
{ {
@@ -61,10 +54,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (Uri.TryCreate(website, UriKind.Absolute, out var site) && site.Scheme is "https" or "http") if (Uri.TryCreate(website, UriKind.Absolute, out var site) && site.Scheme is "https" or "http")
descriptor.Properties["website"] = System.Text.Json.JsonSerializer.SerializeToElement(website); descriptor.Properties["website"] = System.Text.Json.JsonSerializer.SerializeToElement(website);
var application = await _applications.CreateAsync(descriptor, token); var application = await applications.CreateAsync(descriptor, token);
return Json(new Application return Json(new Application
{ {
Id = await _applications.GetIdAsync(application, token), Id = await applications.GetIdAsync(application, token),
Name = name, Name = name,
Website = website, Website = website,
Scopes = scopes.ToList(), Scopes = scopes.ToList(),
@@ -72,7 +65,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
RedirectUri = string.Join("\n", redirects), RedirectUri = string.Join("\n", redirects),
ClientId = descriptor.ClientId, ClientId = descriptor.ClientId,
ClientSecret = descriptor.ClientSecret, ClientSecret = descriptor.ClientSecret,
VapidKey = (await _vapid.Key(token)).ForApi//Web Push's server key, as Mastodon still gives it here VapidKey = (await vapid.Key(token)).ForApi//Web Push's server key, as Mastodon still gives it here
}); });
} }
@@ -80,18 +73,18 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Verify(CancellationToken token) public async Task<IActionResult> Verify(CancellationToken token)
{ {
var clientId = User.GetPresenters().FirstOrDefault() ?? User.GetClaim(Claims.ClientId); var clientId = User.GetPresenters().FirstOrDefault() ?? User.GetClaim(Claims.ClientId);
var application = clientId == default ? default : await _applications.FindByClientIdAsync(clientId, token); var application = clientId == default ? default : await applications.FindByClientIdAsync(clientId, token);
if (application == default) if (application == default)
return Error(StatusCodes.Status401Unauthorized, "The access token is invalid"); return Error(StatusCodes.Status401Unauthorized, "The access token is invalid");
var properties = await _applications.GetPropertiesAsync(application, token); var properties = await applications.GetPropertiesAsync(application, token);
return Json(new return Json(new
{ {
id = await _applications.GetIdAsync(application, token), id = await applications.GetIdAsync(application, token),
name = await _applications.GetDisplayNameAsync(application, token), name = await applications.GetDisplayNameAsync(application, token),
website = properties.TryGetValue("website", out var website) ? website.GetString() : default, website = properties.TryGetValue("website", out var website) ? website.GetString() : default,
scopes = User.GetScopes().ToList(), scopes = User.GetScopes().ToList(),
redirect_uris = (await _applications.GetRedirectUrisAsync(application, token)).ToList(), redirect_uris = (await applications.GetRedirectUrisAsync(application, token)).ToList(),
vapid_key = (await _vapid.Key(token)).ForApi vapid_key = (await vapid.Key(token)).ForApi
}); });
} }
@@ -8,21 +8,19 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// The CDNs in front of the servers this server knows, each named by its own domain (owner decision 2026-10-04): how many // The CDNs in front of the servers this server knows, each named by its own domain (owner decision 2026-10-04): how many
// servers are behind it, how it is recognised, and week by week who joined and who left. // servers are behind it, how it is recognised, and week by week who joined and who left.
public class CdnsController : MastodonController public class CdnsController(
IServerPlaces places) : MastodonController
{ {
const int MaxWeeks = 260; const int MaxWeeks = 260;
readonly IServerPlaces _places;
public CdnsController(IServerPlaces places) => _places = places;
[HttpGet("/api/privapub/v1/cdns"), Scope("read", requiresUser: false), AllowAnonymous] [HttpGet("/api/privapub/v1/cdns"), Scope("read", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> List(CancellationToken token) => Json((await _places.Cdns(token)).Select(Summary).ToList()); public async Task<IActionResult> List(CancellationToken token) => Json((await places.Cdns(token)).Select(Summary).ToList());
[HttpGet("/api/privapub/v1/cdns/{key}"), Scope("read", requiresUser: false), AllowAnonymous] [HttpGet("/api/privapub/v1/cdns/{key}"), Scope("read", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> Detail(string key, CancellationToken token) public async Task<IActionResult> Detail(string key, CancellationToken token)
{ {
var history = await _places.Cdn(key, Math.Clamp(Params.Int("weeks") ?? 52, 1, MaxWeeks), token); var history = await places.Cdn(key, Math.Clamp(Params.Int("weeks") ?? 52, 1, MaxWeeks), token);
if (history == default) if (history == default)
return NotFoundError(); return NotFoundError();
var detail = new CdnDetail var detail = new CdnDetail
@@ -16,42 +16,35 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Featured hashtags as Mastodon's API has them (completion program R8, Domain/Social/FeaturedTags): the persona's own, // Featured hashtags as Mastodon's API has them (completion program R8, Domain/Social/FeaturedTags): the persona's own,
// featured and unfeatured (its followers are told), suggested from the tags it uses, and any account's: a persona's own // featured and unfeatured (its followers are told), suggested from the tags it uses, and any account's: a persona's own
// here, or those an account elsewhere features as its server tells them. They are public, as on Mastodon. // here, or those an account elsewhere features as its server tells them. They are public, as on Mastodon.
public class FeaturedTagsController : MastodonController public class FeaturedTagsController(
IFeaturedTags featuredTags,
DbEntities dbEntities,
ILocalActorService localActors) : MastodonController
{ {
const int MaxSuggested = 10;//Mastodon's RECENT_TAGS_LIMIT const int MaxSuggested = 10;//Mastodon's RECENT_TAGS_LIMIT
const int SuggestionPosts = 200; const int SuggestionPosts = 200;
readonly IFeaturedTags _featured;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public FeaturedTagsController(IFeaturedTags featured, DbEntities dbEntities, ILocalActorService localActors)
{
_featured = featured;
_dbEntities = dbEntities;
_localActors = localActors;
}
[HttpGet("/api/v1/featured_tags"), Scope("read:accounts")] [HttpGet("/api/v1/featured_tags"), Scope("read:accounts")]
public async Task<IActionResult> Mine(CancellationToken token) => Json(await Entities(await _featured.Of(MyId, token), token)); public async Task<IActionResult> Mine(CancellationToken token) => Json(await Entities(await featuredTags.Of(MyId, token), token));
[HttpPost("/api/v1/featured_tags"), Scope("write:accounts")] [HttpPost("/api/v1/featured_tags"), Scope("write:accounts")]
public async Task<IActionResult> Feature(CancellationToken token) public async Task<IActionResult> Feature(CancellationToken token)
{ {
var (tag, error) = await _featured.Feature(Me, Params.Get("name"), token); var (tag, error) = await featuredTags.Feature(Me, Params.Get("name"), token);
return tag == default ? Error(StatusCodes.Status422UnprocessableEntity, error) : Json((await Entities(new List<FeaturedTag> { tag }, token))[0]); return tag == default ? Error(StatusCodes.Status422UnprocessableEntity, error) : Json((await Entities(new List<FeaturedTag> { tag }, token))[0]);
} }
[HttpDelete("/api/v1/featured_tags/{id}"), Scope("write:accounts")] [HttpDelete("/api/v1/featured_tags/{id}"), Scope("write:accounts")]
public async Task<IActionResult> Unfeature(string id, CancellationToken token) => public async Task<IActionResult> Unfeature(string id, CancellationToken token) =>
await _featured.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new { }); await featuredTags.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new { });
// the tags the persona used lately and does not feature yet, the most used first, as Mastodon's Tag // the tags the persona used lately and does not feature yet, the most used first, as Mastodon's Tag
[HttpGet("/api/v1/featured_tags/suggestions"), Scope("read:accounts")] [HttpGet("/api/v1/featured_tags/suggestions"), Scope("read:accounts")]
public async Task<IActionResult> Suggestions(CancellationToken token) public async Task<IActionResult> Suggestions(CancellationToken token)
{ {
var featured = (await _featured.Of(MyId, token)).Select(t => t.Name).ToHashSet(StringComparer.Ordinal); var featured = (await featuredTags.Of(MyId, token)).Select(t => t.Name).ToHashSet(StringComparer.Ordinal);
var recent = await _dbEntities.Posts.Match(p => p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null var recent = await dbEntities.Posts.Match(p => p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null
&& p.Tags.Count > 0) && p.Tags.Count > 0)
.Sort(p => p.ID, Order.Descending).Limit(SuggestionPosts).Project(p => p.Include(x => x.Tags)).ExecuteAsync(token); .Sort(p => p.ID, Order.Descending).Limit(SuggestionPosts).Project(p => p.Include(x => x.Tags)).ExecuteAsync(token);
var used = recent.SelectMany((p, age) => p.Tags.Distinct().Select(tag => (tag, age))) var used = recent.SelectMany((p, age) => p.Tags.Distinct().Select(tag => (tag, age)))
@@ -63,7 +56,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
.ToList(); .ToList();
var views = new List<object>(); var views = new List<object>();
foreach (var tag in used) foreach (var tag in used)
views.Add(await TagsController.TagView(_dbEntities, _localActors.BaseAddress, tag, MyId, default, false, token)); views.Add(await TagsController.TagView(dbEntities, localActors.BaseAddress, tag, MyId, default, false, token));
return Json(views); return Json(views);
} }
@@ -72,19 +65,19 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/accounts/{id}/featured_tags"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/accounts/{id}/featured_tags"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> OfAccount(string id, CancellationToken token) public async Task<IActionResult> OfAccount(string id, CancellationToken token)
{ {
var avatar = await _dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
return _localActors.FromAvatar(avatar) is { Suspended: false } return localActors.FromAvatar(avatar) is { Suspended: false }
? Json(await Entities(await _featured.Of(avatar.ID, token), token)) ? Json(await Entities(await featuredTags.Of(avatar.ID, token), token))
: NotFoundError(); : NotFoundError();
if (await _dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteAnyAsync(token)) if (await dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteAnyAsync(token))
return Json(Array.Empty<FeaturedTagEntity>()); return Json(Array.Empty<FeaturedTagEntity>());
var remote = await _dbEntities.ForeignAvatars.MatchID(id).Match(f => !f.DeletionAt.HasValue).ExecuteFirstAsync(token); var remote = await dbEntities.ForeignAvatars.MatchID(id).Match(f => !f.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (remote == default || remote.SuspendedAt.HasValue) if (remote == default || remote.SuspendedAt.HasValue)
return NotFoundError(); return NotFoundError();
var tags = await DB.Default.Find<RemoteFeaturedTag>().Match(t => t.ActorURI == remote.ActorURI).Sort(t => t.Position, Order.Ascending) var tags = await DB.Default.Find<RemoteFeaturedTag>().Match(t => t.ActorURI == remote.ActorURI).Sort(t => t.Position, Order.Ascending)
.Limit(FeaturedTags.MaxRemote).ExecuteAsync(token); .Limit(FeaturedTags.MaxRemote).ExecuteAsync(token);
var usage = await FeaturedTags.Usage(default, remote.ActorURI, tags.Select(t => t.Name).ToList(), _dbEntities, token); var usage = await FeaturedTags.Usage(default, remote.ActorURI, tags.Select(t => t.Name).ToList(), dbEntities, token);
return Json(tags.Select(t => Entity(t.ID, t.Name, t.DisplayName, t.Href, usage.GetValueOrDefault(t.Name))).ToList()); return Json(tags.Select(t => Entity(t.ID, t.Name, t.DisplayName, t.Href, usage.GetValueOrDefault(t.Name))).ToList());
} }
@@ -94,7 +87,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var entities = new List<FeaturedTagEntity>(); var entities = new List<FeaturedTagEntity>();
foreach (var persona in byPersona) foreach (var persona in byPersona)
{ {
var usage = await FeaturedTags.Usage(persona.Key, default, persona.Select(t => t.Name).ToList(), _dbEntities, token); var usage = await FeaturedTags.Usage(persona.Key, default, persona.Select(t => t.Name).ToList(), dbEntities, token);
entities.AddRange(persona.Select(t => Entity(t.ID, t.Name, t.DisplayName, default, usage.GetValueOrDefault(t.Name)))); entities.AddRange(persona.Select(t => Entity(t.ID, t.Name, t.DisplayName, default, usage.GetValueOrDefault(t.Name))));
} }
return entities; return entities;
@@ -105,7 +98,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
Id = id, Id = id,
Name = string.IsNullOrEmpty(displayName) ? name : displayName, Name = string.IsNullOrEmpty(displayName) ? name : displayName,
// (a link to the remote site is only a link, which the reader follows or not; ours is this server's tag page) // (a link to the remote site is only a link, which the reader follows or not; ours is this server's tag page)
Url = href ?? ActivityPubRenderer.TagUrl(_localActors.BaseAddress, name), Url = href ?? ActivityPubRenderer.TagUrl(localActors.BaseAddress, name),
StatusesCount = usage.Count.ToString(System.Globalization.CultureInfo.InvariantCulture), StatusesCount = usage.Count.ToString(System.Globalization.CultureInfo.InvariantCulture),
LastStatusAt = usage.Last?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) LastStatusAt = usage.Last?.ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture)
}; };
@@ -16,19 +16,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Mastodon's filters (owner decision 2026-10-04, back from the cut list): v2 filters with their keywords and statuses, // Mastodon's filters (owner decision 2026-10-04, back from the cut list): v2 filters with their keywords and statuses,
// and the v1 API, whose filter is one keyword of a v2 filter. Statuses carry what they match in `filtered`; clients // and the v1 API, whose filter is one keyword of a v2 filter. Statuses carry what they match in `filtered`; clients
// apply the context and the action. Nothing here leaves the server. // apply the context and the action. Nothing here leaves the server.
public class FiltersController : MastodonController public class FiltersController(
DbEntities dbEntities) : MastodonController
{ {
const int MaxFilters = 100; const int MaxFilters = 100;
const int MaxEntries = 100; const int MaxEntries = 100;
const int MaxKeywordLength = 100; const int MaxKeywordLength = 100;
static readonly Regex Attribute = new(@"^keywords_attributes\[(\d*)\]\[(\w+)\]$", RegexOptions.Compiled); static readonly Regex Attribute = new(@"^keywords_attributes\[(\d*)\]\[(\w+)\]$", RegexOptions.Compiled);
readonly DbEntities _dbEntities;
public FiltersController(DbEntities dbEntities)
{
_dbEntities = dbEntities;
}
static string NewId() => ObjectId.GenerateNewId().ToString(); static string NewId() => ObjectId.GenerateNewId().ToString();
@@ -242,7 +237,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (await Mine(id, token) is not { } filter) if (await Mine(id, token) is not { } filter)
return NotFoundError(); return NotFoundError();
var statusId = Params.Get("status_id"); var statusId = Params.Get("status_id");
var post = string.IsNullOrEmpty(statusId) ? default : await _dbEntities.Posts.Match(p => p.ID == statusId).ExecuteFirstAsync(token); var post = string.IsNullOrEmpty(statusId) ? default : await dbEntities.Posts.Match(p => p.ID == statusId).ExecuteFirstAsync(token);
if (post == default || !await Domain.Privacy.VisibilityPolicy.CanSee(post, MyId, token)) if (post == default || !await Domain.Privacy.VisibilityPolicy.CanSee(post, MyId, token))
return NotFoundError(); return NotFoundError();
if (filter.Statuses.FirstOrDefault(s => s.PostId == statusId) is { } present) if (filter.Statuses.FirstOrDefault(s => s.PostId == statusId) is { } present)
@@ -26,7 +26,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
// The instance API: what the server says of itself comes from its settings (IInstanceSettings, edited on the // The instance API: what the server says of itself comes from its settings (IInstanceSettings, edited on the
// administrator's page; until then exactly what it said before), its numbers from Counted, its limits from where they // administrator's page; until then exactly what it said before), its numbers from Counted, its limits from where they
// are enforced. // are enforced.
public class InstanceController : MastodonController public class InstanceController(
ILocalActorService localActors,
IOptionsMonitor<RegistrationOptions> registrationOptions,
IInstanceSettings instanceSettings,
MastodonMapper mapper,
PrivaPub.Infrastructure.Push.IVapid vapidKeys) : MastodonController
{ {
// The Mastodon version this API answers as, then PrivaPub's own release (its tag, or the commit a build came from). // The Mastodon version this API answers as, then PrivaPub's own release (its tag, or the commit a build came from).
// 4.5.0 since R9 (2026-10-18): every client route of Mastodon 4.3, 4.4 and 4.5 is served or answers as a documented // 4.5.0 since R9 (2026-10-18): every client route of Mastodon 4.3, 4.4 and 4.5 is served or answers as a documented
@@ -47,27 +52,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
sealed record CachedActivity(DateTime At, object Weeks); sealed record CachedActivity(DateTime At, object Weeks);
readonly ILocalActorService _localActors;
readonly IOptionsMonitor<RegistrationOptions> _registrations;
readonly IInstanceSettings _settings;
readonly MastodonMapper _mapper;
readonly PrivaPub.Infrastructure.Push.IVapid _vapid;
public InstanceController(ILocalActorService localActors, IOptionsMonitor<RegistrationOptions> registrations, IInstanceSettings settings, bool Open => registrationOptions.CurrentValue.IsOpen;
MastodonMapper mapper, PrivaPub.Infrastructure.Push.IVapid vapid)
{
_localActors = localActors;
_registrations = registrations;
_settings = settings;
_mapper = mapper;
_vapid = vapid;
}
bool Open => _registrations.CurrentValue.IsOpen; ServerSettings Settings => instanceSettings.Current;
ServerSettings Settings => _settings.Current; string Thumbnail => Settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}";
string Thumbnail => Settings.ThumbnailUrl ?? $"{_localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}";
static object Rules(ServerSettings settings) => static object Rules(ServerSettings settings) =>
settings.ListedRules().Select(r => new { id = r.Id, text = r.Text ?? string.Empty, hint = r.Hint ?? string.Empty }).ToList(); settings.ListedRules().Select(r => new { id = r.Id, text = r.Text ?? string.Empty, hint = r.Hint ?? string.Empty }).ToList();
@@ -81,7 +71,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar == default || (await Counted.HeldBackPersonas(token)).Contains(id)) if (avatar == default || (await Counted.HeldBackPersonas(token)).Contains(id))
return default; return default;
return await _mapper.Local(_localActors.FromAvatar(avatar), false, token); return await mapper.Local(localActors.FromAvatar(avatar), false, token);
} }
// the languages this server is set up for (AppConfiguration:SupportedLanguages), "en" when none are named // the languages this server is set up for (AppConfiguration:SupportedLanguages), "en" when none are named
@@ -92,10 +82,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
return codes.Count == 0 ? new[] { "en" } : codes; return codes.Count == 0 ? new[] { "en" } : codes;
} }
string Domain => new Uri(_localActors.BaseAddress).Authority; string Domain => new Uri(localActors.BaseAddress).Authority;
// where clients open their streams (StreamingController): this server, as ws or wss // where clients open their streams (StreamingController): this server, as ws or wss
string Streaming => new UriBuilder(_localActors.BaseAddress) { Scheme = _localActors.BaseAddress.StartsWith("https", StringComparison.OrdinalIgnoreCase) ? "wss" : "ws" } string Streaming => new UriBuilder(localActors.BaseAddress) { Scheme = localActors.BaseAddress.StartsWith("https", StringComparison.OrdinalIgnoreCase) ? "wss" : "ws" }
.Uri.GetLeftPart(UriPartial.Authority); .Uri.GetLeftPart(UriPartial.Authority);
// every limit is what the server enforces, read from where it is enforced // every limit is what the server enforces, read from where it is enforced
@@ -180,7 +170,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
media_attachments = MediaAttachments, media_attachments = MediaAttachments,
polls = Polls, polls = Polls,
translation = new { enabled = false }, translation = new { enabled = false },
vapid = new { public_key = (await _vapid.Key(token)).ForApi }//Web Push (R9): the key every push is signed with vapid = new { public_key = (await vapidKeys.Key(token)).ForApi }//Web Push (R9): the key every push is signed with
}, },
registrations = new { enabled = Open, approval_required = false, message = Open ? default : RegistrationOptions.ClosedMessage }, registrations = new { enabled = Open, approval_required = false, message = Open ? default : RegistrationOptions.ClosedMessage },
contact = new { email = Settings.ContactEmail ?? string.Empty, account = await ContactAccount(Settings, token) }, contact = new { email = Settings.ContactEmail ?? string.Empty, account = await ContactAccount(Settings, token) },
@@ -12,19 +12,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// Mastodon's lists (owner decision 2026-10-04, back from the cut list): a persona groups accounts it follows, reads them // Mastodon's lists (owner decision 2026-10-04, back from the cut list): a persona groups accounts it follows, reads them
// as a timeline, and may keep an exclusive list's members out of its home. Nothing here leaves the server. // as a timeline, and may keep an exclusive list's members out of its home. Nothing here leaves the server.
public class ListsController : MastodonController public class ListsController(
DbEntities dbEntities,
MastodonMapper mapper) : MastodonController
{ {
const int MaxLists = 50; const int MaxLists = 50;
const int MaxMembers = 500; const int MaxMembers = 500;
readonly DbEntities _dbEntities;
readonly MastodonMapper _mapper;
public ListsController(DbEntities dbEntities, MastodonMapper mapper)
{
_dbEntities = dbEntities;
_mapper = mapper;
}
static object View(PersonaList list) => new { id = list.ID, title = list.Title, replies_policy = list.RepliesPolicy, exclusive = list.Exclusive }; static object View(PersonaList list) => new { id = list.ID, title = list.Title, replies_policy = list.RepliesPolicy, exclusive = list.Exclusive };
@@ -38,7 +32,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var members = (await DB.Default.Find<PersonaListMember>().Match(m => m.ListId == list.ID).ExecuteAsync(token)).Select(m => m.AccountId).ToList(); var members = (await DB.Default.Find<PersonaListMember>().Match(m => m.ListId == list.ID).ExecuteAsync(token)).Select(m => m.AccountId).ToList();
if (members.Count == 0) if (members.Count == 0)
return members; return members;
var followed = (await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && members.Contains(f.TargetAccountId)) var followed = (await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && members.Contains(f.TargetAccountId))
.ExecuteAsync(token)).Select(f => f.TargetAccountId).ToHashSet(); .ExecuteAsync(token)).Select(f => f.TargetAccountId).ToHashSet();
var gone = members.Where(m => !followed.Contains(m)).ToList(); var gone = members.Where(m => !followed.Contains(m)).ToList();
if (gone.Count > 0) if (gone.Count > 0)
@@ -113,7 +107,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
await Members(list, token); await Members(list, token);
var members = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<PersonaListMember>().Match(m => m.ListId == list.ID), m => m.ID, token); var members = await Page.From(Params, Limit(40, 80)).Fetch(DB.Default.Find<PersonaListMember>().Match(m => m.ListId == list.ID), m => m.ID, token);
var accounts = await _mapper.Accounts(members.Select(m => m.AccountId), token); var accounts = await mapper.Accounts(members.Select(m => m.AccountId), token);
Link($"/api/v1/lists/{id}/accounts", members.LastOrDefault()?.ID, members.FirstOrDefault()?.ID); Link($"/api/v1/lists/{id}/accounts", members.LastOrDefault()?.ID, members.FirstOrDefault()?.ID);
return Json(members.Where(m => accounts.ContainsKey(m.AccountId)).Select(m => accounts[m.AccountId]).ToList()); return Json(members.Where(m => accounts.ContainsKey(m.AccountId)).Select(m => accounts[m.AccountId]).ToList());
} }
@@ -127,7 +121,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var ids = Params.List("account_ids").Distinct().ToList(); var ids = Params.List("account_ids").Distinct().ToList();
if (ids.Count == 0) if (ids.Count == 0)
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Account ids can't be blank"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Account ids can't be blank");
var followed = (await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && ids.Contains(f.TargetAccountId)) var followed = (await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted && ids.Contains(f.TargetAccountId))
.ExecuteAsync(token)).Select(f => f.TargetAccountId).ToHashSet(); .ExecuteAsync(token)).Select(f => f.TargetAccountId).ToHashSet();
if (ids.Any(a => !followed.Contains(a))) if (ids.Any(a => !followed.Contains(a)))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: You must follow this account to add it to a list"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: You must follow this account to add it to a list");
@@ -168,12 +162,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
var members = await Members(list, token); var members = await Members(list, token);
var entries = await Page.From(Params, Limit()).Fetch( var entries = await Page.From(Params, Limit()).Fetch(
_dbEntities.TimelineEntries.Match(e => e.AvatarId == MyId && members.Contains(e.AuthorAccountId)), e => e.PostId, token); dbEntities.TimelineEntries.Match(e => e.AvatarId == MyId && members.Contains(e.AuthorAccountId)), e => e.PostId, token);
var ids = entries.Select(e => e.PostId).ToList(); var ids = entries.Select(e => e.PostId).ToList();
var posts = (await _dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID); var posts = (await dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID);
var answered = list.RepliesPolicy switch var answered = list.RepliesPolicy switch
{ {
ListRepliesPolicy.Followed => (await _dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted).ExecuteAsync(token)) ListRepliesPolicy.Followed => (await dbEntities.Followings.Match(f => f.AvatarId == MyId && f.State == FollowState.Accepted).ExecuteAsync(token))
.Select(f => f.TargetAccountId).Append(MyId).ToHashSet(), .Select(f => f.TargetAccountId).Append(MyId).ToHashSet(),
ListRepliesPolicy.List => members.Append(MyId).ToHashSet(), ListRepliesPolicy.List => members.Append(MyId).ToHashSet(),
_ => new HashSet<string> { MyId } _ => new HashSet<string> { MyId }
@@ -183,7 +177,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|| p.InReplyToAccountId != default && (p.InReplyToAccountId == p.AuthorAccountId || answered.Contains(p.InReplyToAccountId))) || p.InReplyToAccountId != default && (p.InReplyToAccountId == p.AuthorAccountId || answered.Contains(p.InReplyToAccountId)))
.ToList(); .ToList();
Link($"/api/v1/timelines/list/{id}", entries.LastOrDefault()?.PostId, entries.FirstOrDefault()?.PostId); Link($"/api/v1/timelines/list/{id}", entries.LastOrDefault()?.PostId, entries.FirstOrDefault()?.PostId);
return Json(await _mapper.Statuses(shown, MyId, token)); return Json(await mapper.Statuses(shown, MyId, token));
} }
} }
} }
@@ -15,23 +15,15 @@ using System.Globalization;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class MediaController : MastodonController public class MediaController(
IMediaService mediaService,
IMediaProxy mediaProxy,
IJobQueue jobs,
IInteractionLedger ledger = default) : MastodonController
{ {
const long UploadLimit = 100L * 1024 * 1024; const long UploadLimit = 100L * 1024 * 1024;
readonly IMediaService _media;
readonly IMediaProxy _proxy;
readonly IJobQueue _jobs;
readonly IInteractionLedger _ledger;
public MediaController(IMediaService media, IMediaProxy proxy, IJobQueue jobs, IInteractionLedger ledger = default)
{
_media = media;
_proxy = proxy;
_jobs = jobs;
_ledger = ledger;
}
[HttpPost("/api/v1/media"), HttpPost("/api/v2/media"), Scope("write:media"), EnableRateLimiting(RateLimiting.Uploads), RequestSizeLimit(UploadLimit), [HttpPost("/api/v1/media"), HttpPost("/api/v2/media"), Scope("write:media"), EnableRateLimiting(RateLimiting.Uploads), RequestSizeLimit(UploadLimit),
RequestFormLimits(MultipartBodyLengthLimit = UploadLimit)] RequestFormLimits(MultipartBodyLengthLimit = UploadLimit)]
@@ -42,12 +34,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
var form = await Request.ReadFormAsync(token); var form = await Request.ReadFormAsync(token);
// v2 may answer before audio or video is processed (202, its url null until then), as Mastodon does; v1 waits // v2 may answer before audio or video is processed (202, its url null until then), as Mastodon does; v1 waits
var later = Request.Path.StartsWithSegments("/api/v2/media"); var later = Request.Path.StartsWithSegments("/api/v2/media");
var outcome = await _media.Upload(Me, form.Files["file"], form["description"], form["focus"], later, token); var outcome = await mediaService.Upload(Me, form.Files["file"], form["description"], form["focus"], later, token);
if (!outcome.Ok) if (!outcome.Ok)
return Error(outcome.Status, outcome.Error); return Error(outcome.Status, outcome.Error);
if (outcome.Attachment.ProcessingState != "pending") if (outcome.Attachment.ProcessingState != "pending")
return Json(View(outcome.Attachment)); return Json(View(outcome.Attachment));
await _jobs.EnqueueMany(new[] { ProcessMediaJob.JobFor(outcome.Attachment, new Uri(Me.BaseAddress).Host) }, token); await jobs.EnqueueMany(new[] { ProcessMediaJob.JobFor(outcome.Attachment, new Uri(Me.BaseAddress).Host) }, token);
return new JsonResult(View(outcome.Attachment)) { StatusCode = StatusCodes.Status202Accepted }; return new JsonResult(View(outcome.Attachment)) { StatusCode = StatusCodes.Status202Accepted };
} }
@@ -74,7 +66,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
if (attachment.PostId != null || attachment.ScheduledStatusId != null) if (attachment.PostId != null || attachment.ScheduledStatusId != null)
return Error(StatusCodes.Status422UnprocessableEntity, "Media attachment is currently used by a status"); return Error(StatusCodes.Status422UnprocessableEntity, "Media attachment is currently used by a status");
await _media.Trash(m => m.ID == attachment.ID && m.PostId == null && m.ScheduledStatusId == null, "deleted by its owner", token); await mediaService.Trash(m => m.ID == attachment.ID && m.PostId == null && m.ScheduledStatusId == null, "deleted by its owner", token);
return Json(new { }); return Json(new { });
} }
@@ -96,19 +88,19 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/media/proxy/{signature}/{encoded}"), AllowAnonymous, EnableRateLimiting(RateLimiting.Proxy), ApiExplorerSettings(IgnoreApi = true)] [HttpGet("/media/proxy/{signature}/{encoded}"), AllowAnonymous, EnableRateLimiting(RateLimiting.Proxy), ApiExplorerSettings(IgnoreApi = true)]
public async Task<IActionResult> Proxy(string signature, string encoded, CancellationToken token) public async Task<IActionResult> Proxy(string signature, string encoded, CancellationToken token)
{ {
var url = _proxy.Verified(signature, encoded); var url = mediaProxy.Verified(signature, encoded);
if (url == default || _proxy.Refuses(url)) if (url == default || mediaProxy.Refuses(url))
return NotFound(); return NotFound();
Response.Headers["X-Content-Type-Options"] = "nosniff"; Response.Headers["X-Content-Type-Options"] = "nosniff";
Response.Headers["Content-Security-Policy"] = "default-src 'none'; sandbox"; Response.Headers["Content-Security-Policy"] = "default-src 'none'; sandbox";
if (_proxy.Cached(url) is { Path: not null } cached && Serve(cached.Path, cached.ContentType) is { } hit) if (mediaProxy.Cached(url) is { Path: not null } cached && Serve(cached.Path, cached.ContentType) is { } hit)
{ {
_ledger?.Count(Interactions.HostOf(url), "media:hit"); ledger?.Count(Interactions.HostOf(url), "media:hit");
return hit; return hit;
} }
if (Request.Headers.Range.Count == 0) if (Request.Headers.Range.Count == 0)
{ {
var (outcome, path, contentType) = await _proxy.Download(url, token); var (outcome, path, contentType) = await mediaProxy.Download(url, token);
if (outcome == ProxyOutcome.Cached && Serve(path, contentType) is { } fetched) if (outcome == ProxyOutcome.Cached && Serve(path, contentType) is { } fetched)
return fetched; return fetched;
if (outcome == ProxyOutcome.Failed) if (outcome == ProxyOutcome.Failed)
@@ -121,7 +113,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
// once there is something to cache // once there is something to cache
IActionResult Serve(string path, string contentType) IActionResult Serve(string path, string contentType)
{ {
FileStream file; var file = default(FileStream);
try try
{ {
file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, useAsync: true); file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 64 * 1024, useAsync: true);
@@ -137,7 +129,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<IActionResult> Stream(string url, CancellationToken token) async Task<IActionResult> Stream(string url, CancellationToken token)
{ {
var range = System.Net.Http.Headers.RangeHeaderValue.TryParse(Request.Headers.Range.ToString(), out var asked) ? asked : default; var range = System.Net.Http.Headers.RangeHeaderValue.TryParse(Request.Headers.Range.ToString(), out var asked) ? asked : default;
using var upstream = await _proxy.Open(url, range, token); using var upstream = await mediaProxy.Open(url, range, token);
if (upstream == default) if (upstream == default)
return NotFound(); return NotFound();
if (upstream.IsSuccessStatusCode) if (upstream.IsSuccessStatusCode)
@@ -153,7 +145,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return new EmptyResult(); return new EmptyResult();
} }
object View(MediaAttachment attachment) => View(_media, attachment); object View(MediaAttachment attachment) => View(mediaService, attachment);
internal static object View(IMediaService media, MediaAttachment attachment) => new internal static object View(IMediaService media, MediaAttachment attachment) => new
{ {
@@ -14,17 +14,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Mastodon's notification policy and requests (4.3): what the persona's notifications from strangers, new accounts, // Mastodon's notification policy and requests (4.3): what the persona's notifications from strangers, new accounts,
// unasked private mentions and silenced accounts become, and the requests that gather the filtered ones, one per // unasked private mentions and silenced accounts become, and the requests that gather the filtered ones, one per
// account, let in or dismissed // account, let in or dismissed
public class NotificationRequestsController : MastodonController public class NotificationRequestsController(
MastodonMapper mapper,
DbEntities dbEntities) : MastodonController
{ {
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
public NotificationRequestsController(MastodonMapper mapper, DbEntities dbEntities)
{
_mapper = mapper;
_dbEntities = dbEntities;
}
static string Name(NotificationAction action) => action switch static string Name(NotificationAction action) => action switch
{ {
NotificationAction.Filter => "filter", NotificationAction.Filter => "filter",
@@ -101,11 +94,11 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<object> Map(NotificationRequest request, CancellationToken token) async Task<object> Map(NotificationRequest request, CancellationToken token)
{ {
var account = await _mapper.Account(request.FromAccountId, token); var account = await mapper.Account(request.FromAccountId, token);
if (account == default) if (account == default)
return default; return default;
var post = string.IsNullOrEmpty(request.LastPostId) ? default var post = string.IsNullOrEmpty(request.LastPostId) ? default
: await _dbEntities.Posts.Match(p => p.ID == request.LastPostId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); : await dbEntities.Posts.Match(p => p.ID == request.LastPostId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return new return new
{ {
id = request.ID, id = request.ID,
@@ -113,7 +106,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
updated_at = MastodonJson.Time(request.UpdatedAt), updated_at = MastodonJson.Time(request.UpdatedAt),
notifications_count = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture), notifications_count = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture),
account, account,
last_status = post == default ? default : await _mapper.Status(post, MyId, token) last_status = post == default ? default : await mapper.Status(post, MyId, token)
}; };
} }
@@ -12,24 +12,16 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class PollsController : MastodonController public class PollsController(
DbEntities dbEntities,
MastodonMapper mapper,
IPollService pollService) : MastodonController
{ {
readonly DbEntities _dbEntities;
readonly MastodonMapper _mapper;
readonly IPollService _polls;
public PollsController(DbEntities dbEntities, MastodonMapper mapper, IPollService polls)
{
_dbEntities = dbEntities;
_mapper = mapper;
_polls = polls;
}
[HttpGet("/api/v1/polls/{id}"), Scope("read:statuses", requiresUser: false), AllowAnonymous] [HttpGet("/api/v1/polls/{id}"), Scope("read:statuses", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> Get(string id, CancellationToken token) public async Task<IActionResult> Get(string id, CancellationToken token)
{ {
var post = await Visible(id, token); var post = await Visible(id, token);
return post?.Poll == default ? NotFoundError() : Json(_mapper.Poll(post, MyId, await _polls.OwnVotes(post.ID, MyId, token))); return post?.Poll == default ? NotFoundError() : Json(mapper.Poll(post, MyId, await pollService.OwnVotes(post.ID, MyId, token)));
} }
[HttpPost("/api/v1/polls/{id}/votes"), Scope("write:statuses")] [HttpPost("/api/v1/polls/{id}/votes"), Scope("write:statuses")]
@@ -39,15 +31,15 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (post?.Poll == default) if (post?.Poll == default)
return NotFoundError(); return NotFoundError();
var choices = Params.List("choices").Select(c => int.TryParse(c, out var index) ? index : -1).ToList(); var choices = Params.List("choices").Select(c => int.TryParse(c, out var index) ? index : -1).ToList();
var outcome = await _polls.Vote(Me, post, choices, token); var outcome = await pollService.Vote(Me, post, choices, token);
if (!outcome.Ok) if (!outcome.Ok)
return Error(outcome.Status, outcome.Error); return Error(outcome.Status, outcome.Error);
return Json(_mapper.Poll(outcome.Post, MyId, await _polls.OwnVotes(post.ID, MyId, token))); return Json(mapper.Poll(outcome.Post, MyId, await pollService.OwnVotes(post.ID, MyId, token)));
} }
async Task<PostEntity> Visible(string id, CancellationToken token) async Task<PostEntity> Visible(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default; return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default;
} }
} }
@@ -22,34 +22,24 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class ProvenanceController : MastodonController public class ProvenanceController(
DbEntities dbEntities,
ISelfLocation selfLocation,
IServerPlaces places,
ILocalActorService localActors,
IOptionsMonitor<RegistrationOptions> registrations) : MastodonController
{ {
const int MaxHosts = 40; const int MaxHosts = 40;
readonly DbEntities _dbEntities;
const int MaxWeeks = 260; const int MaxWeeks = 260;
readonly ISelfLocation _self;
readonly IServerPlaces _places;
readonly ILocalActorService _localActors;
readonly IOptionsMonitor<RegistrationOptions> _registrations;
public ProvenanceController(DbEntities dbEntities, ISelfLocation self, IServerPlaces places, ILocalActorService localActors,
IOptionsMonitor<RegistrationOptions> registrations)
{
_dbEntities = dbEntities;
_self = self;
_places = places;
_localActors = localActors;
_registrations = registrations;
}
[HttpGet("/api/privapub/v1/statuses/{id}/provenance"), Scope("read:statuses", requiresUser: false), AllowAnonymous] [HttpGet("/api/privapub/v1/statuses/{id}/provenance"), Scope("read:statuses", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> Status(string id, CancellationToken token) public async Task<IActionResult> Status(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id).Match(VisibilityPolicy.IsShown).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id).Match(VisibilityPolicy.IsShown).ExecuteFirstAsync(token);
if (post?.ReblogOfPostId != default) if (post?.ReblogOfPostId != default)
post = await _dbEntities.Posts.Match(p => p.ID == post.ReblogOfPostId).Match(VisibilityPolicy.IsShown).ExecuteFirstAsync(token); post = await dbEntities.Posts.Match(p => p.ID == post.ReblogOfPostId).Match(VisibilityPolicy.IsShown).ExecuteFirstAsync(token);
if (post == default || post.Visibility == PostVisibility.LocalGeo || !await VisibilityPolicy.CanSee(post, MyId, token)) if (post == default || post.Visibility == PostVisibility.LocalGeo || !await VisibilityPolicy.CanSee(post, MyId, token))
return NotFoundError(); return NotFoundError();
if (!post.IsFederatedCopy) if (!post.IsFederatedCopy)
@@ -59,7 +49,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
?? await DB.Default.Find<ObjectRecord>().Match(r => r.ObjectURI == post.ObjectURI).ExecuteFirstAsync(token); ?? await DB.Default.Find<ObjectRecord>().Match(r => r.ObjectURI == post.ObjectURI).ExecuteFirstAsync(token);
var host = record?.Host ?? (Uri.TryCreate(post.ObjectURI, UriKind.Absolute, out var uri) ? uri.Host.ToLowerInvariant() : default); var host = record?.Host ?? (Uri.TryCreate(post.ObjectURI, UriKind.Absolute, out var uri) ? uri.Host.ToLowerInvariant() : default);
var instance = host == default ? default : await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteFirstAsync(token); var instance = host == default ? default : await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteFirstAsync(token);
var beforeCdn = instance?.Geo?.Cdn == default ? default : (await _places.BeforeCdn(new[] { instance.Host }, token)).GetValueOrDefault(instance.Host); var beforeCdn = instance?.Geo?.Cdn == default ? default : (await places.BeforeCdn(new[] { instance.Host }, token)).GetValueOrDefault(instance.Host);
return Json(Describe(post, record, instance, beforeCdn)); return Json(Describe(post, record, instance, beforeCdn));
} }
@@ -82,7 +72,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (string.IsNullOrEmpty(host) || host.Length > 253 || !await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteAnyAsync(token)) if (string.IsNullOrEmpty(host) || host.Length > 253 || !await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteAnyAsync(token))
return NotFoundError(); return NotFoundError();
var weeks = Math.Clamp(Params.Int("weeks") ?? 52, 1, MaxWeeks); var weeks = Math.Clamp(Params.Int("weeks") ?? 52, 1, MaxWeeks);
return Json((await _places.History(host, weeks, token)).Select(s => new InstanceWeek return Json((await places.History(host, weeks, token)).Select(s => new InstanceWeek
{ {
Week = s.Week, Week = s.Week,
TakenAt = MastodonJson.Time(s.TakenAt), TakenAt = MastodonJson.Time(s.TakenAt),
@@ -105,9 +95,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var wanted = hosts.Select(h => h?.Trim().ToLowerInvariant()).Where(h => !string.IsNullOrEmpty(h) && h.Length <= 253) var wanted = hosts.Select(h => h?.Trim().ToLowerInvariant()).Where(h => !string.IsNullOrEmpty(h) && h.Length <= 253)
.Distinct().Take(MaxHosts).ToList(); .Distinct().Take(MaxHosts).ToList();
var selfHost = Uri.TryCreate(_localActors.BaseAddress, UriKind.Absolute, out var self) ? self.Host.ToLowerInvariant() : default; var selfHost = Uri.TryCreate(localActors.BaseAddress, UriKind.Absolute, out var self) ? self.Host.ToLowerInvariant() : default;
var remote = await DB.Default.Find<RemoteInstance>().Match(i => wanted.Contains(i.Host)).ExecuteAsync(token); var remote = await DB.Default.Find<RemoteInstance>().Match(i => wanted.Contains(i.Host)).ExecuteAsync(token);
var beforeCdn = await _places.BeforeCdn(remote.Where(i => i.Geo?.Cdn != default).Select(i => i.Host), token); var beforeCdn = await places.BeforeCdn(remote.Where(i => i.Geo?.Cdn != default).Select(i => i.Host), token);
var described = new List<InstanceDescription>(); var described = new List<InstanceDescription>();
foreach (var host in wanted) foreach (var host in wanted)
{ {
@@ -121,7 +111,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<InstanceDescription> DescribeSelf(string host, CancellationToken token) async Task<InstanceDescription> DescribeSelf(string host, CancellationToken token)
{ {
var geo = await _self.Get(token); var geo = await selfLocation.Get(token);
return new InstanceDescription return new InstanceDescription
{ {
Host = host, Host = host,
@@ -129,7 +119,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
Version = BuildInfo.Ref, Version = BuildInfo.Ref,
NodeName = HttpContext.RequestServices.GetRequiredService<Domain.Instance.IInstanceSettings>().Current.Title, NodeName = HttpContext.RequestServices.GetRequiredService<Domain.Instance.IInstanceSettings>().Current.Title,
Protocols = new() { "activitypub" }, Protocols = new() { "activitypub" },
OpenRegistrations = _registrations.CurrentValue.IsOpen, OpenRegistrations = registrations.CurrentValue.IsOpen,
DescribedAt = MastodonJson.Time(DateTime.UtcNow), DescribedAt = MastodonJson.Time(DateTime.UtcNow),
Geo = Located(PublicGeo.Project(geo), geo) Geo = Located(PublicGeo.Project(geo), geo)
}; };
@@ -21,18 +21,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
// subscription[endpoint], subscription[keys][p256dh], subscription[keys][auth], subscription[standard] (4.4: RFC 8291 // subscription[endpoint], subscription[keys][p256dh], subscription[keys][auth], subscription[standard] (4.4: RFC 8291
// and RFC 8292, else the aesgcm draft), data[alerts][<type>] and data[policy] (all, followed, follower, none). Its answer is // and RFC 8292, else the aesgcm draft), data[alerts][<type>] and data[policy] (all, followed, follower, none). Its answer is
// Mastodon's WebPushSubscription. What is pushed, and how, is WebPushDispatcher's and WebPushJob's. // Mastodon's WebPushSubscription. What is pushed, and how, is WebPushDispatcher's and WebPushJob's.
public class PushController : MastodonController public class PushController(
IVapid vapid,
IOptionsMonitor<FederationOptions> federation) : MastodonController
{ {
const int MaxEndpointLength = 2048; const int MaxEndpointLength = 2048;
readonly IVapid _vapid;
readonly IOptionsMonitor<FederationOptions> _federation;
public PushController(IVapid vapid, IOptionsMonitor<FederationOptions> federation)
{
_vapid = vapid;
_federation = federation;
}
string TokenId => User.GetTokenId(); string TokenId => User.GetTokenId();
@@ -43,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var endpoint = Params.Get("subscription[endpoint]")?.Trim(); var endpoint = Params.Get("subscription[endpoint]")?.Trim();
if (string.IsNullOrEmpty(endpoint)) if (string.IsNullOrEmpty(endpoint))
return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: subscription"); return Error(StatusCodes.Status400BadRequest, "Param is missing or the value is empty: subscription");
if (endpoint.Length > MaxEndpointLength || !Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || !WebPushJob.IsAllowed(uri, _federation.CurrentValue)) if (endpoint.Length > MaxEndpointLength || !Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) || !WebPushJob.IsAllowed(uri, federation.CurrentValue))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Endpoint is not a valid URL"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Endpoint is not a valid URL");
var p256dh = Params.Get("subscription[keys][p256dh]")?.Trim(); var p256dh = Params.Get("subscription[keys][p256dh]")?.Trim();
var auth = Params.Get("subscription[keys][auth]")?.Trim(); var auth = Params.Get("subscription[keys][auth]")?.Trim();
@@ -55,7 +49,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (invalid != default) if (invalid != default)
return invalid; return invalid;
var tokenId = TokenId; var tokenId = TokenId;
var accessToken = await AccessToken(); var accessToken = await AccessToken(token);
if (string.IsNullOrEmpty(tokenId) || string.IsNullOrEmpty(accessToken)) if (string.IsNullOrEmpty(tokenId) || string.IsNullOrEmpty(accessToken))
return Error(StatusCodes.Status401Unauthorized, "The access token is invalid"); return Error(StatusCodes.Status401Unauthorized, "The access token is invalid");
@@ -74,7 +68,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
// (two at once with one token: the unique index on the token keeps one, and the later replaces it) // (two at once with one token: the unique index on the token keeps one, and the later replaces it)
for (var attempt = 0; ; attempt++) for (var attempt = 0; ; attempt++)
{ {
await WebPush.ForgetToken(tokenId); await WebPush.ForgetToken(tokenId, token);
try try
{ {
subscription.ID = default; subscription.ID = default;
@@ -116,7 +110,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpDelete("/api/v1/push/subscription"), Scope("push")] [HttpDelete("/api/v1/push/subscription"), Scope("push")]
public async Task<IActionResult> Delete(CancellationToken token) public async Task<IActionResult> Delete(CancellationToken token)
{ {
await WebPush.ForgetToken(TokenId); await WebPush.ForgetToken(TokenId, token);
return Json(new { }); return Json(new { });
} }
@@ -143,7 +137,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
// the bearer token of this request, wherever the client put it (OpenIddict takes the header, a form field or the // the bearer token of this request, wherever the client put it (OpenIddict takes the header, a form field or the
// query): the payload carries it back, as Mastodon's does // query): the payload carries it back, as Mastodon's does
async Task<string> AccessToken() async Task<string> AccessToken(CancellationToken token = default)
{ {
var stored = await HttpContext.GetTokenAsync(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme, var stored = await HttpContext.GetTokenAsync(OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme,
OpenIddictValidationAspNetCoreConstants.Tokens.AccessToken); OpenIddictValidationAspNetCoreConstants.Tokens.AccessToken);
@@ -162,7 +156,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
endpoint = subscription.Endpoint, endpoint = subscription.Endpoint,
standard = subscription.Standard, standard = subscription.Standard,
alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)), alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)),
server_key = (await _vapid.Key(token)).ForApi, server_key = (await vapid.Key(token)).ForApi,
policy = WebPush.Name(subscription.Policy) policy = WebPush.Name(subscription.Policy)
}; };
} }
@@ -15,19 +15,11 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class ReactionsController : MastodonController public class ReactionsController(
DbEntities dbEntities,
MastodonMapper mapper,
IReactions reactionService) : MastodonController
{ {
readonly DbEntities _dbEntities;
readonly MastodonMapper _mapper;
readonly IReactions _reactions;
public ReactionsController(DbEntities dbEntities, MastodonMapper mapper, IReactions reactions)
{
_dbEntities = dbEntities;
_mapper = mapper;
_reactions = reactions;
}
[HttpGet("/api/v1/pleroma/statuses/{id}/reactions"), Scope("read:statuses", requiresUser: false), AllowAnonymous] [HttpGet("/api/v1/pleroma/statuses/{id}/reactions"), Scope("read:statuses", requiresUser: false), AllowAnonymous]
public async Task<IActionResult> List(string id, CancellationToken token) public async Task<IActionResult> List(string id, CancellationToken token)
{ {
@@ -35,13 +27,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (post == default) if (post == default)
return NotFoundError(); return NotFoundError();
var reactions = await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID).ExecuteAsync(token); var reactions = await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID).ExecuteAsync(token);
var accounts = await _mapper.Accounts(reactions.Select(r => r.AccountId), token); var accounts = await mapper.Accounts(reactions.Select(r => r.AccountId), token);
return Json(reactions.GroupBy(r => r.Emoji).Select(group => new return Json(reactions.GroupBy(r => r.Emoji).Select(group => new
{ {
name = group.Key, name = group.Key,
count = group.Count(), count = group.Count(),
me = MyId != default && group.Any(r => r.AccountId == MyId), me = MyId != default && group.Any(r => r.AccountId == MyId),
url = _mapper.ProxiedUrl(group.First().EmojiURL), url = mapper.ProxiedUrl(group.First().EmojiURL),
accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList() accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList()
}).OrderByDescending(r => r.count).ToList()); }).OrderByDescending(r => r.count).ToList());
} }
@@ -52,9 +44,9 @@ namespace PrivaPub.Api.Mastodon.Controllers
var post = await Visible(id, token); var post = await Visible(id, token);
if (post == default) if (post == default)
return NotFoundError(); return NotFoundError();
if (!await _reactions.React(Me, post, Uri.UnescapeDataString(emoji), token)) if (!await reactionService.React(Me, post, Uri.UnescapeDataString(emoji), token))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: That emoji cannot be used here"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: That emoji cannot be used here");
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
[HttpDelete("/api/v1/pleroma/statuses/{id}/reactions/{emoji}"), Scope("write:favourites")] [HttpDelete("/api/v1/pleroma/statuses/{id}/reactions/{emoji}"), Scope("write:favourites")]
@@ -63,13 +55,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
var post = await Visible(id, token); var post = await Visible(id, token);
if (post == default) if (post == default)
return NotFoundError(); return NotFoundError();
await _reactions.Unreact(Me, post, Uri.UnescapeDataString(emoji), token); await reactionService.Unreact(Me, post, Uri.UnescapeDataString(emoji), token);
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
async Task<PostEntity> Visible(string id, CancellationToken token) async Task<PostEntity> Visible(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default; return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default;
} }
} }
@@ -6,21 +6,14 @@ using PrivaPub.Domain.Relationships;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class ReportsController : MastodonController public class ReportsController(
IReportService reportService,
MastodonMapper mapper) : MastodonController
{ {
readonly IReportService _reports;
readonly MastodonMapper _mapper;
public ReportsController(IReportService reports, MastodonMapper mapper)
{
_reports = reports;
_mapper = mapper;
}
[HttpPost("/api/v1/reports"), Scope("write:reports")] [HttpPost("/api/v1/reports"), Scope("write:reports")]
public async Task<IActionResult> Create(CancellationToken token) public async Task<IActionResult> Create(CancellationToken token)
{ {
var report = await _reports.File(Me, Params.Get("account_id"), Params.List("status_ids"), Params.Get("comment"), Params.Get("category"), var report = await reportService.File(Me, Params.Get("account_id"), Params.List("status_ids"), Params.Get("comment"), Params.Get("category"),
Params.List("rule_ids"), Params.Bool("forward") == true, token); Params.List("rule_ids"), Params.Bool("forward") == true, token);
if (report == default) if (report == default)
return NotFoundError(); return NotFoundError();
@@ -35,7 +28,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
created_at = MastodonJson.Time(report.CreatedAt), created_at = MastodonJson.Time(report.CreatedAt),
status_ids = report.PostIds, status_ids = report.PostIds,
rule_ids = report.RuleIds, rule_ids = report.RuleIds,
target_account = await _mapper.Account(report.TargetAccountId, token) target_account = await mapper.Account(report.TargetAccountId, token)
}); });
} }
} }
@@ -13,17 +13,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// Mastodon's scheduled statuses (owner decision 2026-10-04, back from the cut list): the persona's posts waiting for // Mastodon's scheduled statuses (owner decision 2026-10-04, back from the cut list): the persona's posts waiting for
// their time, moved to another time or dropped. POST /api/v1/statuses with scheduled_at makes them. // their time, moved to another time or dropped. POST /api/v1/statuses with scheduled_at makes them.
public class ScheduledStatusesController : MastodonController public class ScheduledStatusesController(
IMediaService mediaService,
IJobQueue jobs) : MastodonController
{ {
readonly IMediaService _media;
readonly IJobQueue _jobs;
public ScheduledStatusesController(IMediaService media, IJobQueue jobs)
{
_media = media;
_jobs = jobs;
}
public static async Task<object> View(ScheduledStatus scheduled, IMediaService media, CancellationToken token) public static async Task<object> View(ScheduledStatus scheduled, IMediaService media, CancellationToken token)
{ {
var p = scheduled.Params; var p = scheduled.Params;
@@ -66,13 +59,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
Link("/api/v1/scheduled_statuses", page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID); Link("/api/v1/scheduled_statuses", page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID);
var views = new List<object>(); var views = new List<object>();
foreach (var scheduled in page) foreach (var scheduled in page)
views.Add(await View(scheduled, _media, token)); views.Add(await View(scheduled, mediaService, token));
return Json(views); return Json(views);
} }
[HttpGet("/api/v1/scheduled_statuses/{id}"), Scope("read:statuses")] [HttpGet("/api/v1/scheduled_statuses/{id}"), Scope("read:statuses")]
public async Task<IActionResult> One(string id, CancellationToken token) => public async Task<IActionResult> One(string id, CancellationToken token) =>
await Mine(id, token) is { } scheduled ? Json(await View(scheduled, _media, token)) : NotFoundError(); await Mine(id, token) is { } scheduled ? Json(await View(scheduled, mediaService, token)) : NotFoundError();
[HttpPut("/api/v1/scheduled_statuses/{id}"), Scope("write:statuses")] [HttpPut("/api/v1/scheduled_statuses/{id}"), Scope("write:statuses")]
public async Task<IActionResult> Move(string id, CancellationToken token) public async Task<IActionResult> Move(string id, CancellationToken token)
@@ -86,8 +79,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: " + refusal); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: " + refusal);
scheduled.ScheduledAt = at; scheduled.ScheduledAt = at;
await DB.Default.Update<ScheduledStatus>().MatchID(scheduled.ID).Modify(s => s.ScheduledAt, at).ExecuteAsync(token); await DB.Default.Update<ScheduledStatus>().MatchID(scheduled.ID).Modify(s => s.ScheduledAt, at).ExecuteAsync(token);
await _jobs.EnqueueMany(new[] { ScheduledStatuses.JobFor(scheduled, new Uri(Me.BaseAddress).Host) }, token); await jobs.EnqueueMany(new[] { ScheduledStatuses.JobFor(scheduled, new Uri(Me.BaseAddress).Host) }, token);
return Json(await View(scheduled, _media, token)); return Json(await View(scheduled, mediaService, token));
} }
[HttpDelete("/api/v1/scheduled_statuses/{id}"), Scope("write:statuses")] [HttpDelete("/api/v1/scheduled_statuses/{id}"), Scope("write:statuses")]
@@ -97,7 +90,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID); await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID);
// its media were the scheduled post's alone, never posted // its media were the scheduled post's alone, never posted
await _media.Trash(m => m.ScheduledStatusId == scheduled.ID, "scheduled post dropped", token); await mediaService.Trash(m => m.ScheduledStatusId == scheduled.ID, "scheduled post dropped", token);
return Json(new { }); return Json(new { });
} }
} }
@@ -15,26 +15,14 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public partial class SearchController : MastodonController public partial class SearchController(
MastodonMapper mapper,
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IRemotePosts remotePosts,
AccountSearch accountSearch) : MastodonController
{ {
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IRemotePosts _remotePosts;
readonly AccountSearch _search;
public SearchController(MastodonMapper mapper, DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors,
IRemotePosts remotePosts, AccountSearch search)
{
_mapper = mapper;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_remotePosts = remotePosts;
_search = search;
}
// Anyone may search, as on Mastodon; only resolving (which fetches from other servers) and paging need a sign-in. // Anyone may search, as on Mastodon; only resolving (which fetches from other servers) and paging need a sign-in.
[HttpGet("/api/v2/search"), Scope("read:search", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v2/search"), Scope("read:search", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Search(CancellationToken token) public async Task<IActionResult> Search(CancellationToken token)
@@ -51,33 +39,33 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (q.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) if (q.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{ {
var post = await _dbEntities.Posts.Match(p => (p.ObjectURI == q || p.Url == q) && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => (p.ObjectURI == q || p.Url == q) && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (post == default && resolve && type is null or "statuses") if (post == default && resolve && type is null or "statuses")
post = await _remotePosts.StoreContext(q, 0, token); post = await remotePosts.StoreContext(q, 0, token);
if (post != default && type is null or "statuses" && await VisibilityPolicy.CanSee(post, MyId, token)) if (post != default && type is null or "statuses" && await VisibilityPolicy.CanSee(post, MyId, token))
if (await _mapper.Status(post, MyId, token) is { } status) if (await mapper.Status(post, MyId, token) is { } status)
results.Statuses.Add(status); results.Statuses.Add(status);
if (results.Statuses.Count == 0 && type is null or "accounts") if (results.Statuses.Count == 0 && type is null or "accounts")
{ {
var local = await _localActors.FindByUri(q, token); var local = await localActors.FindByUri(q, token);
var foreign = local == default ? (resolve ? await _remoteActors.GetActor(q, refresh: false, token) : default) : default; var foreign = local == default ? (resolve ? await remoteActors.GetActor(q, refresh: false, token) : default) : default;
if (local is { IsFederated: true, IsCircle: false }) if (local is { IsFederated: true, IsCircle: false })
results.Accounts.Add(await _mapper.Local(local, false, token)); results.Accounts.Add(await mapper.Local(local, false, token));
else if (foreign != default) else if (foreign != default)
results.Accounts.Add(_mapper.Foreign(foreign)); results.Accounts.Add(mapper.Foreign(foreign));
} }
return Json(results); return Json(results);
} }
if (type is null or "accounts") if (type is null or "accounts")
{ {
results.Accounts = await _search.Find(q, resolve, Limit(), Math.Max(0, offset), token); results.Accounts = await accountSearch.Find(q, resolve, Limit(), Math.Max(0, offset), token);
} }
// an account's handle asks for the account, never for posts that happen to share its words // an account's handle asks for the account, never for posts that happen to share its words
if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q)) if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q))
results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token); results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token);
if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag)) if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag))
results.Hashtags.Add(new { name = tag, url = $"{_localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", history = await TagsController.History(_dbEntities, tag, token) }); results.Hashtags.Add(new { name = tag, url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", history = await TagsController.History(dbEntities, tag, token) });
return Json(results); return Json(results);
} }
} }
@@ -93,27 +81,27 @@ namespace PrivaPub.Api.Mastodon.Controllers
// named in, and public posts of authors who let themselves be indexed; newest first, what the persona may see only // named in, and public posts of authors who let themselves be indexed; newest first, what the persona may see only
async Task<List<Status>> Words(string q, int offset, int limit, CancellationToken token) async Task<List<Status>> Words(string q, int offset, int limit, CancellationToken token)
{ {
var candidates = await _dbEntities.Posts.Match(f => f.Text(q)).Match(p => p.ReblogOfPostId == null).Match(VisibilityPolicy.IsShown) var candidates = await dbEntities.Posts.Match(f => f.Text(q)).Match(p => p.ReblogOfPostId == null).Match(VisibilityPolicy.IsShown)
.Sort(p => p.ID, MongoDB.Entities.Order.Descending).Limit(WordCandidates).ExecuteAsync(token); .Sort(p => p.ID, MongoDB.Entities.Order.Descending).Limit(WordCandidates).ExecuteAsync(token);
if (candidates.Count == 0) if (candidates.Count == 0)
return new List<Status>(); return new List<Status>();
var ids = candidates.Select(p => p.ID).ToList(); var ids = candidates.Select(p => p.ID).ToList();
var mine = new HashSet<string>(); var mine = new HashSet<string>();
mine.UnionWith((await _dbEntities.Favourites.Match(f => f.AccountId == MyId && ids.Contains(f.PostId)).ExecuteAsync(token)).Select(f => f.PostId)); mine.UnionWith((await dbEntities.Favourites.Match(f => f.AccountId == MyId && ids.Contains(f.PostId)).ExecuteAsync(token)).Select(f => f.PostId));
mine.UnionWith((await MongoDB.Entities.DB.Default.Find<Models.Social.Bookmark>().Match(b => b.AvatarId == MyId && ids.Contains(b.PostId)).ExecuteAsync(token)) mine.UnionWith((await MongoDB.Entities.DB.Default.Find<Models.Social.Bookmark>().Match(b => b.AvatarId == MyId && ids.Contains(b.PostId)).ExecuteAsync(token))
.Select(b => b.PostId)); .Select(b => b.PostId));
mine.UnionWith((await _dbEntities.Posts.Match(p => p.AuthorAccountId == MyId && ids.Contains(p.ReblogOfPostId) && !p.DeletedAt.HasValue).ExecuteAsync(token)) mine.UnionWith((await dbEntities.Posts.Match(p => p.AuthorAccountId == MyId && ids.Contains(p.ReblogOfPostId) && !p.DeletedAt.HasValue).ExecuteAsync(token))
.Select(p => p.ReblogOfPostId)); .Select(p => p.ReblogOfPostId));
var authors = candidates.Select(p => p.AuthorAccountId ?? p.GroupUserId).Where(a => a != default).Distinct().ToList(); var authors = candidates.Select(p => p.AuthorAccountId ?? p.GroupUserId).Where(a => a != default).Distinct().ToList();
var indexable = (await _dbEntities.Avatars.Match(a => authors.Contains(a.ID) && a.Settings.IsIndexable).ExecuteAsync(token)).Select(a => a.ID).ToHashSet(); var indexable = (await dbEntities.Avatars.Match(a => authors.Contains(a.ID) && a.Settings.IsIndexable).ExecuteAsync(token)).Select(a => a.ID).ToHashSet();
// a remote author's searchableBy (FEP-268d) outranks its indexable, and a post's own outranks both // a remote author's searchableBy (FEP-268d) outranks its indexable, and a post's own outranks both
var remoteAuthors = (await _dbEntities.ForeignAvatars.Match(f => authors.Contains(f.ID)).ExecuteAsync(token)).ToDictionary(f => f.ID); var remoteAuthors = (await dbEntities.ForeignAvatars.Match(f => authors.Contains(f.ID)).ExecuteAsync(token)).ToDictionary(f => f.ID);
var stating = remoteAuthors.Values.Where(f => f.SearchableBy != default).Select(f => f.ActorURI) var stating = remoteAuthors.Values.Where(f => f.SearchableBy != default).Select(f => f.ActorURI)
.Concat(candidates.Where(p => p.SearchableBy != default).Select(p => p.ActorURI)) .Concat(candidates.Where(p => p.SearchableBy != default).Select(p => p.ActorURI))
.Where(uri => uri != default).Distinct().ToList(); .Where(uri => uri != default).Distinct().ToList();
var followed = stating.Count == 0 var followed = stating.Count == 0
? new HashSet<string>() ? new HashSet<string>()
: (await _dbEntities.Followings.Match(f => f.AvatarId == MyId && stating.Contains(f.TargetActorURI) && f.State == Models.Social.FollowState.Accepted) : (await dbEntities.Followings.Match(f => f.AvatarId == MyId && stating.Contains(f.TargetActorURI) && f.State == Models.Social.FollowState.Accepted)
.ExecuteAsync(token)).Select(f => f.TargetActorURI).ToHashSet(); .ExecuteAsync(token)).Select(f => f.TargetActorURI).ToHashSet();
bool Searchable(PostEntity post, string author) bool Searchable(PostEntity post, string author)
{ {
@@ -134,7 +122,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (found.Count >= offset + limit) if (found.Count >= offset + limit)
break; break;
} }
return await _mapper.Statuses(found.Skip(offset).Take(limit).ToList(), MyId, token); return await mapper.Statuses(found.Skip(offset).Take(limit).ToList(), MyId, token);
} }
} }
@@ -19,49 +19,33 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class StatusesController : MastodonController public class StatusesController(
IStatusService statusService,
MastodonMapper mapper,
DbEntities dbEntities,
IMemoryCache cache,
IQuoteService quoteService,
IOutboxPublisher outbox,
PrivaPub.Infrastructure.Jobs.IJobQueue jobs,
Domain.Media.IMediaService mediaService,
IParticipations participations = default,
Federation.Actors.IWalls walls = default) : MastodonController
{ {
const int MaxContext = 200; const int MaxContext = 200;
public const int MaxPins = 5; public const int MaxPins = 5;
readonly IStatusService _statuses;
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
readonly IMemoryCache _cache;
readonly IQuoteService _quotes;
readonly IOutboxPublisher _outbox;
readonly PrivaPub.Infrastructure.Jobs.IJobQueue _jobs;
readonly Domain.Media.IMediaService _media;
readonly IParticipations _participations;
readonly Federation.Actors.IWalls _walls;
public StatusesController(IStatusService statuses, MastodonMapper mapper, DbEntities dbEntities, IMemoryCache cache, IQuoteService quotes,
IOutboxPublisher outbox, PrivaPub.Infrastructure.Jobs.IJobQueue jobs, Domain.Media.IMediaService media, IParticipations participations = default,
Federation.Actors.IWalls walls = default)
{
_walls = walls;
_participations = participations;
_jobs = jobs;
_media = media;
_quotes = quotes;
_outbox = outbox;
_statuses = statuses;
_mapper = mapper;
_dbEntities = dbEntities;
_cache = cache;
}
[HttpPost("/api/v1/statuses"), Scope("write:statuses")] [HttpPost("/api/v1/statuses"), Scope("write:statuses")]
public async Task<IActionResult> Create(CancellationToken token) public async Task<IActionResult> Create(CancellationToken token)
{ {
var idempotency = Request.Headers["Idempotency-Key"].ToString(); var idempotency = Request.Headers["Idempotency-Key"].ToString();
var cacheKey = string.IsNullOrEmpty(idempotency) ? default : $"idempotency:{MyId}:{idempotency}"; var cacheKey = string.IsNullOrEmpty(idempotency) ? default : $"idempotency:{MyId}:{idempotency}";
if (cacheKey != default && _cache.TryGetValue(cacheKey, out string earlier)) if (cacheKey != default && cache.TryGetValue(cacheKey, out string earlier))
{ {
var existing = await _dbEntities.Posts.MatchID(earlier).ExecuteFirstAsync(token); var existing = await dbEntities.Posts.MatchID(earlier).ExecuteFirstAsync(token);
if (existing != default) if (existing != default)
return Json(await _mapper.Status(existing, MyId, token)); return Json(await mapper.Status(existing, MyId, token));
} }
var asked = new ScheduledParams var asked = new ScheduledParams
{ {
@@ -87,21 +71,21 @@ namespace PrivaPub.Api.Mastodon.Controllers
}; };
if (Params.Get("scheduled_at") is { Length: > 0 } scheduledAt) if (Params.Get("scheduled_at") is { Length: > 0 } scheduledAt)
return await Schedule(asked, scheduledAt, cacheKey, token); return await Schedule(asked, scheduledAt, cacheKey, token);
var outcome = await _statuses.Publish(Me, ScheduledStatuses.Draft(asked), token); var outcome = await statusService.Publish(Me, ScheduledStatuses.Draft(asked), token);
if (!outcome.Ok) if (!outcome.Ok)
return Error(outcome.Status, outcome.Error); return Error(outcome.Status, outcome.Error);
if (cacheKey != default) if (cacheKey != default)
_cache.Set(cacheKey, outcome.Post.ID, TimeSpan.FromHours(1)); cache.Set(cacheKey, outcome.Post.ID, TimeSpan.FromHours(1));
return Json(await _mapper.Status(outcome.Post, MyId, token)); return Json(await mapper.Status(outcome.Post, MyId, token));
} }
// scheduled_at: the post waits, as asked, for a PublishScheduled job at that time; what it would need then (words, // scheduled_at: the post waits, as asked, for a PublishScheduled job at that time; what it would need then (words,
// media of the persona's own, not yet posted) is checked now // media of the persona's own, not yet posted) is checked now
async Task<IActionResult> Schedule(ScheduledParams asked, string scheduledAt, string cacheKey, CancellationToken token) async Task<IActionResult> Schedule(ScheduledParams asked, string scheduledAt, string cacheKey, CancellationToken token)
{ {
if (cacheKey != default && _cache.TryGetValue(cacheKey + ":scheduled", out string earlier) if (cacheKey != default && cache.TryGetValue(cacheKey + ":scheduled", out string earlier)
&& await DB.Default.Find<ScheduledStatus>().MatchID(earlier).ExecuteFirstAsync(token) is { } waiting) && await DB.Default.Find<ScheduledStatus>().MatchID(earlier).ExecuteFirstAsync(token) is { } waiting)
return Json(await ScheduledStatusesController.View(waiting, _media, token)); return Json(await ScheduledStatusesController.View(waiting, mediaService, token));
if (!DateTime.TryParse(scheduledAt, System.Globalization.CultureInfo.InvariantCulture, if (!DateTime.TryParse(scheduledAt, System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out var at)) System.Globalization.DateTimeStyles.AdjustToUniversal | System.Globalization.DateTimeStyles.AssumeUniversal, out var at))
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Scheduled at is invalid"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Scheduled at is invalid");
@@ -131,36 +115,36 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
} }
await DB.Default.SaveAsync(scheduled, token); await DB.Default.SaveAsync(scheduled, token);
await _jobs.EnqueueMany(new[] { ScheduledStatuses.JobFor(scheduled, new Uri(Me.BaseAddress).Host) }, token); await jobs.EnqueueMany(new[] { ScheduledStatuses.JobFor(scheduled, new Uri(Me.BaseAddress).Host) }, token);
if (cacheKey != default) if (cacheKey != default)
_cache.Set(cacheKey + ":scheduled", scheduled.ID, TimeSpan.FromHours(1)); cache.Set(cacheKey + ":scheduled", scheduled.ID, TimeSpan.FromHours(1));
return Json(await ScheduledStatusesController.View(scheduled, _media, token)); return Json(await ScheduledStatusesController.View(scheduled, mediaService, token));
} }
[HttpGet("/api/v1/statuses"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/statuses"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Many(CancellationToken token) public async Task<IActionResult> Many(CancellationToken token)
{ {
var ids = Params.List("id").Take(20).ToList(); var ids = Params.List("id").Take(20).ToList();
var posts = await _dbEntities.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token); var posts = await dbEntities.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token);
var visible = new List<PostEntity>(); var visible = new List<PostEntity>();
foreach (var post in posts) foreach (var post in posts)
if (await VisibilityPolicy.CanSee(post, MyId, token)) if (await VisibilityPolicy.CanSee(post, MyId, token))
visible.Add(post); visible.Add(post);
return Json(await _mapper.Statuses(visible, MyId, token)); return Json(await mapper.Statuses(visible, MyId, token));
} }
[HttpGet("/api/v1/statuses/{id}"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/statuses/{id}"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Get(string id, CancellationToken token) public async Task<IActionResult> Get(string id, CancellationToken token)
{ {
var post = await Visible(id, token); var post = await Visible(id, token);
var status = post == default ? default : await _mapper.Status(post, MyId, token); var status = post == default ? default : await mapper.Status(post, MyId, token);
return status == default ? NotFoundError() : Json(status); return status == default ? NotFoundError() : Json(status);
} }
[HttpPut("/api/v1/statuses/{id}"), Scope("write:statuses")] [HttpPut("/api/v1/statuses/{id}"), Scope("write:statuses")]
public async Task<IActionResult> Edit(string id, CancellationToken token) public async Task<IActionResult> Edit(string id, CancellationToken token)
{ {
var outcome = await _statuses.Edit(Me, id, new StatusDraft var outcome = await statusService.Edit(Me, id, new StatusDraft
{ {
Text = Params.Get("status"), Text = Params.Get("status"),
PlainText = true, PlainText = true,
@@ -170,7 +154,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
MediaIds = Params.Has("media_ids") ? Params.List("media_ids") : default, MediaIds = Params.Has("media_ids") ? Params.List("media_ids") : default,
MediaChanges = MediaAttributes() MediaChanges = MediaAttributes()
}, token); }, token);
return outcome.Ok ? Json(await _mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error); return outcome.Ok ? Json(await mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error);
} }
// Mastodon's media_attributes: a JSON body's array of objects, or a form's media_attributes[i][field] or // Mastodon's media_attributes: a JSON body's array of objects, or a form's media_attributes[i][field] or
@@ -205,11 +189,11 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpDelete("/api/v1/statuses/{id}"), Scope("write:statuses")] [HttpDelete("/api/v1/statuses/{id}"), Scope("write:statuses")]
public async Task<IActionResult> Delete(string id, CancellationToken token) public async Task<IActionResult> Delete(string id, CancellationToken token)
{ {
var before = await _dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var before = await dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (before == default) if (before == default)
return await OffWall(id, token); return await OffWall(id, token);
var status = await _mapper.Status(before, MyId, token); var status = await mapper.Status(before, MyId, token);
var outcome = await _statuses.Remove(Me, id, token); var outcome = await statusService.Remove(Me, id, token);
if (!outcome.Ok) if (!outcome.Ok)
return Error(outcome.Status, outcome.Error); return Error(outcome.Status, outcome.Error);
if (status != default) if (status != default)
@@ -223,13 +207,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
// someone's post on the persona's wall (FEP-400e), taken off it: as on Smithereen, the owner of a wall deletes what is on it // someone's post on the persona's wall (FEP-400e), taken off it: as on Smithereen, the owner of a wall deletes what is on it
async Task<IActionResult> OffWall(string id, CancellationToken token) async Task<IActionResult> OffWall(string id, CancellationToken token)
{ {
var walled = _walls == default var walled = walls == default
? default ? default
: await _dbEntities.Posts.Match(p => p.ID == id && p.WallOwnerAccountId == MyId && p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); : await dbEntities.Posts.Match(p => p.ID == id && p.WallOwnerAccountId == MyId && p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (walled == default) if (walled == default)
return NotFoundError(); return NotFoundError();
var status = await _mapper.Status(walled, MyId, token); var status = await mapper.Status(walled, MyId, token);
if (!await _walls.Remove(Me, walled, token)) if (!await walls.Remove(Me, walled, token))
return NotFoundError(); return NotFoundError();
return Json(status); return Json(status);
} }
@@ -245,7 +229,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var cursor = post; var cursor = post;
while (!string.IsNullOrEmpty(cursor.AnsweringToPostId) && ancestors.Count < MaxContext) while (!string.IsNullOrEmpty(cursor.AnsweringToPostId) && ancestors.Count < MaxContext)
{ {
cursor = await _dbEntities.Posts.MatchID(cursor.AnsweringToPostId).ExecuteFirstAsync(token); cursor = await dbEntities.Posts.MatchID(cursor.AnsweringToPostId).ExecuteFirstAsync(token);
if (cursor == default || cursor.DeletedAt.HasValue || !await VisibilityPolicy.CanSee(cursor, MyId, token)) if (cursor == default || cursor.DeletedAt.HasValue || !await VisibilityPolicy.CanSee(cursor, MyId, token))
break; break;
ancestors.Insert(0, cursor); ancestors.Insert(0, cursor);
@@ -256,7 +240,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
while (frontier.Count > 0 && descendants.Count < MaxContext) while (frontier.Count > 0 && descendants.Count < MaxContext)
{ {
var parents = frontier; var parents = frontier;
var children = await _dbEntities.Posts.Match(p => parents.Contains(p.AnsweringToPostId) && !p.DeletedAt.HasValue && p.ReblogOfPostId == null) var children = await dbEntities.Posts.Match(p => parents.Contains(p.AnsweringToPostId) && !p.DeletedAt.HasValue && p.ReblogOfPostId == null)
.Sort(p => p.ID, Order.Ascending).Limit(MaxContext).ExecuteAsync(token); .Sort(p => p.ID, Order.Ascending).Limit(MaxContext).ExecuteAsync(token);
frontier = new List<string>(); frontier = new List<string>();
foreach (var child in children) foreach (var child in children)
@@ -268,13 +252,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
// a persona opening a public remote thread has its replies read from their servers, for the next look (once an hour) // a persona opening a public remote thread has its replies read from their servers, for the next look (once an hour)
if (MyId != default) if (MyId != default)
await _jobs.EnqueueMany(new[] { post, ancestors.FirstOrDefault() } await jobs.EnqueueMany(new[] { post, ancestors.FirstOrDefault() }
.Where(p => p is { IsFederatedCopy: true, Visibility: PostVisibility.Public or PostVisibility.Unlisted }).DistinctBy(p => p.ID) .Where(p => p is { IsFederatedCopy: true, Visibility: PostVisibility.Public or PostVisibility.Unlisted }).DistinctBy(p => p.ID)
.Select(p => Federation.Inbox.RepliesJobHandler.For(p, 1)), token); .Select(p => Federation.Inbox.RepliesJobHandler.For(p, 1)), token);
return Json(new Context return Json(new Context
{ {
Ancestors = await _mapper.Statuses(ancestors, MyId, token), Ancestors = await mapper.Statuses(ancestors, MyId, token),
Descendants = await _mapper.Statuses(descendants.OrderBy(d => d.ID, StringComparer.Ordinal).ToList(), MyId, token) Descendants = await mapper.Statuses(descendants.OrderBy(d => d.ID, StringComparer.Ordinal).ToList(), MyId, token)
}); });
} }
@@ -284,7 +268,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
var post = await Visible(id, token); var post = await Visible(id, token);
if (post == default) if (post == default)
return NotFoundError(); return NotFoundError();
var account = await _mapper.Account(MastodonMapper.AuthorOf(post), token); var account = await mapper.Account(MastodonMapper.AuthorOf(post), token);
var edits = post.Revisions.Select(r => new StatusEdit var edits = post.Revisions.Select(r => new StatusEdit
{ {
Content = r.ContentHtml ?? string.Empty, Content = r.ContentHtml ?? string.Empty,
@@ -292,7 +276,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
Sensitive = r.HasContentWarning, Sensitive = r.HasContentWarning,
CreatedAt = MastodonJson.Time(r.EditedAt), CreatedAt = MastodonJson.Time(r.EditedAt),
Account = account, Account = account,
Emojis = _mapper.EmojisOf(post, r.Emojis, r.ContentHtml, r.SpoilerText, r.Title) Emojis = mapper.EmojisOf(post, r.Emojis, r.ContentHtml, r.SpoilerText, r.Title)
}).ToList(); }).ToList();
edits.Add(new StatusEdit edits.Add(new StatusEdit
{ {
@@ -301,7 +285,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
Sensitive = post.HasContentWarning, Sensitive = post.HasContentWarning,
CreatedAt = MastodonJson.Time(post.EditedAt ?? post.CreationDate), CreatedAt = MastodonJson.Time(post.EditedAt ?? post.CreationDate),
Account = account, Account = account,
Emojis = _mapper.EmojisOf(post, post.Emojis, post.ContentHtml, post.Text, post.SpoilerText, post.Title) Emojis = mapper.EmojisOf(post, post.Emojis, post.ContentHtml, post.Text, post.SpoilerText, post.Title)
}); });
return Json(edits); return Json(edits);
} }
@@ -309,7 +293,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/statuses/{id}/source"), Scope("read:statuses")] [HttpGet("/api/v1/statuses/{id}/source"), Scope("read:statuses")]
public async Task<IActionResult> Source(string id, CancellationToken token) public async Task<IActionResult> Source(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return post == default ? NotFoundError() : Json(new StatusSource { Id = post.ID, Text = post.Text ?? string.Empty, SpoilerText = post.SpoilerText ?? string.Empty }); return post == default ? NotFoundError() : Json(new StatusSource { Id = post.ID, Text = post.Text ?? string.Empty, SpoilerText = post.SpoilerText ?? string.Empty });
} }
@@ -318,47 +302,47 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpPost("/api/privapub/v1/statuses/{id}/join"), Scope("write:statuses")] [HttpPost("/api/privapub/v1/statuses/{id}/join"), Scope("write:statuses")]
public async Task<IActionResult> Join(string id, CancellationToken token) public async Task<IActionResult> Join(string id, CancellationToken token)
{ {
var outcome = await _participations.Join(Me, id, token); var outcome = await participations.Join(Me, id, token);
return outcome.Ok ? Json(await _mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error); return outcome.Ok ? Json(await mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error);
} }
[HttpPost("/api/privapub/v1/statuses/{id}/leave"), Scope("write:statuses")] [HttpPost("/api/privapub/v1/statuses/{id}/leave"), Scope("write:statuses")]
public async Task<IActionResult> Leave(string id, CancellationToken token) public async Task<IActionResult> Leave(string id, CancellationToken token)
{ {
var outcome = await _participations.Leave(Me, id, token); var outcome = await participations.Leave(Me, id, token);
return outcome.Ok ? Json(await _mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error); return outcome.Ok ? Json(await mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error);
} }
[HttpPost("/api/v1/statuses/{id}/favourite"), Scope("write:favourites")] [HttpPost("/api/v1/statuses/{id}/favourite"), Scope("write:favourites")]
public Task<IActionResult> Favourite(string id, CancellationToken token) => Toggle(_statuses.Favourite(Me, id, true, token), id, token); public Task<IActionResult> Favourite(string id, CancellationToken token) => Toggle(statusService.Favourite(Me, id, true, token), id, token);
[HttpPost("/api/v1/statuses/{id}/unfavourite"), Scope("write:favourites")] [HttpPost("/api/v1/statuses/{id}/unfavourite"), Scope("write:favourites")]
public Task<IActionResult> Unfavourite(string id, CancellationToken token) => Toggle(_statuses.Favourite(Me, id, false, token), id, token); public Task<IActionResult> Unfavourite(string id, CancellationToken token) => Toggle(statusService.Favourite(Me, id, false, token), id, token);
// PrivaPub's own, for the threadiverse's downvotes (a favourite is the upvote) // PrivaPub's own, for the threadiverse's downvotes (a favourite is the upvote)
[HttpPost("/api/v1/statuses/{id}/downvote"), Scope("write:favourites")] [HttpPost("/api/v1/statuses/{id}/downvote"), Scope("write:favourites")]
public Task<IActionResult> Downvote(string id, CancellationToken token) => Toggle(_statuses.Downvote(Me, id, true, token), id, token); public Task<IActionResult> Downvote(string id, CancellationToken token) => Toggle(statusService.Downvote(Me, id, true, token), id, token);
[HttpPost("/api/v1/statuses/{id}/undownvote"), Scope("write:favourites")] [HttpPost("/api/v1/statuses/{id}/undownvote"), Scope("write:favourites")]
public Task<IActionResult> Undownvote(string id, CancellationToken token) => Toggle(_statuses.Downvote(Me, id, false, token), id, token); public Task<IActionResult> Undownvote(string id, CancellationToken token) => Toggle(statusService.Downvote(Me, id, false, token), id, token);
[HttpPost("/api/v1/statuses/{id}/reblog"), Scope("write:statuses")] [HttpPost("/api/v1/statuses/{id}/reblog"), Scope("write:statuses")]
public async Task<IActionResult> Reblog(string id, CancellationToken token) public async Task<IActionResult> Reblog(string id, CancellationToken token)
{ {
var outcome = await _statuses.Reblog(Me, id, true, Visibility(Params.Get("visibility")), token); var outcome = await statusService.Reblog(Me, id, true, Visibility(Params.Get("visibility")), token);
return outcome.Ok ? Json(await _mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error); return outcome.Ok ? Json(await mapper.Status(outcome.Post, MyId, token)) : Error(outcome.Status, outcome.Error);
} }
[HttpPost("/api/v1/statuses/{id}/unreblog"), Scope("write:statuses")] [HttpPost("/api/v1/statuses/{id}/unreblog"), Scope("write:statuses")]
public Task<IActionResult> Unreblog(string id, CancellationToken token) => Toggle(_statuses.Reblog(Me, id, false, PostVisibility.Public, token), id, token); public Task<IActionResult> Unreblog(string id, CancellationToken token) => Toggle(statusService.Reblog(Me, id, false, PostVisibility.Public, token), id, token);
[HttpGet("/api/v1/statuses/{id}/favourited_by"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/statuses/{id}/favourited_by"), Scope("read:accounts", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> FavouritedBy(string id, CancellationToken token) public async Task<IActionResult> FavouritedBy(string id, CancellationToken token)
{ {
if (await Visible(id, token) == default) if (await Visible(id, token) == default)
return NotFoundError(); return NotFoundError();
var favourites = await _dbEntities.Favourites.Match(f => f.PostId == id).Sort(f => f.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token); var favourites = await dbEntities.Favourites.Match(f => f.PostId == id).Sort(f => f.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token);
var accounts = await _mapper.Accounts(favourites.Select(f => f.AccountId), token); var accounts = await mapper.Accounts(favourites.Select(f => f.AccountId), token);
return Json(favourites.Select(f => accounts.GetValueOrDefault(f.AccountId)).Where(a => a != default).ToList()); return Json(favourites.Select(f => accounts.GetValueOrDefault(f.AccountId)).Where(a => a != default).ToList());
} }
@@ -367,8 +351,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
if (await Visible(id, token) == default) if (await Visible(id, token) == default)
return NotFoundError(); return NotFoundError();
var reblogs = await _dbEntities.Posts.Match(p => p.ReblogOfPostId == id).Match(VisibilityPolicy.IsShown).Sort(p => p.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token); var reblogs = await dbEntities.Posts.Match(p => p.ReblogOfPostId == id).Match(VisibilityPolicy.IsShown).Sort(p => p.ID, Order.Descending).Limit(Limit(40, 80)).ExecuteAsync(token);
var accounts = await _mapper.Accounts(reblogs.Select(MastodonMapper.AuthorOf), token); var accounts = await mapper.Accounts(reblogs.Select(MastodonMapper.AuthorOf), token);
return Json(reblogs.Select(r => accounts.GetValueOrDefault(MastodonMapper.AuthorOf(r))).Where(a => a != default).ToList()); return Json(reblogs.Select(r => accounts.GetValueOrDefault(MastodonMapper.AuthorOf(r))).Where(a => a != default).ToList());
} }
@@ -377,30 +361,30 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
if (await Visible(id, token) == default) if (await Visible(id, token) == default)
return NotFoundError(); return NotFoundError();
var query = _dbEntities.Posts.Match(p => p.QuotedPostId == id && p.QuoteState == QuoteState.Accepted && !p.DeletedAt.HasValue); var query = dbEntities.Posts.Match(p => p.QuotedPostId == id && p.QuoteState == QuoteState.Accepted && !p.DeletedAt.HasValue);
var quotes = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token); var quotes = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token);
var visible = new List<PostEntity>(); var visible = new List<PostEntity>();
foreach (var quote in quotes) foreach (var quote in quotes)
if (quote.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(quote, MyId, token)) if (quote.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(quote, MyId, token))
visible.Add(quote); visible.Add(quote);
Link($"/api/v1/statuses/{id}/quotes", quotes.LastOrDefault()?.ID, quotes.FirstOrDefault()?.ID); Link($"/api/v1/statuses/{id}/quotes", quotes.LastOrDefault()?.ID, quotes.FirstOrDefault()?.ID);
return Json(await _mapper.Statuses(visible, MyId, token)); return Json(await mapper.Statuses(visible, MyId, token));
} }
[HttpPost("/api/v1/statuses/{id}/quotes/{quotingId}/revoke"), Scope("write:statuses")] [HttpPost("/api/v1/statuses/{id}/quotes/{quotingId}/revoke"), Scope("write:statuses")]
public async Task<IActionResult> RevokeQuote(string id, string quotingId, CancellationToken token) public async Task<IActionResult> RevokeQuote(string id, string quotingId, CancellationToken token)
{ {
var quoted = await _dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var quoted = await dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var quoting = quoted == default ? default : await _dbEntities.Posts.Match(p => p.ID == quotingId && p.QuotedPostId == quoted.ID).ExecuteFirstAsync(token); var quoting = quoted == default ? default : await dbEntities.Posts.Match(p => p.ID == quotingId && p.QuotedPostId == quoted.ID).ExecuteFirstAsync(token);
if (quoting == default || !await _quotes.RevokeLicence(quoted, quoting, token)) if (quoting == default || !await quoteService.RevokeLicence(quoted, quoting, token))
return NotFoundError(); return NotFoundError();
return Json(await _mapper.Status(await _dbEntities.Posts.MatchID(quoting.ID).ExecuteFirstAsync(token), MyId, token)); return Json(await mapper.Status(await dbEntities.Posts.MatchID(quoting.ID).ExecuteFirstAsync(token), MyId, token));
} }
[HttpPut("/api/v1/statuses/{id}/interaction_policy"), Scope("write:statuses")] [HttpPut("/api/v1/statuses/{id}/interaction_policy"), Scope("write:statuses")]
public async Task<IActionResult> InteractionPolicy(string id, CancellationToken token) public async Task<IActionResult> InteractionPolicy(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
if (post == default) if (post == default)
return NotFoundError(); return NotFoundError();
var policy = Params.Get("quote_approval_policy"); var policy = Params.Get("quote_approval_policy");
@@ -409,8 +393,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.LocalQuotePolicy, policy).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.LocalQuotePolicy, policy).ExecuteAsync(token);
post.LocalQuotePolicy = policy; post.LocalQuotePolicy = policy;
if (!post.IsLocalOnly) if (!post.IsLocalOnly)
await _outbox.PublishUpdate(Me, post, $"policy-{DateTime.UtcNow.Ticks}", token); await outbox.PublishUpdate(Me, post, $"policy-{DateTime.UtcNow.Ticks}", token);
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
[HttpPost("/api/v1/statuses/{id}/bookmark"), Scope("write:bookmarks")] [HttpPost("/api/v1/statuses/{id}/bookmark"), Scope("write:bookmarks")]
@@ -426,7 +410,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
catch (MongoDB.Driver.MongoWriteException ex) when (ex.WriteError?.Category == MongoDB.Driver.ServerErrorCategory.DuplicateKey) catch (MongoDB.Driver.MongoWriteException ex) when (ex.WriteError?.Category == MongoDB.Driver.ServerErrorCategory.DuplicateKey)
{ {
} }
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
[HttpPost("/api/v1/statuses/{id}/unbookmark"), Scope("write:bookmarks")] [HttpPost("/api/v1/statuses/{id}/unbookmark"), Scope("write:bookmarks")]
@@ -441,13 +425,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var bookmarks = await Page.From(Params, Limit()).Fetch(DB.Default.Find<Models.Social.Bookmark>().Match(b => b.AvatarId == MyId), b => b.ID, token); var bookmarks = await Page.From(Params, Limit()).Fetch(DB.Default.Find<Models.Social.Bookmark>().Match(b => b.AvatarId == MyId), b => b.ID, token);
var ids = bookmarks.Select(b => b.PostId).ToList(); var ids = bookmarks.Select(b => b.PostId).ToList();
var posts = (await _dbEntities.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token)).ToDictionary(p => p.ID); var posts = (await dbEntities.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token)).ToDictionary(p => p.ID);
var visible = new List<PostEntity>(); var visible = new List<PostEntity>();
foreach (var postId in ids.Where(posts.ContainsKey)) foreach (var postId in ids.Where(posts.ContainsKey))
if (await VisibilityPolicy.CanSee(posts[postId], MyId, token)) if (await VisibilityPolicy.CanSee(posts[postId], MyId, token))
visible.Add(posts[postId]); visible.Add(posts[postId]);
Link("/api/v1/bookmarks", bookmarks.LastOrDefault()?.ID, bookmarks.FirstOrDefault()?.ID); Link("/api/v1/bookmarks", bookmarks.LastOrDefault()?.ID, bookmarks.FirstOrDefault()?.ID);
return Json(await _mapper.Statuses(visible, MyId, token)); return Json(await mapper.Statuses(visible, MyId, token));
} }
[HttpPost("/api/v1/statuses/{id}/mute"), Scope("write:mutes")] [HttpPost("/api/v1/statuses/{id}/mute"), Scope("write:mutes")]
@@ -459,7 +443,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpPost("/api/v1/statuses/{id}/pin"), Scope("write:accounts")] [HttpPost("/api/v1/statuses/{id}/pin"), Scope("write:accounts")]
public async Task<IActionResult> Pin(string id, CancellationToken token) public async Task<IActionResult> Pin(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null) var post = await dbEntities.Posts.Match(p => p.ID == id && p.GroupUserId == MyId && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
if (post == default) if (post == default)
return await Visible(id, token) is { } other return await Visible(id, token) is { } other
@@ -474,20 +458,20 @@ namespace PrivaPub.Api.Mastodon.Controllers
try try
{ {
await DB.Default.SaveAsync(new Models.Social.Pin { AvatarId = MyId, PostId = post.ID }, token); await DB.Default.SaveAsync(new Models.Social.Pin { AvatarId = MyId, PostId = post.ID }, token);
await _outbox.PublishFeatured(MyId, post, featured: true, token); await outbox.PublishFeatured(MyId, post, featured: true, token);
} }
catch (MongoDB.Driver.MongoWriteException ex) when (ex.WriteError?.Category == MongoDB.Driver.ServerErrorCategory.DuplicateKey) catch (MongoDB.Driver.MongoWriteException ex) when (ex.WriteError?.Category == MongoDB.Driver.ServerErrorCategory.DuplicateKey)
{ {
} }
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
[HttpPost("/api/v1/statuses/{id}/unpin"), Scope("write:accounts")] [HttpPost("/api/v1/statuses/{id}/unpin"), Scope("write:accounts")]
public async Task<IActionResult> Unpin(string id, CancellationToken token) public async Task<IActionResult> Unpin(string id, CancellationToken token)
{ {
var unpinned = await DB.Default.DeleteAsync<Models.Social.Pin>(p => p.AvatarId == MyId && p.PostId == id); var unpinned = await DB.Default.DeleteAsync<Models.Social.Pin>(p => p.AvatarId == MyId && p.PostId == id);
if (unpinned is { IsAcknowledged: true, DeletedCount: > 0 } && await _dbEntities.Posts.MatchID(id).ExecuteFirstAsync(token) is { } post) if (unpinned is { IsAcknowledged: true, DeletedCount: > 0 } && await dbEntities.Posts.MatchID(id).ExecuteFirstAsync(token) is { } post)
await _outbox.PublishFeatured(MyId, post, featured: false, token); await outbox.PublishFeatured(MyId, post, featured: false, token);
return await Unchanged(id, token); return await Unchanged(id, token);
} }
@@ -496,20 +480,20 @@ namespace PrivaPub.Api.Mastodon.Controllers
var outcome = await action; var outcome = await action;
if (!outcome.Ok) if (!outcome.Ok)
return Error(outcome.Status, outcome.Error); return Error(outcome.Status, outcome.Error);
var post = await _dbEntities.Posts.MatchID(id).ExecuteFirstAsync(token); var post = await dbEntities.Posts.MatchID(id).ExecuteFirstAsync(token);
return Json(await _mapper.Status(post, MyId, token)); return Json(await mapper.Status(post, MyId, token));
} }
async Task<IActionResult> Unchanged(string id, CancellationToken token) async Task<IActionResult> Unchanged(string id, CancellationToken token)
{ {
var post = await Visible(id, token); var post = await Visible(id, token);
var status = post == default ? default : await _mapper.Status(post, MyId, token); var status = post == default ? default : await mapper.Status(post, MyId, token);
return status == default ? NotFoundError() : Json(status); return status == default ? NotFoundError() : Json(status);
} }
async Task<PostEntity> Visible(string id, CancellationToken token) async Task<PostEntity> Visible(string id, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default; return post != default && post.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(post, MyId, token) ? post : default;
} }
@@ -20,18 +20,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
// per request as server-sent events on /api/v1/streaming/{stream}. Every stream needs a signed-in persona (the token // per request as server-sent events on /api/v1/streaming/{stream}. Every stream needs a signed-in persona (the token
// comes as access_token, in the Authorization header, or as the WebSocket's protocol). What a stream tells is mapped // comes as access_token, in the Authorization header, or as the WebSocket's protocol). What a stream tells is mapped
// for that persona as it is sent: a post it may not see, or whose author it blocked or muted, is never sent. // for that persona as it is sent: a post it may not see, or whose author it blocked or muted, is never sent.
public class StreamingController : MastodonController public class StreamingController(
MastodonMapper mapper,
DbEntities dbEntities) : MastodonController
{ {
static readonly TimeSpan KeepAlive = TimeSpan.FromSeconds(15); static readonly TimeSpan KeepAlive = TimeSpan.FromSeconds(15);
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
public StreamingController(MastodonMapper mapper, DbEntities dbEntities)
{
_mapper = mapper;
_dbEntities = dbEntities;
}
[HttpGet("/api/v1/streaming/health"), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/streaming/health"), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public IActionResult Health() => Content("OK", "text/plain"); public IActionResult Health() => Content("OK", "text/plain");
@@ -72,22 +66,22 @@ namespace PrivaPub.Api.Mastodon.Controllers
// a direct conversation the persona takes part in (R8): Mastodon's Conversation, as /api/v1/conversations lists it // a direct conversation the persona takes part in (R8): Mastodon's Conversation, as /api/v1/conversations lists it
if (e.Name == "conversation") if (e.Name == "conversation")
{ {
var group = await _dbEntities.DmGroups.Match(g => g.ID == e.Id && !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId)) var group = await dbEntities.DmGroups.Match(g => g.ID == e.Id && !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId))
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
var conversation = group == default ? default var conversation = group == default ? default
: (await TimelinesController.ConversationsOf(_mapper, _dbEntities, MyId, new List<Models.Group.DmGroup> { group }, token)).FirstOrDefault(); : (await TimelinesController.ConversationsOf(mapper, dbEntities, MyId, new List<Models.Group.DmGroup> { group }, token)).FirstOrDefault();
return conversation == default ? default : JsonSerializer.Serialize(conversation, MastodonJson.Options); return conversation == default ? default : JsonSerializer.Serialize(conversation, MastodonJson.Options);
} }
if (e.Name == "notification") if (e.Name == "notification")
{ {
var notification = await _dbEntities.Notifications.Match(n => n.ID == e.Id && n.AvatarId == MyId).ExecuteFirstAsync(token); var notification = await dbEntities.Notifications.Match(n => n.ID == e.Id && n.AvatarId == MyId).ExecuteFirstAsync(token);
var mapped = notification == default ? default : (await _mapper.Notifications(new List<Notification> { notification }, MyId, token)).FirstOrDefault(); var mapped = notification == default ? default : (await mapper.Notifications(new List<Notification> { notification }, MyId, token)).FirstOrDefault();
return mapped == default ? default : JsonSerializer.Serialize(mapped, MastodonJson.Options); return mapped == default ? default : JsonSerializer.Serialize(mapped, MastodonJson.Options);
} }
var post = await _dbEntities.Posts.MatchID(e.Id).ExecuteFirstAsync(token); var post = await dbEntities.Posts.MatchID(e.Id).ExecuteFirstAsync(token);
if (post == default || !await VisibilityPolicy.CanSee(post, MyId, token)) if (post == default || !await VisibilityPolicy.CanSee(post, MyId, token))
return default; return default;
var status = (await _mapper.Statuses(new[] { post }, MyId, token)).FirstOrDefault(); var status = (await mapper.Statuses(new[] { post }, MyId, token)).FirstOrDefault();
return status == default ? default : JsonSerializer.Serialize(status, MastodonJson.Options); return status == default ? default : JsonSerializer.Serialize(status, MastodonJson.Options);
} }
@@ -137,7 +131,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
while (socket.State == WebSocketState.Open && !done.IsCancellationRequested) while (socket.State == WebSocketState.Open && !done.IsCancellationRequested)
{ {
var text = new StringBuilder(); var text = new StringBuilder();
WebSocketReceiveResult received; var received = default(WebSocketReceiveResult);
do do
{ {
received = await socket.ReceiveAsync(buffer, done.Token); received = await socket.ReceiveAsync(buffer, done.Token);
@@ -149,7 +143,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
text.Append(Encoding.UTF8.GetString(buffer, 0, received.Count)); text.Append(Encoding.UTF8.GetString(buffer, 0, received.Count));
} }
while (!received.EndOfMessage && text.Length < 16384); while (!received.EndOfMessage && text.Length < 16384);
JsonNode message; var message = default(JsonNode);
try try
{ {
message = JsonNode.Parse(text.ToString()); message = JsonNode.Parse(text.ToString());
@@ -15,17 +15,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// Follow suggestions as Mastodon's API has them (completion program R8; who and why in Domain/Social/Suggestions): v1 the // Follow suggestions as Mastodon's API has them (completion program R8; who and why in Domain/Social/Suggestions): v1 the
// accounts, v2 each with its reasons; a dismissed account is never suggested to that persona again. // accounts, v2 each with its reasons; a dismissed account is never suggested to that persona again.
public class SuggestionsController : MastodonController public class SuggestionsController(
MastodonMapper mapper,
IInstanceSettings settings) : MastodonController
{ {
readonly MastodonMapper _mapper;
readonly IInstanceSettings _settings;
public SuggestionsController(MastodonMapper mapper, IInstanceSettings settings)
{
_mapper = mapper;
_settings = settings;
}
[HttpGet("/api/v1/suggestions"), Scope("read")] [HttpGet("/api/v1/suggestions"), Scope("read")]
public async Task<IActionResult> V1(CancellationToken token) => Json((await Suggested(token)).Select(s => s.Account).ToList()); public async Task<IActionResult> V1(CancellationToken token) => Json((await Suggested(token)).Select(s => s.Account).ToList());
@@ -53,12 +46,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<List<Suggestion>> Suggested(CancellationToken token) async Task<List<Suggestion>> Suggested(CancellationToken token)
{ {
var limit = Limit(40, 80); var limit = Limit(40, 80);
var candidates = await Suggestions.For(Me, _settings.Current.StaffPicks, token); var candidates = await Suggestions.For(Me, settings.Current.StaffPicks, token);
var suggested = new List<Suggestion>(); var suggested = new List<Suggestion>();
for (var start = 0; start < candidates.Count && suggested.Count < limit; start += limit * 2) for (var start = 0; start < candidates.Count && suggested.Count < limit; start += limit * 2)
{ {
var chunk = candidates.Skip(start).Take(limit * 2).ToList(); var chunk = candidates.Skip(start).Take(limit * 2).ToList();
var accounts = await _mapper.Accounts(chunk.Select(c => c.AccountId), token); var accounts = await mapper.Accounts(chunk.Select(c => c.AccountId), token);
var hidden = await Hidden.AuthorsHiddenFrom(MyId, accounts.Values.Select(a => a.Uri), forNotifications: false, token); var hidden = await Hidden.AuthorsHiddenFrom(MyId, accounts.Values.Select(a => a.Uri), forNotifications: false, token);
foreach (var candidate in chunk) foreach (var candidate in chunk)
{ {
@@ -16,18 +16,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Hashtags as Mastodon shows them (owner decision 2026-10-04, followed tags back from the cut list): a tag with the // Hashtags as Mastodon shows them (owner decision 2026-10-04, followed tags back from the cut list): a tag with the
// last week of its use in public posts PrivaPub holds, and whether the persona follows it; following one brings its // last week of its use in public posts PrivaPub holds, and whether the persona follows it; following one brings its
// public posts to the persona's home as they arrive (Fanout). // public posts to the persona's home as they arrive (Fanout).
public class TagsController : MastodonController public class TagsController(
DbEntities db,
ILocalActorService localActors) : MastodonController
{ {
const int MaxFollowed = 500; const int MaxFollowed = 500;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public TagsController(DbEntities dbEntities, ILocalActorService localActors)
{
_dbEntities = dbEntities;
_localActors = localActors;
}
public static string Normalise(string name) => name?.Trim().TrimStart('#').Normalize(NormalizationForm.FormKC).ToLowerInvariant() ?? string.Empty; public static string Normalise(string name) => name?.Trim().TrimStart('#').Normalize(NormalizationForm.FormKC).ToLowerInvariant() ?? string.Empty;
@@ -59,8 +53,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
}).ToList(); }).ToList();
} }
Task<object> View(string tag, bool? following, CancellationToken token, bool? featuring = default) => Task<object> View(string tag, bool? following, bool? featuring = default, CancellationToken token = default) =>
TagView(_dbEntities, _localActors.BaseAddress, tag, MyId, following, featuring, token); TagView(db, localActors.BaseAddress, tag, MyId, following, featuring, token);
// Mastodon's Tag: its week of use, and for a signed-in persona whether it follows it and (Mastodon 4.4) features it // Mastodon's Tag: its week of use, and for a signed-in persona whether it follows it and (Mastodon 4.4) features it
internal static async Task<object> TagView(DbEntities dbEntities, string baseAddress, string tag, string viewerId, bool? following, bool? featuring, internal static async Task<object> TagView(DbEntities dbEntities, string baseAddress, string tag, string viewerId, bool? following, bool? featuring,
@@ -78,7 +72,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Tag(string name, CancellationToken token) public async Task<IActionResult> Tag(string name, CancellationToken token)
{ {
var tag = Normalise(name); var tag = Normalise(name);
return tag.Length == 0 ? NotFoundError() : Json(await View(tag, default, token)); return tag.Length == 0 ? NotFoundError() : Json(await View(tag, default, token: token));
} }
[HttpPost("/api/v1/tags/{name}/follow"), Scope("write:follows")] [HttpPost("/api/v1/tags/{name}/follow"), Scope("write:follows")]
@@ -99,7 +93,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
} }
} }
return Json(await View(tag, true, token)); return Json(await View(tag, true, token: token));
} }
[HttpPost("/api/v1/tags/{name}/unfollow"), Scope("write:follows")] [HttpPost("/api/v1/tags/{name}/unfollow"), Scope("write:follows")]
@@ -107,7 +101,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var tag = Normalise(name); var tag = Normalise(name);
await DB.Default.DeleteAsync<FollowedTag>(t => t.AvatarId == MyId && t.Name == tag); await DB.Default.DeleteAsync<FollowedTag>(t => t.AvatarId == MyId && t.Name == tag);
return Json(await View(tag, false, token)); return Json(await View(tag, false, token: token));
} }
// Mastodon 4.4: a hashtag featured on the persona's profile, or no longer (R8, Domain/Social/FeaturedTags) // Mastodon 4.4: a hashtag featured on the persona's profile, or no longer (R8, Domain/Social/FeaturedTags)
@@ -115,7 +109,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Feature(string name, [FromServices] Domain.Social.IFeaturedTags featured, CancellationToken token) public async Task<IActionResult> Feature(string name, [FromServices] Domain.Social.IFeaturedTags featured, CancellationToken token)
{ {
var (tag, error) = await featured.Feature(Me, name, token); var (tag, error) = await featured.Feature(Me, name, token);
return tag == default ? Error(StatusCodes.Status422UnprocessableEntity, error) : Json(await View(tag.Name, default, token, featuring: true)); return tag == default ? Error(StatusCodes.Status422UnprocessableEntity, error) : Json(await View(tag.Name, default, featuring: true, token));
} }
[HttpPost("/api/v1/tags/{name}/unfeature"), Scope("write:accounts")] [HttpPost("/api/v1/tags/{name}/unfeature"), Scope("write:accounts")]
@@ -125,7 +119,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (!IsHashtag(tag)) if (!IsHashtag(tag))
return NotFoundError(); return NotFoundError();
await featured.Unfeature(Me, default, tag, token); await featured.Unfeature(Me, default, tag, token);
return Json(await View(tag, default, token, featuring: false)); return Json(await View(tag, default, featuring: false, token));
} }
[HttpGet("/api/v1/followed_tags"), Scope("read:follows")] [HttpGet("/api/v1/followed_tags"), Scope("read:follows")]
@@ -135,7 +129,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
Link("/api/v1/followed_tags", page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID); Link("/api/v1/followed_tags", page.LastOrDefault()?.ID, page.FirstOrDefault()?.ID);
var views = new List<object>(); var views = new List<object>();
foreach (var followed in page) foreach (var followed in page)
views.Add(await View(followed.Name, true, token)); views.Add(await View(followed.Name, true, token: token));
return Json(views); return Json(views);
} }
} }
@@ -19,17 +19,10 @@ using MarkerEntity = PrivaPub.Models.Social.Marker;
namespace PrivaPub.Api.Mastodon.Controllers namespace PrivaPub.Api.Mastodon.Controllers
{ {
public class TimelinesController : MastodonController public class TimelinesController(
MastodonMapper mastodonMapper,
DbEntities db) : MastodonController
{ {
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
public TimelinesController(MastodonMapper mapper, DbEntities dbEntities)
{
_mapper = mapper;
_dbEntities = dbEntities;
}
[HttpGet("/api/v1/timelines/home"), Scope("read:statuses")] [HttpGet("/api/v1/timelines/home"), Scope("read:statuses")]
public async Task<IActionResult> Home(CancellationToken token) public async Task<IActionResult> Home(CancellationToken token)
{ {
@@ -38,15 +31,15 @@ namespace PrivaPub.Api.Mastodon.Controllers
var apart = exclusive.Count == 0 var apart = exclusive.Count == 0
? new List<string>() ? new List<string>()
: (await DB.Default.Find<PersonaListMember>().Match(m => exclusive.Contains(m.ListId)).ExecuteAsync(token)).Select(m => m.AccountId).Distinct().ToList(); : (await DB.Default.Find<PersonaListMember>().Match(m => exclusive.Contains(m.ListId)).ExecuteAsync(token)).Select(m => m.AccountId).Distinct().ToList();
var home = _dbEntities.TimelineEntries.Match(e => e.AvatarId == MyId); var home = db.TimelineEntries.Match(e => e.AvatarId == MyId);
if (apart.Count > 0) if (apart.Count > 0)
home.Match(e => !apart.Contains(e.AuthorAccountId)); home.Match(e => !apart.Contains(e.AuthorAccountId));
var entries = await Page.From(Params, Limit()).Fetch(home, e => e.PostId, token); var entries = await Page.From(Params, Limit()).Fetch(home, e => e.PostId, token);
var ids = entries.Select(e => e.PostId).ToList(); var ids = entries.Select(e => e.PostId).ToList();
// (located posts once reached their author's home: the entries left from then are passed over) // (located posts once reached their author's home: the entries left from then are passed over)
var posts = (await _dbEntities.Posts.Match(p => ids.Contains(p.ID) && p.Visibility != PostVisibility.LocalGeo).Match(VisibilityPolicy.IsShown) var posts = (await db.Posts.Match(p => ids.Contains(p.ID) && p.Visibility != PostVisibility.LocalGeo).Match(VisibilityPolicy.IsShown)
.ExecuteAsync(token)).ToDictionary(p => p.ID); .ExecuteAsync(token)).ToDictionary(p => p.ID);
var statuses = await _mapper.Statuses(ids.Where(posts.ContainsKey).Select(id => posts[id]).ToList(), MyId, token); var statuses = await mastodonMapper.Statuses(ids.Where(posts.ContainsKey).Select(id => posts[id]).ToList(), MyId, token);
Link("/api/v1/timelines/home", entries.LastOrDefault()?.PostId, entries.FirstOrDefault()?.PostId); Link("/api/v1/timelines/home", entries.LastOrDefault()?.PostId, entries.FirstOrDefault()?.PostId);
return Json(statuses); return Json(statuses);
} }
@@ -54,7 +47,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/timelines/public"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/timelines/public"), Scope("read:statuses", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Public(CancellationToken token) public async Task<IActionResult> Public(CancellationToken token)
{ {
var query = _dbEntities.Posts.Match(p => p.Visibility == PostVisibility.Public && p.ReblogOfPostId == null).Match(VisibilityPolicy.IsPublic) var query = db.Posts.Match(p => p.Visibility == PostVisibility.Public && p.ReblogOfPostId == null).Match(VisibilityPolicy.IsPublic)
.Match(VisibilityPolicy.IsListed); .Match(VisibilityPolicy.IsListed);
if (Params.Bool("local") == true) if (Params.Bool("local") == true)
query.Match(p => !p.IsFederatedCopy); query.Match(p => !p.IsFederatedCopy);
@@ -70,7 +63,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/timelines/feed/{id}"), Scope("read:statuses")] [HttpGet("/api/v1/timelines/feed/{id}"), Scope("read:statuses")]
public async Task<IActionResult> Feed(string id, CancellationToken token) public async Task<IActionResult> Feed(string id, CancellationToken token)
{ {
var feed = await _dbEntities.ForeignAvatars.MatchID(id).ExecuteFirstAsync(token); var feed = await db.ForeignAvatars.MatchID(id).ExecuteFirstAsync(token);
if (feed is not { AvatarType: Models.User.AvatarType.Feed } if (feed is not { AvatarType: Models.User.AvatarType.Feed }
|| !await DB.Default.Find<FeedSubscription>().Match(s => s.AvatarId == MyId && s.FeedActorURI == feed.ActorURI).ExecuteAnyAsync(token)) || !await DB.Default.Find<FeedSubscription>().Match(s => s.AvatarId == MyId && s.FeedActorURI == feed.ActorURI).ExecuteAnyAsync(token))
return NotFoundError(); return NotFoundError();
@@ -79,8 +72,8 @@ namespace PrivaPub.Api.Mastodon.Controllers
var names = communities.Where(c => c.StartsWith(ours, StringComparison.Ordinal)).Select(c => c[ours.Length..]).ToList(); var names = communities.Where(c => c.StartsWith(ours, StringComparison.Ordinal)).Select(c => c[ours.Length..]).ToList();
var groups = names.Count == 0 var groups = names.Count == 0
? new List<string>() ? new List<string>()
: (await _dbEntities.Groups.Match(g => names.Contains(g.UserName) && !g.DeletionAt.HasValue).ExecuteAsync(token)).Select(g => g.ID).ToList(); : (await db.Groups.Match(g => names.Contains(g.UserName) && !g.DeletionAt.HasValue).ExecuteAsync(token)).Select(g => g.ID).ToList();
var query = _dbEntities.Posts.Match(p => (communities.Contains(p.AudienceURI) || groups.Contains(p.GroupId)) var query = db.Posts.Match(p => (communities.Contains(p.AudienceURI) || groups.Contains(p.GroupId))
&& p.ReblogOfPostId == null && p.InReplyToURI == null).Match(VisibilityPolicy.IsPublic); && p.ReblogOfPostId == null && p.InReplyToURI == null).Match(VisibilityPolicy.IsPublic);
return await Respond(query, $"/api/v1/timelines/feed/{id}", token); return await Respond(query, $"/api/v1/timelines/feed/{id}", token);
} }
@@ -89,7 +82,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Tag(string hashtag, CancellationToken token) public async Task<IActionResult> Tag(string hashtag, CancellationToken token)
{ {
var tag = hashtag.TrimStart('#').ToLowerInvariant(); var tag = hashtag.TrimStart('#').ToLowerInvariant();
var query = _dbEntities.Posts.Match(p => p.Tags.Contains(tag) && p.Visibility == PostVisibility.Public && p.ReblogOfPostId == null).Match(VisibilityPolicy.IsPublic) var query = db.Posts.Match(p => p.Tags.Contains(tag) && p.Visibility == PostVisibility.Public && p.ReblogOfPostId == null).Match(VisibilityPolicy.IsPublic)
.Match(VisibilityPolicy.IsListed); .Match(VisibilityPolicy.IsListed);
if (Params.Bool("local") == true) if (Params.Bool("local") == true)
query.Match(p => !p.IsFederatedCopy); query.Match(p => !p.IsFederatedCopy);
@@ -99,15 +92,15 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/favourites"), Scope("read:favourites")] [HttpGet("/api/v1/favourites"), Scope("read:favourites")]
public async Task<IActionResult> Favourites(CancellationToken token) public async Task<IActionResult> Favourites(CancellationToken token)
{ {
var favourites = await Page.From(Params, Limit()).Fetch(_dbEntities.Favourites.Match(f => f.AccountId == MyId), f => f.ID, token); var favourites = await Page.From(Params, Limit()).Fetch(db.Favourites.Match(f => f.AccountId == MyId), f => f.ID, token);
var ids = favourites.Select(f => f.PostId).ToList(); var ids = favourites.Select(f => f.PostId).ToList();
var posts = (await _dbEntities.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token)).ToDictionary(p => p.ID); var posts = (await db.Posts.Match(p => ids.Contains(p.ID) && !p.DeletedAt.HasValue).ExecuteAsync(token)).ToDictionary(p => p.ID);
var visible = new List<PostEntity>(); var visible = new List<PostEntity>();
foreach (var id in ids.Where(posts.ContainsKey)) foreach (var id in ids.Where(posts.ContainsKey))
if (await VisibilityPolicy.CanSee(posts[id], MyId, token)) if (await VisibilityPolicy.CanSee(posts[id], MyId, token))
visible.Add(posts[id]); visible.Add(posts[id]);
Link("/api/v1/favourites", favourites.LastOrDefault()?.ID, favourites.FirstOrDefault()?.ID); Link("/api/v1/favourites", favourites.LastOrDefault()?.ID, favourites.FirstOrDefault()?.ID);
return Json(await _mapper.Statuses(visible, MyId, token)); return Json(await mastodonMapper.Statuses(visible, MyId, token));
} }
// the persona's direct conversations, by their newest post (paged like Mastodon's by that post's id), each with its // the persona's direct conversations, by their newest post (paged like Mastodon's by that post's id), each with its
@@ -117,13 +110,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Conversations(CancellationToken token) public async Task<IActionResult> Conversations(CancellationToken token)
{ {
var groups = await Page.From(Params, Limit(20, 40)).Fetch( var groups = await Page.From(Params, Limit(20, 40)).Fetch(
_dbEntities.DmGroups.Match(g => !g.DeletionAt.HasValue && g.LastPostId != null && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId)), db.DmGroups.Match(g => !g.DeletionAt.HasValue && g.LastPostId != null && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId)),
g => g.LastPostId, token); g => g.LastPostId, token);
Link("/api/v1/conversations", groups.LastOrDefault()?.LastPostId, groups.FirstOrDefault()?.LastPostId); Link("/api/v1/conversations", groups.LastOrDefault()?.LastPostId, groups.FirstOrDefault()?.LastPostId);
return Json(await ConversationsOf(groups, token)); return Json(await ConversationsOf(groups, token));
} }
Task<List<Conversation>> ConversationsOf(List<DmGroup> groups, CancellationToken token) => ConversationsOf(_mapper, _dbEntities, MyId, groups, token); Task<List<Conversation>> ConversationsOf(List<DmGroup> groups, CancellationToken token) => ConversationsOf(mastodonMapper, db, MyId, groups, token);
// (also the `direct` stream's conversation event, StreamingController) // (also the `direct` stream's conversation event, StreamingController)
internal static async Task<List<Conversation>> ConversationsOf(MastodonMapper mapper, DbEntities dbEntities, string viewerId, List<DmGroup> groups, internal static async Task<List<Conversation>> ConversationsOf(MastodonMapper mapper, DbEntities dbEntities, string viewerId, List<DmGroup> groups,
@@ -163,7 +156,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
async Task<DmGroup> MyConversation(string id, CancellationToken token) => async Task<DmGroup> MyConversation(string id, CancellationToken token) =>
await _dbEntities.DmGroups.Match(g => g.ID == id && !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId)) await db.DmGroups.Match(g => g.ID == id && !g.DeletionAt.HasValue && g.Members.Any(m => !m.IsForeign && m.AvatarId == MyId))
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
[HttpPost("/api/v1/conversations/{id}/read"), Scope("write:conversations")] [HttpPost("/api/v1/conversations/{id}/read"), Scope("write:conversations")]
@@ -239,11 +232,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var posts = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token); var posts = await Page.From(Params, Limit()).Fetch(query, p => p.ID, token);
Link(path, posts.LastOrDefault()?.ID, posts.FirstOrDefault()?.ID); Link(path, posts.LastOrDefault()?.ID, posts.FirstOrDefault()?.ID);
return Json(await _mapper.Statuses(posts, MyId, token)); return Json(await mastodonMapper.Statuses(posts, MyId, token));
} }
} }
public class NotificationsController : MastodonController public class NotificationsController(
MastodonMapper mapper,
DbEntities dbEntities) : MastodonController
{ {
internal static readonly Dictionary<NotificationType, string> Names = new() internal static readonly Dictionary<NotificationType, string> Names = new()
{ {
@@ -260,20 +255,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
[NotificationType.Status] = "status"//an account followed with notify posted (R8) [NotificationType.Status] = "status"//an account followed with notify posted (R8)
}; };
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
public NotificationsController(MastodonMapper mapper, DbEntities dbEntities)
{
_mapper = mapper;
_dbEntities = dbEntities;
}
Find<NotificationEntity, NotificationEntity> Filtered() Find<NotificationEntity, NotificationEntity> Filtered()
{ {
var types = Params.List("types").Select(Parse).Where(t => t.HasValue).Select(t => t.Value).ToList(); var types = Params.List("types").Select(Parse).Where(t => t.HasValue).Select(t => t.Value).ToList();
var excluded = Params.List("exclude_types").Select(Parse).Where(t => t.HasValue).Select(t => t.Value).ToList(); var excluded = Params.List("exclude_types").Select(Parse).Where(t => t.HasValue).Select(t => t.Value).ToList();
var query = _dbEntities.Notifications.Match(n => n.AvatarId == MyId); var query = dbEntities.Notifications.Match(n => n.AvatarId == MyId);
// what the persona's notification policy filtered stays in its requests, unless asked for (a request's own page) // what the persona's notification policy filtered stays in its requests, unless asked for (a request's own page)
if (Params.Bool("include_filtered") != true) if (Params.Bool("include_filtered") != true)
query.Match(NotFiltered); query.Match(NotFiltered);
@@ -332,7 +319,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<List<NotificationEntity>> Members(string key, CancellationToken token) => async Task<List<NotificationEntity>> Members(string key, CancellationToken token) =>
InGroup(key) is { } filter InGroup(key) is { } filter
? await _dbEntities.Notifications.Match(filter).Match(NotFiltered).Sort(n => n.ID, Order.Descending).Limit(80).ExecuteAsync(token) ? await dbEntities.Notifications.Match(filter).Match(NotFiltered).Sort(n => n.ID, Order.Descending).Limit(80).ExecuteAsync(token)
: new List<NotificationEntity>(); : new List<NotificationEntity>();
async Task<object> Groups(List<NotificationEntity> page, ISet<string> grouped, CancellationToken token) async Task<object> Groups(List<NotificationEntity> page, ISet<string> grouped, CancellationToken token)
@@ -417,7 +404,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/notifications/{id}"), Scope("read:notifications")] [HttpGet("/api/v1/notifications/{id}"), Scope("read:notifications")]
public async Task<IActionResult> Get(string id, CancellationToken token) public async Task<IActionResult> Get(string id, CancellationToken token)
{ {
var notification = await _dbEntities.Notifications.Match(n => n.ID == id && n.AvatarId == MyId).ExecuteFirstAsync(token); var notification = await dbEntities.Notifications.Match(n => n.ID == id && n.AvatarId == MyId).ExecuteFirstAsync(token);
var mapped = notification == default ? default : (await Map(new List<NotificationEntity> { notification }, token)).FirstOrDefault(); var mapped = notification == default ? default : (await Map(new List<NotificationEntity> { notification }, token)).FirstOrDefault();
return mapped == default ? NotFoundError() : Json(mapped); return mapped == default ? NotFoundError() : Json(mapped);
} }
@@ -447,7 +434,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
Task<List<Entities.Notification>> Map(List<NotificationEntity> notifications, CancellationToken token) => Task<List<Entities.Notification>> Map(List<NotificationEntity> notifications, CancellationToken token) =>
_mapper.Notifications(notifications, MyId, token); mapper.Notifications(notifications, MyId, token);
static NotificationType? Parse(string name) => Names.FirstOrDefault(n => n.Value == name) is { Value: not null } pair ? pair.Key : (NotificationType?)null; static NotificationType? Parse(string name) => Names.FirstOrDefault(n => n.Value == name) is { Value: not null } pair ? pair.Key : (NotificationType?)null;
} }
@@ -15,21 +15,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
// Trends and the directory (owner decision 2026-10-04, back from the cut list), from what PrivaPub already holds // Trends and the directory (owner decision 2026-10-04, back from the cut list), from what PrivaPub already holds
// (Trends). The directory lists only accounts that let themselves be discovered. // (Trends). The directory lists only accounts that let themselves be discovered.
public class TrendsController : MastodonController public class TrendsController(
Trends trendService,
MastodonMapper mapper,
DbEntities dbEntities,
ILocalActorService localActors) : MastodonController
{ {
readonly Trends _trends;
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public TrendsController(Trends trends, MastodonMapper mapper, DbEntities dbEntities, ILocalActorService localActors)
{
_trends = trends;
_mapper = mapper;
_dbEntities = dbEntities;
_localActors = localActors;
}
static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new
{ {
day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(),
@@ -46,10 +37,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
var followed = MyId == default var followed = MyId == default
? new HashSet<string>() ? new HashSet<string>()
: (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet(); : (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet();
return Json(Window(await _trends.Tags(token), 10, 20).Select(t => new return Json(Window(await trendService.Tags(token), 10, 20).Select(t => new
{ {
name = t.Key, name = t.Key,
url = $"{_localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}", url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}",
history = History(t), history = History(t),
following = MyId == default ? default(bool?) : followed.Contains(t.Key) following = MyId == default ? default(bool?) : followed.Contains(t.Key)
}).ToList()); }).ToList());
@@ -58,21 +49,21 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet("/api/v1/trends/statuses"), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/trends/statuses"), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Statuses(CancellationToken token) public async Task<IActionResult> Statuses(CancellationToken token)
{ {
var ids = Window(await _trends.Statuses(token), 20, 40).ToList(); var ids = Window(await trendService.Statuses(token), 20, 40).ToList();
var posts = (await _dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID); var posts = (await dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID);
return Json(await _mapper.Statuses(ids.Where(posts.ContainsKey).Select(id => posts[id]).ToList(), MyId, token)); return Json(await mapper.Statuses(ids.Where(posts.ContainsKey).Select(id => posts[id]).ToList(), MyId, token));
} }
[HttpGet("/api/v1/trends/links"), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet("/api/v1/trends/links"), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Links(CancellationToken token) public async Task<IActionResult> Links(CancellationToken token)
{ {
var trends = Window(await _trends.Links(token), 10, 20).ToList(); var trends = Window(await trendService.Links(token), 10, 20).ToList();
var sampleIds = trends.Select(t => t.SamplePostId).ToList(); var sampleIds = trends.Select(t => t.SamplePostId).ToList();
var samples = (await _dbEntities.Posts.Match(p => sampleIds.Contains(p.ID)).ExecuteAsync(token)).ToDictionary(p => p.ID); var samples = (await dbEntities.Posts.Match(p => sampleIds.Contains(p.ID)).ExecuteAsync(token)).ToDictionary(p => p.ID);
return Json(trends.Where(t => samples.ContainsKey(t.SamplePostId)).Select(t => return Json(trends.Where(t => samples.ContainsKey(t.SamplePostId)).Select(t =>
{ {
var link = samples[t.SamplePostId].Link; var link = samples[t.SamplePostId].Link;
var card = _mapper.LinkCard(t.Key, link.Title, link.Description, link.ImageURL); var card = mapper.LinkCard(t.Key, link.Title, link.Description, link.ImageURL);
return card == default ? default : (object)new return card == default ? default : (object)new
{ {
card.Url, card.Title, card.Description, card.Type, card.AuthorName, card.AuthorUrl, card.ProviderName, card.ProviderUrl, card.Url, card.Title, card.Description, card.Type, card.AuthorName, card.AuthorUrl, card.ProviderName, card.ProviderUrl,
@@ -96,24 +87,24 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (Params.Get("order") == "new") if (Params.Get("order") == "new")
{ {
// many share a day: the first `wanted` are read with every other of the last one's day, so each page is cut the same way // many share a day: the first `wanted` are read with every other of the last one's day, so each page is cut the same way
var personas = await _dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue) var personas = await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue)
.Sort(a => a.PublishedOn, Order.Descending).Limit(wanted).ExecuteAsync(token); .Sort(a => a.PublishedOn, Order.Descending).Limit(wanted).ExecuteAsync(token);
if (personas.Count == wanted) if (personas.Count == wanted)
{ {
var edge = personas[^1].PublishedOn; var edge = personas[^1].PublishedOn;
var known = personas.Select(a => a.ID).ToList(); var known = personas.Select(a => a.ID).ToList();
personas.AddRange(await _dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue personas.AddRange(await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue
&& a.PublishedOn == edge && !known.Contains(a.ID)).ExecuteAsync(token)); && a.PublishedOn == edge && !known.Contains(a.ID)).ExecuteAsync(token));
} }
var remote = localOnly var remote = localOnly
? new List<ForeignAvatar>() ? new List<ForeignAvatar>()
: await _dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue && f.Published != null) : await dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue && f.Published != null)
.Sort(f => f.Published, Order.Descending).Limit(wanted).ExecuteAsync(token); .Sort(f => f.Published, Order.Descending).Limit(wanted).ExecuteAsync(token);
if (remote.Count == wanted) if (remote.Count == wanted)
{ {
var edge = remote[^1].Published; var edge = remote[^1].Published;
var known = remote.Select(f => f.ID).ToList(); var known = remote.Select(f => f.ID).ToList();
remote.AddRange(await _dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue remote.AddRange(await dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue
&& f.Published == edge && !known.Contains(f.ID)).ExecuteAsync(token)); && f.Published == edge && !known.Contains(f.ID)).ExecuteAsync(token));
} }
ordered = personas.Select(a => (a.ID, Joined: a.PublishedOn, Tie: Tie(a.UserName))) ordered = personas.Select(a => (a.ID, Joined: a.PublishedOn, Tie: Tie(a.UserName)))
@@ -123,13 +114,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
else else
{ {
var discoverableLocal = (await _dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue) var discoverableLocal = (await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue)
.Project(a => a.Include(x => x.ID)).ExecuteAsync(token)).Select(a => a.ID).ToHashSet(); .Project(a => a.Include(x => x.ID)).ExecuteAsync(token)).Select(a => a.ID).ToHashSet();
var seen = new HashSet<string>(); var seen = new HashSet<string>();
var maxId = default(string); var maxId = default(string);
for (var round = 0; round < 20 && ordered.Count < wanted; round++) for (var round = 0; round < 20 && ordered.Count < wanted; round++)
{ {
var page = _dbEntities.Posts.Match(p => p.Visibility == Models.Post.PostVisibility.Public && !p.DeletedAt.HasValue && p.ReblogOfPostId == null); var page = dbEntities.Posts.Match(p => p.Visibility == Models.Post.PostVisibility.Public && !p.DeletedAt.HasValue && p.ReblogOfPostId == null);
if (maxId != default) if (maxId != default)
page.Match(f => f.Lt(p => p.ID, maxId)); page.Match(f => f.Lt(p => p.ID, maxId));
if (localOnly) if (localOnly)
@@ -144,13 +135,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
var remoteIds = fresh.Where(a => a.IsFederatedCopy).Select(a => a.Id).ToList(); var remoteIds = fresh.Where(a => a.IsFederatedCopy).Select(a => a.Id).ToList();
var discoverableRemote = remoteIds.Count == 0 var discoverableRemote = remoteIds.Count == 0
? new HashSet<string>() ? new HashSet<string>()
: (await _dbEntities.ForeignAvatars.Match(f => remoteIds.Contains(f.ID) && f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue) : (await dbEntities.ForeignAvatars.Match(f => remoteIds.Contains(f.ID) && f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue)
.Project(f => f.Include(x => x.ID)).ExecuteAsync(token)).Select(f => f.ID).ToHashSet(); .Project(f => f.Include(x => x.ID)).ExecuteAsync(token)).Select(f => f.ID).ToHashSet();
ordered.AddRange(fresh.Where(a => a.IsFederatedCopy ? discoverableRemote.Contains(a.Id) : discoverableLocal.Contains(a.Id)).Select(a => a.Id)); ordered.AddRange(fresh.Where(a => a.IsFederatedCopy ? discoverableRemote.Contains(a.Id) : discoverableLocal.Contains(a.Id)).Select(a => a.Id));
} }
ordered = ordered.Skip(offset).Take(limit).ToList(); ordered = ordered.Skip(offset).Take(limit).ToList();
} }
var accounts = await _mapper.Accounts(ordered, token); var accounts = await mapper.Accounts(ordered, token);
return Json(ordered.Where(accounts.ContainsKey).Select(id => accounts[id]).ToList()); return Json(ordered.Where(accounts.ContainsKey).Select(id => accounts[id]).ToList());
} }
@@ -9,26 +9,20 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Mastodon 4.4's OAuth userinfo (OpenID Connect's shape, GET or POST, the `profile` scope): who the token's persona is, // Mastodon 4.4's OAuth userinfo (OpenID Connect's shape, GET or POST, the `profile` scope): who the token's persona is,
// for a site that signs in with it. Only what its public account says already; never its login. The authorization // for a site that signs in with it. Only what its public account says already; never its login. The authorization
// server's metadata names it (OAuthSetup). // server's metadata names it (OAuthSetup).
public class UserinfoController : MastodonController public class UserinfoController(
MastodonMapper mapper,
ILocalActorService localActors) : MastodonController
{ {
public const string Path = "/oauth/userinfo"; public const string Path = "/oauth/userinfo";
readonly MastodonMapper _mapper;
readonly ILocalActorService _localActors;
public UserinfoController(MastodonMapper mapper, ILocalActorService localActors)
{
_mapper = mapper;
_localActors = localActors;
}
[HttpGet(Path), HttpPost(Path), Scope("profile")] [HttpGet(Path), HttpPost(Path), Scope("profile")]
public async Task<IActionResult> Show(CancellationToken token) public async Task<IActionResult> Show(CancellationToken token)
{ {
var account = await _mapper.Local(Me, false, token); var account = await mapper.Local(Me, false, token);
return Json(new return Json(new
{ {
iss = _localActors.BaseAddress + "/", iss = localActors.BaseAddress + "/",
sub = Me.Uri, sub = Me.Uri,
name = account.DisplayName, name = account.DisplayName,
preferred_username = account.Username, preferred_username = account.Username,
@@ -29,7 +29,9 @@
public List<object> Roles { get; set; } = new(); public List<object> Roles { get; set; } = new();
public bool? Memorial { get; set; } public bool? Memorial { get; set; }
public bool? Limited { get; set; }//silenced by this server's staff, or its server silenced (Mastodon's `limited`) public bool? Limited { get; set; }//silenced by this server's staff, or its server silenced (Mastodon's `limited`)
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string AvatarDescription { get; set; } = string.Empty; public string AvatarDescription { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string HeaderDescription { get; set; } = string.Empty; public string HeaderDescription { get; set; } = string.Empty;
public List<Field> Fields { get; set; } = new(); public List<Field> Fields { get; set; } = new();
public Source Source { get; set; } public Source Source { get; set; }
@@ -57,6 +59,7 @@
public string Privacy { get; set; } = "public"; public string Privacy { get; set; } = "public";
public bool Sensitive { get; set; } public bool Sensitive { get; set; }
public string Language { get; set; } public string Language { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Note { get; set; } = string.Empty; public string Note { get; set; } = string.Empty;
public List<Field> Fields { get; set; } = new(); public List<Field> Fields { get; set; } = new();
public int FollowRequestsCount { get; set; } public int FollowRequestsCount { get; set; }
@@ -225,7 +228,9 @@
public class FilterResultEntity public class FilterResultEntity
{ {
public FilterEntity Filter { get; set; } public FilterEntity Filter { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "The Mastodon API sends null when no keyword of the filter matched.")]
public List<string> KeywordMatches { get; set; } public List<string> KeywordMatches { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "The Mastodon API sends null when no status of the filter matched.")]
public List<string> StatusMatches { get; set; } public List<string> StatusMatches { get; set; }
} }
@@ -263,6 +268,7 @@
public int VotesCount { get; set; } public int VotesCount { get; set; }
public int? VotersCount { get; set; } public int? VotersCount { get; set; }
public bool? Voted { get; set; } public bool? Voted { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "The Mastodon API leaves own_votes null for a viewer who is not signed in.")]
public List<int> OwnVotes { get; set; } public List<int> OwnVotes { get; set; }
public List<PollOptionEntity> Options { get; set; } = new(); public List<PollOptionEntity> Options { get; set; } = new();
public List<CustomEmojiEntity> Emojis { get; set; } = new(); public List<CustomEmojiEntity> Emojis { get; set; } = new();
@@ -277,18 +283,27 @@
public class PreviewCard public class PreviewCard
{ {
public string Url { get; set; } public string Url { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Title { get; set; } = string.Empty; public string Title { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Description { get; set; } = string.Empty; public string Description { get; set; } = string.Empty;
public string Type { get; set; } = "link"; public string Type { get; set; } = "link";
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string AuthorName { get; set; } = string.Empty; public string AuthorName { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string AuthorUrl { get; set; } = string.Empty; public string AuthorUrl { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string ProviderName { get; set; } = string.Empty; public string ProviderName { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string ProviderUrl { get; set; } = string.Empty; public string ProviderUrl { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Html { get; set; } = string.Empty; public string Html { get; set; } = string.Empty;
public int Width { get; set; } public int Width { get; set; }
public int Height { get; set; } public int Height { get; set; }
public string Image { get; set; } public string Image { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string ImageDescription { get; set; } = string.Empty; public string ImageDescription { get; set; } = string.Empty;
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string EmbedUrl { get; set; } = string.Empty; public string EmbedUrl { get; set; } = string.Empty;
public string Blurhash { get; set; } public string Blurhash { get; set; }
public string Language { get; set; } public string Language { get; set; }
@@ -305,6 +320,7 @@
public string InReplyToId { get; set; } public string InReplyToId { get; set; }
public string InReplyToAccountId { get; set; } public string InReplyToAccountId { get; set; }
public Status Reblog { get; set; } public Status Reblog { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Content { get; set; } = string.Empty; public string Content { get; set; } = string.Empty;
public string CreatedAt { get; set; } public string CreatedAt { get; set; }
public string EditedAt { get; set; } public string EditedAt { get; set; }
@@ -318,6 +334,7 @@
public bool Bookmarked { get; set; } public bool Bookmarked { get; set; }
public bool Pinned { get; set; } public bool Pinned { get; set; }
public bool Sensitive { get; set; } public bool Sensitive { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string SpoilerText { get; set; } = string.Empty; public string SpoilerText { get; set; } = string.Empty;
public string Visibility { get; set; } public string Visibility { get; set; }
public List<MediaAttachment> MediaAttachments { get; set; } = new(); public List<MediaAttachment> MediaAttachments { get; set; } = new();
@@ -388,6 +405,7 @@
public string RedirectUri { get; set; } public string RedirectUri { get; set; }
public string ClientId { get; set; } public string ClientId { get; set; }
public string ClientSecret { get; set; } public string ClientSecret { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string VapidKey { get; set; } = string.Empty; public string VapidKey { get; set; } = string.Empty;
} }
@@ -397,6 +415,7 @@
public bool Following { get; set; } public bool Following { get; set; }
public bool ShowingReblogs { get; set; } public bool ShowingReblogs { get; set; }
public bool Notifying { get; set; } public bool Notifying { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "The Mastodon API sends null when every language of the account is followed.")]
public List<string> Languages { get; set; } public List<string> Languages { get; set; }
public bool FollowedBy { get; set; } public bool FollowedBy { get; set; }
public bool Blocking { get; set; } public bool Blocking { get; set; }
@@ -407,6 +426,7 @@
public bool RequestedBy { get; set; } public bool RequestedBy { get; set; }
public bool DomainBlocking { get; set; } public bool DomainBlocking { get; set; }
public bool Endorsed { get; set; } public bool Endorsed { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Note { get; set; } = string.Empty; public string Note { get; set; } = string.Empty;
} }
@@ -445,6 +465,7 @@
{ {
public string Id { get; set; } public string Id { get; set; }
public string Action { get; set; } = "none"; public string Action { get; set; } = "none";
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0005", Justification = "The Mastodon API sends this as a string, \"\" when empty; clients break on null.")]
public string Text { get; set; } = string.Empty; public string Text { get; set; } = string.Empty;
public List<string> StatusIds { get; set; } = new(); public List<string> StatusIds { get; set; } = new();
public Account TargetAccount { get; set; } public Account TargetAccount { get; set; }
+19 -28
View File
@@ -4,21 +4,12 @@ using PrivaPub.StaticServices;
namespace PrivaPub.Api.Mastodon.Mappers namespace PrivaPub.Api.Mastodon.Mappers
{ {
public class AccountSearch public class AccountSearch(
MastodonMapper mapper,
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors)
{ {
readonly MastodonMapper _mapper;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
public AccountSearch(MastodonMapper mapper, DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors)
{
_mapper = mapper;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
}
public async Task<List<Account>> Find(string q, bool resolve, int limit, CancellationToken token) => await Find(q, resolve, limit, 0, token); public async Task<List<Account>> Find(string q, bool resolve, int limit, CancellationToken token) => await Find(q, resolve, limit, 0, token);
// following=true: only accounts the persona follows, matched by the start of their name, display name or server // following=true: only accounts the persona follows, matched by the start of their name, display name or server
@@ -26,22 +17,22 @@ namespace PrivaPub.Api.Mastodon.Mappers
public async Task<List<Account>> Followed(string viewerId, string q, int limit, CancellationToken token) public async Task<List<Account>> Followed(string viewerId, string q, int limit, CancellationToken token)
{ {
q = q?.Trim().TrimStart('@') ?? string.Empty; q = q?.Trim().TrimStart('@') ?? string.Empty;
var ids = (await _dbEntities.Followings.Match(f => f.AvatarId == viewerId && f.State == Models.Social.FollowState.Accepted).ExecuteAsync(token)) var ids = (await dbEntities.Followings.Match(f => f.AvatarId == viewerId && f.State == Models.Social.FollowState.Accepted).ExecuteAsync(token))
.Select(f => f.TargetAccountId).Where(id => !string.IsNullOrEmpty(id)).ToList(); .Select(f => f.TargetAccountId).Where(id => !string.IsNullOrEmpty(id)).ToList();
if (ids.Count == 0) if (ids.Count == 0)
return new List<Account>(); return new List<Account>();
var parts = q.Split('@'); var parts = q.Split('@');
var localDomain = new Uri(_localActors.BaseAddress).Authority; var localDomain = new Uri(localActors.BaseAddress).Authority;
bool Matches(string userName, string name, string domain) => bool Matches(string userName, string name, string domain) =>
userName?.StartsWith(parts[0], StringComparison.OrdinalIgnoreCase) == true userName?.StartsWith(parts[0], StringComparison.OrdinalIgnoreCase) == true
&& (parts.Length < 2 || domain?.StartsWith(parts[1], StringComparison.OrdinalIgnoreCase) == true) && (parts.Length < 2 || domain?.StartsWith(parts[1], StringComparison.OrdinalIgnoreCase) == true)
|| parts.Length == 1 && name?.Contains(q, StringComparison.OrdinalIgnoreCase) == true; || parts.Length == 1 && name?.Contains(q, StringComparison.OrdinalIgnoreCase) == true;
var found = (await _dbEntities.Avatars.Match(a => ids.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)) var found = (await dbEntities.Avatars.Match(a => ids.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token))
.Where(a => Matches(a.UserName, a.Name, localDomain)).Select(a => (a.UserName, a.ID)) .Where(a => Matches(a.UserName, a.Name, localDomain)).Select(a => (a.UserName, a.ID))
.Concat((await _dbEntities.ForeignAvatars.Match(f => ids.Contains(f.ID) && !f.DeletionAt.HasValue).ExecuteAsync(token)) .Concat((await dbEntities.ForeignAvatars.Match(f => ids.Contains(f.ID) && !f.DeletionAt.HasValue).ExecuteAsync(token))
.Where(f => Matches(f.UserName, f.Name, f.Domain)).Select(f => (f.UserName, f.ID))) .Where(f => Matches(f.UserName, f.Name, f.Domain)).Select(f => (f.UserName, f.ID)))
.OrderBy(a => a.UserName, StringComparer.OrdinalIgnoreCase).Take(limit).Select(a => a.ID).ToList(); .OrderBy(a => a.UserName, StringComparer.OrdinalIgnoreCase).Take(limit).Select(a => a.ID).ToList();
var accounts = await _mapper.Accounts(found, token); var accounts = await mapper.Accounts(found, token);
return found.Where(accounts.ContainsKey).Select(id => accounts[id]).ToList(); return found.Where(accounts.ContainsKey).Select(id => accounts[id]).ToList();
} }
@@ -53,39 +44,39 @@ namespace PrivaPub.Api.Mastodon.Mappers
return new List<Account>(); return new List<Account>();
var results = new List<Account>(); var results = new List<Account>();
var parts = q.Split('@'); var parts = q.Split('@');
var localDomain = new Uri(_localActors.BaseAddress).Authority; var localDomain = new Uri(localActors.BaseAddress).Authority;
if (parts.Length == 2 && !parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(parts[0])) if (parts.Length == 2 && !parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(parts[0]))
{ {
var userName = parts[0]; var userName = parts[0];
var domain = parts[1].ToLowerInvariant(); var domain = parts[1].ToLowerInvariant();
var known = await _dbEntities.ForeignAvatars.Match(f => f.UserName == userName && f.Domain == domain && !f.DeletionAt.HasValue).ExecuteFirstAsync(token); var known = await dbEntities.ForeignAvatars.Match(f => f.UserName == userName && f.Domain == domain && !f.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (known == default && resolve) if (known == default && resolve)
{ {
var actorUri = await _remoteActors.ResolveHandle(q, token); var actorUri = await remoteActors.ResolveHandle(q, token);
known = actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token); known = actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token);
} }
if (known is { DeletionAt: null, SuspendedAt: null } && offset == 0) if (known is { DeletionAt: null, SuspendedAt: null } && offset == 0)
results.Add(_mapper.Foreign(known)); results.Add(mapper.Foreign(known));
return results; return results;
} }
var prefix = parts[0].ToLowerInvariant(); var prefix = parts[0].ToLowerInvariant();
var barred = await Domain.Privacy.Counted.HeldBackPersonas(token); var barred = await Domain.Privacy.Counted.HeldBackPersonas(token);
var locals = await _dbEntities.Avatars var locals = await dbEntities.Avatars
// a silenced persona is found only by its exact name (R6), as its followers look for it // a silenced persona is found only by its exact name (R6), as its followers look for it
.Match(a => a.UserName.StartsWith(prefix) && !a.DeletionAt.HasValue && a.Settings.IsDiscoverable != false && !barred.Contains(a.ID) .Match(a => a.UserName.StartsWith(prefix) && !a.DeletionAt.HasValue && a.Settings.IsDiscoverable != false && !barred.Contains(a.ID)
&& (!a.SilencedAt.HasValue || a.UserName == prefix)) && (!a.SilencedAt.HasValue || a.UserName == prefix))
.Sort(a => a.UserName, MongoDB.Entities.Order.Ascending) .Sort(a => a.UserName, MongoDB.Entities.Order.Ascending)
.Limit(offset + limit).ExecuteAsync(token); .Limit(offset + limit).ExecuteAsync(token);
foreach (var avatar in locals.Skip(offset)) foreach (var avatar in locals.Skip(offset))
results.Add(await _mapper.Local(_localActors.FromAvatar(avatar), false, token)); results.Add(await mapper.Local(localActors.FromAvatar(avatar), false, token));
var skipRemote = Math.Max(0, offset - locals.Count); var skipRemote = Math.Max(0, offset - locals.Count);
if (results.Count < limit) if (results.Count < limit)
foreach (var foreign in await _dbEntities.ForeignAvatars.Match(f => f.UserName.StartsWith(parts[0]) && f.IsDiscoverable && !f.DeletionAt.HasValue foreach (var foreign in await dbEntities.ForeignAvatars.Match(f => f.UserName.StartsWith(parts[0]) && f.IsDiscoverable && !f.DeletionAt.HasValue
&& !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue) && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue)
.Sort(f => f.UserName, MongoDB.Entities.Order.Ascending) .Sort(f => f.UserName, MongoDB.Entities.Order.Ascending)
.Skip(skipRemote).Limit(limit - results.Count).ExecuteAsync(token)) .Skip(skipRemote).Limit(limit - results.Count).ExecuteAsync(token))
results.Add(_mapper.Foreign(foreign)); results.Add(mapper.Foreign(foreign));
return results; return results;
} }
} }
+33 -42
View File
@@ -24,23 +24,13 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Api.Mastodon.Mappers namespace PrivaPub.Api.Mastodon.Mappers
{ {
public class MastodonMapper public class MastodonMapper(
DbEntities dbEntities,
ILocalActorService localActors,
IMediaProxy proxy = default,
PrivaPub.Federation.Moderation.IDomainBlocks domainBlocks = default)
{ {
readonly DbEntities _dbEntities; string Proxied(string url) => proxy == default ? url : proxy.Wrap(url);
readonly ILocalActorService _localActors;
readonly IMediaProxy _proxy;
readonly PrivaPub.Federation.Moderation.IDomainBlocks _domainBlocks;
public MastodonMapper(DbEntities dbEntities, ILocalActorService localActors, IMediaProxy proxy = default,
PrivaPub.Federation.Moderation.IDomainBlocks domainBlocks = default)
{
_dbEntities = dbEntities;
_localActors = localActors;
_proxy = proxy;
_domainBlocks = domainBlocks;
}
string Proxied(string url) => _proxy == default ? url : _proxy.Wrap(url);
public string ProxiedUrl(string url) => Proxied(url); public string ProxiedUrl(string url) => Proxied(url);
@@ -51,7 +41,7 @@ namespace PrivaPub.Api.Mastodon.Mappers
var postIds = notifications.Where(n => n.PostId != default).Select(n => n.PostId).Distinct().ToList(); var postIds = notifications.Where(n => n.PostId != default).Select(n => n.PostId).Distinct().ToList();
var posts = postIds.Count == 0 var posts = postIds.Count == 0
? new List<PostEntity>() ? new List<PostEntity>()
: await _dbEntities.Posts.Match(p => postIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token); : await dbEntities.Posts.Match(p => postIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token);
var statuses = (await Statuses(posts, viewerId, token)).ToDictionary(s => s.Id); var statuses = (await Statuses(posts, viewerId, token)).ToDictionary(s => s.Id);
var warned = notifications.Any(n => n.Type == NotificationType.ModerationWarning) && viewerId != default ? await Account(viewerId, token) : default; var warned = notifications.Any(n => n.Type == NotificationType.ModerationWarning) && viewerId != default ? await Account(viewerId, token) : default;
return notifications return notifications
@@ -82,8 +72,8 @@ namespace PrivaPub.Api.Mastodon.Mappers
.ToList(); .ToList();
} }
string MissingAvatar => $"{_localActors.BaseAddress}/media/missing-avatar.png"; string MissingAvatar => $"{localActors.BaseAddress}/media/missing-avatar.png";
string MissingHeader => $"{_localActors.BaseAddress}/media/missing-header.png"; string MissingHeader => $"{localActors.BaseAddress}/media/missing-header.png";
public async Task<Account> Local(LocalActor actor, bool withSource, CancellationToken token) public async Task<Account> Local(LocalActor actor, bool withSource, CancellationToken token)
{ {
@@ -91,7 +81,7 @@ namespace PrivaPub.Api.Mastodon.Mappers
var following = actor.Kind == LocalActorKind.Person var following = actor.Kind == LocalActorKind.Person
? await DB.Default.CountAsync<Following>(f => f.AvatarId == actor.Id && f.State == FollowState.Accepted, token) ? await DB.Default.CountAsync<Following>(f => f.AvatarId == actor.Id && f.State == FollowState.Accepted, token)
: 0; : 0;
var latest = await _dbEntities.Posts var latest = await dbEntities.Posts
.Match(Counted.By(actor)) .Match(Counted.By(actor))
.Sort(p => p.ID, Order.Descending) .Sort(p => p.ID, Order.Descending)
.Limit(1) .Limit(1)
@@ -172,8 +162,8 @@ namespace PrivaPub.Api.Mastodon.Mappers
}; };
bool DomainSilenced(ForeignAvatar foreign) => bool DomainSilenced(ForeignAvatar foreign) =>
_domainBlocks != default && Uri.TryCreate(foreign.ActorURI, UriKind.Absolute, out var uri) domainBlocks != default && Uri.TryCreate(foreign.ActorURI, UriKind.Absolute, out var uri)
&& _domainBlocks.Find(uri.Host)?.Severity == DomainBlockSeverity.Silence; && domainBlocks.Find(uri.Host)?.Severity == DomainBlockSeverity.Silence;
public async Task<Account> Account(string id, CancellationToken token) => public async Task<Account> Account(string id, CancellationToken token) =>
(await Accounts(new[] { id }, token)).GetValueOrDefault(id); (await Accounts(new[] { id }, token)).GetValueOrDefault(id);
@@ -187,19 +177,19 @@ namespace PrivaPub.Api.Mastodon.Mappers
// a suspended account, here or elsewhere, and a banned login's personas are shown to nobody (R6): their posts and // a suspended account, here or elsewhere, and a banned login's personas are shown to nobody (R6): their posts and
// what they notify are left out with them, wherever a list holds them // what they notify are left out with them, wherever a list holds them
foreach (var avatar in await _dbEntities.Avatars.Match(a => wanted.Contains(a.ID) && !a.DeletionAt.HasValue && !a.SuspendedAt.HasValue).ExecuteAsync(token)) foreach (var avatar in await dbEntities.Avatars.Match(a => wanted.Contains(a.ID) && !a.DeletionAt.HasValue && !a.SuspendedAt.HasValue).ExecuteAsync(token))
if (_localActors.FromAvatar(avatar) is { Suspended: false } persona) if (localActors.FromAvatar(avatar) is { Suspended: false } persona)
accounts[avatar.ID] = await Local(persona, false, token); accounts[avatar.ID] = await Local(persona, false, token);
foreach (var group in await _dbEntities.Groups.Match(g => wanted.Contains(g.ID) && !g.DeletionAt.HasValue && g.Kind == GroupKind.Community).ExecuteAsync(token)) foreach (var group in await dbEntities.Groups.Match(g => wanted.Contains(g.ID) && !g.DeletionAt.HasValue && g.Kind == GroupKind.Community).ExecuteAsync(token))
accounts[group.ID] = await Local(_localActors.FromGroup(group), false, token); accounts[group.ID] = await Local(localActors.FromGroup(group), false, token);
var foreigns = await _dbEntities.ForeignAvatars.Match(f => wanted.Contains(f.ID) && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue).ExecuteAsync(token); var foreigns = await dbEntities.ForeignAvatars.Match(f => wanted.Contains(f.ID) && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue).ExecuteAsync(token);
foreach (var foreign in foreigns) foreach (var foreign in foreigns)
accounts[foreign.ID] = Foreign(foreign); accounts[foreign.ID] = Foreign(foreign);
// an account that moved shows where to, once the new account names it as one of its own (as a Move is believed) // an account that moved shows where to, once the new account names it as one of its own (as a Move is believed)
var movedTo = foreigns.Where(f => !string.IsNullOrEmpty(f.MovedToURL)).Select(f => f.MovedToURL).Distinct().ToList(); var movedTo = foreigns.Where(f => !string.IsNullOrEmpty(f.MovedToURL)).Select(f => f.MovedToURL).Distinct().ToList();
if (movedTo.Count > 0) if (movedTo.Count > 0)
{ {
var targets = (await _dbEntities.ForeignAvatars.Match(f => movedTo.Contains(f.ActorURI) && !f.DeletionAt.HasValue).ExecuteAsync(token)) var targets = (await dbEntities.ForeignAvatars.Match(f => movedTo.Contains(f.ActorURI) && !f.DeletionAt.HasValue).ExecuteAsync(token))
.ToDictionary(f => f.ActorURI); .ToDictionary(f => f.ActorURI);
foreach (var foreign in foreigns) foreach (var foreign in foreigns)
if (foreign.MovedToURL != default && targets.TryGetValue(foreign.MovedToURL, out var target) && target.AlsoKnownAs.Contains(foreign.ActorURI)) if (foreign.MovedToURL != default && targets.TryGetValue(foreign.MovedToURL, out var target) && target.AlsoKnownAs.Contains(foreign.ActorURI))
@@ -209,32 +199,33 @@ namespace PrivaPub.Api.Mastodon.Mappers
} }
public async Task<Status> Status(PostEntity post, string viewerId, CancellationToken token) => public async Task<Status> Status(PostEntity post, string viewerId, CancellationToken token) =>
(await Statuses(new[] { post }, viewerId, nested: false, token, hideFromViewer: false)).FirstOrDefault(); (await Statuses(new[] { post }, viewerId, nested: false, hideFromViewer: false, token)).FirstOrDefault();
public Task<List<Status>> Statuses(IReadOnlyCollection<PostEntity> posts, string viewerId, CancellationToken token) => public Task<List<Status>> Statuses(IReadOnlyCollection<PostEntity> posts, string viewerId, CancellationToken token) =>
Statuses(posts, viewerId, nested: false, token); Statuses(posts, viewerId, nested: false, token: token);
// Lists leave out what the viewer blocked or muted; a status asked for by its id is still shown, as Mastodon shows it // Lists leave out what the viewer blocked or muted; a status asked for by its id is still shown, as Mastodon shows it
// (only its author's block of the viewer hides it, and that is decided before mapping) // (only its author's block of the viewer hides it, and that is decided before mapping)
async Task<List<Status>> Statuses(IReadOnlyCollection<PostEntity> posts, string viewerId, bool nested, CancellationToken token, async Task<List<Status>> Statuses(IReadOnlyCollection<PostEntity> posts, string viewerId, bool nested,
bool hideFromViewer = true) bool hideFromViewer = true,
CancellationToken token = default)
{ {
var originalIds = posts.Where(p => p.ReblogOfPostId != default).Select(p => p.ReblogOfPostId).Distinct().ToList(); var originalIds = posts.Where(p => p.ReblogOfPostId != default).Select(p => p.ReblogOfPostId).Distinct().ToList();
var originals = originalIds.Count == 0 var originals = originalIds.Count == 0
? new Dictionary<string, PostEntity>() ? new Dictionary<string, PostEntity>()
: (await _dbEntities.Posts.Match(p => originalIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID); : (await dbEntities.Posts.Match(p => originalIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID);
var all = posts.Concat(originals.Values).ToList(); var all = posts.Concat(originals.Values).ToList();
var mentionUris = all.SelectMany(p => p.Mentions).Where(m => !m.IsLocal).Select(m => m.ActorURI).Distinct().ToList(); var mentionUris = all.SelectMany(p => p.Mentions).Where(m => !m.IsLocal).Select(m => m.ActorURI).Distinct().ToList();
var mentionAccounts = mentionUris.Count == 0 var mentionAccounts = mentionUris.Count == 0
? new Dictionary<string, ForeignAvatar>() ? new Dictionary<string, ForeignAvatar>()
: (await _dbEntities.ForeignAvatars.Match(f => mentionUris.Contains(f.ActorURI)).ExecuteAsync(token)).ToDictionary(f => f.ActorURI); : (await dbEntities.ForeignAvatars.Match(f => mentionUris.Contains(f.ActorURI)).ExecuteAsync(token)).ToDictionary(f => f.ActorURI);
var accounts = await Accounts(all.Select(AuthorOf).Concat(all.Select(p => p.WallOwnerAccountId).Where(w => w != default)), token); var accounts = await Accounts(all.Select(AuthorOf).Concat(all.Select(p => p.WallOwnerAccountId).Where(w => w != default)), token);
var ids = all.Select(p => p.ID).ToList(); var ids = all.Select(p => p.ID).ToList();
var favourited = viewerId == default var favourited = viewerId == default
? new HashSet<string>() ? new HashSet<string>()
: (await _dbEntities.Favourites.Match(f => f.AccountId == viewerId && ids.Contains(f.PostId)).ExecuteAsync(token)).Select(f => f.PostId).ToHashSet(); : (await dbEntities.Favourites.Match(f => f.AccountId == viewerId && ids.Contains(f.PostId)).ExecuteAsync(token)).Select(f => f.PostId).ToHashSet();
var downvoted = viewerId == default var downvoted = viewerId == default
? new HashSet<string>() ? new HashSet<string>()
: (await DB.Default.Find<Downvote>().Match(d => d.AccountId == viewerId && ids.Contains(d.PostId)).ExecuteAsync(token)).Select(d => d.PostId).ToHashSet(); : (await DB.Default.Find<Downvote>().Match(d => d.AccountId == viewerId && ids.Contains(d.PostId)).ExecuteAsync(token)).Select(d => d.PostId).ToHashSet();
@@ -271,7 +262,7 @@ namespace PrivaPub.Api.Mastodon.Mappers
var filters = await Domain.Social.Filters.Of(viewerId, token); var filters = await Domain.Social.Filters.Of(viewerId, token);
var reblogged = viewerId == default var reblogged = viewerId == default
? new HashSet<string>() ? new HashSet<string>()
: (await _dbEntities.Posts.Match(p => p.AuthorAccountId == viewerId && ids.Contains(p.ReblogOfPostId) && !p.DeletedAt.HasValue).ExecuteAsync(token)) : (await dbEntities.Posts.Match(p => p.AuthorAccountId == viewerId && ids.Contains(p.ReblogOfPostId) && !p.DeletedAt.HasValue).ExecuteAsync(token))
.Select(p => p.ReblogOfPostId).ToHashSet(); .Select(p => p.ReblogOfPostId).ToHashSet();
Status Map(PostEntity post) Status Map(PostEntity post)
@@ -310,7 +301,7 @@ namespace PrivaPub.Api.Mastodon.Mappers
EmojiReactions = reactions.GetValueOrDefault(post.ID) ?? new(), EmojiReactions = reactions.GetValueOrDefault(post.ID) ?? new(),
Pleroma = new PleromaStatus { EmojiReactions = reactions.GetValueOrDefault(post.ID) ?? new() }, Pleroma = new PleromaStatus { EmojiReactions = reactions.GetValueOrDefault(post.ID) ?? new() },
Mentions = post.Mentions.Where(m => !m.Silent).Select(m => Mention(m, mentionAccounts)).Where(m => m != default).ToList(), Mentions = post.Mentions.Where(m => !m.Silent).Select(m => Mention(m, mentionAccounts)).Where(m => m != default).ToList(),
Tags = post.Tags.Select(t => new StatusTag { Name = t, Url = ActivityPubRenderer.TagUrl(_localActors.BaseAddress, t) }).ToList(), Tags = post.Tags.Select(t => new StatusTag { Name = t, Url = ActivityPubRenderer.TagUrl(localActors.BaseAddress, t) }).ToList(),
Filtered = filters.Of(post) Filtered = filters.Of(post)
}; };
return status; return status;
@@ -322,12 +313,12 @@ namespace PrivaPub.Api.Mastodon.Mappers
: await FollowedLocalAuthors(viewerId, localAuthors, token); : await FollowedLocalAuthors(viewerId, localAuthors, token);
var quotedIds = nested ? new List<string>() : all.Where(p => p.QuoteState == QuoteState.Accepted && p.QuotedPostId != default).Select(p => p.QuotedPostId).Distinct().ToList(); var quotedIds = nested ? new List<string>() : all.Where(p => p.QuoteState == QuoteState.Accepted && p.QuotedPostId != default).Select(p => p.QuotedPostId).Distinct().ToList();
var quotedPosts = new List<PostEntity>(); var quotedPosts = new List<PostEntity>();
foreach (var quotedPost in quotedIds.Count == 0 ? new List<PostEntity>() : await _dbEntities.Posts.Match(p => quotedIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)) foreach (var quotedPost in quotedIds.Count == 0 ? new List<PostEntity>() : await dbEntities.Posts.Match(p => quotedIds.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token))
if (quotedPost.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(quotedPost, viewerId, token)) if (quotedPost.Visibility != PostVisibility.LocalGeo && await VisibilityPolicy.CanSee(quotedPost, viewerId, token))
quotedPosts.Add(quotedPost); quotedPosts.Add(quotedPost);
var quotedStatuses = quotedPosts.Count == 0 var quotedStatuses = quotedPosts.Count == 0
? new Dictionary<string, Status>() ? new Dictionary<string, Status>()
: (await Statuses(quotedPosts, viewerId, nested: true, token)).ToDictionary(q => q.Id); : (await Statuses(quotedPosts, viewerId, nested: true, token: token)).ToDictionary(q => q.Id);
void Quote(Status status, PostEntity post) void Quote(Status status, PostEntity post)
{ {
@@ -390,10 +381,10 @@ namespace PrivaPub.Api.Mastodon.Mappers
async Task<HashSet<string>> FollowedLocalAuthors(string viewerId, List<string> authorIds, CancellationToken token) async Task<HashSet<string>> FollowedLocalAuthors(string viewerId, List<string> authorIds, CancellationToken token)
{ {
var uris = new Dictionary<string, string>(); var uris = new Dictionary<string, string>();
foreach (var avatar in await _dbEntities.Avatars.Match(a => authorIds.Contains(a.ID)).ExecuteAsync(token)) foreach (var avatar in await dbEntities.Avatars.Match(a => authorIds.Contains(a.ID)).ExecuteAsync(token))
uris[_localActors.FromAvatar(avatar).Uri] = avatar.ID; uris[localActors.FromAvatar(avatar).Uri] = avatar.ID;
var targets = uris.Keys.ToList(); var targets = uris.Keys.ToList();
return (await _dbEntities.Followings.Match(f => f.AvatarId == viewerId && targets.Contains(f.TargetActorURI) && f.State == FollowState.Accepted).ExecuteAsync(token)) return (await dbEntities.Followings.Match(f => f.AvatarId == viewerId && targets.Contains(f.TargetActorURI) && f.State == FollowState.Accepted).ExecuteAsync(token))
.Select(f => uris[f.TargetActorURI]).ToHashSet(); .Select(f => uris[f.TargetActorURI]).ToHashSet();
} }
@@ -31,31 +31,16 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/admin"), Route("clientapi/admin"),
Authorize(Policy = Policies.IsAdmin)] Authorize(Policy = Policies.IsAdmin)]
public class AdminController : ControllerBase public class AdminController(
ILogger<RootUserController> logger,
IStringLocalizer<GenericRes> localizer,
IRootUsersService rootUsersService,
IModerationLog moderationLog,
DbEntities dbEntities,
ILocalActorService localActors) : ControllerBase
{ {
const int MaxRootsPage = 100; const int MaxRootsPage = 100;
readonly IRootUsersService RootUsersService;
readonly ILogger<RootUserController> Logger;
readonly IStringLocalizer Localizer;
readonly IModerationLog _log;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
public AdminController(ILogger<RootUserController> logger,
IStringLocalizer<GenericRes> localizer,
IRootUsersService rootUsersService,
IModerationLog log,
DbEntities dbEntities,
ILocalActorService localActors)
{
Logger = logger;
Localizer = localizer;
RootUsersService = rootUsersService;
_log = log;
_dbEntities = dbEntities;
_localActors = localActors;
}
// an administrator never removes, bans or unbans itself; the request's own list is left as it came // an administrator never removes, bans or unbans itself; the request's own list is left as it came
UsersIds Others(UsersIds usersIds) UsersIds Others(UsersIds usersIds)
@@ -81,17 +66,17 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var others = Others(usersIds); var others = Others(usersIds);
var named = await Named(others, token); var named = await Named(others, token);
result = await RootUsersService.RemoveUserAsync(others); result = await rootUsersService.RemoveUserAsync(others, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
foreach (var (id, name) in named) foreach (var (id, name) in named)
await _log.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.RootDelete, AdminTargets.Root, id, name, token: CancellationToken.None);
return Ok(); return Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -108,7 +93,7 @@ namespace PrivaPub.Controllers.ClientToServer
var others = Others(usersIds); var others = Others(usersIds);
var named = await Named(others, token); var named = await Named(others, token);
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet(); var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
result = await RootUsersService.BanUserAsync(others); result = await rootUsersService.BanUserAsync(others, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -116,16 +101,16 @@ namespace PrivaPub.Controllers.ClientToServer
foreach (var (id, name) in named.Where(n => !banned.Contains(n.Key))) foreach (var (id, name) in named.Where(n => !banned.Contains(n.Key)))
{ {
await sessions.Revoke(id, CancellationToken.None); await sessions.Revoke(id, CancellationToken.None);
foreach (var link in await _dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token)) foreach (var link in await dbEntities.RootToAvatars.Match(ra => ra.RootId == id).ExecuteAsync(token))
Streams.CloseFor(link.AvatarId); Streams.CloseFor(link.AvatarId);
await _log.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.RootBan, AdminTargets.Root, id, name, token: CancellationToken.None);
} }
return Ok(); return Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(BanUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -140,18 +125,18 @@ namespace PrivaPub.Controllers.ClientToServer
var others = Others(usersIds); var others = Others(usersIds);
var named = await Named(others, token); var named = await Named(others, token);
var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet(); var banned = (await DB.Default.Find<RootUser>().Match(u => others.UserIdList.Contains(u.ID) && u.IsBanned).ExecuteAsync(token)).Select(u => u.ID).ToHashSet();
result = await RootUsersService.UnbanUserAsync(others); result = await rootUsersService.UnbanUserAsync(others, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
await Restrictions.Reload(CancellationToken.None); await Restrictions.Reload(CancellationToken.None);
foreach (var (id, name) in named.Where(n => banned.Contains(n.Key))) foreach (var (id, name) in named.Where(n => banned.Contains(n.Key)))
await _log.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.RootUnban, AdminTargets.Root, id, name, token: CancellationToken.None);
return Ok(); return Ok();
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(UnbanUsers)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -198,9 +183,9 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> Role(string id, RootRoleForm form, CancellationToken token) public async Task<IActionResult> Role(string id, RootRoleForm form, CancellationToken token)
{ {
if (!ModelState.IsValid || !RootUser.TryParseRole(form.Role, out var role)) if (!ModelState.IsValid || !RootUser.TryParseRole(form.Role, out var role))
return UnprocessableEntity(new WebResult().Invalidate(Localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity)); return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown role."], StatusCodes.Status422UnprocessableEntity));
if (id == User.GetUserId()) if (id == User.GetUserId())
return Conflict(new WebResult().Invalidate(Localizer["You can't change your own role."], StatusCodes.Status409Conflict)); return Conflict(new WebResult().Invalidate(localizer["You can't change your own role."], StatusCodes.Status409Conflict));
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token); var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (root == default) if (root == default)
return NotFound(); return NotFound();
@@ -208,7 +193,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (was == role) if (was == role)
return Ok((await Views(new List<RootUser> { root }, token))[0]); return Ok((await Views(new List<RootUser> { root }, token))[0]);
if (was == RootRole.Admin && !await OtherAdministrators(root.ID, token)) if (was == RootRole.Admin && !await OtherAdministrators(root.ID, token))
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict)); return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
root.SetRole(role); root.SetRole(role);
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).Modify(u => u.UpdatedAt, root.UpdatedAt) await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).Modify(u => u.UpdatedAt, root.UpdatedAt)
.ExecuteAsync(CancellationToken.None); .ExecuteAsync(CancellationToken.None);
@@ -217,11 +202,11 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
root.SetRole(was); root.SetRole(was);
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).ExecuteAsync(CancellationToken.None); await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Policies, root.Policies).ExecuteAsync(CancellationToken.None);
return Conflict(new WebResult().Invalidate(Localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict)); return Conflict(new WebResult().Invalidate(localizer["The last administrator can't be demoted."], StatusCodes.Status409Conflict));
} }
if (role == RootRole.Admin) if (role == RootRole.Admin)
await ServerSetup.Seal(root.ID, default);//an administrator exists: the client's setup is closed await ServerSetup.Seal(root.ID, default);//an administrator exists: the client's setup is closed
await _log.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName, await moderationLog.Write(User.GetUserId(), AdminActions.RootRole, AdminTargets.Root, root.ID, root.UserName,
note: $"{RoleName(was)} → {RoleName(role)}", token: CancellationToken.None); note: $"{RoleName(was)} → {RoleName(role)}", token: CancellationToken.None);
return Ok((await Views(new List<RootUser> { root }, token))[0]); return Ok((await Views(new List<RootUser> { root }, token))[0]);
} }
@@ -236,12 +221,12 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> ResetTotp(string id, CancellationToken token) public async Task<IActionResult> ResetTotp(string id, CancellationToken token)
{ {
if (id == User.GetUserId()) if (id == User.GetUserId())
return Conflict(new WebResult().Invalidate(Localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict)); return Conflict(new WebResult().Invalidate(localizer["Turn your own two-factor sign-in off from your account."], StatusCodes.Status409Conflict));
var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token); var root = await DB.Default.Find<RootUser>().MatchID(id).Match(u => u.DeletedAt == null).ExecuteFirstAsync(token);
if (root == default) if (root == default)
return NotFound(); return NotFound();
await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync(CancellationToken.None); await DB.Default.Update<RootUser>().MatchID(root.ID).Modify(u => u.Totp, null).ExecuteAsync(CancellationToken.None);
await _log.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.RootResetTotp, AdminTargets.Root, root.ID, root.UserName, token: CancellationToken.None);
return Ok(); return Ok();
} }
@@ -251,16 +236,16 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> DeletePersona(string id, AdminPasswordForm form, [FromServices] IPersonaRemoval personas, CancellationToken token) public async Task<IActionResult> DeletePersona(string id, AdminPasswordForm form, [FromServices] IPersonaRemoval personas, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password)) if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var avatar = await _dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(id).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar == default) if (avatar == default)
return NotFound(); return NotFound();
var label = "@" + _localActors.FromAvatar(avatar).Handle; var label = "@" + localActors.FromAvatar(avatar).Handle;
if (!await personas.Remove(avatar.ID, CancellationToken.None)) if (!await personas.Remove(avatar.ID, CancellationToken.None))
return NotFound(); return NotFound();
await _log.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.PersonaDelete, AdminTargets.Persona, avatar.ID, label, note: form.Note, token: CancellationToken.None);
return Ok(); return Ok();
} }
@@ -268,30 +253,30 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> DeleteGroup(string id, AdminPasswordForm form, [FromServices] IGroupRemoval groups, CancellationToken token) public async Task<IActionResult> DeleteGroup(string id, AdminPasswordForm form, [FromServices] IGroupRemoval groups, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
if (!await RootUsersService.PasswordMatches(User.GetUserId(), form.Password)) if (!await rootUsersService.PasswordMatches(User.GetUserId(), form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(Localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var group = await _dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token); var group = await dbEntities.Groups.MatchID(id).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (group == default) if (group == default)
return NotFound(); return NotFound();
var label = "@" + _localActors.FromGroup(group).Handle; var label = "@" + localActors.FromGroup(group).Handle;
if (!await groups.Remove(group.ID, CancellationToken.None)) if (!await groups.Remove(group.ID, CancellationToken.None))
return NotFound(); return NotFound();
await _log.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None); await moderationLog.Write(User.GetUserId(), AdminActions.GroupDelete, AdminTargets.Group, group.ID, label, note: form.Note, token: CancellationToken.None);
return Ok(); return Ok();
} }
async Task<List<ViewAdminRoot>> Views(List<RootUser> roots, CancellationToken token) async Task<List<ViewAdminRoot>> Views(List<RootUser> roots, CancellationToken token)
{ {
var ids = roots.Select(r => r.ID).ToList(); var ids = roots.Select(r => r.ID).ToList();
var links = ids.Count == 0 ? new List<RootToAvatar>() : await _dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token); var links = ids.Count == 0 ? new List<RootToAvatar>() : await dbEntities.RootToAvatars.Match(ra => ids.Contains(ra.RootId)).ExecuteAsync(token);
var avatarIds = links.Select(l => l.AvatarId).Distinct().ToList(); var avatarIds = links.Select(l => l.AvatarId).Distinct().ToList();
var avatars = avatarIds.Count == 0 var avatars = avatarIds.Count == 0
? new Dictionary<string, Avatar>() ? new Dictionary<string, Avatar>()
: (await _dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID); : (await dbEntities.Avatars.Match(a => avatarIds.Contains(a.ID) && !a.DeletionAt.HasValue).ExecuteAsync(token)).ToDictionary(a => a.ID);
var owned = avatarIds.Count == 0 var owned = avatarIds.Count == 0
? new List<GroupEntity>() ? new List<GroupEntity>()
: await _dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token); : await dbEntities.Groups.Match(g => avatarIds.Contains(g.OwnerAvatarId) && !g.DeletionAt.HasValue).ExecuteAsync(token);
var me = User.GetUserId(); var me = User.GetUserId();
return roots.Select(root => new ViewAdminRoot return roots.Select(root => new ViewAdminRoot
{ {
@@ -308,7 +293,7 @@ namespace PrivaPub.Controllers.ClientToServer
.OrderBy(a => a.UserName, StringComparer.Ordinal) .OrderBy(a => a.UserName, StringComparer.Ordinal)
.Select(a => .Select(a =>
{ {
var persona = _localActors.FromAvatar(a); var persona = localActors.FromAvatar(a);
return new ViewAdminPersona return new ViewAdminPersona
{ {
Id = a.ID, Id = a.ID,
@@ -9,24 +9,16 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
[ApiController, [ApiController,
Route("clientapi/data")] Route("clientapi/data")]
public class DataController : ControllerBase public class DataController(
IDataService dataService,
ILogger<DataController> logger) : ControllerBase
{ {
readonly IDataService DataService;
readonly ILogger<DataController> Logger;
public DataController(IDataService dataService,
ILogger<DataController> logger)
{
DataService = dataService;
Logger = logger;
}
[HttpGet, Route("/clientapi/data/ping"), AllowAnonymous] [HttpGet, Route("/clientapi/data/ping"), AllowAnonymous]
public async ValueTask<IActionResult> Ping() => NoContent(); public async ValueTask<IActionResult> Ping(CancellationToken token = default) => NoContent();
[HttpGet, Route("/clientapi/data/current-version"), AllowAnonymous] [HttpGet, Route("/clientapi/data/current-version"), AllowAnonymous]
public IActionResult CurrentVersion() => public IActionResult CurrentVersion() =>
Ok(DataService.GetCurrentVersion()); Ok(dataService.GetCurrentVersion());
[HttpGet, Route("/clientapi/data/languages"), AllowAnonymous] [HttpGet, Route("/clientapi/data/languages"), AllowAnonymous]
public async Task<IActionResult> Languages(CancellationToken cancellationToken) public async Task<IActionResult> Languages(CancellationToken cancellationToken)
@@ -34,7 +26,7 @@ namespace PrivaPub.Controllers.ClientToServer
var result = new WebResult(); var result = new WebResult();
try try
{ {
var languages = await DataService.GetLanguages(cancellationToken); var languages = await dataService.GetLanguages(cancellationToken);
var viewLanguages = new List<ViewLanguage>(); var viewLanguages = new List<ViewLanguage>();
viewLanguages.AddRange(languages.Select(l => new ViewLanguage viewLanguages.AddRange(languages.Select(l => new ViewLanguage
@@ -47,7 +39,7 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(DataController)}.{nameof(Languages)}()"); logger.LogError(ex, $"{nameof(DataController)}.{nameof(Languages)}()");
return BadRequest(result.Invalidate("Something went wrong.", exception: ex)); return BadRequest(result.Invalidate("Something went wrong.", exception: ex));
} }
} }
@@ -18,24 +18,13 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/admin/domainblocks"), Route("clientapi/admin/domainblocks"),
Authorize(Policy = Policies.IsAdmin)] Authorize(Policy = Policies.IsAdmin)]
public class DomainBlockController : ControllerBase public class DomainBlockController(
IDomainBlocks domainBlocks,
IStringLocalizer<GenericRes> localizer,
Domain.Media.IMediaProxy mediaProxy,
IModerationLog log,
IAccountModeration moderation) : ControllerBase
{ {
readonly IDomainBlocks _domainBlocks;
readonly IStringLocalizer _localizer;
readonly Domain.Media.IMediaProxy _proxy;
readonly IModerationLog _log;
readonly IAccountModeration _moderation;
public DomainBlockController(IDomainBlocks domainBlocks, IStringLocalizer<GenericRes> localizer, Domain.Media.IMediaProxy proxy, IModerationLog log,
IAccountModeration moderation)
{
_moderation = moderation;
_domainBlocks = domainBlocks;
_localizer = localizer;
_proxy = proxy;
_log = log;
}
[HttpGet, Route("/clientapi/admin/domainblocks/list")] [HttpGet, Route("/clientapi/admin/domainblocks/list")]
public async Task<IActionResult> List(CancellationToken token) => public async Task<IActionResult> List(CancellationToken token) =>
Ok((await DB.Default.Find<DomainBlock>().Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token)).Select(ToView).ToList()); Ok((await DB.Default.Find<DomainBlock>().Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token)).Select(ToView).ToList());
@@ -45,7 +34,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var domain = DomainBlocks.Normalise(form.Domain); var domain = DomainBlocks.Normalise(form.Domain);
if (!ModelState.IsValid || Uri.CheckHostName(domain) != UriHostNameType.Dns) if (!ModelState.IsValid || Uri.CheckHostName(domain) != UriHostNameType.Dns)
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var block = await DB.Default.UpdateAndGet<DomainBlock>() var block = await DB.Default.UpdateAndGet<DomainBlock>()
.Match(b => b.Domain == domain) .Match(b => b.Domain == domain)
@@ -59,13 +48,13 @@ namespace PrivaPub.Controllers.ClientToServer
.Modify(b => b.SetOnInsert(x => x.CreatedAt, DateTime.UtcNow)) .Modify(b => b.SetOnInsert(x => x.CreatedAt, DateTime.UtcNow))
.Option(o => o.IsUpsert = true) .Option(o => o.IsUpsert = true)
.ExecuteAsync(token); .ExecuteAsync(token);
await _domainBlocks.Reload(token); await domainBlocks.Reload(token);
// a silenced server's posts are limited from now on, and no longer once it is not (R6) // a silenced server's posts are limited from now on, and no longer once it is not (R6)
await _moderation.DomainChanged(domain, token); await moderation.DomainChanged(domain, token);
// what the media proxy holds of it goes with the block // what the media proxy holds of it goes with the block
if (block.Severity == DomainBlockSeverity.Suspend || block.RejectMedia) if (block.Severity == DomainBlockSeverity.Suspend || block.RejectMedia)
_proxy.Purge(domain); mediaProxy.Purge(domain);
await _log.Write(User.GetUserId(), AdminActions.DomainBlockInsert, AdminTargets.Domain, domain, domain, await log.Write(User.GetUserId(), AdminActions.DomainBlockInsert, AdminTargets.Domain, domain, domain,
note: string.Join(", ", new[] { block.Severity.ToString().ToLowerInvariant(), block.RejectMedia ? "media rejected" : default, note: string.Join(", ", new[] { block.Severity.ToString().ToLowerInvariant(), block.RejectMedia ? "media rejected" : default,
block.Published ? (block.Obfuscate ? "published, obfuscated" : "published") : default }.Where(n => n != default)), token: token); block.Published ? (block.Obfuscate ? "published, obfuscated" : "published") : default }.Where(n => n != default)), token: token);
return Ok(ToView(block)); return Ok(ToView(block));
@@ -76,11 +65,11 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
domain = DomainBlocks.Normalise(domain); domain = DomainBlocks.Normalise(domain);
var deleted = await DB.Default.DeleteAsync<DomainBlock>(b => b.Domain == domain); var deleted = await DB.Default.DeleteAsync<DomainBlock>(b => b.Domain == domain);
await _domainBlocks.Reload(token); await domainBlocks.Reload(token);
if (deleted.DeletedCount > 0) if (deleted.DeletedCount > 0)
await _moderation.DomainChanged(domain, token); await moderation.DomainChanged(domain, token);
if (deleted.DeletedCount > 0) if (deleted.DeletedCount > 0)
await _log.Write(User.GetUserId(), AdminActions.DomainBlockDelete, AdminTargets.Domain, domain, domain, token: token); await log.Write(User.GetUserId(), AdminActions.DomainBlockDelete, AdminTargets.Domain, domain, domain, token: token);
return Ok(); return Ok();
} }
@@ -26,23 +26,15 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/admin/emoji"), Route("clientapi/admin/emoji"),
Authorize(Policy = Policies.IsAdmin)] Authorize(Policy = Policies.IsAdmin)]
public class EmojiAdminController : ControllerBase public class EmojiAdminController(
IModerationLog log,
IStringLocalizer<GenericRes> localizer,
IMediaService media,
ILocalActorService localActors) : ControllerBase
{ {
// a picture up to a megabyte reaches EmojiImage, which refuses one over 256 KB with its reason // a picture up to a megabyte reaches EmojiImage, which refuses one over 256 KB with its reason
const long MaxRequestBytes = 1024 * 1024; const long MaxRequestBytes = 1024 * 1024;
readonly IModerationLog _log;
readonly IStringLocalizer _localizer;
readonly IMediaService _media;
readonly ILocalActorService _localActors;
public EmojiAdminController(IModerationLog log, IStringLocalizer<GenericRes> localizer, IMediaService media, ILocalActorService localActors)
{
_log = log;
_localizer = localizer;
_media = media;
_localActors = localActors;
}
// the token says administrator; the database has the last word // the token says administrator; the database has the last word
async Task<RootUser> Administrator(CancellationToken token) async Task<RootUser> Administrator(CancellationToken token)
@@ -51,7 +43,7 @@ namespace PrivaPub.Controllers.ClientToServer
return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default; return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default;
} }
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(_localizer[message], status)); IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status));
[HttpGet, Route("list")] [HttpGet, Route("list")]
public async Task<IActionResult> List(CancellationToken token) public async Task<IActionResult> List(CancellationToken token)
@@ -73,7 +65,7 @@ namespace PrivaPub.Controllers.ClientToServer
var existing = await DB.Default.Find<LocalEmoji>().Match(e => e.Key == key).ExecuteFirstAsync(token); var existing = await DB.Default.Find<LocalEmoji>().Match(e => e.Key == key).ExecuteFirstAsync(token);
if (existing != default && (existing.DeletedAt == default || existing.Shortcode != form.Shortcode)) if (existing != default && (existing.DeletedAt == default || existing.Shortcode != form.Shortcode))
return Refused(StatusCodes.Status409Conflict, "This shortcode is taken."); return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.");
var outcome = await _media.EmojiImage(form.Shortcode, await Picture(token), token); var outcome = await media.EmojiImage(form.Shortcode, await Picture(token), token);
if (!outcome.Ok) if (!outcome.Ok)
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
@@ -100,12 +92,12 @@ namespace PrivaPub.Controllers.ClientToServer
.ModifiedCount > 0; .ModifiedCount > 0;
if (!saved) if (!saved)
{ {
await _media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token); await media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
return Refused(StatusCodes.Status409Conflict, "This shortcode is taken."); return Refused(StatusCodes.Status409Conflict, "This shortcode is taken.");
} }
await LocalEmojis.Reload(CancellationToken.None); await LocalEmojis.Reload(CancellationToken.None);
var notes = new[] { existing != default ? "added again" : default, emoji.Disabled ? "disabled" : default, Animated(emoji) }.Where(n => n != default).ToList(); var notes = new[] { existing != default ? "added again" : default, emoji.Disabled ? "disabled" : default, Animated(emoji) }.Where(n => n != default).ToList();
await _log.Write(admin.ID, AdminActions.EmojiInsert, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", await log.Write(admin.ID, AdminActions.EmojiInsert, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:",
note: notes.Count > 0 ? string.Join(", ", notes) : default, token: token); note: notes.Count > 0 ? string.Join(", ", notes) : default, token: token);
return Ok(View(emoji)); return Ok(View(emoji));
} }
@@ -139,7 +131,7 @@ namespace PrivaPub.Controllers.ClientToServer
MediaOutcome outcome = default; MediaOutcome outcome = default;
if (image != default) if (image != default)
{ {
outcome = await _media.EmojiImage(emoji.Shortcode, image, token); outcome = await media.EmojiImage(emoji.Shortcode, image, token);
if (!outcome.Ok) if (!outcome.Ok)
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
Picture(emoji, outcome.Attachment, now); Picture(emoji, outcome.Attachment, now);
@@ -151,14 +143,14 @@ namespace PrivaPub.Controllers.ClientToServer
if ((await DB.Default.Update<LocalEmoji>().Match(e => e.ID == emoji.ID && e.DeletedAt == null).ModifyWith(emoji).ExecuteAsync(token)).ModifiedCount == 0) if ((await DB.Default.Update<LocalEmoji>().Match(e => e.ID == emoji.ID && e.DeletedAt == null).ModifyWith(emoji).ExecuteAsync(token)).ModifiedCount == 0)
{ {
if (outcome != default) if (outcome != default)
await _media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token); await media.Trash(m => m.ID == outcome.Attachment.ID, "emoji not saved", token);
return NotFound();//deleted meanwhile return NotFound();//deleted meanwhile
} }
if (outcome != default) if (outcome != default)
{ {
var use = LocalEmojis.ServerUse(emoji.Shortcode); var use = LocalEmojis.ServerUse(emoji.Shortcode);
if (previous.MediaId != default) if (previous.MediaId != default)
await _media.Trash(m => m.ID == previous.MediaId && m.ServerUse == use, "emoji image replaced", token); await media.Trash(m => m.ID == previous.MediaId && m.ServerUse == use, "emoji image replaced", token);
// the reactions made with it show the picture it has now // the reactions made with it show the picture it has now
if (previous.Url != default) if (previous.Url != default)
{ {
@@ -169,7 +161,7 @@ namespace PrivaPub.Controllers.ClientToServer
} }
} }
await LocalEmojis.Reload(CancellationToken.None); await LocalEmojis.Reload(CancellationToken.None);
await _log.Write(admin.ID, AdminActions.EmojiUpdate, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", note: string.Join(", ", changed), token: token); await log.Write(admin.ID, AdminActions.EmojiUpdate, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", note: string.Join(", ", changed), token: token);
return Ok(View(emoji)); return Ok(View(emoji));
} }
@@ -189,9 +181,9 @@ namespace PrivaPub.Controllers.ClientToServer
.Modify(e => e.DeletedAt, now).Modify(e => e.UpdatedAt, now).ExecuteAsync(token)).ModifiedCount == 0) .Modify(e => e.DeletedAt, now).Modify(e => e.UpdatedAt, now).ExecuteAsync(token)).ModifiedCount == 0)
return NotFound(); return NotFound();
var use = LocalEmojis.ServerUse(emoji.Shortcode); var use = LocalEmojis.ServerUse(emoji.Shortcode);
await _media.Trash(m => m.ID == emoji.MediaId && m.ServerUse == use, "emoji deleted", token); await media.Trash(m => m.ID == emoji.MediaId && m.ServerUse == use, "emoji deleted", token);
await LocalEmojis.Reload(CancellationToken.None); await LocalEmojis.Reload(CancellationToken.None);
await _log.Write(admin.ID, AdminActions.EmojiDelete, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", token: token); await log.Write(admin.ID, AdminActions.EmojiDelete, AdminTargets.Emoji, emoji.ID, $":{emoji.Shortcode}:", token: token);
return Ok(); return Ok();
} }
@@ -211,8 +203,8 @@ namespace PrivaPub.Controllers.ClientToServer
void Picture(LocalEmoji emoji, Models.Media.MediaAttachment attachment, DateTime now) void Picture(LocalEmoji emoji, Models.Media.MediaAttachment attachment, DateTime now)
{ {
emoji.MediaId = attachment.ID; emoji.MediaId = attachment.ID;
emoji.Url = _media.Url(attachment.FilePath); emoji.Url = media.Url(attachment.FilePath);
emoji.StaticUrl = attachment.PreviewPath == default ? emoji.Url : _media.Url(attachment.PreviewPath); emoji.StaticUrl = attachment.PreviewPath == default ? emoji.Url : media.Url(attachment.PreviewPath);
emoji.ContentType = attachment.ContentType; emoji.ContentType = attachment.ContentType;
emoji.Width = attachment.Width; emoji.Width = attachment.Width;
emoji.Height = attachment.Height; emoji.Height = attachment.Height;
@@ -237,7 +229,7 @@ namespace PrivaPub.Controllers.ClientToServer
Width = emoji.Width, Width = emoji.Width,
Height = emoji.Height, Height = emoji.Height,
Size = emoji.Size, Size = emoji.Size,
Uri = LocalEmojis.Uri(_localActors.BaseAddress, emoji.Shortcode), Uri = LocalEmojis.Uri(localActors.BaseAddress, emoji.Shortcode),
CreatedAt = emoji.CreatedAt, CreatedAt = emoji.CreatedAt,
UpdatedAt = emoji.UpdatedAt, UpdatedAt = emoji.UpdatedAt,
ImageUpdatedAt = emoji.ImageUpdatedAt ImageUpdatedAt = emoji.ImageUpdatedAt
@@ -13,52 +13,45 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/group"), Route("clientapi/group"),
Authorize(Policy = Policies.IsUser)] Authorize(Policy = Policies.IsUser)]
public class GroupController : ControllerBase public class GroupController(
IGroupUsersService groupUsersService,
IStringLocalizer<GenericRes> localizer) : ControllerBase
{ {
readonly IGroupUsersService _groupUsersService;
readonly IStringLocalizer _localizer;
public GroupController(IGroupUsersService groupUsersService, IStringLocalizer<GenericRes> localizer)
{
_groupUsersService = groupUsersService;
_localizer = localizer;
}
[HttpGet, Route("/clientapi/group/list")] [HttpGet, Route("/clientapi/group/list")]
public async Task<IActionResult> List([FromQuery] string avatarId, CancellationToken token) => public async Task<IActionResult> List([FromQuery] string avatarId, CancellationToken token) =>
Answer(await _groupUsersService.GetGroups(User.GetUserId(), avatarId, token)); Answer(await groupUsersService.GetGroups(User.GetUserId(), avatarId, token));
[HttpPost, Route("/clientapi/group/insert")] [HttpPost, Route("/clientapi/group/insert")]
public async Task<IActionResult> Insert(InsertGroupForm form, CancellationToken token) => public async Task<IActionResult> Insert(InsertGroupForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.InsertGroup(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.InsertGroup(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/group/update")] [HttpPost, Route("/clientapi/group/update")]
public async Task<IActionResult> Update(UpdateGroupForm form, CancellationToken token) => public async Task<IActionResult> Update(UpdateGroupForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.UpdateGroup(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.UpdateGroup(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/group/join")] [HttpPost, Route("/clientapi/group/join")]
public async Task<IActionResult> Join(JoinGroupForm form, CancellationToken token) => public async Task<IActionResult> Join(JoinGroupForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.JoinGroup(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.JoinGroup(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/group/leave")] [HttpPost, Route("/clientapi/group/leave")]
public async Task<IActionResult> Leave(GroupMembershipForm form, CancellationToken token) => public async Task<IActionResult> Leave(GroupMembershipForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.LeaveGroup(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.LeaveGroup(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/group/approve")] [HttpPost, Route("/clientapi/group/approve")]
public async Task<IActionResult> Approve(GroupMembershipForm form, CancellationToken token) => public async Task<IActionResult> Approve(GroupMembershipForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.ApproveMember(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.ApproveMember(User.GetUserId(), form, token));
[HttpGet, Route("/clientapi/group/members")] [HttpGet, Route("/clientapi/group/members")]
public async Task<IActionResult> Members([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) => public async Task<IActionResult> Members([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) =>
Answer(await _groupUsersService.GetMembers(User.GetUserId(), avatarId, groupId, token)); Answer(await groupUsersService.GetMembers(User.GetUserId(), avatarId, groupId, token));
[HttpPost, Route("/clientapi/group/reject")] [HttpPost, Route("/clientapi/group/reject")]
public async Task<IActionResult> Reject(GroupMembershipForm form, CancellationToken token) => public async Task<IActionResult> Reject(GroupMembershipForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.RejectMember(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.RejectMember(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/group/remove")] [HttpPost, Route("/clientapi/group/remove")]
public async Task<IActionResult> Remove(GroupMembershipForm form, CancellationToken token) => public async Task<IActionResult> Remove(GroupMembershipForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _groupUsersService.RemoveMember(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await groupUsersService.RemoveMember(User.GetUserId(), form, token));
// the group's owner deletes it, with the login's password (R6): its members and followers are told, its name stays // the group's owner deletes it, with the login's password (R6): its members and followers are told, its name stays
// taken (GroupRemoval) // taken (GroupRemoval)
@@ -69,19 +62,19 @@ namespace PrivaPub.Controllers.ClientToServer
if (!ModelState.IsValid) if (!ModelState.IsValid)
return Invalid(); return Invalid();
var rootId = User.GetUserId(); var rootId = User.GetUserId();
if (!await users.PasswordMatches(rootId, form.Password)) if (!await users.PasswordMatches(rootId, form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer[RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
var owns = await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token); var owns = await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token);
var group = owns ? await dbEntities.Groups.MatchID(form.GroupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token) : default; var group = owns ? await dbEntities.Groups.MatchID(form.GroupId).Match(g => !g.DeletionAt.HasValue).ExecuteFirstAsync(token) : default;
if (group == default) if (group == default)
return NotFound(new WebResult().Invalidate(_localizer["Group not found."], StatusCodes.Status404NotFound)); return NotFound(new WebResult().Invalidate(localizer["Group not found."], StatusCodes.Status404NotFound));
if (group.OwnerAvatarId != form.AvatarId) if (group.OwnerAvatarId != form.AvatarId)
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer["Only the group's owner can delete it."], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer["Only the group's owner can delete it."], StatusCodes.Status403Forbidden));
await groups.Remove(group.ID, CancellationToken.None); await groups.Remove(group.ID, CancellationToken.None);
return Ok(); return Ok();
} }
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
@@ -30,26 +30,16 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/admin"), Route("clientapi/admin"),
Authorize(Policy = Policies.IsAdmin)] Authorize(Policy = Policies.IsAdmin)]
public class InstanceAdminController : ControllerBase public class InstanceAdminController(
IInstanceSettings instanceSettings,
IModerationLog moderationLog,
IStringLocalizer<GenericRes> localizer,
ILocalActorService localActors,
ILogger<InstanceAdminController> logger) : ControllerBase
{ {
const int MaxSettingsRelays = 20; const int MaxSettingsRelays = 20;
const string Thumbnail = "thumbnail"; const string Thumbnail = "thumbnail";
readonly IInstanceSettings _settings;
readonly IModerationLog _log;
readonly IStringLocalizer _localizer;
readonly ILocalActorService _localActors;
readonly ILogger<InstanceAdminController> _logger;
public InstanceAdminController(IInstanceSettings settings, IModerationLog log, IStringLocalizer<GenericRes> localizer, ILocalActorService localActors,
ILogger<InstanceAdminController> logger)
{
_settings = settings;
_log = log;
_localizer = localizer;
_localActors = localActors;
_logger = logger;
}
// the token says administrator; the database has the last word // the token says administrator; the database has the last word
async Task<RootUser> Administrator(CancellationToken token) async Task<RootUser> Administrator(CancellationToken token)
@@ -58,7 +48,7 @@ namespace PrivaPub.Controllers.ClientToServer
return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default; return root is { IsBanned: false, DeletedAt: null } && root.Policies.Contains(Policies.IsAdmin) ? root : default;
} }
IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(_localizer[message], status)); IActionResult Refused(int status, string message) => StatusCode(status, new WebResult().Invalidate(localizer[message], status));
#region settings #region settings
@@ -67,7 +57,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
if (await Administrator(token) == default) if (await Administrator(token) == default)
return Forbid(); return Forbid();
return Ok(await View(_settings.Current, token)); return Ok(await View(instanceSettings.Current, token));
} }
[HttpPost, Route("/clientapi/admin/settings")] [HttpPost, Route("/clientapi/admin/settings")]
@@ -86,7 +76,7 @@ namespace PrivaPub.Controllers.ClientToServer
var changed = new List<string>(); var changed = new List<string>();
var ruleActs = new List<(string Action, ServerRule Rule)>(); var ruleActs = new List<(string Action, ServerRule Rule)>();
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
var saved = await _settings.Update(settings => var saved = await instanceSettings.Update(settings =>
{ {
void Set(string name, string value, Func<string> get, Action<string> set) void Set(string name, string value, Func<string> get, Action<string> set)
{ {
@@ -175,9 +165,9 @@ namespace PrivaPub.Controllers.ClientToServer
}, admin.ID, token); }, admin.ID, token);
if (changed.Count > 0) if (changed.Count > 0)
await _log.Write(admin.ID, AdminActions.SettingsUpdate, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: string.Join(", ", changed), token: token); await moderationLog.Write(admin.ID, AdminActions.SettingsUpdate, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: string.Join(", ", changed), token: token);
foreach (var (action, rule) in ruleActs) foreach (var (action, rule) in ruleActs)
await _log.Write(admin.ID, action, AdminTargets.Rule, rule.Id, rule.Text, token: token); await moderationLog.Write(admin.ID, action, AdminTargets.Rule, rule.Id, rule.Text, token: token);
return Ok(await View(saved, token)); return Ok(await View(saved, token));
} }
@@ -194,7 +184,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (!outcome.Ok) if (!outcome.Ok)
return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status)); return StatusCode(outcome.Status, new WebResult().Invalidate(outcome.Error, outcome.Status));
var previous = default(string); var previous = default(string);
var saved = await _settings.Update(settings => var saved = await instanceSettings.Update(settings =>
{ {
previous = settings.ThumbnailMediaId; previous = settings.ThumbnailMediaId;
settings.ThumbnailMediaId = outcome.Attachment.ID; settings.ThumbnailMediaId = outcome.Attachment.ID;
@@ -202,7 +192,7 @@ namespace PrivaPub.Controllers.ClientToServer
}, admin.ID, token); }, admin.ID, token);
if (previous != default) if (previous != default)
await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail replaced", token); await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail replaced", token);
await _log.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "replaced", token: token); await moderationLog.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "replaced", token: token);
return Ok(await View(saved, token)); return Ok(await View(saved, token));
} }
@@ -213,7 +203,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (admin == default) if (admin == default)
return Forbid(); return Forbid();
var previous = default(string); var previous = default(string);
var saved = await _settings.Update(settings => var saved = await instanceSettings.Update(settings =>
{ {
previous = settings.ThumbnailMediaId; previous = settings.ThumbnailMediaId;
settings.ThumbnailMediaId = default; settings.ThumbnailMediaId = default;
@@ -222,7 +212,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (previous != default) if (previous != default)
{ {
await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail removed", token); await media.Trash(m => m.ID == previous && m.ServerUse == Thumbnail, "thumbnail removed", token);
await _log.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "removed", token: token); await moderationLog.Write(admin.ID, AdminActions.SettingsThumbnail, AdminTargets.Settings, ServerSettings.Name, saved.Title, note: "removed", token: token);
} }
return Ok(await View(saved, token)); return Ok(await View(saved, token));
} }
@@ -257,9 +247,9 @@ namespace PrivaPub.Controllers.ClientToServer
Id = contact.ID, Id = contact.ID,
UserName = contact.UserName, UserName = contact.UserName,
Name = contact.Name, Name = contact.Name,
Handle = _localActors.FromAvatar(contact).Handle Handle = localActors.FromAvatar(contact).Handle
}, },
ThumbnailUrl = settings.ThumbnailUrl ?? $"{_localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}", ThumbnailUrl = settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}",
ThumbnailIsDefault = settings.ThumbnailUrl == default, ThumbnailIsDefault = settings.ThumbnailUrl == default,
PrivacyPolicy = settings.PrivacyPolicy, PrivacyPolicy = settings.PrivacyPolicy,
PrivacyPolicyUpdatedAt = settings.PrivacyPolicyUpdatedAt, PrivacyPolicyUpdatedAt = settings.PrivacyPolicyUpdatedAt,
@@ -322,7 +312,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (Invalid(form) is { } refused) if (Invalid(form) is { } refused)
return refused; return refused;
var made = await announcements.Insert(Draft(form), token); var made = await announcements.Insert(Draft(form), token);
await _log.Write(admin.ID, AdminActions.AnnouncementInsert, AdminTargets.Announcement, made.ID, made.Text, await moderationLog.Write(admin.ID, AdminActions.AnnouncementInsert, AdminTargets.Announcement, made.ID, made.Text,
note: made.IsPublished ? "published" : "draft", token: token); note: made.IsPublished ? "published" : "draft", token: token);
return Ok(await View(made, token)); return Ok(await View(made, token));
} }
@@ -338,7 +328,7 @@ namespace PrivaPub.Controllers.ClientToServer
var updated = await announcements.Update(form.Id, Draft(form), token); var updated = await announcements.Update(form.Id, Draft(form), token);
if (updated == default) if (updated == default)
return NotFound(); return NotFound();
await _log.Write(admin.ID, AdminActions.AnnouncementUpdate, AdminTargets.Announcement, updated.ID, updated.Text, await moderationLog.Write(admin.ID, AdminActions.AnnouncementUpdate, AdminTargets.Announcement, updated.ID, updated.Text,
note: updated.IsPublished ? "published" : "draft", token: token); note: updated.IsPublished ? "published" : "draft", token: token);
return Ok(await View(updated, token)); return Ok(await View(updated, token));
} }
@@ -352,7 +342,7 @@ namespace PrivaPub.Controllers.ClientToServer
var deleted = await announcements.Delete(id, token); var deleted = await announcements.Delete(id, token);
if (deleted == default) if (deleted == default)
return NotFound(); return NotFound();
await _log.Write(admin.ID, AdminActions.AnnouncementDelete, AdminTargets.Announcement, deleted.ID, deleted.Text, token: token); await moderationLog.Write(admin.ID, AdminActions.AnnouncementDelete, AdminTargets.Announcement, deleted.ID, deleted.Text, token: token);
return Ok(); return Ok();
} }
@@ -398,7 +388,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
if (await Administrator(token) == default) if (await Administrator(token) == default)
return Forbid(); return Forbid();
return Ok(await StaffPickViews(_settings.Current, token)); return Ok(await StaffPickViews(instanceSettings.Current, token));
} }
[HttpPost, Route("/clientapi/admin/staff-picks/insert")] [HttpPost, Route("/clientapi/admin/staff-picks/insert")]
@@ -411,16 +401,16 @@ namespace PrivaPub.Controllers.ClientToServer
var picked = await Pickable(id, token); var picked = await Pickable(id, token);
if (picked == default) if (picked == default)
return Refused(StatusCodes.Status404NotFound, "No such account to suggest."); return Refused(StatusCodes.Status404NotFound, "No such account to suggest.");
if (_settings.Current.StaffPicks.Contains(id)) if (instanceSettings.Current.StaffPicks.Contains(id))
return Refused(StatusCodes.Status409Conflict, "This account is suggested already."); return Refused(StatusCodes.Status409Conflict, "This account is suggested already.");
if (_settings.Current.StaffPicks.Count >= MaxStaffPicks) if (instanceSettings.Current.StaffPicks.Count >= MaxStaffPicks)
return Refused(StatusCodes.Status422UnprocessableEntity, "40 accounts at most are suggested."); return Refused(StatusCodes.Status422UnprocessableEntity, "40 accounts at most are suggested.");
var saved = await _settings.Update(settings => var saved = await instanceSettings.Update(settings =>
{ {
if (!settings.StaffPicks.Contains(id)) if (!settings.StaffPicks.Contains(id))
settings.StaffPicks.Add(id); settings.StaffPicks.Add(id);
}, admin.ID, token); }, admin.ID, token);
await _log.Write(admin.ID, AdminActions.StaffPickInsert, picked.Value.IsLocal ? AdminTargets.Persona : AdminTargets.Account, id, picked.Value.Handle, await moderationLog.Write(admin.ID, AdminActions.StaffPickInsert, picked.Value.IsLocal ? AdminTargets.Persona : AdminTargets.Account, id, picked.Value.Handle,
token: token); token: token);
return Ok(await StaffPickViews(saved, token)); return Ok(await StaffPickViews(saved, token));
} }
@@ -432,11 +422,11 @@ namespace PrivaPub.Controllers.ClientToServer
if (admin == default) if (admin == default)
return Forbid(); return Forbid();
accountId = accountId?.Trim(); accountId = accountId?.Trim();
if (string.IsNullOrEmpty(accountId) || !_settings.Current.StaffPicks.Contains(accountId)) if (string.IsNullOrEmpty(accountId) || !instanceSettings.Current.StaffPicks.Contains(accountId))
return NotFound(); return NotFound();
var view = (await StaffPickViews(_settings.Current, token)).FirstOrDefault(p => p.AccountId == accountId); var view = (await StaffPickViews(instanceSettings.Current, token)).FirstOrDefault(p => p.AccountId == accountId);
var saved = await _settings.Update(settings => settings.StaffPicks.Remove(accountId), admin.ID, token); var saved = await instanceSettings.Update(settings => settings.StaffPicks.Remove(accountId), admin.ID, token);
await _log.Write(admin.ID, AdminActions.StaffPickDelete, view?.IsLocal == true ? AdminTargets.Persona : AdminTargets.Account, accountId, await moderationLog.Write(admin.ID, AdminActions.StaffPickDelete, view?.IsLocal == true ? AdminTargets.Persona : AdminTargets.Account, accountId,
view?.Handle ?? accountId, token: token); view?.Handle ?? accountId, token: token);
return Ok(await StaffPickViews(saved, token)); return Ok(await StaffPickViews(saved, token));
} }
@@ -451,7 +441,7 @@ namespace PrivaPub.Controllers.ClientToServer
return default; return default;
var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue && !a.SuspendedAt.HasValue).ExecuteFirstAsync(token); var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue && !a.SuspendedAt.HasValue).ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
return (await Counted.HeldBackPersonas(token)).Contains(avatar.ID) ? ((bool, string)?)null : (true, _localActors.FromAvatar(avatar).Handle); return (await Counted.HeldBackPersonas(token)).Contains(avatar.ID) ? ((bool, string)?)null : (true, localActors.FromAvatar(avatar).Handle);
var foreign = await DB.Default.Find<ForeignAvatar>().Match(f => f.ID == id && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue var foreign = await DB.Default.Find<ForeignAvatar>().Match(f => f.ID == id && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue
&& (f.AvatarType == AvatarType.Person || f.AvatarType == AvatarType.Service || f.AvatarType == AvatarType.Organization)).ExecuteFirstAsync(token); && (f.AvatarType == AvatarType.Person || f.AvatarType == AvatarType.Service || f.AvatarType == AvatarType.Organization)).ExecuteFirstAsync(token);
return foreign == default ? ((bool, string)?)null : (false, $"{foreign.UserName}@{foreign.Domain}"); return foreign == default ? ((bool, string)?)null : (false, $"{foreign.UserName}@{foreign.Domain}");
@@ -468,7 +458,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
AccountId = id, AccountId = id,
IsLocal = true, IsLocal = true,
Handle = _localActors.FromAvatar(avatar).Handle, Handle = localActors.FromAvatar(avatar).Handle,
Name = avatar.Name, Name = avatar.Name,
IsShown = avatar.DeletionAt == default && avatar.SuspendedAt == default && avatar.SilencedAt == default && !held.Contains(id) IsShown = avatar.DeletionAt == default && avatar.SuspendedAt == default && avatar.SilencedAt == default && !held.Contains(id)
} }
@@ -492,7 +482,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
if (await Administrator(token) == default) if (await Administrator(token) == default)
return Forbid(); return Forbid();
return Ok(await RelayViews(_settings.Current, token)); return Ok(await RelayViews(instanceSettings.Current, token));
} }
// a relay named by the settings: subscribed to at once (in the background: resolving it is a fetch), the page polls // a relay named by the settings: subscribed to at once (in the background: resolving it is a fetch), the page polls
@@ -508,16 +498,16 @@ namespace PrivaPub.Controllers.ClientToServer
return Refused(StatusCodes.Status422UnprocessableEntity, "A relay is named by the https address of its actor or its inbox."); return Refused(StatusCodes.Status422UnprocessableEntity, "A relay is named by the https address of its actor or its inbox.");
if (relays.Configured.Contains(address)) if (relays.Configured.Contains(address))
return Refused(StatusCodes.Status409Conflict, "The configuration names this relay already."); return Refused(StatusCodes.Status409Conflict, "The configuration names this relay already.");
if (_settings.Current.Relays.Contains(address)) if (instanceSettings.Current.Relays.Contains(address))
return Ok(await RelayViews(_settings.Current, token)); return Ok(await RelayViews(instanceSettings.Current, token));
if (_settings.Current.Relays.Count >= MaxSettingsRelays) if (instanceSettings.Current.Relays.Count >= MaxSettingsRelays)
return Refused(StatusCodes.Status422UnprocessableEntity, "The settings name 20 relays at most."); return Refused(StatusCodes.Status422UnprocessableEntity, "The settings name 20 relays at most.");
var saved = await _settings.Update(settings => var saved = await instanceSettings.Update(settings =>
{ {
if (!settings.Relays.Contains(address)) if (!settings.Relays.Contains(address))
settings.Relays.Add(address); settings.Relays.Add(address);
}, admin.ID, token); }, admin.ID, token);
await _log.Write(admin.ID, AdminActions.RelayInsert, AdminTargets.Relay, address, address, token: token); await moderationLog.Write(admin.ID, AdminActions.RelayInsert, AdminTargets.Relay, address, address, token: token);
Reconcile(relays); Reconcile(relays);
return Accepted(await RelayViews(saved, token)); return Accepted(await RelayViews(saved, token));
} }
@@ -532,10 +522,10 @@ namespace PrivaPub.Controllers.ClientToServer
address = address?.Trim(); address = address?.Trim();
if (relays.Configured.Contains(address)) if (relays.Configured.Contains(address))
return Refused(StatusCodes.Status409Conflict, "This relay is named by the configuration (Federation:Relays): remove it there."); return Refused(StatusCodes.Status409Conflict, "This relay is named by the configuration (Federation:Relays): remove it there.");
if (string.IsNullOrEmpty(address) || !_settings.Current.Relays.Contains(address)) if (string.IsNullOrEmpty(address) || !instanceSettings.Current.Relays.Contains(address))
return NotFound(); return NotFound();
var saved = await _settings.Update(settings => settings.Relays.Remove(address), admin.ID, token); var saved = await instanceSettings.Update(settings => settings.Relays.Remove(address), admin.ID, token);
await _log.Write(admin.ID, AdminActions.RelayDelete, AdminTargets.Relay, address, address, token: token); await moderationLog.Write(admin.ID, AdminActions.RelayDelete, AdminTargets.Relay, address, address, token: token);
Reconcile(relays); Reconcile(relays);
return Accepted(await RelayViews(saved, token)); return Accepted(await RelayViews(saved, token));
} }
@@ -548,7 +538,7 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, "Relay subscriptions could not be brought up to date"); logger.LogWarning(ex, "Relay subscriptions could not be brought up to date");
} }
}, CancellationToken.None); }, CancellationToken.None);
@@ -17,32 +17,22 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/moderator"), Route("clientapi/moderator"),
Authorize(Policy = Policies.IsModerator)] Authorize(Policy = Policies.IsModerator)]
public class ModeratorController : ControllerBase public class ModeratorController(
IInstanceSettings settings,
IModerationLog moderationLog,
IAccountModeration accountModeration,
Federation.Actors.ILocalActorService localActors,
Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> localizer) : ControllerBase
{ {
const int MaxLogPage = 100; const int MaxLogPage = 100;
const int MaxAccountsPage = 100; const int MaxAccountsPage = 100;
readonly IInstanceSettings _settings;
readonly IModerationLog _log;
readonly IAccountModeration _moderation;
readonly Federation.Actors.ILocalActorService _localActors;
readonly Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> _localizer;
public ModeratorController(IInstanceSettings settings, IModerationLog log, IAccountModeration moderation,
Federation.Actors.ILocalActorService localActors, Microsoft.Extensions.Localization.IStringLocalizer<Resources.GenericRes> localizer)
{
_settings = settings;
_log = log;
_moderation = moderation;
_localActors = localActors;
_localizer = localizer;
}
[HttpGet, Route("/clientapi/moderator/reports")] [HttpGet, Route("/clientapi/moderator/reports")]
public async Task<IActionResult> Reports([FromQuery] bool resolved, CancellationToken token) public async Task<IActionResult> Reports([FromQuery] bool resolved, CancellationToken token)
{ {
var rules = _settings.Current.Rules.ToDictionary(r => r.Id, r => r.Text ?? string.Empty); var rules = settings.Current.Rules.ToDictionary(r => r.Id, r => r.Text ?? string.Empty);
return Ok((await DB.Default.Find<Report>().Match(r => r.IsResolved == resolved).Sort(r => r.ID, Order.Descending).Limit(100).ExecuteAsync(token)) return Ok((await DB.Default.Find<Report>().Match(r => r.IsResolved == resolved).Sort(r => r.ID, Order.Descending).Limit(100).ExecuteAsync(token))
.Select(r => new ViewReport .Select(r => new ViewReport
{ {
@@ -77,7 +67,7 @@ namespace PrivaPub.Controllers.ClientToServer
form ??= new ResolveReportForm(); form ??= new ResolveReportForm();
var action = string.IsNullOrWhiteSpace(form.Action) ? ModerationActions.None : form.Action.Trim().ToLowerInvariant(); var action = string.IsNullOrWhiteSpace(form.Action) ? ModerationActions.None : form.Action.Trim().ToLowerInvariant();
if (!ModerationActions.IsResolution(action)) if (!ModerationActions.IsResolution(action))
return UnprocessableEntity(new WebResult().Invalidate(_localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity)); return UnprocessableEntity(new WebResult().Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity));
var by = User.GetUserId(); var by = User.GetUserId();
var report = await DB.Default.Find<Report>().MatchID(id).ExecuteFirstAsync(token); var report = await DB.Default.Find<Report>().MatchID(id).ExecuteFirstAsync(token);
if (report == default) if (report == default)
@@ -85,16 +75,16 @@ namespace PrivaPub.Controllers.ClientToServer
switch (action) switch (action)
{ {
case ModerationActions.Silence or ModerationActions.Suspend: case ModerationActions.Silence or ModerationActions.Suspend:
var moderated = await _moderation.Moderate(by, report.TargetAccountId, action, form.Note, form.Warning, report.ID, token); var moderated = await accountModeration.Moderate(by, report.TargetAccountId, action, form.Note, form.Warning, report.ID, token);
if (!moderated.IsValid) if (!moderated.IsValid)
return StatusCode(moderated.StatusCode, moderated); return StatusCode(moderated.StatusCode, moderated);
break; break;
case ModerationActions.RemovePosts: case ModerationActions.RemovePosts:
if (report.PostIds.Count == 0) if (report.PostIds.Count == 0)
return UnprocessableEntity(new WebResult().Invalidate(_localizer["The report names no posts."], StatusCodes.Status422UnprocessableEntity)); return UnprocessableEntity(new WebResult().Invalidate(localizer["The report names no posts."], StatusCodes.Status422UnprocessableEntity));
foreach (var postId in report.PostIds) foreach (var postId in report.PostIds)
{ {
var removed = await _moderation.RemovePost(by, postId, form.Note, form.Warning, report.ID, token); var removed = await accountModeration.RemovePost(by, postId, form.Note, form.Warning, report.ID, token);
if (!removed.IsValid && removed.StatusCode != StatusCodes.Status404NotFound)//one already gone is removed if (!removed.IsValid && removed.StatusCode != StatusCodes.Status404NotFound)//one already gone is removed
return StatusCode(removed.StatusCode, removed); return StatusCode(removed.StatusCode, removed);
} }
@@ -107,7 +97,7 @@ namespace PrivaPub.Controllers.ClientToServer
.Modify(r => r.Resolution, action) .Modify(r => r.Resolution, action)
.Modify(r => r.ResolutionNote, string.IsNullOrWhiteSpace(form.Note) ? null : form.Note.Trim()) .Modify(r => r.ResolutionNote, string.IsNullOrWhiteSpace(form.Note) ? null : form.Note.Trim())
.ExecuteAsync(CancellationToken.None); .ExecuteAsync(CancellationToken.None);
await _log.Write(by, AdminActions.ReportResolve, AdminTargets.Report, id, report.Category, reportId: id, await moderationLog.Write(by, AdminActions.ReportResolve, AdminTargets.Report, id, report.Category, reportId: id,
note: action == ModerationActions.None ? form.Note : string.IsNullOrWhiteSpace(form.Note) ? action : $"{action}: {form.Note.Trim()}", note: action == ModerationActions.None ? form.Note : string.IsNullOrWhiteSpace(form.Note) ? action : $"{action}: {form.Note.Trim()}",
token: CancellationToken.None); token: CancellationToken.None);
return Ok(); return Ok();
@@ -125,21 +115,21 @@ namespace PrivaPub.Controllers.ClientToServer
return Ok(new ViewModeratedAccountsPage { Items = items }); return Ok(new ViewModeratedAccountsPage { Items = items });
if (Uri.TryCreate(q, UriKind.Absolute, out var address) && address.Scheme is "https" or "http") if (Uri.TryCreate(q, UriKind.Absolute, out var address) && address.Scheme is "https" or "http")
{ {
if (await _localActors.FindByUri(q, token) is { Kind: Models.Federation.LocalActorKind.Person } local if (await localActors.FindByUri(q, token) is { Kind: Models.Federation.LocalActorKind.Person } local
&& await DB.Default.Find<Avatar>().MatchID(local.Id).ExecuteFirstAsync(token) is { } persona) && await DB.Default.Find<Avatar>().MatchID(local.Id).ExecuteFirstAsync(token) is { } persona)
items.Add(_moderation.View(persona)); items.Add(accountModeration.View(persona));
items.AddRange((await DB.Default.Find<ForeignAvatar>().Match(f => f.ActorURI == q || f.Url == q).Limit(limit).ExecuteAsync(token)).Select(_moderation.View)); items.AddRange((await DB.Default.Find<ForeignAvatar>().Match(f => f.ActorURI == q || f.Url == q).Limit(limit).ExecuteAsync(token)).Select(accountModeration.View));
return Ok(new ViewModeratedAccountsPage { Items = items.Take(limit).ToList() }); return Ok(new ViewModeratedAccountsPage { Items = items.Take(limit).ToList() });
} }
var parts = q.Split('@', 2); var parts = q.Split('@', 2);
var name = parts[0]; var name = parts[0];
var domain = parts.Length > 1 ? parts[1].ToLowerInvariant() : default; var domain = parts.Length > 1 ? parts[1].ToLowerInvariant() : default;
var here = new Uri(_localActors.BaseAddress).Authority; var here = new Uri(localActors.BaseAddress).Authority;
if (domain == default || domain == here) if (domain == default || domain == here)
{ {
var lowered = name.ToLowerInvariant(); var lowered = name.ToLowerInvariant();
items.AddRange((await DB.Default.Find<Avatar>().Match(a => a.UserName.StartsWith(lowered) && !a.DeletionAt.HasValue) items.AddRange((await DB.Default.Find<Avatar>().Match(a => a.UserName.StartsWith(lowered) && !a.DeletionAt.HasValue)
.Sort(a => a.UserName, Order.Ascending).Limit(limit).ExecuteAsync(token)).Select(_moderation.View)); .Sort(a => a.UserName, Order.Ascending).Limit(limit).ExecuteAsync(token)).Select(accountModeration.View));
} }
if (domain != here && items.Count < limit && name.Length > 0) if (domain != here && items.Count < limit && name.Length > 0)
{ {
@@ -148,7 +138,7 @@ namespace PrivaPub.Controllers.ClientToServer
if (domain != default) if (domain != default)
remote.Match(f => f.Regex(a => a.Domain, new MongoDB.Bson.BsonRegularExpression("^" + System.Text.RegularExpressions.Regex.Escape(domain), "i"))); remote.Match(f => f.Regex(a => a.Domain, new MongoDB.Bson.BsonRegularExpression("^" + System.Text.RegularExpressions.Regex.Escape(domain), "i")));
items.AddRange((await remote.Match(f => !f.DeletionAt.HasValue).Sort(f => f.UserName, Order.Ascending).Limit(limit - items.Count).ExecuteAsync(token)) items.AddRange((await remote.Match(f => !f.DeletionAt.HasValue).Sort(f => f.UserName, Order.Ascending).Limit(limit - items.Count).ExecuteAsync(token))
.Select(_moderation.View)); .Select(accountModeration.View));
} }
return Ok(new ViewModeratedAccountsPage { Items = items }); return Ok(new ViewModeratedAccountsPage { Items = items });
} }
@@ -162,7 +152,7 @@ namespace PrivaPub.Controllers.ClientToServer
limit = Math.Clamp(limit, 1, MaxAccountsPage); limit = Math.Clamp(limit, 1, MaxAccountsPage);
var locals = await DB.Default.Find<Avatar>().Match(a => (a.SilencedAt != null || a.SuspendedAt != null) && a.DeletionAt == null).ExecuteAsync(token); var locals = await DB.Default.Find<Avatar>().Match(a => (a.SilencedAt != null || a.SuspendedAt != null) && a.DeletionAt == null).ExecuteAsync(token);
var remotes = await DB.Default.Find<ForeignAvatar>().Match(f => f.SilencedAt != null || f.SuspendedAt != null).ExecuteAsync(token); var remotes = await DB.Default.Find<ForeignAvatar>().Match(f => f.SilencedAt != null || f.SuspendedAt != null).ExecuteAsync(token);
var all = locals.Select(_moderation.View).Concat(remotes.Select(_moderation.View)) var all = locals.Select(accountModeration.View).Concat(remotes.Select(accountModeration.View))
.OrderByDescending(a => Latest(a.SilencedAt, a.SuspendedAt)).ThenBy(a => a.Id, StringComparer.Ordinal).ToList(); .OrderByDescending(a => Latest(a.SilencedAt, a.SuspendedAt)).ThenBy(a => a.Id, StringComparer.Ordinal).ToList();
return Ok(new ViewModeratedAccountsPage return Ok(new ViewModeratedAccountsPage
{ {
@@ -175,15 +165,15 @@ namespace PrivaPub.Controllers.ClientToServer
[HttpGet, Route("/clientapi/moderator/accounts/{id}")] [HttpGet, Route("/clientapi/moderator/accounts/{id}")]
public async Task<IActionResult> Account(string id, CancellationToken token) => public async Task<IActionResult> Account(string id, CancellationToken token) =>
await _moderation.View(id, token) is { } account ? Ok(account) : NotFound(); await accountModeration.View(id, token) is { } account ? Ok(account) : NotFound();
// silence, unsilence, suspend or unsuspend a persona here or an account elsewhere // silence, unsilence, suspend or unsuspend a persona here or an account elsewhere
[HttpPost, Route("/clientapi/moderator/accounts/moderate")] [HttpPost, Route("/clientapi/moderator/accounts/moderate")]
public async Task<IActionResult> Moderate(ModerateAccountForm form, CancellationToken token) public async Task<IActionResult> Moderate(ModerateAccountForm form, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await _moderation.Moderate(User.GetUserId(), form.AccountId, form.Action.Trim().ToLowerInvariant(), form.Note, form.Warning, default, token); var result = await accountModeration.Moderate(User.GetUserId(), form.AccountId, form.Action.Trim().ToLowerInvariant(), form.Note, form.Warning, default, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
@@ -192,8 +182,8 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> RemovePost(RemovePostForm form, CancellationToken token) public async Task<IActionResult> RemovePost(RemovePostForm form, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await _moderation.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token); var result = await accountModeration.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token);
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result); return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
} }
@@ -13,46 +13,39 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/post"), Route("clientapi/post"),
Authorize(Policy = Policies.IsUser)] Authorize(Policy = Policies.IsUser)]
public class PostController : ControllerBase public class PostController(
IPostsService postsService,
IStringLocalizer<GenericRes> localizer) : ControllerBase
{ {
readonly IPostsService _postsService;
readonly IStringLocalizer _localizer;
public PostController(IPostsService postsService, IStringLocalizer<GenericRes> localizer)
{
_postsService = postsService;
_localizer = localizer;
}
[HttpGet, Route("/clientapi/post/list")] [HttpGet, Route("/clientapi/post/list")]
public async Task<IActionResult> List([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) => public async Task<IActionResult> List([FromQuery] string avatarId, [FromQuery] string groupId, CancellationToken token) =>
Answer(await _postsService.GetPosts(User.GetUserId(), avatarId, groupId, token)); Answer(await postsService.GetPosts(User.GetUserId(), avatarId, groupId, token));
[HttpPost, Route("/clientapi/post/insert")] [HttpPost, Route("/clientapi/post/insert")]
public async Task<IActionResult> Insert(InsertPostForm form, CancellationToken token) => public async Task<IActionResult> Insert(InsertPostForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _postsService.InsertPost(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await postsService.InsertPost(User.GetUserId(), form, token));
[HttpGet, Route("/clientapi/post/nearby")] [HttpGet, Route("/clientapi/post/nearby")]
public async Task<IActionResult> Nearby([FromQuery] string avatarId, [FromQuery] double latitude, [FromQuery] double longitude, CancellationToken token) => public async Task<IActionResult> Nearby([FromQuery] string avatarId, [FromQuery] double latitude, [FromQuery] double longitude, CancellationToken token) =>
Answer(await _postsService.Nearby(User.GetUserId(), avatarId, latitude, longitude, token)); Answer(await postsService.Nearby(User.GetUserId(), avatarId, latitude, longitude, token));
[HttpPost, Route("/clientapi/post/update")] [HttpPost, Route("/clientapi/post/update")]
public async Task<IActionResult> Update(UpdatePostForm form, CancellationToken token) => public async Task<IActionResult> Update(UpdatePostForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _postsService.UpdatePost(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await postsService.UpdatePost(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/post/delete")] [HttpPost, Route("/clientapi/post/delete")]
public async Task<IActionResult> Delete(DeletePostForm form, CancellationToken token) => public async Task<IActionResult> Delete(DeletePostForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _postsService.DeletePost(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await postsService.DeletePost(User.GetUserId(), form, token));
[HttpGet, Route("/clientapi/dm/list")] [HttpGet, Route("/clientapi/dm/list")]
public async Task<IActionResult> Dms([FromQuery] string avatarId, [FromQuery] string dmGroupId, CancellationToken token) => public async Task<IActionResult> Dms([FromQuery] string avatarId, [FromQuery] string dmGroupId, CancellationToken token) =>
Answer(await _postsService.GetDms(User.GetUserId(), avatarId, dmGroupId, token)); Answer(await postsService.GetDms(User.GetUserId(), avatarId, dmGroupId, token));
[HttpPost, Route("/clientapi/dm/insert")] [HttpPost, Route("/clientapi/dm/insert")]
public async Task<IActionResult> InsertDm(InsertDmForm form, CancellationToken token) => public async Task<IActionResult> InsertDm(InsertDmForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _postsService.InsertDm(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await postsService.InsertDm(User.GetUserId(), form, token));
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
@@ -13,38 +13,28 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/avatar/private"), Route("clientapi/avatar/private"),
Authorize(Policy = Policies.IsUser)] Authorize(Policy = Policies.IsUser)]
public class PrivateAvatarController : ControllerBase public class PrivateAvatarController(
IPrivateAvatarUsersService privateAvatarUsersService,
IStringLocalizer<GenericRes> localizer,
ILogger<PrivateAvatarController> logger) : ControllerBase
{ {
readonly ILogger<PrivateAvatarController> _logger;
readonly IPrivateAvatarUsersService _privateAvatarUsersService;
readonly IStringLocalizer _localizer;
public PrivateAvatarController(IPrivateAvatarUsersService privateAvatarUsersService,
IStringLocalizer<GenericRes> localizer,
ILogger<PrivateAvatarController> logger)
{
_privateAvatarUsersService = privateAvatarUsersService;
_localizer = localizer;
_logger = logger;
}
[HttpGet, Route("/clientapi/avatar/private/list")] [HttpGet, Route("/clientapi/avatar/private/list")]
public async Task<IActionResult> GetAvatars(CancellationToken token) public async Task<IActionResult> GetAvatars(CancellationToken token)
{ {
var result = await _privateAvatarUsersService.GetRootAvatars(User.GetUserId(), token); var result = await privateAvatarUsersService.GetRootAvatars(User.GetUserId(), token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/avatar/private/insert")] [HttpPost, Route("/clientapi/avatar/private/insert")]
public async Task<IActionResult> InsertAvatar(InsertAvatarForm model) public async Task<IActionResult> InsertAvatar(InsertAvatarForm model, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(_localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
model.RootId = User.GetUserId(); model.RootId = User.GetUserId();
result = await _privateAvatarUsersService.InsertAvatar(model); result = await privateAvatarUsersService.InsertAvatar(model, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -52,8 +42,8 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()"); logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()");
return BadRequest(result.Invalidate(_localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -64,13 +54,13 @@ namespace PrivaPub.Controllers.ClientToServer
[FromServices] Services.IPersonaRemoval personas, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token) [FromServices] Services.IPersonaRemoval personas, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var rootId = User.GetUserId(); var rootId = User.GetUserId();
if (!await users.PasswordMatches(rootId, form.Password)) if (!await users.PasswordMatches(rootId, form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(_localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(localizer[Services.RootUsersService.NoMatch], StatusCodes.Status403Forbidden));
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token) if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token)
|| !await personas.Remove(form.AvatarId, CancellationToken.None)) || !await personas.Remove(form.AvatarId, CancellationToken.None))
return NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound)); return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound));
return Ok(); return Ok();
} }
@@ -80,7 +70,7 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var avatar = await OwnPersona(avatarId, dbEntities, token); var avatar = await OwnPersona(avatarId, dbEntities, token);
return avatar == default return avatar == default
? NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound)) ? NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound))
: Ok(PreferencesOf(avatar)); : Ok(PreferencesOf(avatar));
} }
@@ -88,12 +78,12 @@ namespace PrivaPub.Controllers.ClientToServer
public async Task<IActionResult> SavePreferences(PersonaPreferencesForm form, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token) public async Task<IActionResult> SavePreferences(PersonaPreferencesForm form, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
if (!Models.User.ExpandMediaModes.IsKnown(form.ExpandMedia)) if (!Models.User.ExpandMediaModes.IsKnown(form.ExpandMedia))
return UnprocessableEntity(new WebResult().Invalidate(_localizer["Media are shown as default, show_all or hide_all."], StatusCodes.Status422UnprocessableEntity)); return UnprocessableEntity(new WebResult().Invalidate(localizer["Media are shown as default, show_all or hide_all."], StatusCodes.Status422UnprocessableEntity));
var avatar = await OwnPersona(form.AvatarId, dbEntities, token); var avatar = await OwnPersona(form.AvatarId, dbEntities, token);
if (avatar == default) if (avatar == default)
return NotFound(new WebResult().Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound)); return NotFound(new WebResult().Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound));
await MongoDB.Entities.DB.Default.Update<Models.User.Avatar>().MatchID(avatar.ID) await MongoDB.Entities.DB.Default.Update<Models.User.Avatar>().MatchID(avatar.ID)
.Modify(a => a.Settings.ExpandMedia, form.ExpandMedia) .Modify(a => a.Settings.ExpandMedia, form.ExpandMedia)
.Modify(a => a.Settings.ExpandSpoilers, form.ExpandSpoilers) .Modify(a => a.Settings.ExpandSpoilers, form.ExpandSpoilers)
@@ -120,15 +110,15 @@ namespace PrivaPub.Controllers.ClientToServer
}; };
[HttpPost, Route("/clientapi/avatar/private/update")] [HttpPost, Route("/clientapi/avatar/private/update")]
public async Task<IActionResult> UpdateAvatar(UpdateAvatarForm model) public async Task<IActionResult> UpdateAvatar(UpdateAvatarForm model, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(_localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
model.RootId = User.GetUserId(); model.RootId = User.GetUserId();
result = await _privateAvatarUsersService.UpdateAvatar(model); result = await privateAvatarUsersService.UpdateAvatar(model, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -136,8 +126,8 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()"); logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()");
return BadRequest(result.Invalidate(_localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -28,90 +28,68 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
[ApiController, [ApiController,
Route("clientapi/user")] Route("clientapi/user")]
public class RootUserController : ControllerBase public class RootUserController(
IRootUsersService usersService,
IGroupUsersService groupUsersService,
IPrivateAvatarUsersService avatarUsersService,
ILocalActorService localActors,
AuthTokenManager authTokenManager,
IOptionsMonitor<AppConfiguration> appConfiguration,
IOptionsMonitor<RegistrationOptions> registrations,
IStringLocalizer<GenericRes> localizer,
ILogger<RootUserController> logger) : ControllerBase
{ {
readonly IRootUsersService UsersService;
readonly IGroupUsersService GroupUsersService;
readonly IPrivateAvatarUsersService AvatarUsersService;
readonly ILocalActorService LocalActors;
readonly AuthTokenManager AuthTokenManager;
readonly IOptionsMonitor<AppConfiguration> AppConfiguration;
readonly IOptionsMonitor<RegistrationOptions> Registrations;
readonly ILogger<RootUserController> Logger;
readonly IStringLocalizer Localizer;
public RootUserController(IRootUsersService usersService,
IGroupUsersService groupUsersService,
IPrivateAvatarUsersService avatarUsersService,
ILocalActorService localActors,
AuthTokenManager authTokenManager,
IOptionsMonitor<AppConfiguration> appConfiguration,
IOptionsMonitor<RegistrationOptions> registrations,
IStringLocalizer<GenericRes> localizer,
ILogger<RootUserController> logger)
{
Registrations = registrations;
UsersService = usersService;
GroupUsersService = groupUsersService;
AvatarUsersService = avatarUsersService;
LocalActors = localActors;
AuthTokenManager = authTokenManager;
AppConfiguration = appConfiguration;
Localizer = localizer;
Logger = logger;
}
#region User endpoints #region User endpoints
[HttpPost, Route("/clientapi/user/signup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous] [HttpPost, Route("/clientapi/user/signup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
public async Task<IActionResult> SignUp(LoginForm signUpForm) public async Task<IActionResult> SignUp(LoginForm signUpForm, CancellationToken token = default)
{ {
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
var result = new WebResult(); var result = new WebResult();
if (!Registrations.CurrentValue.IsOpen) if (!registrations.CurrentValue.IsOpen)
return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(Localizer[RegistrationOptions.ClosedMessage], StatusCodes.Status403Forbidden)); return StatusCode(StatusCodes.Status403Forbidden, result.Invalidate(localizer[RegistrationOptions.ClosedMessage], StatusCodes.Status403Forbidden));
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.SignUpAsync(signUpForm); result = await usersService.SignUpAsync(signUpForm, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
(var user, var userSettings) = ((RootUser, ViewUserSettings))result.Data; (var user, var userSettings) = ((RootUser, ViewUserSettings))result.Data;
var jwtUser = AuthTokenManager.GenerateToken(user, userSettings); var jwtUser = authTokenManager.GenerateToken(user, userSettings);
return Ok(jwtUser); return Ok(jwtUser);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(SignUp)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
[HttpPost, Route("/clientapi/user/login"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous] [HttpPost, Route("/clientapi/user/login"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser), AllowAnonymous]
public async Task<IActionResult> Login(LoginForm loginForm) public async Task<IActionResult> Login(LoginForm loginForm, CancellationToken token = default)
{ {
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.LoginAsync(loginForm); result = await usersService.LoginAsync(loginForm, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
var (user, userSettings) = var (user, userSettings) =
((RootUser, ViewUserSettings))result.Data; ((RootUser, ViewUserSettings))result.Data;
var jwtUser = AuthTokenManager.GenerateToken(user, userSettings); var jwtUser = authTokenManager.GenerateToken(user, userSettings);
return Ok(jwtUser); return Ok(jwtUser);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(Login)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -120,10 +98,10 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
var invitation = await GroupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token); var invitation = await groupUsersService.GetInvitation(signUpForm.InvitationCode, signUpForm.InvitationPassword, token);
if (!invitation.IsValid) if (!invitation.IsValid)
return StatusCode(invitation.StatusCode, invitation); return StatusCode(invitation.StatusCode, invitation);
@@ -132,16 +110,16 @@ namespace PrivaPub.Controllers.ClientToServer
if (personaProblem != default) if (personaProblem != default)
return BadRequest(result.Invalidate(personaProblem)); return BadRequest(result.Invalidate(personaProblem));
result = await UsersService.SignUpAsync(signUpForm); result = await usersService.SignUpAsync(signUpForm, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data; var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
var avatar = await InsertPersona(user.ID, avatarUserName, signUpForm.AvatarName); var avatar = await InsertPersona(user.ID, avatarUserName, signUpForm.AvatarName, token);
if (!avatar.IsValid) if (!avatar.IsValid)
return StatusCode(avatar.StatusCode, avatar); return StatusCode(avatar.StatusCode, avatar);
var joined = await GroupUsersService.JoinGroup(user.ID, new JoinGroupForm var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
{ {
AvatarId = ((ViewAvatar)avatar.Data).Id, AvatarId = ((ViewAvatar)avatar.Data).Id,
InvitationCode = signUpForm.InvitationCode, InvitationCode = signUpForm.InvitationCode,
@@ -150,12 +128,12 @@ namespace PrivaPub.Controllers.ClientToServer
if (!joined.IsValid) if (!joined.IsValid)
return StatusCode(joined.StatusCode, joined); return StatusCode(joined.StatusCode, joined);
return Ok(AuthTokenManager.GenerateToken(user, userSettings)); return Ok(authTokenManager.GenerateToken(user, userSettings));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationSignUp)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -164,19 +142,19 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
var invitation = await GroupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token); var invitation = await groupUsersService.GetInvitation(loginForm.InvitationCode, loginForm.InvitationPassword, token);
if (!invitation.IsValid) if (!invitation.IsValid)
return StatusCode(invitation.StatusCode, invitation); return StatusCode(invitation.StatusCode, invitation);
result = await UsersService.LoginAsync(loginForm); result = await usersService.LoginAsync(loginForm, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data; var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
var avatars = await AvatarUsersService.GetRootAvatars(user.ID, token); var avatars = await avatarUsersService.GetRootAvatars(user.ID, token);
var avatarUserName = loginForm.AvatarUserName?.Trim().ToLowerInvariant(); var avatarUserName = loginForm.AvatarUserName?.Trim().ToLowerInvariant();
var avatar = string.IsNullOrEmpty(avatarUserName) var avatar = string.IsNullOrEmpty(avatarUserName)
? (avatars.Data as List<ViewAvatar>)?.FirstOrDefault() ? (avatars.Data as List<ViewAvatar>)?.FirstOrDefault()
@@ -186,13 +164,13 @@ namespace PrivaPub.Controllers.ClientToServer
var personaProblem = await PersonaProblem(avatarUserName, user.UserName, token); var personaProblem = await PersonaProblem(avatarUserName, user.UserName, token);
if (personaProblem != default) if (personaProblem != default)
return BadRequest(new WebResult().Invalidate(personaProblem)); return BadRequest(new WebResult().Invalidate(personaProblem));
var inserted = await InsertPersona(user.ID, avatarUserName, loginForm.AvatarName); var inserted = await InsertPersona(user.ID, avatarUserName, loginForm.AvatarName, token);
if (!inserted.IsValid) if (!inserted.IsValid)
return StatusCode(inserted.StatusCode, inserted); return StatusCode(inserted.StatusCode, inserted);
avatar = (ViewAvatar)inserted.Data; avatar = (ViewAvatar)inserted.Data;
} }
var joined = await GroupUsersService.JoinGroup(user.ID, new JoinGroupForm var joined = await groupUsersService.JoinGroup(user.ID, new JoinGroupForm
{ {
AvatarId = avatar.Id, AvatarId = avatar.Id,
InvitationCode = loginForm.InvitationCode, InvitationCode = loginForm.InvitationCode,
@@ -201,12 +179,12 @@ namespace PrivaPub.Controllers.ClientToServer
if (!joined.IsValid) if (!joined.IsValid)
return StatusCode(joined.StatusCode, joined); return StatusCode(joined.StatusCode, joined);
return Ok(AuthTokenManager.GenerateToken(user, userSettings)); return Ok(authTokenManager.GenerateToken(user, userSettings));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(InvitationLogin)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -216,14 +194,14 @@ namespace PrivaPub.Controllers.ClientToServer
// The server's first login, made while it has no administrator (owner decision 2026-10-16: first come, first served): // The server's first login, made while it has no administrator (owner decision 2026-10-16: first come, first served):
// it is made the administrator, with its first persona, and setup closes for good. Sign-up stays closed to everyone // it is made the administrator, with its first persona, and setup closes for good. Sign-up stays closed to everyone
// else (Registrations), so NodeInfo and the instance API don't change. // else (registrations), so NodeInfo and the instance API don't change.
[HttpPost, Route("/clientapi/user/setup"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous] [HttpPost, Route("/clientapi/user/setup"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
public async Task<IActionResult> SetUp(SetupForm setupForm, CancellationToken token) public async Task<IActionResult> SetUp(SetupForm setupForm, CancellationToken token)
{ {
if (User.Identity?.IsAuthenticated ?? false) return Redirect("/"); if (User.Identity?.IsAuthenticated ?? false) return Redirect("/");
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
var claimed = false; var claimed = false;
var adminId = default(string); var adminId = default(string);
try try
@@ -240,10 +218,10 @@ namespace PrivaPub.Controllers.ClientToServer
if (!claimed) if (!claimed)
return SetUpAlready(); return SetUpAlready();
result = await UsersService.SignUpAsync(setupForm); result = await usersService.SignUpAsync(setupForm, token);
if (!result.IsValid) if (!result.IsValid)
{ {
await ServerSetup.Release(); await ServerSetup.Release(CancellationToken.None);
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
} }
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data; var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
@@ -253,42 +231,42 @@ namespace PrivaPub.Controllers.ClientToServer
await ServerSetup.Claimed(adminId, CancellationToken.None); await ServerSetup.Claimed(adminId, CancellationToken.None);
// set up from here, whatever happens to the persona: it can be made in the client's settings // set up from here, whatever happens to the persona: it can be made in the client's settings
var avatar = await InsertPersona(user.ID, avatarUserName, setupForm.AvatarName); var avatar = await InsertPersona(user.ID, avatarUserName, setupForm.AvatarName, token);
if (!avatar.IsValid) if (!avatar.IsValid)
return StatusCode(avatar.StatusCode, avatar); return StatusCode(avatar.StatusCode, avatar);
return Ok(AuthTokenManager.GenerateToken(user, userSettings)); return Ok(authTokenManager.GenerateToken(user, userSettings));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(SetUp)}()");
if (claimed && adminId == default) if (claimed && adminId == default)
await ServerSetup.Release(); await ServerSetup.Release(CancellationToken.None);
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
IActionResult SetUpAlready() => IActionResult SetUpAlready() =>
StatusCode(StatusCodes.Status403Forbidden, StatusCode(StatusCodes.Status403Forbidden,
new WebResult().Invalidate(Localizer["This server is already set up: joining it takes a group invitation."], StatusCodes.Status403Forbidden)); new WebResult().Invalidate(localizer["This server is already set up: joining it takes a group invitation."], StatusCodes.Status403Forbidden));
Task<WebResult> InsertPersona(string rootId, string avatarUserName, string avatarName) => Task<WebResult> InsertPersona(string rootId, string avatarUserName, string avatarName, CancellationToken token = default) =>
AvatarUsersService.InsertAvatar(new InsertAvatarForm avatarUsersService.InsertAvatar(new InsertAvatarForm
{ {
RootId = rootId, RootId = rootId,
Name = string.IsNullOrWhiteSpace(avatarName) ? avatarUserName : avatarName.Trim(), Name = string.IsNullOrWhiteSpace(avatarName) ? avatarUserName : avatarName.Trim(),
UserName = avatarUserName, UserName = avatarUserName,
Biography = string.Empty Biography = string.Empty
}); }, token);
async Task<string> PersonaProblem(string avatarUserName, string rootUserName, CancellationToken token) async Task<string> PersonaProblem(string avatarUserName, string rootUserName, CancellationToken token)
{ {
if (string.IsNullOrEmpty(avatarUserName)) if (string.IsNullOrEmpty(avatarUserName))
return Localizer["Choose a username for your persona."]; return localizer["Choose a username for your persona."];
if (string.Equals(avatarUserName, rootUserName?.Trim(), StringComparison.OrdinalIgnoreCase)) if (string.Equals(avatarUserName, rootUserName?.Trim(), StringComparison.OrdinalIgnoreCase))
return Localizer["Your persona's username must differ from your login."]; return localizer["Your persona's username must differ from your login."];
if (await LocalActors.IsUserNameTaken(avatarUserName, token)) if (await localActors.IsUserNameTaken(avatarUserName, token))
return Localizer["The username '{0}' is already taken.", avatarUserName]; return localizer["The username '{0}' is already taken.", avatarUserName];
return default; return default;
} }
@@ -309,8 +287,8 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(Logout)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -325,8 +303,8 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(LogoutEverywhere)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -335,82 +313,82 @@ namespace PrivaPub.Controllers.ClientToServer
[HttpPost, Route("/clientapi/user/update"), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/update"), Authorize(Policy = Policies.IsUser)]
public IActionResult UpdateUser(UserForm userEmailForm) => public IActionResult UpdateUser(UserForm userEmailForm) =>
StatusCode(StatusCodes.Status422UnprocessableEntity, StatusCode(StatusCodes.Status422UnprocessableEntity,
new WebResult().Invalidate(Localizer["Changing the address takes your password and a code sent to it."], StatusCodes.Status422UnprocessableEntity)); new WebResult().Invalidate(localizer["Changing the address takes your password and a code sent to it."], StatusCodes.Status422UnprocessableEntity));
[HttpGet, Route("/clientapi/user/account"), Authorize(Policy = Policies.IsUser)] [HttpGet, Route("/clientapi/user/account"), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> Account() public async Task<IActionResult> Account(CancellationToken token = default)
{ {
var result = await UsersService.AccountAsync(User.GetUserId()); var result = await usersService.AccountAsync(User.GetUserId(), token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/user/email"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/email"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> RequestEmailChange(EmailChangeForm form) public async Task<IActionResult> RequestEmailChange(EmailChangeForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.RequestEmailChangeAsync(User.GetUserId(), form); var result = await usersService.RequestEmailChangeAsync(User.GetUserId(), form, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/user/email/verify"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/email/verify"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> VerifyEmail(EmailCodeForm form) public async Task<IActionResult> VerifyEmail(EmailCodeForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.VerifyEmailAsync(User.GetUserId(), form.Code); var result = await usersService.VerifyEmailAsync(User.GetUserId(), form.Code, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/user/totp/setup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/totp/setup"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> TotpSetup(PasswordForm form) public async Task<IActionResult> TotpSetup(PasswordForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.TotpSetupAsync(User.GetUserId(), form.Password); var result = await usersService.TotpSetupAsync(User.GetUserId(), form.Password, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
// on with the app's first code; every other session ends, and this device goes on with a new one // on with the app's first code; every other session ends, and this device goes on with a new one
[HttpPost, Route("/clientapi/user/totp/enable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/totp/enable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> TotpEnable(TotpCodeForm form) public async Task<IActionResult> TotpEnable(TotpCodeForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.TotpEnableAsync(User.GetUserId(), form.Code); var result = await usersService.TotpEnableAsync(User.GetUserId(), form.Code, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
var (user, userSettings, codes) = ((RootUser, ViewUserSettings, List<string>))result.Data; var (user, userSettings, codes) = ((RootUser, ViewUserSettings, List<string>))result.Data;
return Ok(new ViewTotpEnabled { RecoveryCodes = codes, Session = AuthTokenManager.GenerateToken(user, userSettings) }); return Ok(new ViewTotpEnabled { RecoveryCodes = codes, Session = authTokenManager.GenerateToken(user, userSettings) });
} }
[HttpPost, Route("/clientapi/user/totp/disable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/totp/disable"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> TotpDisable(TotpDisableForm form) public async Task<IActionResult> TotpDisable(TotpDisableForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.TotpDisableAsync(User.GetUserId(), form.Password, form.Code); var result = await usersService.TotpDisableAsync(User.GetUserId(), form.Password, form.Code, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/user/email/remove"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/email/remove"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> RemoveEmail(PasswordForm form) public async Task<IActionResult> RemoveEmail(PasswordForm form, CancellationToken token = default)
{ {
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(Localizer["Invalid model."])); return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
var result = await UsersService.RemoveEmailAsync(User.GetUserId(), form.Password); var result = await usersService.RemoveEmailAsync(User.GetUserId(), form.Password, token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
[HttpPost, Route("/clientapi/user/update/settings"), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/update/settings"), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> UpdateUserSettings(ViewUserSettings userSettings) public async Task<IActionResult> UpdateUserSettings(ViewUserSettings userSettings, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.UpdateUserSettingsAsync(userSettings, User.GetUserId()); result = await usersService.UpdateUserSettingsAsync(userSettings, User.GetUserId(), token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -418,31 +396,31 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(UpdateUserSettings)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
[HttpPost, Route("/clientapi/user/update/password"), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/update/password"), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> UpdatePassword(UserPasswordForm userPasswordForm) public async Task<IActionResult> UpdatePassword(UserPasswordForm userPasswordForm, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId()); result = await usersService.UpdateUserPasswordAsync(userPasswordForm, User.GetUserId(), token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
// every session ended with the change; this device goes on with a new one // every session ended with the change; this device goes on with a new one
var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data; var (user, userSettings) = ((RootUser, ViewUserSettings))result.Data;
return Ok(AuthTokenManager.GenerateToken(user, userSettings)); return Ok(authTokenManager.GenerateToken(user, userSettings));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(UpdatePassword)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -456,35 +434,35 @@ namespace PrivaPub.Controllers.ClientToServer
} }
[HttpGet, Route("/clientapi/user/settings"), Authorize(Policy = Policies.IsUser)] [HttpGet, Route("/clientapi/user/settings"), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> GetUserSettings() public async Task<IActionResult> GetUserSettings(CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
try try
{ {
result = await UsersService.GetUserSettingsAsync(User.GetUserId()); result = await usersService.GetUserSettingsAsync(User.GetUserId(), token: token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
return Ok(result.Data); return Ok(result.Data);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(GetUserSettings)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
[HttpPost, Route("/clientapi/user/recover/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous] [HttpPost, Route("/clientapi/user/recover/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
public async Task<IActionResult> RecoverPassword(PasswordRecoveryForm passwordRecoveryForm) public async Task<IActionResult> RecoverPassword(PasswordRecoveryForm passwordRecoveryForm, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
var host = string.IsNullOrEmpty(AppConfiguration.CurrentValue.FrontendBaseAddress) var host = string.IsNullOrEmpty(appConfiguration.CurrentValue.FrontendBaseAddress)
? $"{Request.Scheme}://{Request.Host.Host}" ? $"{Request.Scheme}://{Request.Host.Host}"
: AppConfiguration.CurrentValue.FrontendBaseAddress.TrimEnd('/'); : appConfiguration.CurrentValue.FrontendBaseAddress.TrimEnd('/');
result = await UsersService.SetupAndSendRecoveryEmail(passwordRecoveryForm, host); result = await usersService.SetupAndSendRecoveryEmail(passwordRecoveryForm, host, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -492,8 +470,8 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(RecoverPassword)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -502,12 +480,12 @@ namespace PrivaPub.Controllers.ClientToServer
[FromBody, [FromBody,
Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)), Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)),
Display(Name = "RecoveryCode", ResourceType = typeof(FieldsNameResource))] Display(Name = "RecoveryCode", ResourceType = typeof(FieldsNameResource))]
string recoveryCode) string recoveryCode, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
try try
{ {
result = await UsersService.IsValidRecoveryCode(recoveryCode); result = await usersService.IsValidRecoveryCode(recoveryCode, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -515,20 +493,20 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(IsValidRecoveryCode)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
[HttpPost, Route("/clientapi/user/recover/update/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous] [HttpPost, Route("/clientapi/user/recover/update/password"), EnableRateLimiting(RateLimiting.Accounts), AllowAnonymous]
public async Task<IActionResult> ChangePassword(NewPasswordForm newPasswordForm) public async Task<IActionResult> ChangePassword(NewPasswordForm newPasswordForm, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.ChangePassword(newPasswordForm); result = await usersService.ChangePassword(newPasswordForm, token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
@@ -536,26 +514,26 @@ namespace PrivaPub.Controllers.ClientToServer
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(ChangePassword)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
[HttpPost, Route("/clientapi/user/delete"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)] [HttpPost, Route("/clientapi/user/delete"), EnableRateLimiting(RateLimiting.Accounts), Authorize(Policy = Policies.IsUser)]
public async Task<IActionResult> RemoveSelf(RemoveSelfForm form) public async Task<IActionResult> RemoveSelf(RemoveSelfForm form, CancellationToken token = default)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(result.Invalidate(Localizer["Invalid model."])); return BadRequest(result.Invalidate(localizer["Invalid model."]));
try try
{ {
result = await UsersService.RemoveSelfAsync(User.GetUserId(), form.Password); result = await usersService.RemoveSelfAsync(User.GetUserId(), form.Password, token);
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result); return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(RemoveSelf)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -571,17 +549,17 @@ namespace PrivaPub.Controllers.ClientToServer
{ {
var user = await dbEntities.RootUsers.MatchID(User.GetUserId()).ExecuteFirstAsync(token); var user = await dbEntities.RootUsers.MatchID(User.GetUserId()).ExecuteFirstAsync(token);
if (user is not { IsBanned: false, DeletedAt: null }) if (user is not { IsBanned: false, DeletedAt: null })
return Unauthorized(result.Invalidate(Localizer["Unauthorized."], StatusCodes.Status401Unauthorized)); return Unauthorized(result.Invalidate(localizer["Unauthorized."], StatusCodes.Status401Unauthorized));
result = await UsersService.GetUserSettingsAsync(user.ID); result = await usersService.GetUserSettingsAsync(user.ID, token: token);
if (!result.IsValid) if (!result.IsValid)
return StatusCode(result.StatusCode, result); return StatusCode(result.StatusCode, result);
return Ok(AuthTokenManager.GenerateToken(user, (ViewUserSettings)result.Data, User.FindFirst(AuthTokenManager.SessionId)?.Value)); return Ok(authTokenManager.GenerateToken(user, (ViewUserSettings)result.Data, User.FindFirst(AuthTokenManager.SessionId)?.Value));
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()"); logger.LogError(ex, $"{nameof(User)}.{nameof(SniffAgain)}()");
return BadRequest(result.Invalidate(Localizer["Something went wrong."])); return BadRequest(result.Invalidate(localizer["Something went wrong."]));
} }
} }
@@ -13,30 +13,23 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/social"), Route("clientapi/social"),
Authorize(Policy = Policies.IsUser)] Authorize(Policy = Policies.IsUser)]
public class SocialController : ControllerBase public class SocialController(
IFollowService follows,
IStringLocalizer<GenericRes> localizer) : ControllerBase
{ {
readonly IFollowService _follows;
readonly IStringLocalizer _localizer;
public SocialController(IFollowService follows, IStringLocalizer<GenericRes> localizer)
{
_follows = follows;
_localizer = localizer;
}
[HttpPost, Route("/clientapi/follow")] [HttpPost, Route("/clientapi/follow")]
public async Task<IActionResult> Follow(FollowForm form, CancellationToken token) => public async Task<IActionResult> Follow(FollowForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _follows.Follow(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await follows.Follow(User.GetUserId(), form, token));
[HttpPost, Route("/clientapi/unfollow")] [HttpPost, Route("/clientapi/unfollow")]
public async Task<IActionResult> Unfollow(FollowForm form, CancellationToken token) => public async Task<IActionResult> Unfollow(FollowForm form, CancellationToken token) =>
!ModelState.IsValid ? Invalid() : Answer(await _follows.Unfollow(User.GetUserId(), form, token)); !ModelState.IsValid ? Invalid() : Answer(await follows.Unfollow(User.GetUserId(), form, token));
[HttpGet, Route("/clientapi/following")] [HttpGet, Route("/clientapi/following")]
public async Task<IActionResult> Following([FromQuery] string avatarId, CancellationToken token) => public async Task<IActionResult> Following([FromQuery] string avatarId, CancellationToken token) =>
Answer(await _follows.Followings(User.GetUserId(), avatarId, token)); Answer(await follows.Followings(User.GetUserId(), avatarId, token));
IActionResult Invalid() => BadRequest(new WebResult().Invalidate(_localizer["Invalid model."])); IActionResult Invalid() => BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
@@ -14,27 +14,19 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/admin/statistics"), Route("clientapi/admin/statistics"),
Authorize(Policy = Policies.IsAdmin)] Authorize(Policy = Policies.IsAdmin)]
public class StatisticsController : ControllerBase public class StatisticsController(
StatisticsQueries queries,
IJobQueue queue,
Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> options) : ControllerBase
{ {
readonly StatisticsQueries _queries;
readonly IJobQueue _queue;
readonly Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> _options;
public StatisticsController(StatisticsQueries queries, IJobQueue queue, Microsoft.Extensions.Options.IOptionsMonitor<StatisticsOptions> options)
{
_queries = queries;
_queue = queue;
_options = options;
}
[HttpGet, Route("/clientapi/admin/statistics/crawler")] [HttpGet, Route("/clientapi/admin/statistics/crawler")]
public async Task<IActionResult> Crawler(CancellationToken token) => public async Task<IActionResult> Crawler(CancellationToken token) =>
Ok(await _queries.Crawler(_options.CurrentValue.Crawler.Enabled, _options.CurrentValue.Crawler.RevisitDays, token)); Ok(await queries.Crawler(options.CurrentValue.Crawler.Enabled, options.CurrentValue.Crawler.RevisitDays, token));
[HttpGet, Route("/clientapi/admin/statistics/overview")] [HttpGet, Route("/clientapi/admin/statistics/overview")]
public async Task<IActionResult> Overview([FromServices] Domain.Media.IMediaService media, [FromQuery] int days = 30, CancellationToken token = default) public async Task<IActionResult> Overview([FromServices] Domain.Media.IMediaService media, [FromQuery] int days = 30, CancellationToken token = default)
{ {
var overview = await _queries.Overview(days, token); var overview = await queries.Overview(days, token);
overview.Media.ProxyCacheBytes = Bytes(media.ProxyRoot); overview.Media.ProxyCacheBytes = Bytes(media.ProxyRoot);
overview.Media.TrashBytes = Bytes(media.TrashRoot); overview.Media.TrashBytes = Bytes(media.TrashRoot);
return Ok(overview); return Ok(overview);
@@ -46,20 +38,20 @@ namespace PrivaPub.Controllers.ClientToServer
[HttpGet, Route("/clientapi/admin/statistics/hosts")] [HttpGet, Route("/clientapi/admin/statistics/hosts")]
public async Task<IActionResult> Hosts([FromQuery] int days = 30, [FromQuery] string sort = default, [FromQuery] string software = default, public async Task<IActionResult> Hosts([FromQuery] int days = 30, [FromQuery] string sort = default, [FromQuery] string software = default,
[FromQuery] int page = 1, [FromQuery] int limit = 50, CancellationToken token = default) => [FromQuery] int page = 1, [FromQuery] int limit = 50, CancellationToken token = default) =>
Ok(await _queries.Hosts(days, sort, software, page, limit, token)); Ok(await queries.Hosts(days, sort, software, page, limit, token));
[HttpGet, Route("/clientapi/admin/statistics/hosts/{host}")] [HttpGet, Route("/clientapi/admin/statistics/hosts/{host}")]
public async Task<IActionResult> Host(string host, [FromQuery] int days = 90, CancellationToken token = default) => public async Task<IActionResult> Host(string host, [FromQuery] int days = 90, CancellationToken token = default) =>
await _queries.Host(host, days, token) is { } found ? Ok(found) : NotFound(); await queries.Host(host, days, token) is { } found ? Ok(found) : NotFound();
[HttpGet, Route("/clientapi/admin/statistics/events")] [HttpGet, Route("/clientapi/admin/statistics/events")]
public async Task<IActionResult> Events([FromQuery] string host = default, [FromQuery] string channel = default, [FromQuery] string outcome = default, public async Task<IActionResult> Events([FromQuery] string host = default, [FromQuery] string channel = default, [FromQuery] string outcome = default,
[FromQuery] string reason = default, [FromQuery] DateTime? before = default, [FromQuery] int limit = 100, CancellationToken token = default) => [FromQuery] string reason = default, [FromQuery] DateTime? before = default, [FromQuery] int limit = 100, CancellationToken token = default) =>
Ok(await _queries.Events(host, channel, outcome, reason, before, limit, token)); Ok(await queries.Events(host, channel, outcome, reason, before, limit, token));
[HttpGet, Route("/clientapi/admin/statistics/server")] [HttpGet, Route("/clientapi/admin/statistics/server")]
public async Task<IActionResult> Server([FromQuery] int days = 30, CancellationToken token = default) => public async Task<IActionResult> Server([FromQuery] int days = 30, CancellationToken token = default) =>
Ok(await _queries.Server(days, token)); Ok(await queries.Server(days, token));
[HttpPost, Route("/clientapi/admin/statistics/rollups/{day}")] [HttpPost, Route("/clientapi/admin/statistics/rollups/{day}")]
public async Task<IActionResult> Rollup(string day, CancellationToken token) public async Task<IActionResult> Rollup(string day, CancellationToken token)
@@ -69,7 +61,7 @@ namespace PrivaPub.Controllers.ClientToServer
return BadRequest(); return BadRequest();
var job = RollupJob.For(parsed.Date, $"rollup|{day}|rerun|{DateTime.UtcNow.Ticks}"); var job = RollupJob.For(parsed.Date, $"rollup|{day}|rerun|{DateTime.UtcNow.Ticks}");
job.RunAt = DateTime.UtcNow; job.RunAt = DateTime.UtcNow;
await _queue.EnqueueMany(new[] { job }, token); await queue.EnqueueMany(new[] { job }, token);
return Accepted(); return Accepted();
} }
@@ -79,7 +71,7 @@ namespace PrivaPub.Controllers.ClientToServer
host = Interactions.Host(host); host = Interactions.Host(host);
if (host == Interactions.Unknown) if (host == Interactions.Unknown)
return BadRequest(); return BadRequest();
await _queue.Enqueue(JobKind.DescribeInstance, host, host, $"describe|{host}|admin|{DateTime.UtcNow.Ticks}", token); await queue.Enqueue(JobKind.DescribeInstance, host, host, $"describe|{host}|admin|{DateTime.UtcNow.Ticks}", token);
return Accepted(); return Accepted();
} }
} }
@@ -10,28 +10,22 @@ namespace PrivaPub.Controllers.ClientToServer
[ApiController, [ApiController,
Route("clientapi/timeline"), Route("clientapi/timeline"),
Authorize(Policy = Policies.IsUser)] Authorize(Policy = Policies.IsUser)]
public class TimelineController : ControllerBase public class TimelineController(
ITimelineService timelines) : ControllerBase
{ {
readonly ITimelineService _timelines;
public TimelineController(ITimelineService timelines)
{
_timelines = timelines;
}
[HttpGet, Route("/clientapi/timeline/home")] [HttpGet, Route("/clientapi/timeline/home")]
public async Task<IActionResult> Home([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20, public async Task<IActionResult> Home([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20,
CancellationToken token = default) => CancellationToken token = default) =>
Answer(await _timelines.Home(User.GetUserId(), avatarId, maxId, limit, token)); Answer(await timelines.Home(User.GetUserId(), avatarId, maxId, limit, token));
[HttpGet, Route("/clientapi/notifications")] [HttpGet, Route("/clientapi/notifications")]
public async Task<IActionResult> Notifications([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20, public async Task<IActionResult> Notifications([FromQuery] string avatarId, [FromQuery(Name = "max_id")] string maxId, [FromQuery] int limit = 20,
CancellationToken token = default) => CancellationToken token = default) =>
Answer(await _timelines.Notifications(User.GetUserId(), avatarId, maxId, limit, token)); Answer(await timelines.Notifications(User.GetUserId(), avatarId, maxId, limit, token));
[HttpPost, Route("/clientapi/notifications/read")] [HttpPost, Route("/clientapi/notifications/read")]
public async Task<IActionResult> Read([FromQuery] string avatarId, CancellationToken token) => public async Task<IActionResult> Read([FromQuery] string avatarId, CancellationToken token) =>
Answer(await _timelines.MarkNotificationsRead(User.GetUserId(), avatarId, token)); Answer(await timelines.MarkNotificationsRead(User.GetUserId(), avatarId, token));
IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result); IActionResult Answer(WebResult result) => result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
} }
+11 -11
View File
@@ -10,17 +10,17 @@ namespace PrivaPub.Data
{ {
public static class InitDb public static class InitDb
{ {
public static async Task Init(this DbEntities dbClient) public static async Task Init(this DbEntities dbClient, CancellationToken token = default)
{ {
await SyncLanguages(dbClient); await SyncLanguages(dbClient, token);
await UpdateNewLanguages(dbClient); await UpdateNewLanguages(dbClient, token);
} }
static async Task SyncLanguages(DbEntities dbClient) static async Task SyncLanguages(DbEntities dbClient, CancellationToken token = default)
{ {
if (await dbClient.Languages.ExecuteAnyAsync()) return; if (await dbClient.Languages.ExecuteAnyAsync(token)) return;
var languagesJson = await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "Data", "languagesNative.json"), Encoding.UTF8); var languagesJson = await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "Data", "languagesNative.json"), Encoding.UTF8, token);
var languagesRows = JsonSerializer.Deserialize<IEnumerable<LanguagesRow>>(languagesJson); var languagesRows = JsonSerializer.Deserialize<IEnumerable<LanguagesRow>>(languagesJson);
var languages = new List<Language>(); var languages = new List<Language>();
@@ -34,12 +34,12 @@ namespace PrivaPub.Data
International2Code = languageRow.International2Code International2Code = languageRow.International2Code
}); });
await DB.Default.SaveAsync(languages); await DB.Default.SaveAsync(languages, token);
} }
static async Task UpdateNewLanguages(DbEntities dbClient) static async Task UpdateNewLanguages(DbEntities dbClient, CancellationToken token = default)
{ {
var bulgarianLanguage = await dbClient.Languages.Match(l => l.International2Code == "bg").ExecuteFirstAsync(); var bulgarianLanguage = await dbClient.Languages.Match(l => l.International2Code == "bg").ExecuteFirstAsync(token);
if (bulgarianLanguage.NativeName == "Български") return; if (bulgarianLanguage.NativeName == "Български") return;
var languagesToUpdate = new Dictionary<string, string>() var languagesToUpdate = new Dictionary<string, string>()
@@ -96,9 +96,9 @@ namespace PrivaPub.Data
foreach (var languageToUpdate in languagesToUpdate) foreach (var languageToUpdate in languagesToUpdate)
{ {
var bgLang = await dbClient.Languages.Match(l => l.International2Code == languageToUpdate.Key).ExecuteFirstAsync(); var bgLang = await dbClient.Languages.Match(l => l.International2Code == languageToUpdate.Key).ExecuteFirstAsync(token);
bgLang.NativeName = languageToUpdate.Value; bgLang.NativeName = languageToUpdate.Value;
await DB.Default.SaveAsync(bgLang); await DB.Default.SaveAsync(bgLang, token);
} }
} }
} }
+8 -14
View File
@@ -26,22 +26,16 @@ namespace PrivaPub.Domain.Content
string TagUrl(string tag); string TagUrl(string tag);
} }
public partial class ContentRenderer : IContentRenderer public partial class ContentRenderer(
ILocalActorService localActors,
IRemoteActorService remoteActors) : IContentRenderer
{ {
const int MaxMentions = 20; const int MaxMentions = 20;
static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().DisableHtml().UseAutoLinks().UseEmphasisExtras().Build(); static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().DisableHtml().UseAutoLinks().UseEmphasisExtras().Build();
static readonly HtmlParser Parser = new(); static readonly HtmlParser Parser = new();
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
public ContentRenderer(ILocalActorService localActors, IRemoteActorService remoteActors) public string TagUrl(string tag) => $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}";
{
_localActors = localActors;
_remoteActors = remoteActors;
}
public string TagUrl(string tag) => $"{_localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}";
/// <summary>A text of the server's own (its description, privacy policy, terms, an announcement) from Markdown to /// <summary>A text of the server's own (its description, privacy policy, terms, an announcement) from Markdown to
/// sanitized HTML: the posts' pipeline (raw HTML off), without mentions or hashtags, so nothing is looked up.</summary> /// sanitized HTML: the posts' pipeline (raw HTML off), without mentions or hashtags, so nothing is looked up.</summary>
@@ -123,17 +117,17 @@ namespace PrivaPub.Domain.Content
async Task<ResolvedMention> Resolve(string handle, CancellationToken token) async Task<ResolvedMention> Resolve(string handle, CancellationToken token)
{ {
var parts = handle.TrimStart('@').Split('@'); var parts = handle.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)) if (parts.Length == 1 || parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase))
{ {
var local = await _localActors.FindByUserName(parts[0], token); var local = await localActors.FindByUserName(parts[0], token);
return local is { IsFederated: true, IsCircle: false, IsServerActor: false } return local is { IsFederated: true, IsCircle: false, IsServerActor: false }
? new ResolvedMention(local.Uri, local.UserName, local.Domain, local.Uri, true, local.Id, local.Inbox) ? new ResolvedMention(local.Uri, local.UserName, local.Domain, local.Uri, true, local.Id, local.Inbox)
: default; : default;
} }
var actorUri = await _remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token); var actorUri = await remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
var actor = actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token); var actor = actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token);
return actor == default return actor == default
? default ? default
: new ResolvedMention(actor.ActorURI, actor.UserName ?? parts[0], parts[1].ToLowerInvariant(), actor.Url ?? actor.ActorURI, false, actor.ID, : new ResolvedMention(actor.ActorURI, actor.UserName ?? parts[0], parts[1].ToLowerInvariant(), actor.Url ?? actor.ActorURI, false, actor.ID,
+14 -25
View File
@@ -37,30 +37,19 @@ namespace PrivaPub.Domain.Content
Task Wanted(PostEntity post, CancellationToken token); Task Wanted(PostEntity post, CancellationToken token);
} }
public class LinkPreviews : ILinkPreviews, IJobHandler public class LinkPreviews(
DbEntities dbEntities,
ILocalActorService localActors,
IFederationHttp federationHttp,
IJobQueue queue,
IOptionsMonitor<FederationOptions> options,
IInteractionLedger ledger = default) : ILinkPreviews, IJobHandler
{ {
const int MaxJitterSeconds = 60; const int MaxJitterSeconds = 60;
static readonly TimeSpan Freshness = TimeSpan.FromDays(7); static readonly TimeSpan Freshness = TimeSpan.FromDays(7);
static readonly HtmlParser Parser = new(); static readonly HtmlParser Parser = new();
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IFederationHttp _http;
readonly IJobQueue _queue;
readonly IOptionsMonitor<FederationOptions> _options;
readonly IInteractionLedger _ledger;
public LinkPreviews(DbEntities dbEntities, ILocalActorService localActors, IFederationHttp http, IJobQueue queue,
IOptionsMonitor<FederationOptions> options, IInteractionLedger ledger = default)
{
_dbEntities = dbEntities;
_localActors = localActors;
_http = http;
_queue = queue;
_options = options;
_ledger = ledger;
}
public JobKind Kind => JobKind.FetchPreview; public JobKind Kind => JobKind.FetchPreview;
public int Concurrency => 2; public int Concurrency => 2;
@@ -69,12 +58,12 @@ namespace PrivaPub.Domain.Content
public async Task Wanted(PostEntity post, CancellationToken token) public async Task Wanted(PostEntity post, CancellationToken token)
{ {
if (!_options.CurrentValue.FetchLinkPreviews || !Previewable(post) || post.Link == default && post.Media.Count > 0) if (!options.CurrentValue.FetchLinkPreviews || !Previewable(post) || post.Link == default && post.Media.Count > 0)
return; return;
var url = post.Link?.Href ?? FirstLink(post, _localActors.BaseAddress); var url = post.Link?.Href ?? FirstLink(post, localActors.BaseAddress);
if (url == default) if (url == default)
return; return;
await _queue.EnqueueMany(new[] await queue.EnqueueMany(new[]
{ {
new Job new Job
{ {
@@ -86,10 +75,10 @@ namespace PrivaPub.Domain.Content
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var post = await _dbEntities.Posts.MatchID(job.Payload).ExecuteFirstAsync(token); var post = await dbEntities.Posts.MatchID(job.Payload).ExecuteFirstAsync(token);
if (!VisibilityPolicy.Shown(post) || !Previewable(post)) if (!VisibilityPolicy.Shown(post) || !Previewable(post))
return JobOutcome.Done; return JobOutcome.Done;
var url = post.Link?.Href ?? FirstLink(post, _localActors.BaseAddress); var url = post.Link?.Href ?? FirstLink(post, localActors.BaseAddress);
if (url == default) if (url == default)
return JobOutcome.Done; return JobOutcome.Done;
@@ -110,9 +99,9 @@ namespace PrivaPub.Domain.Content
async Task<LinkPreview> Fetch(string url, CancellationToken token) async Task<LinkPreview> Fetch(string url, CancellationToken token)
{ {
var started = System.Diagnostics.Stopwatch.GetTimestamp(); var started = System.Diagnostics.Stopwatch.GetTimestamp();
var (finalUri, html) = await _http.GetPage(url, token); var (finalUri, html) = await federationHttp.GetPage(url, token);
var preview = html == default ? new LinkPreview { Url = url, Failed = true } : Read(url, finalUri, html); var preview = html == default ? new LinkPreview { Url = url, Failed = true } : Read(url, finalUri, html);
_ledger?.Record(new InteractionEvent ledger?.Record(new InteractionEvent
{ {
Channel = Interactions.Preview, Channel = Interactions.Preview,
Host = Interactions.HostOf(url), Host = Interactions.HostOf(url),
+3 -8
View File
@@ -25,19 +25,14 @@ namespace PrivaPub.Domain.Instance
// The server's own settings (Models/ServerSettings.cs) in memory: read at start, saved from the administrator's page, and // The server's own settings (Models/ServerSettings.cs) in memory: read at start, saved from the administrator's page, and
// read again every five minutes (InstanceSettingsRefresher), so an edit made elsewhere takes too. What reads them reads // read again every five minutes (InstanceSettingsRefresher), so an edit made elsewhere takes too. What reads them reads
// Current, which is never null and never changed in place. // Current, which is never null and never changed in place.
public class InstanceSettings : IInstanceSettings public class InstanceSettings(
ILogger<InstanceSettings> logger) : IInstanceSettings
{ {
readonly ILogger<InstanceSettings> _logger;
readonly SemaphoreSlim _saving = new(1, 1); readonly SemaphoreSlim _saving = new(1, 1);
volatile ServerSettings _current = ServerSettings.Defaults(); volatile ServerSettings _current = ServerSettings.Defaults();
volatile bool _stored;//whether Current came from the document (or is the defaults) volatile bool _stored;//whether Current came from the document (or is the defaults)
CancellationTokenSource _changed = new(); CancellationTokenSource _changed = new();
public InstanceSettings(ILogger<InstanceSettings> logger)
{
_logger = logger;
}
public ServerSettings Current => _current; public ServerSettings Current => _current;
public IChangeToken ChangeToken() => new CancellationChangeToken(Volatile.Read(ref _changed).Token); public IChangeToken ChangeToken() => new CancellationChangeToken(Volatile.Read(ref _changed).Token);
@@ -85,7 +80,7 @@ namespace PrivaPub.Domain.Instance
} }
catch (AggregateException ex) catch (AggregateException ex)
{ {
_logger.LogWarning(ex, "A listener to the server's settings failed"); logger.LogWarning(ex, "A listener to the server's settings failed");
} }
//(not disposed: a reader may still be registering on its token) //(not disposed: a reader may still be registering on its token)
} }
+1 -1
View File
@@ -36,7 +36,7 @@ namespace PrivaPub.Domain.Media
if (i != 0 || j != 0) if (i != 0 || j != 0)
for (var c = 0; c < 3; c++) for (var c = 0; c < 3; c++)
maximum = Math.Max(maximum, Math.Abs(factors[j, i, c])); maximum = Math.Max(maximum, Math.Abs(factors[j, i, c]));
double maximumValue; var maximumValue = default(double);
if (componentsX * componentsY > 1) if (componentsX * componentsY > 1)
{ {
var quantised = (int)Math.Max(0, Math.Min(82, Math.Floor(maximum * 166 - 0.5))); var quantised = (int)Math.Max(0, Math.Min(82, Math.Floor(maximum * 166 - 0.5)));
+33 -49
View File
@@ -44,17 +44,17 @@ namespace PrivaPub.Domain.Media
// - what is too big to cache is remembered for an hour (it is streamed instead), what failed for five minutes; // - what is too big to cache is remembered for an hour (it is streamed instead), what failed for five minutes;
// - the cache's size is counted as it grows, and trimmed as soon as it passes the cap; // - the cache's size is counted as it grows, and trimmed as soon as it passes the cap;
// - nothing of a suspended server, or of one whose media are rejected, is proxied, and blocking one purges its files. // - nothing of a suspended server, or of one whose media are rejected, is proxied, and blocking one purges its files.
public class MediaProxy : IMediaProxy public class MediaProxy(
ILocalActorService localActors,
IFederationHttp http,
IMediaService mediaService,
IOptionsMonitor<MediaOptions> options,
Federation.Moderation.IDomainBlocks domainBlocks = default) : IMediaProxy
{ {
static readonly TimeSpan TooBigFor = TimeSpan.FromHours(1); static readonly TimeSpan TooBigFor = TimeSpan.FromHours(1);
static readonly TimeSpan FailedFor = TimeSpan.FromMinutes(5); static readonly TimeSpan FailedFor = TimeSpan.FromMinutes(5);
const int Downloads = 8;//remote files fetched at once, however many clients ask const int Downloads = 8;//remote files fetched at once, however many clients ask
readonly ILocalActorService _localActors;
readonly IFederationHttp _http;
readonly IMediaService _media;
readonly IOptionsMonitor<MediaOptions> _options;
readonly Federation.Moderation.IDomainBlocks _domainBlocks;
// Lazy: GetOrAdd may run its factory more than once when asked at the same time, but only one Lazy is ever evaluated // Lazy: GetOrAdd may run its factory more than once when asked at the same time, but only one Lazy is ever evaluated
readonly ConcurrentDictionary<string, Lazy<Task<(ProxyOutcome, string, string)>>> _inFlight = new(); readonly ConcurrentDictionary<string, Lazy<Task<(ProxyOutcome, string, string)>>> _inFlight = new();
readonly ConcurrentDictionary<string, (ProxyOutcome Outcome, DateTime Until)> _refused = new(); readonly ConcurrentDictionary<string, (ProxyOutcome Outcome, DateTime Until)> _refused = new();
@@ -64,16 +64,6 @@ namespace PrivaPub.Domain.Media
long _bytes = -1;//what the cache holds, counted once from the disk and then as it changes long _bytes = -1;//what the cache holds, counted once from the disk and then as it changes
int _trimming; int _trimming;
public MediaProxy(ILocalActorService localActors, IFederationHttp http, IMediaService media, IOptionsMonitor<MediaOptions> options,
Federation.Moderation.IDomainBlocks domainBlocks = default)
{
_localActors = localActors;
_http = http;
_media = media;
_options = options;
_domainBlocks = domainBlocks;
}
byte[] Key byte[] Key
{ {
get get
@@ -87,15 +77,15 @@ namespace PrivaPub.Domain.Media
public string Wrap(string remoteUrl) public string Wrap(string remoteUrl)
{ {
if (string.IsNullOrEmpty(remoteUrl) || remoteUrl.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (string.IsNullOrEmpty(remoteUrl) || remoteUrl.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return remoteUrl; return remoteUrl;
var encoded = Base64Url(Encoding.UTF8.GetBytes(remoteUrl)); var encoded = Base64Url(Encoding.UTF8.GetBytes(remoteUrl));
return $"{_localActors.BaseAddress}/media/proxy/{Sign(remoteUrl)}/{encoded}"; return $"{localActors.BaseAddress}/media/proxy/{Sign(remoteUrl)}/{encoded}";
} }
public string Verified(string signature, string encodedUrl) public string Verified(string signature, string encodedUrl)
{ {
string url; var url = default(string);
try try
{ {
url = Encoding.UTF8.GetString(FromBase64Url(encodedUrl)); url = Encoding.UTF8.GetString(FromBase64Url(encodedUrl));
@@ -109,9 +99,9 @@ namespace PrivaPub.Domain.Media
public bool Refuses(string url) public bool Refuses(string url)
{ {
if (_domainBlocks == default || !Uri.TryCreate(url, UriKind.Absolute, out var target)) if (domainBlocks == default || !Uri.TryCreate(url, UriKind.Absolute, out var target))
return false; return false;
var block = _domainBlocks.Find(target.Host); var block = domainBlocks.Find(target.Host);
return block is { Severity: DomainBlockSeverity.Suspend } or { RejectMedia: true }; return block is { Severity: DomainBlockSeverity.Suspend } or { RejectMedia: true };
} }
@@ -132,7 +122,7 @@ namespace PrivaPub.Domain.Media
} }
public Task<HttpResponseMessage> Open(string url, System.Net.Http.Headers.RangeHeaderValue range, CancellationToken token) => public Task<HttpResponseMessage> Open(string url, System.Net.Http.Headers.RangeHeaderValue range, CancellationToken token) =>
_http.OpenMedia(url, range, token); http.OpenMedia(url, range, token);
public async Task<(string Path, string ContentType)> Fetch(string signature, string encodedUrl, CancellationToken token) public async Task<(string Path, string ContentType)> Fetch(string signature, string encodedUrl, CancellationToken token)
{ {
@@ -166,10 +156,10 @@ namespace PrivaPub.Domain.Media
} }
} }
async Task<(ProxyOutcome, string, string)> DownloadOnce(string url) async Task<(ProxyOutcome, string, string)> DownloadOnce(string url, CancellationToken token = default)
{ {
await Task.Yield(); await Task.Yield();
if (!await _downloads.WaitAsync(TimeSpan.FromSeconds(30))) if (!await _downloads.WaitAsync(TimeSpan.FromSeconds(30), token))
return (ProxyOutcome.Failed, default, default);//too busy: the client tries again return (ProxyOutcome.Failed, default, default);//too busy: the client tries again
// cached by a download that ended just before this one began // cached by a download that ended just before this one began
if (Cached(url) is { Path: not null } done) if (Cached(url) is { Path: not null } done)
@@ -182,16 +172,17 @@ namespace PrivaPub.Domain.Media
try try
{ {
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!); Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
string contentType, refusal; var contentType = default(string);
var refusal = default(string);
await using (var file = new FileStream(part, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, useAsync: true)) await using (var file = new FileStream(part, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, useAsync: true))
(contentType, refusal) = await _http.DownloadMedia(url, _options.CurrentValue.MaxProxiedBytes, file, CancellationToken.None); (contentType, refusal) = await http.DownloadMedia(url, options.CurrentValue.MaxProxiedBytes, file, CancellationToken.None);
if (contentType == default) if (contentType == default)
{ {
var outcome = refusal == "too-large" ? ProxyOutcome.TooBig : ProxyOutcome.Failed; var outcome = refusal == "too-large" ? ProxyOutcome.TooBig : ProxyOutcome.Failed;
_refused[url] = (outcome, DateTime.UtcNow + (outcome == ProxyOutcome.TooBig ? TooBigFor : FailedFor)); _refused[url] = (outcome, DateTime.UtcNow + (outcome == ProxyOutcome.TooBig ? TooBigFor : FailedFor));
return (outcome, default, default); return (outcome, default, default);
} }
await File.WriteAllTextAsync(typePath, contentType + "\n" + new Uri(url).Host); await File.WriteAllTextAsync(typePath, contentType + "\n" + new Uri(url).Host, token);
var size = new FileInfo(part).Length; var size = new FileInfo(part).Length;
File.Move(part, path, overwrite: true); File.Move(part, path, overwrite: true);
Grew(size); Grew(size);
@@ -209,7 +200,7 @@ namespace PrivaPub.Domain.Media
{ {
if (Interlocked.Read(ref _bytes) < 0) if (Interlocked.Read(ref _bytes) < 0)
Interlocked.CompareExchange(ref _bytes, Measure(), -1); Interlocked.CompareExchange(ref _bytes, Measure(), -1);
if (Interlocked.Add(ref _bytes, bytes) > _options.CurrentValue.ProxyCacheBytes) if (Interlocked.Add(ref _bytes, bytes) > options.CurrentValue.ProxyCacheBytes)
_ = Task.Run(Trim); _ = Task.Run(Trim);
} }
@@ -219,7 +210,7 @@ namespace PrivaPub.Domain.Media
return; return;
try try
{ {
Interlocked.Exchange(ref _bytes, TrimDirectory(_media.ProxyRoot, _options.CurrentValue.ProxyCacheBytes)); Interlocked.Exchange(ref _bytes, TrimDirectory(mediaService.ProxyRoot, options.CurrentValue.ProxyCacheBytes));
} }
finally finally
{ {
@@ -229,7 +220,7 @@ namespace PrivaPub.Domain.Media
public int Purge(string domain) public int Purge(string domain)
{ {
var directory = new DirectoryInfo(_media.ProxyRoot); var directory = new DirectoryInfo(mediaService.ProxyRoot);
if (string.IsNullOrEmpty(domain) || !directory.Exists) if (string.IsNullOrEmpty(domain) || !directory.Exists)
return 0; return 0;
var purged = 0; var purged = 0;
@@ -256,7 +247,7 @@ namespace PrivaPub.Domain.Media
long Measure() long Measure()
{ {
var directory = new DirectoryInfo(_media.ProxyRoot); var directory = new DirectoryInfo(mediaService.ProxyRoot);
return directory.Exists ? directory.EnumerateFiles("*", SearchOption.AllDirectories).Where(f => f.Extension is not (".type" or ".part")).Sum(f => f.Length) : 0; return directory.Exists ? directory.EnumerateFiles("*", SearchOption.AllDirectories).Where(f => f.Extension is not (".type" or ".part")).Sum(f => f.Length) : 0;
} }
@@ -290,7 +281,7 @@ namespace PrivaPub.Domain.Media
(string Path, string TypePath) CachePaths(string url) (string Path, string TypePath) CachePaths(string url)
{ {
var name = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(url))); var name = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(url)));
var path = System.IO.Path.Combine(_media.ProxyRoot, name[..2], name); var path = System.IO.Path.Combine(mediaService.ProxyRoot, name[..2], name);
return (path, path + ".type"); return (path, path + ".type");
} }
@@ -317,7 +308,10 @@ namespace PrivaPub.Domain.Media
} }
} }
public class MediaJanitor : BackgroundService public class MediaJanitor(
IMediaService mediaService,
IOptionsMonitor<MediaOptions> options,
ILogger<MediaJanitor> logger) : BackgroundService
{ {
static readonly TimeSpan FirstPass = TimeSpan.FromMinutes(5); static readonly TimeSpan FirstPass = TimeSpan.FromMinutes(5);
static readonly TimeSpan Interval = TimeSpan.FromHours(1); static readonly TimeSpan Interval = TimeSpan.FromHours(1);
@@ -325,16 +319,6 @@ namespace PrivaPub.Domain.Media
// a trashed file waits this long before it is deleted, already out of what /media/files serves // a trashed file waits this long before it is deleted, already out of what /media/files serves
public static readonly TimeSpan TrashGrace = TimeSpan.FromDays(1); public static readonly TimeSpan TrashGrace = TimeSpan.FromDays(1);
readonly IMediaService _media;
readonly IOptionsMonitor<MediaOptions> _options;
readonly ILogger<MediaJanitor> _logger;
public MediaJanitor(IMediaService media, IOptionsMonitor<MediaOptions> options, ILogger<MediaJanitor> logger)
{
_media = media;
_options = options;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{ {
@@ -353,7 +337,7 @@ namespace PrivaPub.Domain.Media
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, "{Service} pass failed", nameof(MediaJanitor)); logger.LogWarning(ex, "{Service} pass failed", nameof(MediaJanitor));
} }
} }
} }
@@ -368,7 +352,7 @@ namespace PrivaPub.Domain.Media
public async Task Sweep(CancellationToken token) public async Task Sweep(CancellationToken token)
{ {
var cutoff = DateTime.UtcNow - UnattachedLifetime; var cutoff = DateTime.UtcNow - UnattachedLifetime;
var unattached = await _media.Trash(m => m.PostId == null && m.ScheduledStatusId == null && m.ProfileOfAvatarId == null && m.ServerUse == null var unattached = await mediaService.Trash(m => m.PostId == null && m.ScheduledStatusId == null && m.ProfileOfAvatarId == null && m.ServerUse == null
&& m.CreatedAt < cutoff, "never posted", token); && m.CreatedAt < cutoff, "never posted", token);
var trashed = await DB.Default.Find<MediaAttachment>().Match(m => m.TrashedAt != null).Limit(2000).ExecuteAsync(token); var trashed = await DB.Default.Find<MediaAttachment>().Match(m => m.TrashedAt != null).Limit(2000).ExecuteAsync(token);
@@ -379,18 +363,18 @@ namespace PrivaPub.Domain.Media
{ {
if (row.TrashedAt < purgeBefore && !maintenance) if (row.TrashedAt < purgeBefore && !maintenance)
{ {
await _media.Purge(row, token); await mediaService.Purge(row, token);
purged++; purged++;
} }
else else
_media.Hide(row); mediaService.Hide(row);
} }
if (unattached > 0 || purged > 0) if (unattached > 0 || purged > 0)
_logger.LogInformation("{Service}: {Unattached} uploads never posted trashed, {Purged} trashed files deleted", logger.LogInformation("{Service}: {Unattached} uploads never posted trashed, {Purged} trashed files deleted",
nameof(MediaJanitor), unattached, purged); nameof(MediaJanitor), unattached, purged);
TrimProxyCache(); TrimProxyCache();
} }
void TrimProxyCache() => MediaProxy.TrimDirectory(_media.ProxyRoot, _options.CurrentValue.ProxyCacheBytes); void TrimProxyCache() => MediaProxy.TrimDirectory(mediaService.ProxyRoot, options.CurrentValue.ProxyCacheBytes);
} }
} }
+38 -43
View File
@@ -62,8 +62,14 @@ namespace PrivaPub.Domain.Media
Task Purge(MediaAttachment trashed, CancellationToken token); Task Purge(MediaAttachment trashed, CancellationToken token);
} }
public class MediaService : IMediaService public class MediaService(
IOptionsMonitor<MediaOptions> mediaOptions,
ILocalActorService localActors,
IWebHostEnvironment environment,
ILogger<MediaService> logger) : IMediaService
{ {
readonly SemaphoreSlim _processing = new(Math.Max(1, mediaOptions.CurrentValue.Concurrency));
// HEIC and HEIF are not among them: the libvips bundled here decodes AVIF but has no HEVC decoder // HEIC and HEIF are not among them: the libvips bundled here decodes AVIF but has no HEVC decoder
static readonly string[] ImageTypes = { "image/jpeg", "image/png", "image/gif", "image/webp", "image/avif" }; static readonly string[] ImageTypes = { "image/jpeg", "image/png", "image/gif", "image/webp", "image/avif" };
// the only loaders an upload ever reaches: everything else libvips could read (SVG, PDF, TIFF, ImageMagick, ...) is // the only loaders an upload ever reaches: everything else libvips could read (SVG, PDF, TIFF, ImageMagick, ...) is
@@ -94,22 +100,7 @@ namespace PrivaPub.Domain.Media
Cache.Max = 0;//an upload is decoded once: nothing to keep between operations Cache.Max = 0;//an upload is decoded once: nothing to keep between operations
} }
readonly IOptionsMonitor<MediaOptions> _options; public string Root => Path.GetFullPath(mediaOptions.CurrentValue.Root ?? Path.Combine(environment.ContentRootPath, "media-store"));
readonly ILocalActorService _localActors;
readonly SemaphoreSlim _processing;
readonly IWebHostEnvironment _environment;
readonly ILogger<MediaService> _logger;
public MediaService(IOptionsMonitor<MediaOptions> options, ILocalActorService localActors, IWebHostEnvironment environment, ILogger<MediaService> logger)
{
_options = options;
_localActors = localActors;
_processing = new SemaphoreSlim(Math.Max(1, options.CurrentValue.Concurrency));
_environment = environment;
_logger = logger;
}
public string Root => Path.GetFullPath(_options.CurrentValue.Root ?? Path.Combine(_environment.ContentRootPath, "media-store"));
public string ProxyRoot => Root.TrimEnd(Path.DirectorySeparatorChar) + "-proxy"; public string ProxyRoot => Root.TrimEnd(Path.DirectorySeparatorChar) + "-proxy";
@@ -119,13 +110,13 @@ namespace PrivaPub.Domain.Media
string Incoming(string id) => Path.Combine(IncomingRoot, id + ".in"); string Incoming(string id) => Path.Combine(IncomingRoot, id + ".in");
public string Url(string relativePath) => relativePath == default ? default : $"{_localActors.BaseAddress}/media/files/{relativePath.Replace('\\', '/')}"; public string Url(string relativePath) => relativePath == default ? default : $"{localActors.BaseAddress}/media/files/{relativePath.Replace('\\', '/')}";
public async Task<MediaOutcome> Upload(LocalActor owner, IFormFile file, string description, string focus, bool later, CancellationToken token) public async Task<MediaOutcome> Upload(LocalActor owner, IFormFile file, string description, string focus, bool later, CancellationToken token)
{ {
if (file == default || file.Length == 0) if (file == default || file.Length == 0)
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank");
var options = _options.CurrentValue; var options = mediaOptions.CurrentValue;
var contentType = file.ContentType?.Split(';')[0].Trim().ToLowerInvariant(); var contentType = file.ContentType?.Split(';')[0].Trim().ToLowerInvariant();
if (await OverQuota(owner.Id, file.Length, token) is { } full) if (await OverQuota(owner.Id, file.Length, token) is { } full)
return full; return full;
@@ -168,7 +159,7 @@ namespace PrivaPub.Domain.Media
} }
catch (VipsException ex) catch (VipsException ex)
{ {
_logger.LogInformation("Refused an image upload: {Error}", ex.Message); logger.LogInformation("Refused an image upload: {Error}", ex.Message);
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image");
} }
finally finally
@@ -210,15 +201,16 @@ namespace PrivaPub.Domain.Media
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank");
if (!ImageTypes.Contains(contentType)) if (!ImageTypes.Contains(contentType))
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File type is not supported"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File type is not supported");
if (file.Length > _options.CurrentValue.MaxImageBytes) if (file.Length > mediaOptions.CurrentValue.MaxImageBytes)
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File is too big"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File is too big");
if (await OverQuota(avatarId, file.Length, token) is { } full) if (await OverQuota(avatarId, file.Length, token) is { } full)
return full; return full;
var input = await Read(file, token); var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused) if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused; return refused;
byte[] bytes; var bytes = default(byte[]);
int outWidth, outHeight; var outWidth = default(int);
var outHeight = default(int);
await _processing.WaitAsync(token); await _processing.WaitAsync(token);
try try
{ {
@@ -229,7 +221,7 @@ namespace PrivaPub.Domain.Media
} }
catch (VipsException ex) catch (VipsException ex)
{ {
_logger.LogInformation("Refused a profile picture: {Error}", ex.Message); logger.LogInformation("Refused a profile picture: {Error}", ex.Message);
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image");
} }
finally finally
@@ -264,13 +256,14 @@ namespace PrivaPub.Domain.Media
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank");
if (!ImageTypes.Contains(contentType)) if (!ImageTypes.Contains(contentType))
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File type is not supported"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File type is not supported");
if (file.Length > _options.CurrentValue.MaxImageBytes) if (file.Length > mediaOptions.CurrentValue.MaxImageBytes)
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File is too big"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File is too big");
var input = await Read(file, token); var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused) if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused; return refused;
byte[] bytes; var bytes = default(byte[]);
int outWidth, outHeight; var outWidth = default(int);
var outHeight = default(int);
await _processing.WaitAsync(token); await _processing.WaitAsync(token);
try try
{ {
@@ -281,7 +274,7 @@ namespace PrivaPub.Domain.Media
} }
catch (VipsException ex) catch (VipsException ex)
{ {
_logger.LogInformation("Refused a server picture: {Error}", ex.Message); logger.LogInformation("Refused a server picture: {Error}", ex.Message);
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image");
} }
finally finally
@@ -327,11 +320,13 @@ namespace PrivaPub.Domain.Media
if (file.Length > EmojiMaxUploadBytes) if (file.Length > EmojiMaxUploadBytes)
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: An emoji's image is at most 256 KB"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: An emoji's image is at most 256 KB");
var input = await Read(file, token); var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused) if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused; return refused;
byte[] bytes, still = default; var bytes = default(byte[]);
int width, height; var still = default(byte[]);
bool animated; var width = default(int);
var height = default(int);
var animated = default(bool);
await _processing.WaitAsync(token); await _processing.WaitAsync(token);
try try
{ {
@@ -342,7 +337,7 @@ namespace PrivaPub.Domain.Media
} }
catch (VipsException ex) catch (VipsException ex)
{ {
_logger.LogInformation("Refused an emoji's picture: {Error}", ex.Message); logger.LogInformation("Refused an emoji's picture: {Error}", ex.Message);
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file is not a readable image");
} }
finally finally
@@ -408,7 +403,7 @@ namespace PrivaPub.Domain.Media
// a login over its quota (Media:QuotaBytesPerRoot; none when 0) uploads nothing more // a login over its quota (Media:QuotaBytesPerRoot; none when 0) uploads nothing more
async Task<MediaOutcome> OverQuota(string avatarId, long incoming, CancellationToken token) async Task<MediaOutcome> OverQuota(string avatarId, long incoming, CancellationToken token)
{ {
var quota = _options.CurrentValue.QuotaBytesPerRoot; var quota = mediaOptions.CurrentValue.QuotaBytesPerRoot;
if (quota <= 0) if (quota <= 0)
return default; return default;
var rootId = (await DB.Default.Find<Models.User.RootToAvatar>().Match(r => r.AvatarId == avatarId).ExecuteFirstAsync(token))?.RootId; var rootId = (await DB.Default.Find<Models.User.RootToAvatar>().Match(r => r.AvatarId == avatarId).ExecuteFirstAsync(token))?.RootId;
@@ -472,7 +467,7 @@ namespace PrivaPub.Domain.Media
// an upload refused before anything is decoded: no loader takes it, or it would decode to too many pixels or frames // an upload refused before anything is decoded: no loader takes it, or it would decode to too many pixels or frames
static MediaOutcome Refusal(byte[] input, MediaOptions options) static MediaOutcome Refusal(byte[] input, MediaOptions options)
{ {
ImageHeader header; var header = default(ImageHeader);
try try
{ {
header = Inspect(input); header = Inspect(input);
@@ -511,7 +506,7 @@ namespace PrivaPub.Domain.Media
// its first frame the poster // its first frame the poster
async Task<MediaOutcome> ProcessAnimation(byte[] input, ImageHeader header, MediaAttachment attachment, CancellationToken token) async Task<MediaOutcome> ProcessAnimation(byte[] input, ImageHeader header, MediaAttachment attachment, CancellationToken token)
{ {
var options = _options.CurrentValue; var options = mediaOptions.CurrentValue;
var temp = Path.Combine(Path.GetTempPath(), $"privapub-{Guid.NewGuid():N}"); var temp = Path.Combine(Path.GetTempPath(), $"privapub-{Guid.NewGuid():N}");
var gif = temp + ".gif"; var gif = temp + ".gif";
var mp4 = temp + ".mp4"; var mp4 = temp + ".mp4";
@@ -538,7 +533,7 @@ namespace PrivaPub.Domain.Media
} }
catch (Exception ex) when (ex is not OperationCanceledException) catch (Exception ex) when (ex is not OperationCanceledException)
{ {
_logger.LogInformation(ex, "Refused a GIF upload"); logger.LogInformation(ex, "Refused a GIF upload");
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed");
} }
finally finally
@@ -598,7 +593,7 @@ namespace PrivaPub.Domain.Media
// saved until everything succeeded, and every temporary file goes, the stored upload too. // saved until everything succeeded, and every temporary file goes, the stored upload too.
async Task<MediaOutcome> ProcessIncoming(MediaAttachment attachment, CancellationToken token) async Task<MediaOutcome> ProcessIncoming(MediaAttachment attachment, CancellationToken token)
{ {
var options = _options.CurrentValue; var options = mediaOptions.CurrentValue;
var input = Incoming(attachment.ID); var input = Incoming(attachment.ID);
var temp = Path.Combine(Path.GetTempPath(), $"privapub-{Guid.NewGuid():N}"); var temp = Path.Combine(Path.GetTempPath(), $"privapub-{Guid.NewGuid():N}");
var frame = temp + ".png"; var frame = temp + ".png";
@@ -615,7 +610,7 @@ namespace PrivaPub.Domain.Media
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed");
var extension = AvTypes[attachment.ContentType]; var extension = AvTypes[attachment.ContentType];
var format = probe.Format.FormatName.Split(',')[0]; var format = probe.Format.FormatName.Split(',')[0];
string arguments; var arguments = default(string);
if (video == default) if (video == default)
arguments = "-map 0:a:0 -vn -dn -sn -map_metadata -1 -map_chapters -1 -c copy" + (extension == "m4a" ? " -movflags +faststart" : string.Empty); arguments = "-map 0:a:0 -vn -dn -sn -map_metadata -1 -map_chapters -1 -c copy" + (extension == "m4a" ? " -movflags +faststart" : string.Empty);
else if (video.CodecName is "h264" or "vp8" or "vp9" or "av1" && (long)video.Width * video.Height <= options.MaxVideoPixels else if (video.CodecName is "h264" or "vp8" or "vp9" or "av1" && (long)video.Width * video.Height <= options.MaxVideoPixels
@@ -642,7 +637,7 @@ namespace PrivaPub.Domain.Media
{ {
attachment.Width = made.PrimaryVideoStream?.Width; attachment.Width = made.PrimaryVideoStream?.Width;
attachment.Height = made.PrimaryVideoStream?.Height; attachment.Height = made.PrimaryVideoStream?.Height;
await FFMpeg.SnapshotAsync(output, frame, captureTime: TimeSpan.FromSeconds(Math.Min(1, made.Duration.TotalSeconds / 2))); await FFMpeg.SnapshotAsync(output, frame, captureTime: TimeSpan.FromSeconds(Math.Min(1, made.Duration.TotalSeconds / 2)), cancellationToken: token);
var still = ProcessImage(await File.ReadAllBytesAsync(frame, token), 640, options.PreviewSide); var still = ProcessImage(await File.ReadAllBytesAsync(frame, token), 640, options.PreviewSide);
poster = still.Preview; poster = still.Preview;
attachment.Blurhash = still.Blurhash; attachment.Blurhash = still.Blurhash;
@@ -668,7 +663,7 @@ namespace PrivaPub.Domain.Media
} }
catch (Exception ex) when (ex is not OperationCanceledException) catch (Exception ex) when (ex is not OperationCanceledException)
{ {
_logger.LogInformation(ex, "Refused an audio or video upload"); logger.LogInformation(ex, "Refused an audio or video upload");
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed"); return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: The file could not be processed");
} }
finally finally
+5 -12
View File
@@ -8,17 +8,10 @@ namespace PrivaPub.Domain.Media
{ {
// Audio and video sent to /api/v2/media, processed off the request (its lease renewed while ffmpeg runs): playable, or // Audio and video sent to /api/v2/media, processed off the request (its lease renewed while ffmpeg runs): playable, or
// marked failed with why. One at a time, since a transcode takes the machine's cores. // marked failed with why. One at a time, since a transcode takes the machine's cores.
public class ProcessMediaJob : IJobHandler public class ProcessMediaJob(
IMediaService mediaService,
ILogger<ProcessMediaJob> logger) : IJobHandler
{ {
readonly IMediaService _media;
readonly ILogger<ProcessMediaJob> _logger;
public ProcessMediaJob(IMediaService media, ILogger<ProcessMediaJob> logger)
{
_media = media;
_logger = logger;
}
public JobKind Kind => JobKind.ProcessMedia; public JobKind Kind => JobKind.ProcessMedia;
public int Concurrency => 1; public int Concurrency => 1;
public int MaxAttempts => 3; public int MaxAttempts => 3;
@@ -37,8 +30,8 @@ namespace PrivaPub.Domain.Media
var pending = await DB.Default.Find<MediaAttachment>().Match(m => m.ID == job.Payload && m.ProcessingState == "pending" && m.TrashedAt == null).ExecuteFirstAsync(token); var pending = await DB.Default.Find<MediaAttachment>().Match(m => m.ID == job.Payload && m.ProcessingState == "pending" && m.TrashedAt == null).ExecuteFirstAsync(token);
if (pending == default) if (pending == default)
return JobOutcome.Done;//processed already, or trashed meanwhile return JobOutcome.Done;//processed already, or trashed meanwhile
if (!await _media.ProcessPending(pending, token)) if (!await mediaService.ProcessPending(pending, token))
_logger.LogInformation("Upload {Id} could not be processed", pending.ID); logger.LogInformation("Upload {Id} could not be processed", pending.ID);
return JobOutcome.Done; return JobOutcome.Done;
} }
} }
+38 -54
View File
@@ -53,57 +53,41 @@ namespace PrivaPub.Domain.Moderation
// and nothing is delivered to its own inbox. It is told nothing. // and nothing is delivered to its own inbox. It is told nothing.
// //
// Every act is kept in the staff's log (ModerationLog), without who acted when the persona is the acting login's own. // Every act is kept in the staff's log (ModerationLog), without who acted when the persona is the acting login's own.
public class AccountModeration : IAccountModeration public class AccountModeration(
DbEntities dbEntities,
ILocalActorService localActors,
IModerationLog log,
IOpenIddictTokenManager openIddictTokenManager,
IOpenIddictAuthorizationManager authorizations,
IStatusService statuses,
IDomainBlocks domainBlocks,
IStringLocalizer<GenericRes> localizer,
ILogger<AccountModeration> logger) : IAccountModeration
{ {
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IModerationLog _log;
readonly IOpenIddictTokenManager _tokens;
readonly IOpenIddictAuthorizationManager _authorizations;
readonly IStatusService _statuses;
readonly IDomainBlocks _domainBlocks;
readonly IStringLocalizer<GenericRes> _localizer;
readonly ILogger<AccountModeration> _logger;
public AccountModeration(DbEntities dbEntities, ILocalActorService localActors, IModerationLog log, IOpenIddictTokenManager tokens,
IOpenIddictAuthorizationManager authorizations, IStatusService statuses, IDomainBlocks domainBlocks, IStringLocalizer<GenericRes> localizer,
ILogger<AccountModeration> logger)
{
_dbEntities = dbEntities;
_localActors = localActors;
_log = log;
_tokens = tokens;
_authorizations = authorizations;
_statuses = statuses;
_domainBlocks = domainBlocks;
_localizer = localizer;
_logger = logger;
}
public async Task<WebResult> Moderate(string byRootId, string accountId, string action, string note, string warning, string reportId, public async Task<WebResult> Moderate(string byRootId, string accountId, string action, string note, string warning, string reportId,
CancellationToken token) CancellationToken token)
{ {
var result = new WebResult(); var result = new WebResult();
if (!ModerationActions.IsAccountAction(action)) if (!ModerationActions.IsAccountAction(action))
return result.Invalidate(_localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity); return result.Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity);
try try
{ {
var avatar = string.IsNullOrEmpty(accountId) ? default : await _dbEntities.Avatars.MatchID(accountId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var avatar = string.IsNullOrEmpty(accountId) ? default : await dbEntities.Avatars.MatchID(accountId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
{ {
result.Data = await Persona(byRootId, avatar, action, note, warning, reportId, token); result.Data = await Persona(byRootId, avatar, action, note, warning, reportId, token);
return result; return result;
} }
var account = string.IsNullOrEmpty(accountId) ? default : await _dbEntities.ForeignAvatars.MatchID(accountId).ExecuteFirstAsync(token); var account = string.IsNullOrEmpty(accountId) ? default : await dbEntities.ForeignAvatars.MatchID(accountId).ExecuteFirstAsync(token);
if (account == default) if (account == default)
return result.Invalidate(_localizer["Account not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Account not found."], StatusCodes.Status404NotFound);
result.Data = await Remote(byRootId, account, action, note, reportId, token); result.Data = await Remote(byRootId, account, action, note, reportId, token);
return result; return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "{Service}.{Method}({Action})", nameof(AccountModeration), nameof(Moderate), action); logger.LogError(ex, "{Service}.{Method}({Action})", nameof(AccountModeration), nameof(Moderate), action);
return result.Invalidate(_localizer["Something went wrong."], exception: ex); return result.Invalidate(localizer["Something went wrong."], exception: ex);
} }
} }
@@ -148,18 +132,18 @@ namespace PrivaPub.Domain.Moderation
.Modify(p => p.AuthorLimited, silenced.HasValue) .Modify(p => p.AuthorLimited, silenced.HasValue)
.ExecuteAsync(CancellationToken.None); .ExecuteAsync(CancellationToken.None);
await Restrictions.Reload(CancellationToken.None); await Restrictions.Reload(CancellationToken.None);
var persona = _localActors.FromAvatar(avatar); var persona = localActors.FromAvatar(avatar);
if (action == ModerationActions.Suspend) if (action == ModerationActions.Suspend)
{ {
// nothing acts as it from now on: its Mastodon tokens end and its open streams close // nothing acts as it from now on: its Mastodon tokens end and its open streams close
await _tokens.RevokeBySubjectAsync(avatar.ID, CancellationToken.None); await openIddictTokenManager.RevokeBySubjectAsync(avatar.ID, CancellationToken.None);
await _authorizations.RevokeBySubjectAsync(avatar.ID, CancellationToken.None); await authorizations.RevokeBySubjectAsync(avatar.ID, CancellationToken.None);
await Social.WebPush.Forget(new[] { avatar.ID });//and its Web Push subscriptions with them (R9): it is pushed nothing await Social.WebPush.Forget(new[] { avatar.ID }, token);//and its Web Push subscriptions with them (R9): it is pushed nothing
Streams.CloseFor(avatar.ID); Streams.CloseFor(avatar.ID);
} }
if (action is ModerationActions.Silence or ModerationActions.Suspend) if (action is ModerationActions.Silence or ModerationActions.Suspend)
await Social.Notifications.Warn(avatar.ID, persona.Uri, action, warning, default, token); await Social.Notifications.Warn(avatar.ID, persona.Uri, action, warning, default, token);
await _log.Write(byRootId, action switch await log.Write(byRootId, action switch
{ {
ModerationActions.Silence => AdminActions.PersonaSilence, ModerationActions.Silence => AdminActions.PersonaSilence,
ModerationActions.Unsilence => AdminActions.PersonaUnsilence, ModerationActions.Unsilence => AdminActions.PersonaUnsilence,
@@ -212,7 +196,7 @@ namespace PrivaPub.Domain.Moderation
.Modify(p => p.AuthorLimited, limited) .Modify(p => p.AuthorLimited, limited)
.ExecuteAsync(CancellationToken.None); .ExecuteAsync(CancellationToken.None);
await Restrictions.Reload(CancellationToken.None); await Restrictions.Reload(CancellationToken.None);
await _log.Write(byRootId, action switch await log.Write(byRootId, action switch
{ {
ModerationActions.Silence => AdminActions.AccountSilence, ModerationActions.Silence => AdminActions.AccountSilence,
ModerationActions.Unsilence => AdminActions.AccountUnsilence, ModerationActions.Unsilence => AdminActions.AccountUnsilence,
@@ -227,22 +211,22 @@ namespace PrivaPub.Domain.Moderation
var result = new WebResult(); var result = new WebResult();
try try
{ {
var post = string.IsNullOrEmpty(postId) ? default : await _dbEntities.Posts.MatchID(postId).ExecuteFirstAsync(token); var post = string.IsNullOrEmpty(postId) ? default : await dbEntities.Posts.MatchID(postId).ExecuteFirstAsync(token);
if (post == default || post.DeletedAt.HasValue || post.ModeratedAt.HasValue) if (post == default || post.DeletedAt.HasValue || post.ModeratedAt.HasValue)
return result.Invalidate(_localizer["Post not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Post not found."], StatusCodes.Status404NotFound);
if (!post.IsFederatedCopy) if (!post.IsFederatedCopy)
{ {
var author = await _localActors.FindById(LocalActorKind.Person, post.GroupUserId, token); var author = await localActors.FindById(LocalActorKind.Person, post.GroupUserId, token);
if (author == default) if (author == default)
return result.Invalidate(_localizer["Post not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Post not found."], StatusCodes.Status404NotFound);
// deleted as its author deletes it: emptied, out of every timeline, and a Delete to its audience (but from a // deleted as its author deletes it: emptied, out of every timeline, and a Delete to its audience (but from a
// suspended persona, which delivers nothing) // suspended persona, which delivers nothing)
var outcome = await _statuses.Remove(author, post.ID, CancellationToken.None); var outcome = await statuses.Remove(author, post.ID, CancellationToken.None);
if (!outcome.Ok) if (!outcome.Ok)
return result.Invalidate(_localizer["Post not found."], outcome.Status); return result.Invalidate(localizer["Post not found."], outcome.Status);
await Social.Notifications.Warn(author.Id, author.Uri, "delete_statuses", warning, new[] { post.ID }, token); await Social.Notifications.Warn(author.Id, author.Uri, "delete_statuses", warning, new[] { post.ID }, token);
await _log.Write(byRootId, AdminActions.PostRemove, AdminTargets.Post, post.ID, $"@{author.Handle}: {post.ObjectURI}", reportId, note, await log.Write(byRootId, AdminActions.PostRemove, AdminTargets.Post, post.ID, $"@{author.Handle}: {post.ObjectURI}", reportId, note,
CancellationToken.None); CancellationToken.None);
return result; return result;
} }
@@ -250,13 +234,13 @@ namespace PrivaPub.Domain.Moderation
// a copy of a post from elsewhere: kept (its address stays known, so it is never taken in again), hidden here // a copy of a post from elsewhere: kept (its address stays known, so it is never taken in again), hidden here
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.ModeratedAt, DateTime.UtcNow).ExecuteAsync(CancellationToken.None); await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.ModeratedAt, DateTime.UtcNow).ExecuteAsync(CancellationToken.None);
await Fanout.Deleting(post, CancellationToken.None); await Fanout.Deleting(post, CancellationToken.None);
await _log.Write(byRootId, AdminActions.PostRemove, AdminTargets.Post, post.ID, post.Url ?? post.ObjectURI, reportId, note, CancellationToken.None); await log.Write(byRootId, AdminActions.PostRemove, AdminTargets.Post, post.ID, post.Url ?? post.ObjectURI, reportId, note, CancellationToken.None);
return result; return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "{Service}.{Method}()", nameof(AccountModeration), nameof(RemovePost)); logger.LogError(ex, "{Service}.{Method}()", nameof(AccountModeration), nameof(RemovePost));
return result.Invalidate(_localizer["Something went wrong."], exception: ex); return result.Invalidate(localizer["Something went wrong."], exception: ex);
} }
} }
@@ -265,7 +249,7 @@ namespace PrivaPub.Domain.Moderation
domain = DomainBlocks.Normalise(domain); domain = DomainBlocks.Normalise(domain);
if (string.IsNullOrEmpty(domain)) if (string.IsNullOrEmpty(domain))
return; return;
var silenced = _domainBlocks.Find(domain)?.Severity == DomainBlockSeverity.Silence; var silenced = domainBlocks.Find(domain)?.Severity == DomainBlockSeverity.Silence;
// the posts of that server and of its subdomains, by their authors' addresses // the posts of that server and of its subdomains, by their authors' addresses
var pattern = ModerationFlags.OfDomain(domain); var pattern = ModerationFlags.OfDomain(domain);
await DB.Default.Update<PostEntity>().Match(f => f.Regex(p => p.ActorURI, pattern) & f.Eq(p => p.IsFederatedCopy, true)) await DB.Default.Update<PostEntity>().Match(f => f.Regex(p => p.ActorURI, pattern) & f.Eq(p => p.IsFederatedCopy, true))
@@ -283,21 +267,21 @@ namespace PrivaPub.Domain.Moderation
} }
bool IsDomainSilenced(string actorUri) => bool IsDomainSilenced(string actorUri) =>
Uri.TryCreate(actorUri, UriKind.Absolute, out var uri) && _domainBlocks.Find(uri.Host)?.Severity == DomainBlockSeverity.Silence; Uri.TryCreate(actorUri, UriKind.Absolute, out var uri) && domainBlocks.Find(uri.Host)?.Severity == DomainBlockSeverity.Silence;
public async Task<ViewModeratedAccount> View(string accountId, CancellationToken token) public async Task<ViewModeratedAccount> View(string accountId, CancellationToken token)
{ {
var avatar = await _dbEntities.Avatars.MatchID(accountId).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(accountId).ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
return View(avatar); return View(avatar);
var account = await _dbEntities.ForeignAvatars.MatchID(accountId).ExecuteFirstAsync(token); var account = await dbEntities.ForeignAvatars.MatchID(accountId).ExecuteFirstAsync(token);
return account == default ? default : View(account); return account == default ? default : View(account);
} }
// a persona as moderators see it: never its login // a persona as moderators see it: never its login
public ViewModeratedAccount View(Avatar avatar) public ViewModeratedAccount View(Avatar avatar)
{ {
var persona = _localActors.FromAvatar(avatar); var persona = localActors.FromAvatar(avatar);
return new ViewModeratedAccount return new ViewModeratedAccount
{ {
Id = avatar.ID, Id = avatar.ID,
@@ -315,7 +299,7 @@ namespace PrivaPub.Domain.Moderation
public ViewModeratedAccount View(ForeignAvatar account) public ViewModeratedAccount View(ForeignAvatar account)
{ {
var block = Uri.TryCreate(account.ActorURI, UriKind.Absolute, out var uri) ? _domainBlocks.Find(uri.Host) : default; var block = Uri.TryCreate(account.ActorURI, UriKind.Absolute, out var uri) ? domainBlocks.Find(uri.Host) : default;
return new ViewModeratedAccount return new ViewModeratedAccount
{ {
Id = account.ID, Id = account.ID,
+3 -8
View File
@@ -17,17 +17,12 @@ namespace PrivaPub.Domain.Moderation
// (ModeratorController's /clientapi/moderator/log). An entry never holds an IP address, and never pairs a root with its // (ModeratorController's /clientapi/moderator/log). An entry never holds an IP address, and never pairs a root with its
// own personas: an act on a persona that the acting root owns, on a post of it, a group it owns or a report about it // own personas: an act on a persona that the acting root owns, on a post of it, a group it owns or a report about it
// (R6), is kept without who acted. // (R6), is kept without who acted.
public class ModerationLog : IModerationLog public class ModerationLog(
ILogger<ModerationLog> logger) : IModerationLog
{ {
const int MaxLabel = 200; const int MaxLabel = 200;
const int MaxNote = 1000; const int MaxNote = 1000;
readonly ILogger<ModerationLog> _logger;
public ModerationLog(ILogger<ModerationLog> logger)
{
_logger = logger;
}
public async Task Write(string byRootId, string action, string targetKind, string targetId, string targetLabel, string reportId = default, public async Task Write(string byRootId, string action, string targetKind, string targetId, string targetLabel, string reportId = default,
string note = default, CancellationToken token = default) string note = default, CancellationToken token = default)
@@ -49,7 +44,7 @@ namespace PrivaPub.Domain.Moderation
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogWarning(ex, "The staff's log could not keep a {Action}", action); logger.LogWarning(ex, "The staff's log could not keep a {Action}", action);
} }
} }
@@ -118,7 +118,7 @@ namespace PrivaPub.Domain.Portability
state.ImportFrom = actorId; state.ImportFrom = actorId;
state.ImportSameActor = run.SameActor; state.ImportSameActor = run.SameActor;
state.ImportCounts = []; state.ImportCounts = [];
await Save(run, token, force: true); await Save(run, force: true, token);
var parts = state.ImportParts.ToHashSet(StringComparer.Ordinal); var parts = state.ImportParts.ToHashSet(StringComparer.Ordinal);
var privapub = Text((archive.Json("privapub/archive.json") as JsonObject)?["software"]) == "privapub"; var privapub = Text((archive.Json("privapub/archive.json") as JsonObject)?["software"]) == "privapub";
@@ -185,7 +185,7 @@ namespace PrivaPub.Domain.Portability
.ExecuteAsync(token); .ExecuteAsync(token);
// progress written at most every two seconds; the answer to whether the root asked to stop // progress written at most every two seconds; the answer to whether the root asked to stop
static async Task Save(Run run, CancellationToken token, bool force = false) static async Task Save(Run run, bool force = false, CancellationToken token = default)
{ {
if (!force && DateTime.UtcNow - run.LastSaved < TimeSpan.FromSeconds(2)) if (!force && DateTime.UtcNow - run.LastSaved < TimeSpan.FromSeconds(2))
return; return;
@@ -199,7 +199,7 @@ namespace PrivaPub.Domain.Portability
static async Task<bool> Stopped(Run run, CancellationToken token) static async Task<bool> Stopped(Run run, CancellationToken token)
{ {
await Save(run, token); await Save(run, token: token);
return await DB.Default.Find<PersonaArchive>().MatchID(run.State.ID).Match(a => a.StopAsked).ExecuteAnyAsync(token); return await DB.Default.Find<PersonaArchive>().MatchID(run.State.ID).Match(a => a.StopAsked).ExecuteAnyAsync(token);
} }
@@ -710,7 +710,7 @@ namespace PrivaPub.Domain.Portability
// Mastodon's columns: notify on new posts, and the languages (", " between them) its posts reach the home in (R8) // Mastodon's columns: notify on new posts, and the languages (", " between them) its posts reach the home in (R8)
var notify = cells.Length >= 3 && cells[2].Trim().Equals("true", StringComparison.OrdinalIgnoreCase); var notify = cells.Length >= 3 && cells[2].Trim().Equals("true", StringComparison.OrdinalIgnoreCase);
var languages = cells.Length >= 4 ? cells[3].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : []; var languages = cells.Length >= 4 ? cells[3].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) : [];
return await run.Services.GetRequiredService<IFollowService>().FollowAs(run.Me, uri, boosts, token, notify, languages) != default; return await run.Services.GetRequiredService<IFollowService>().FollowAs(run.Me, uri, boosts, notify, languages, token) != default;
} }
// lists by title, with only the accounts the persona follows // lists by title, with only the accounts the persona follows
+1 -1
View File
@@ -29,7 +29,7 @@ namespace PrivaPub.Domain.Portability
public static (SafeArchive Archive, string Error) Open(string path) public static (SafeArchive Archive, string Error) Open(string path)
{ {
ZipArchive zip; var zip = default(ZipArchive);
try try
{ {
zip = ZipFile.OpenRead(path); zip = ZipFile.OpenRead(path);
@@ -25,19 +25,11 @@ namespace PrivaPub.Domain.Relationships
Task UnblockDomain(LocalActor me, string domain, CancellationToken token); Task UnblockDomain(LocalActor me, string domain, CancellationToken token);
} }
public class RelationshipService : IRelationshipService public class RelationshipService(
DbEntities dbEntities,
IFollowService follows,
IDeliveryService delivery) : IRelationshipService
{ {
readonly DbEntities _dbEntities;
readonly IFollowService _follows;
readonly IDeliveryService _delivery;
public RelationshipService(DbEntities dbEntities, IFollowService follows, IDeliveryService delivery)
{
_dbEntities = dbEntities;
_follows = follows;
_delivery = delivery;
}
public async Task Block(LocalActor me, string targetActorUri, string targetAccountId, CancellationToken token) public async Task Block(LocalActor me, string targetActorUri, string targetAccountId, CancellationToken token)
{ {
var block = new Block { AvatarId = me.Id, TargetAccountId = targetAccountId, TargetActorURI = targetActorUri }; var block = new Block { AvatarId = me.Id, TargetAccountId = targetAccountId, TargetActorURI = targetActorUri };
@@ -50,7 +42,7 @@ namespace PrivaPub.Domain.Relationships
block = await DB.Default.Find<Block>().Match(b => b.AvatarId == me.Id && b.TargetActorURI == targetActorUri).ExecuteFirstAsync(token); block = await DB.Default.Find<Block>().Match(b => b.AvatarId == me.Id && b.TargetActorURI == targetActorUri).ExecuteFirstAsync(token);
} }
await _follows.UnfollowAs(me, targetActorUri, token); await follows.UnfollowAs(me, targetActorUri, token);
await RemoveFollower(me, targetActorUri, targetAccountId, token); await RemoveFollower(me, targetActorUri, targetAccountId, token);
await Forget(me, targetAccountId, token); await Forget(me, targetAccountId, token);
if (block != default) if (block != default)
@@ -59,7 +51,7 @@ namespace PrivaPub.Domain.Relationships
public async Task RemoveFollower(LocalActor me, string followerActorUri, string followerAccountId, CancellationToken token) public async Task RemoveFollower(LocalActor me, string followerActorUri, string followerAccountId, CancellationToken token)
{ {
var follower = await _dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.ActorURI == followerActorUri).ExecuteFirstAsync(token); var follower = await dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.ActorURI == followerActorUri).ExecuteFirstAsync(token);
if (follower == default) if (follower == default)
return; return;
await DB.Default.DeleteAsync<Follower>(follower.ID); await DB.Default.DeleteAsync<Follower>(follower.ID);
@@ -73,7 +65,7 @@ namespace PrivaPub.Domain.Relationships
["actor"] = me.Uri, ["actor"] = me.Uri,
["object"] = new JsonObject { ["id"] = follower.FollowActivityURI, ["type"] = "Follow", ["actor"] = followerActorUri, ["object"] = me.Uri } ["object"] = new JsonObject { ["id"] = follower.FollowActivityURI, ["type"] = "Follow", ["actor"] = followerActorUri, ["object"] = me.Uri }
}; };
await _delivery.Enqueue(me, new[] { follower.InboxURL }, reject, token); await delivery.Enqueue(me, new[] { follower.InboxURL }, reject, token: token);
} }
else else
await DB.Default.DeleteAsync<Following>(f => f.TargetActorURI == me.Uri && f.AvatarId == followerAccountId); await DB.Default.DeleteAsync<Following>(f => f.TargetActorURI == me.Uri && f.AvatarId == followerAccountId);
@@ -109,9 +101,9 @@ namespace PrivaPub.Domain.Relationships
{ {
if (targetActorUri.StartsWith(me.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (targetActorUri.StartsWith(me.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return; return;
var target = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == targetActorUri).ExecuteFirstAsync(token); var target = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == targetActorUri).ExecuteFirstAsync(token);
if (!string.IsNullOrEmpty(target?.InboxURL)) if (!string.IsNullOrEmpty(target?.InboxURL))
await _delivery.Enqueue(me, new[] { target.InboxURL }, activity, token); await delivery.Enqueue(me, new[] { target.InboxURL }, activity, token: token);
} }
public async Task Mute(LocalActor me, string targetActorUri, string targetAccountId, bool hideNotifications, TimeSpan? duration, CancellationToken token) public async Task Mute(LocalActor me, string targetActorUri, string targetAccountId, bool hideNotifications, TimeSpan? duration, CancellationToken token)
@@ -142,12 +134,12 @@ namespace PrivaPub.Domain.Relationships
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
{ {
} }
var followings = await _dbEntities.Followings.Match(f => f.AvatarId == me.Id && !f.TargetIsLocal).ExecuteAsync(token); var followings = await dbEntities.Followings.Match(f => f.AvatarId == me.Id && !f.TargetIsLocal).ExecuteAsync(token);
var followers = await _dbEntities.Followers.Match(f => f.LocalActorId == me.Id).ExecuteAsync(token); var followers = await dbEntities.Followers.Match(f => f.LocalActorId == me.Id).ExecuteAsync(token);
var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token); var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token);
foreach (var following in followings) foreach (var following in followings)
if (Hidden.Blocks(domain, following.TargetActorURI, handles.GetValueOrDefault(following.TargetActorURI))) if (Hidden.Blocks(domain, following.TargetActorURI, handles.GetValueOrDefault(following.TargetActorURI)))
await _follows.UnfollowAs(me, following.TargetActorURI, token); await follows.UnfollowAs(me, following.TargetActorURI, token);
foreach (var follower in followers) foreach (var follower in followers)
if (Hidden.Blocks(domain, follower.ActorURI, handles.GetValueOrDefault(follower.ActorURI))) if (Hidden.Blocks(domain, follower.ActorURI, handles.GetValueOrDefault(follower.ActorURI)))
await DB.Default.DeleteAsync<Follower>(follower.ID); await DB.Default.DeleteAsync<Follower>(follower.ID);
+17 -26
View File
@@ -18,27 +18,18 @@ namespace PrivaPub.Domain.Relationships
IReadOnlyList<string> ruleIds, bool forward, CancellationToken token); IReadOnlyList<string> ruleIds, bool forward, CancellationToken token);
} }
public class ReportService : IReportService public class ReportService(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery,
Instance.IInstanceSettings settings) : IReportService
{ {
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
readonly Instance.IInstanceSettings _settings;
public ReportService(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery, Instance.IInstanceSettings settings)
{
_dbEntities = dbEntities;
_localActors = localActors;
_delivery = delivery;
_settings = settings;
}
public async Task<Report> File(LocalActor reporter, string targetAccountId, IReadOnlyList<string> postIds, string comment, string category, public async Task<Report> File(LocalActor reporter, string targetAccountId, IReadOnlyList<string> postIds, string comment, string category,
IReadOnlyList<string> ruleIds, bool forward, CancellationToken token) IReadOnlyList<string> ruleIds, bool forward, CancellationToken token)
{ {
// the server's rules it names, deleted ones too (they may have been listed when the reader opened the dialog); a // the server's rules it names, deleted ones too (they may have been listed when the reader opened the dialog); a
// report naming rules is a violation unless it says what else it is, and only a violation names rules, as on Mastodon // report naming rules is a violation unless it says what else it is, and only a violation names rules, as on Mastodon
var known = _settings.Current.Rules.Select(r => r.Id).ToHashSet(StringComparer.Ordinal); var known = settings.Current.Rules.Select(r => r.Id).ToHashSet(StringComparer.Ordinal);
var rules = (ruleIds ?? Array.Empty<string>()).Where(known.Contains).Distinct().ToList(); var rules = (ruleIds ?? Array.Empty<string>()).Where(known.Contains).Distinct().ToList();
if (rules.Count > 0 && string.IsNullOrEmpty(category)) if (rules.Count > 0 && string.IsNullOrEmpty(category))
category = "violation"; category = "violation";
@@ -46,14 +37,14 @@ namespace PrivaPub.Domain.Relationships
if (category != "violation") if (category != "violation")
rules.Clear(); rules.Clear();
var localTarget = await _dbEntities.Avatars.MatchID(targetAccountId).ExecuteFirstAsync(token); var localTarget = await dbEntities.Avatars.MatchID(targetAccountId).ExecuteFirstAsync(token);
var remoteTarget = localTarget == default ? await _dbEntities.ForeignAvatars.MatchID(targetAccountId).ExecuteFirstAsync(token) : default; var remoteTarget = localTarget == default ? await dbEntities.ForeignAvatars.MatchID(targetAccountId).ExecuteFirstAsync(token) : default;
if (localTarget == default && remoteTarget == default) if (localTarget == default && remoteTarget == default)
return default; return default;
var targetUri = localTarget != default ? _localActors.FromAvatar(localTarget).Uri : remoteTarget.ActorURI; var targetUri = localTarget != default ? localActors.FromAvatar(localTarget).Uri : remoteTarget.ActorURI;
var posts = postIds.Count == 0 var posts = postIds.Count == 0
? new List<Models.Post.Post>() ? new List<Models.Post.Post>()
: await _dbEntities.Posts.Match(p => postIds.Contains(p.ID) && p.ActorURI == targetUri).ExecuteAsync(token); : await dbEntities.Posts.Match(p => postIds.Contains(p.ID) && p.ActorURI == targetUri).ExecuteAsync(token);
var report = new Report var report = new Report
{ {
@@ -75,15 +66,15 @@ namespace PrivaPub.Domain.Relationships
var reason = string.IsNullOrEmpty(report.Comment) ? report.Category : report.Comment; var reason = string.IsNullOrEmpty(report.Comment) ? report.Category : report.Comment;
foreach (var post in posts) foreach (var post in posts)
{ {
var community = await Communities.Of(post, _dbEntities, token); var community = await Communities.Of(post, dbEntities, token);
if (community == default || !await TakesServiceReports(community, token)) if (community == default || !await TakesServiceReports(community, token))
continue; continue;
var group = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == community).ExecuteFirstAsync(token); var group = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == community).ExecuteFirstAsync(token);
var inbox = string.IsNullOrEmpty(group?.SharedInboxURL) ? group?.InboxURL : group.SharedInboxURL; var inbox = string.IsNullOrEmpty(group?.SharedInboxURL) ? group?.InboxURL : group.SharedInboxURL;
if (string.IsNullOrEmpty(inbox)) if (string.IsNullOrEmpty(inbox))
continue; continue;
var serviceReporter = await _localActors.GetReporterActor(token); var serviceReporter = await localActors.GetReporterActor(token);
await _delivery.Enqueue(serviceReporter, new[] { inbox }, new JsonObject await delivery.Enqueue(serviceReporter, new[] { inbox }, new JsonObject
{ {
["@context"] = ActivityPubRenderer.ActivityStreams, ["@context"] = ActivityPubRenderer.ActivityStreams,
["id"] = serviceReporter.ActivityUri($"flag-{report.ID}-{++flagged}"), ["id"] = serviceReporter.ActivityUri($"flag-{report.ID}-{++flagged}"),
@@ -94,13 +85,13 @@ namespace PrivaPub.Domain.Relationships
["object"] = post.ObjectURI, ["object"] = post.ObjectURI,
["summary"] = reason, ["summary"] = reason,
["content"] = reason ["content"] = reason
}, token); }, token: token);
} }
// every other server, the author's, as before: an account alone, or posts outside such communities, go nowhere when // every other server, the author's, as before: an account alone, or posts outside such communities, go nowhere when
// the author's server takes reports only in Lemmy's shape // the author's server takes reports only in Lemmy's shape
if (!await TakesServiceReports(targetUri, token)) if (!await TakesServiceReports(targetUri, token))
{ {
var instance = await _localActors.GetInstanceActor(token); var instance = await localActors.GetInstanceActor(token);
var flag = new JsonObject var flag = new JsonObject
{ {
["@context"] = ActivityPubRenderer.ActivityStreams, ["@context"] = ActivityPubRenderer.ActivityStreams,
@@ -110,7 +101,7 @@ namespace PrivaPub.Domain.Relationships
["content"] = report.Comment ?? string.Empty, ["content"] = report.Comment ?? string.Empty,
["object"] = new JsonArray(report.ObjectURIs.Prepend(targetUri).Select(u => (JsonNode)u).ToArray()) ["object"] = new JsonArray(report.ObjectURIs.Prepend(targetUri).Select(u => (JsonNode)u).ToArray())
}; };
await _delivery.Enqueue(instance, new[] { remoteTarget.SharedInboxURL ?? remoteTarget.InboxURL }, flag, token); await delivery.Enqueue(instance, new[] { remoteTarget.SharedInboxURL ?? remoteTarget.InboxURL }, flag, token: token);
flagged++; flagged++;
} }
if (flagged > 0) if (flagged > 0)
+6 -12
View File
@@ -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 // 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 // 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. // 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 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 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 // 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 // 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 }) if (persona is not { IsFederated: true, Kind: Models.Federation.LocalActorKind.Person })
return; return;
await _delivery.EnqueueToFollowers(persona, new JsonObject await delivery.EnqueueToFollowers(persona, new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
["id"] = persona.ActivityUri($"{(add ? "feature" : "unfeature")}-tag-{tag.ID}-{DateTime.UtcNow.Ticks}"), ["id"] = persona.ActivityUri($"{(add ? "feature" : "unfeature")}-tag-{tag.ID}-{DateTime.UtcNow.Ticks}"),
@@ -129,7 +123,7 @@ namespace PrivaPub.Domain.Social
["target"] = persona.Featured, ["target"] = persona.Featured,
["to"] = new JsonArray(ActivityPubRenderer.Public), ["to"] = new JsonArray(ActivityPubRenderer.Public),
["cc"] = new JsonArray(persona.Followers) ["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 // 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) 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; return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? default : JsonNode.Parse(fetched.Root.GetRawText()) as JsonObject;
} }
} }
+15 -24
View File
@@ -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 // 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 // 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. // 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; public const int MaxCommunities = 500;
static readonly TimeSpan Stale = TimeSpan.FromDays(1); 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) => public static Task<bool> Sync(IJobQueue jobs, CancellationToken token) =>
jobs.Enqueue(JobKind.SyncFeeds, string.Empty, default, $"feeds|{Guid.NewGuid():N}", 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) else if ((await DB.Default.DeleteAsync<FeedSubscription>(s => s.AvatarId == me.Id && s.FeedActorURI == feed.ActorURI)).DeletedCount == 0)
return true; return true;
await Sync(_jobs, token); await Sync(jobQueue, token);
return true; return true;
} }
@@ -69,26 +60,26 @@ namespace PrivaPub.Domain.Social
public async Task Reconcile(CancellationToken token) public async Task Reconcile(CancellationToken token)
{ {
var read = (await DB.Default.Find<FeedSubscription, string>().Project(s => s.FeedActorURI).ExecuteAsync(token)).Distinct().ToList(); 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); .ExecuteAsync(token);
// a feed's communities are as its server listed them a day ago at most (AccountCountsJob reads them, then asks // a feed's communities are as its server listed them a day ago at most (AccountCountsJob reads them, then asks
// for this again) // for this again)
foreach (var stale in feeds.Where(f => !(DateTime.UtcNow - f.CountedAt < Stale))) foreach (var stale in feeds.Where(f => !(DateTime.UtcNow - f.CountedAt < Stale)))
if (Uri.TryCreate(stale.ActorURI, UriKind.Absolute, out var uri)) 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)) var wanted = feeds.SelectMany(f => f.FeedCommunities).Where(c => !c.StartsWith(ours, StringComparison.Ordinal))
.Distinct(StringComparer.Ordinal).Take(MaxCommunities).ToHashSet(StringComparer.Ordinal); .Distinct(StringComparer.Ordinal).Take(MaxCommunities).ToHashSet(StringComparer.Ordinal);
var reader = await _localActors.GetReaderActor(token); var reader = await localActors.GetReaderActor(token);
var following = await _dbEntities.Followings.Match(f => f.AvatarId == reader.Id).ExecuteAsync(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))) 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); var followed = following.Select(f => f.TargetActorURI).ToHashSet(StringComparer.Ordinal);
foreach (var community in wanted.Where(c => !followed.Contains(c))) foreach (var community in wanted.Where(c => !followed.Contains(c)))
// only a community: a feed lists nothing else, and the reader follows nothing else // 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 }) if (await remoteActors.GetActor(community, refresh: false, token) is { AvatarType: AvatarType.Group })
await _follows.FollowAs(reader, community, showReblogs: false, token); await followService.FollowAs(reader, community, showReblogs: false, token: token);
} }
} }
+49 -59
View File
@@ -28,8 +28,9 @@ namespace PrivaPub.Domain.Social
Task<WebResult> Followings(string rootUserId, string avatarId, CancellationToken token); 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 /// <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> /// when given (languages empty: every language).</summary>
Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default, Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
IReadOnlyList<string> languages = default); IReadOnlyList<string> languages = default,
CancellationToken token = default);
Task UnfollowAs(LocalActor follower, string target, CancellationToken token); Task UnfollowAs(LocalActor follower, string target, CancellationToken token);
Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token); Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token);
Task<int> ResendPending(DateTime now, 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); 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) public async Task<WebResult> Follow(string rootUserId, FollowForm form, CancellationToken token)
{ {
var result = new WebResult(); var result = new WebResult();
@@ -64,17 +53,17 @@ namespace PrivaPub.Domain.Social
{ {
var follower = await OwnedAvatar(rootUserId, form.AvatarId, token); var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
if (follower == default) if (follower == default)
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
var following = await FollowAs(follower, form.Target, true, token); var following = await FollowAs(follower, form.Target, true, token: token);
if (following == default) 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); result.Data = ToView(following);
return result; return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}"); logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}");
return result.Invalidate(_localizer["Something went wrong."], exception: ex); 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); var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
if (follower == default) 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); await UnfollowAs(follower, form.Target, token);
return result; return result;
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}"); logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}");
return result.Invalidate(_localizer["Something went wrong."], exception: ex); return result.Invalidate(localizer["Something went wrong."], exception: ex);
} }
} }
@@ -106,8 +95,9 @@ namespace PrivaPub.Domain.Social
return kept.Count == 0 ? null : kept; return kept.Count == 0 ? null : kept;
} }
public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default, public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
IReadOnlyList<string> languages = default) IReadOnlyList<string> languages = default,
CancellationToken token = default)
{ {
var (local, remote) = await ResolveTarget(target, token); var (local, remote) = await ResolveTarget(target, token);
if (local == default && remote == default) if (local == default && remote == default)
@@ -116,7 +106,7 @@ namespace PrivaPub.Domain.Social
return default; return default;
var targetUri = local?.Uri ?? remote.ActorURI; 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 != default)
{ {
if (existing.ShowReblogs != showReblogs) 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 // 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 // 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) if (existing.State == FollowState.Requested && remote != default)
await _delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing), token, await delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing),
again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture)); again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture), token);
return existing; return existing;
} }
@@ -162,7 +152,7 @@ namespace PrivaPub.Domain.Social
} }
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) 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 //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); 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) if (local != default)
await FollowLocally(follower, local, following, token); await FollowLocally(follower, local, following, token);
else 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; return following;
} }
@@ -178,7 +168,7 @@ namespace PrivaPub.Domain.Social
{ {
var (local, remote) = await ResolveTarget(target, token); var (local, remote) = await ResolveTarget(target, token);
var targetUri = local?.Uri ?? remote?.ActorURI ?? target; 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) if (following == default)
return; return;
@@ -202,17 +192,17 @@ namespace PrivaPub.Domain.Social
["actor"] = follower.Uri, ["actor"] = follower.Uri,
["object"] = FollowActivity(follower, following) ["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) public async Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token)
{ {
var localFollower = await _localActors.FindById(LocalActorKind.Person, followerAccountId, token); var localFollower = await localActors.FindById(LocalActorKind.Person, followerAccountId, token);
var remoteFollower = localFollower == default ? await _dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default; var remoteFollower = localFollower == default ? await dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default;
var followerUri = localFollower?.Uri ?? remoteFollower?.ActorURI; var followerUri = localFollower?.Uri ?? remoteFollower?.ActorURI;
if (followerUri == default) if (followerUri == default)
return false; 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); .ExecuteFirstAsync(token);
if (request == default) if (request == default)
return false; return false;
@@ -249,10 +239,10 @@ namespace PrivaPub.Domain.Social
["actor"] = me.Uri, ["actor"] = me.Uri,
["object"] = follow ["object"] = follow
}; };
await _delivery.Enqueue(me, new[] { request.InboxURL }, answer, token); await delivery.Enqueue(me, new[] { request.InboxURL }, answer, token: token);
} }
if (accept) 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; return true;
} }
@@ -261,8 +251,8 @@ namespace PrivaPub.Domain.Social
var result = new WebResult(); var result = new WebResult();
var follower = await OwnedAvatar(rootUserId, avatarId, token); var follower = await OwnedAvatar(rootUserId, avatarId, token);
if (follower == default) if (follower == default)
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound); 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)) result.Data = (await dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token))
.Select(ToView).ToList(); .Select(ToView).ToList();
return result; return result;
} }
@@ -286,7 +276,7 @@ namespace PrivaPub.Domain.Social
.ExecuteAsync(token); .ExecuteAsync(token);
if (target.Kind == LocalActorKind.Person) if (target.Kind == LocalActorKind.Person)
await Notifications.Add(target.Id, following.State == FollowState.Accepted ? NotificationType.Follow : NotificationType.FollowRequest, 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); public Task<(LocalActor Local, ForeignAvatar Remote)> Resolve(string target, CancellationToken token) => ResolveTarget(target, token);
@@ -298,17 +288,17 @@ namespace PrivaPub.Domain.Social
return default; return default;
if (target.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || target.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) if (target.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || target.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
{ {
var byUri = await _localActors.FindByUri(target, token); var byUri = await localActors.FindByUri(target, token);
return byUri != default ? (byUri, default) : (default, await _remoteActors.GetActor(target, refresh: false, token)); return byUri != default ? (byUri, default) : (default, await remoteActors.GetActor(target, refresh: false, token));
} }
var parts = target.TrimStart('@').Split('@'); 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)) 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); var actorUri = await remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
return (default, actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, 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 // 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; var sent = 0;
// (a request older than the count has no Resent yet: "not at least" matches it, "less than" would not) // (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); .ExecuteAsync(token);
foreach (var following in pending.Where(f => (f.ResentAt ?? f.CreatedAt) + ResendAfter[f.Resent] <= now)) 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 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 inbox = following.TargetInboxURL ?? (await remoteActors.GetActor(following.TargetActorURI, refresh: false, token))?.InboxURL;
if (follower != default && !string.IsNullOrEmpty(inbox)) if (follower != default && !string.IsNullOrEmpty(inbox))
{ {
// under a new id each time: Lemmy keeps the ids it received and never answers one again // under a new id each time: Lemmy keeps the ids it received and never answers one again
var again = FollowActivity(follower, following); var again = FollowActivity(follower, following);
again["id"] = AgainId(following.FollowActivityURI, following.Resent + 1); again["id"] = AgainId(following.FollowActivityURI, following.Resent + 1);
await _delivery.Enqueue(follower, new[] { inbox }, again, token, await delivery.Enqueue(follower, new[] { inbox }, again,
again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture)); again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture), token);
sent++; sent++;
} }
await DB.Default.Update<Following>().MatchID(following.ID).Modify(b => b.Inc(f => f.Resent, 1)).Modify(f => f.ResentAt, now) 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)) if (string.IsNullOrEmpty(rootUserId) || string.IsNullOrEmpty(avatarId))
return default; 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; return default;
// a suspended persona does nothing through the client API either (R6) // 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() static ViewFollowing ToView(Following following) => new()
+1 -2
View File
@@ -26,8 +26,7 @@ namespace PrivaPub.Domain.Social
} }
} }
public static async Task Add(string avatarId, NotificationType type, string fromAccountId, string fromActorUri, string postId, 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)
CancellationToken token, string emoji = default, string emojiUrl = default, string text = default)
{ {
if (string.IsNullOrEmpty(avatarId) || avatarId == fromAccountId && type != NotificationType.Poll) if (string.IsNullOrEmpty(avatarId) || avatarId == fromAccountId && type != NotificationType.Poll)
return; return;
+8 -14
View File
@@ -27,18 +27,12 @@ namespace PrivaPub.Domain.Social
Task<bool> Unreact(LocalActor me, PostEntity post, string emoji, CancellationToken token); 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 = { "❤", "❤️", "♥", "♥️" }; 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()); public static bool IsHeart(string content) => content == default || Hearts.Contains(content.Trim());
@@ -64,7 +58,7 @@ namespace PrivaPub.Domain.Social
} }
Arrival.Accept("reaction"); Arrival.Accept("reaction");
if (!post.IsFederatedCopy) 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) 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); : 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) 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 reaction = post == default
? default ? default
: await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID && r.ActorURI == actor.ActorURI && r.Emoji == emoji.Name).ExecuteFirstAsync(token); : 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; return true;
} }
if (!post.IsFederatedCopy) 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 else
await Tell(me, post, Activity(me, post, reaction), token); await Tell(me, post, Activity(me, post, reaction), token);
return true; return true;
@@ -169,9 +163,9 @@ namespace PrivaPub.Domain.Social
async Task Tell(LocalActor me, PostEntity post, JsonObject activity, CancellationToken token) 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)) 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); public sealed record Picked(string Name, string Url);
+9 -15
View File
@@ -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 // 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 // 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. // 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); public static readonly TimeSpan Fresh = TimeSpan.FromMinutes(10);
const int MinAuthors = 2;//one account alone never makes a trend const int MinAuthors = 2;//one account alone never makes a trend
const int Kept = 40; 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 // what is computed is forgotten: the next read computes it again
public void Forget() public void Forget()
{ {
foreach (var key in new[] { "trends:tags", "trends:links", "trends:statuses" }) 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); 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 sealed record Trend(string Key, List<DayUse> History, string SamplePostId);
public Task<List<Trend>> Tags(CancellationToken token) => public Task<List<Trend>> Tags(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:tags", async entry => cache.GetOrCreateAsync("trends:tags", async entry =>
{ {
entry.AbsoluteExpirationRelativeToNow = Fresh; entry.AbsoluteExpirationRelativeToNow = Fresh;
var posts = await Week(p => p.Tags.Count > 0, token); 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) => public Task<List<Trend>> Links(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:links", async entry => cache.GetOrCreateAsync("trends:links", async entry =>
{ {
entry.AbsoluteExpirationRelativeToNow = Fresh; entry.AbsoluteExpirationRelativeToNow = Fresh;
var posts = await Week(p => p.Link != null, token); 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 // the ids of the trending posts, best first
public Task<List<string>> Statuses(CancellationToken token) => public Task<List<string>> Statuses(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:statuses", async entry => cache.GetOrCreateAsync("trends:statuses", async entry =>
{ {
entry.AbsoluteExpirationRelativeToNow = Fresh; entry.AbsoluteExpirationRelativeToNow = Fresh;
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
var since = now.AddHours(-48); 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 .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.ReblogOfPostId == null && p.InReplyToURI == null && p.AnsweringToPostId == null && p.CreationDate >= since
&& p.FavouritesCount + p.ReblogsCount + p.RepliesCount > 0) && 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) Task<List<Post>> Week(System.Linq.Expressions.Expression<Func<Post, bool>> with, CancellationToken token)
{ {
var since = DateTime.UtcNow.Date.AddDays(-6); 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 .Match(p => p.Visibility == PostVisibility.Public && !p.DeletedAt.HasValue && !p.AuthorGone && !p.HasContentWarning && !p.IsLocalOnly
&& p.ReblogOfPostId == null && p.CreationDate >= since) && p.ReblogOfPostId == null && p.CreationDate >= since)
.Match(Privacy.VisibilityPolicy.IsPublic).Match(Privacy.VisibilityPolicy.IsListed) .Match(Privacy.VisibilityPolicy.IsPublic).Match(Privacy.VisibilityPolicy.IsListed)
+7 -14
View File
@@ -83,7 +83,7 @@ namespace PrivaPub.Domain.Social
} }
/// <summary>Every subscription of these personas goes (their tokens ended, or they did).</summary> /// <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>(); var ids = avatarIds?.Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList() ?? new List<string>();
if (ids.Count > 0) 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> /// <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)) if (!string.IsNullOrEmpty(tokenId))
await DB.Default.DeleteAsync<PushSubscription>(s => s.TokenId == 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 // 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. // (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) public Task StartAsync(CancellationToken cancellationToken)
{ {
Notifications.Told = Dispatch; Notifications.Told = Dispatch;
@@ -145,11 +138,11 @@ namespace PrivaPub.Domain.Social
DedupeKey = $"push|{subscription.ID}|{notification.ID}" DedupeKey = $"push|{subscription.ID}|{notification.ID}"
}); });
if (jobs.Count > 0) if (jobs.Count > 0)
await _jobs.EnqueueMany(jobs, token); await jobQueue.EnqueueMany(jobs, token);
} }
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested) 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));
} }
} }
} }
+12 -22
View File
@@ -19,33 +19,23 @@ namespace PrivaPub.Domain.Statistics
// This server's own place, for the instance API (the client's globe draws every server from it). The owner may set it, // This server's own place, for the instance API (the client's globe draws every server from it). The owner may set it,
// for a server behind a proxy or a CDN; otherwise the server's own host name is resolved and located like any other // for a server behind a proxy or a CDN; otherwise the server's own host name is resolved and located like any other
// server's, once a day. Never the address of a request. // server's, once a day. Never the address of a request.
public class SelfLocation : ISelfLocation public class SelfLocation(
IGeoLocator geo,
IOptionsMonitor<StatisticsOptions> options,
IOptionsMonitor<AppConfiguration> app,
ILogger<SelfLocation> logger,
ICdnRanges cdnRanges = default) : ISelfLocation
{ {
static readonly TimeSpan Lifetime = TimeSpan.FromDays(1); static readonly TimeSpan Lifetime = TimeSpan.FromDays(1);
readonly IGeoLocator _geo;
readonly ICdnRanges _cdnRanges;
readonly IOptionsMonitor<StatisticsOptions> _options;
readonly IOptionsMonitor<AppConfiguration> _app;
readonly ILogger<SelfLocation> _logger;
readonly SemaphoreSlim _gate = new(1, 1); readonly SemaphoreSlim _gate = new(1, 1);
InstanceGeo _located; InstanceGeo _located;
DateTime _locatedAt = DateTime.MinValue; DateTime _locatedAt = DateTime.MinValue;
public SelfLocation(IGeoLocator geo, IOptionsMonitor<StatisticsOptions> options, IOptionsMonitor<AppConfiguration> app, ILogger<SelfLocation> logger,
ICdnRanges cdnRanges = default)
{
_geo = geo;
_cdnRanges = cdnRanges;
_options = options;
_app = app;
_logger = logger;
}
public async Task<InstanceGeo> Get(CancellationToken token) public async Task<InstanceGeo> Get(CancellationToken token)
{ {
if (_options.CurrentValue.Geo.Self is { Latitude: { } latitude, Longitude: { } longitude } self) if (options.CurrentValue.Geo.Self is { Latitude: { } latitude, Longitude: { } longitude } self)
return new InstanceGeo return new InstanceGeo
{ {
Country = self.Country, Country = self.Country,
@@ -77,12 +67,12 @@ namespace PrivaPub.Domain.Statistics
{ {
try try
{ {
if (!Uri.TryCreate(_app.CurrentValue.BackendBaseAddress, UriKind.Absolute, out var self)) if (!Uri.TryCreate(app.CurrentValue.BackendBaseAddress, UriKind.Absolute, out var self))
return default; return default;
var addresses = await Dns.GetHostAddressesAsync(self.Host, token); var addresses = await Dns.GetHostAddressesAsync(self.Host, token);
var address = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? addresses.FirstOrDefault(); var address = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? addresses.FirstOrDefault();
var fix = address == default ? default : _geo.Locate(address); var fix = address == default ? default : geo.Locate(address);
var (cdn, cdnSource) = Federation.Objects.InstanceDescriber.Cdn(address, self.Host, fix?.Asn, _cdnRanges, default); var (cdn, cdnSource) = Federation.Objects.InstanceDescriber.Cdn(address, self.Host, fix?.Asn, cdnRanges, default);
return fix == default ? default : new InstanceGeo return fix == default ? default : new InstanceGeo
{ {
Country = fix.Country, Country = fix.Country,
@@ -95,13 +85,13 @@ namespace PrivaPub.Domain.Statistics
CdnDomain = cdn?.Domain, CdnDomain = cdn?.Domain,
CdnSource = cdnSource, CdnSource = cdnSource,
Ipv6 = address.AddressFamily == AddressFamily.InterNetworkV6, Ipv6 = address.AddressFamily == AddressFamily.InterNetworkV6,
Source = _geo.Source, Source = geo.Source,
LocatedAt = DateTime.UtcNow LocatedAt = DateTime.UtcNow
}; };
} }
catch (Exception ex) when (ex is SocketException or ArgumentException) catch (Exception ex) when (ex is SocketException or ArgumentException)
{ {
_logger.LogInformation("{Service}: this server's host does not resolve", nameof(SelfLocation)); logger.LogInformation("{Service}: this server's host does not resolve", nameof(SelfLocation));
return default; return default;
} }
} }
+6 -12
View File
@@ -29,20 +29,14 @@ namespace PrivaPub.Domain.Statistics
// Servers through time (owner decision 2026-10-04): each server's weekly snapshots (place, CDN, size), and the servers // Servers through time (owner decision 2026-10-04): each server's weekly snapshots (place, CDN, size), and the servers
// grouped by the CDN in front of them, named by the CDN's own domain. Read from the weekly snapshots InstanceDescriber // grouped by the CDN in front of them, named by the CDN's own domain. Read from the weekly snapshots InstanceDescriber
// writes; the CDN pages are kept for half an hour, because a large CDN reads many snapshots. // writes; the CDN pages are kept for half an hour, because a large CDN reads many snapshots.
public class ServerPlaces : IServerPlaces public class ServerPlaces(
ICdnRanges cdnRanges,
IMemoryCache cache) : IServerPlaces
{ {
public const int MaxHosts = 500; public const int MaxHosts = 500;
const int MaxChanges = 50; const int MaxChanges = 50;
static readonly TimeSpan CacheFor = TimeSpan.FromMinutes(30); static readonly TimeSpan CacheFor = TimeSpan.FromMinutes(30);
readonly ICdnRanges _ranges;
readonly IMemoryCache _cache;
public ServerPlaces(ICdnRanges ranges, IMemoryCache cache)
{
_ranges = ranges;
_cache = cache;
}
// the CDN key a server's place belongs to: the CDN's domain, or its name for a CDN that has none // the CDN key a server's place belongs to: the CDN's domain, or its name for a CDN that has none
public static string KeyOf(InstanceGeo geo) => public static string KeyOf(InstanceGeo geo) =>
@@ -75,7 +69,7 @@ namespace PrivaPub.Domain.Statistics
public async Task<List<CdnGroup>> Cdns(CancellationToken token) public async Task<List<CdnGroup>> Cdns(CancellationToken token)
{ {
var fronted = await Fronted(token); var fronted = await Fronted(token);
var status = _ranges.Status; var status = cdnRanges.Status;
var keys = CdnCatalog.All.Select(p => p.Key).Concat(fronted.Select(i => KeyOf(i.Geo))).Distinct(StringComparer.OrdinalIgnoreCase); var keys = CdnCatalog.All.Select(p => p.Key).Concat(fronted.Select(i => KeyOf(i.Geo))).Distinct(StringComparer.OrdinalIgnoreCase);
return keys.Select(key => Group(key, fronted, status)).OrderByDescending(g => g.Servers).ThenBy(g => g.Name).ToList(); return keys.Select(key => Group(key, fronted, status)).OrderByDescending(g => g.Servers).ThenBy(g => g.Name).ToList();
} }
@@ -85,14 +79,14 @@ namespace PrivaPub.Domain.Statistics
key = key?.Trim().ToLowerInvariant(); key = key?.Trim().ToLowerInvariant();
if (string.IsNullOrEmpty(key) || key.Length > 100) if (string.IsNullOrEmpty(key) || key.Length > 100)
return default; return default;
return await _cache.GetOrCreateAsync($"cdn-history|{key}|{weeks}", async entry => return await cache.GetOrCreateAsync($"cdn-history|{key}|{weeks}", async entry =>
{ {
entry.AbsoluteExpirationRelativeToNow = CacheFor; entry.AbsoluteExpirationRelativeToNow = CacheFor;
var fronted = await Fronted(token); var fronted = await Fronted(token);
var provider = CdnCatalog.ByKey(key); var provider = CdnCatalog.ByKey(key);
if (provider == default && fronted.All(i => KeyOf(i.Geo) != key)) if (provider == default && fronted.All(i => KeyOf(i.Geo) != key))
return default; return default;
var group = Group(provider?.Key ?? key, fronted, _ranges.Status); var group = Group(provider?.Key ?? key, fronted, cdnRanges.Status);
var hosts = fronted.Where(i => KeyOf(i.Geo) == group.Key).Select(i => i.Host).OrderBy(h => h).Take(MaxHosts).ToList(); var hosts = fronted.Where(i => KeyOf(i.Geo) == group.Key).Select(i => i.Host).OrderBy(h => h).Take(MaxHosts).ToList();
return new CdnHistory(group, hosts, await Weeks(group, weeks, token)); return new CdnHistory(group, hosts, await Weeks(group, weeks, token));
}); });
@@ -38,24 +38,13 @@ namespace PrivaPub.Domain.Statuses
Task<bool> MayReply(NoteDocument reply, ForeignAvatar replier, PostEntity parent, CancellationToken token); Task<bool> MayReply(NoteDocument reply, ForeignAvatar replier, PostEntity parent, CancellationToken token);
} }
public class InteractionApprovals : IInteractionApprovals public class InteractionApprovals(
DbEntities dbEntities,
IRemoteActorService remoteActors,
ILocalActorService localActors,
IDeliveryService deliveryService,
IOutboxPublisher outbox) : IInteractionApprovals
{ {
readonly DbEntities _dbEntities;
readonly IRemoteActorService _remoteActors;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
readonly IOutboxPublisher _outbox;
public InteractionApprovals(DbEntities dbEntities, IRemoteActorService remoteActors, ILocalActorService localActors, IDeliveryService delivery,
IOutboxPublisher outbox)
{
_dbEntities = dbEntities;
_remoteActors = remoteActors;
_localActors = localActors;
_delivery = delivery;
_outbox = outbox;
}
static string Prefix(InteractionKind kind) => kind switch static string Prefix(InteractionKind kind) => kind switch
{ {
InteractionKind.Reply => "reply-request-", InteractionKind.Reply => "reply-request-",
@@ -98,33 +87,33 @@ namespace PrivaPub.Domain.Statuses
return false; return false;
if (who.Any(Addressing.IsPublic) || who.Contains(actor.Uri)) if (who.Any(Addressing.IsPublic) || who.Contains(actor.Uri))
return true; return true;
var author = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == target.ActorURI).ExecuteFirstAsync(token); var author = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == target.ActorURI).ExecuteFirstAsync(token);
if (author == default) if (author == default)
return false; return false;
if (!string.IsNullOrEmpty(author.FollowersURL) && who.Contains(author.FollowersURL) if (!string.IsNullOrEmpty(author.FollowersURL) && who.Contains(author.FollowersURL)
&& await _dbEntities.Followings.Match(f => f.AvatarId == actor.Id && f.TargetActorURI == author.ActorURI && f.State == FollowState.Accepted) && await dbEntities.Followings.Match(f => f.AvatarId == actor.Id && f.TargetActorURI == author.ActorURI && f.State == FollowState.Accepted)
.ExecuteAnyAsync(token)) .ExecuteAnyAsync(token))
return true; return true;
return !string.IsNullOrEmpty(author.FollowingURL) && who.Contains(author.FollowingURL) return !string.IsNullOrEmpty(author.FollowingURL) && who.Contains(author.FollowingURL)
&& await _dbEntities.Followers.Match(f => f.LocalActorId == actor.Id && f.ActorURI == author.ActorURI && f.IsAccepted).ExecuteAnyAsync(token); && await dbEntities.Followers.Match(f => f.LocalActorId == actor.Id && f.ActorURI == author.ActorURI && f.IsAccepted).ExecuteAnyAsync(token);
} }
// asks the author, with the interaction as the request's instrument; it goes to no one else until the author agrees // asks the author, with the interaction as the request's instrument; it goes to no one else until the author agrees
public async Task Ask(LocalActor actor, PostEntity target, InteractionKind kind, JsonObject interaction, string localId, CancellationToken token) public async Task Ask(LocalActor actor, PostEntity target, InteractionKind kind, JsonObject interaction, string localId, CancellationToken token)
{ {
var author = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == target.ActorURI).ExecuteFirstAsync(token); var author = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == target.ActorURI).ExecuteFirstAsync(token);
if (string.IsNullOrEmpty(author?.InboxURL)) if (string.IsNullOrEmpty(author?.InboxURL))
return; return;
// FEP-5624: the reply itself is the question, to the author alone // FEP-5624: the reply itself is the question, to the author alone
if (ApprovesReplies(target, kind)) if (ApprovesReplies(target, kind))
{ {
await _delivery.Enqueue(actor, new[] { author.InboxURL }, ActivityPubRenderer.Create(actor, (JsonObject)interaction.DeepClone(), $"create-{localId}"), await deliveryService.Enqueue(actor, new[] { author.InboxURL }, ActivityPubRenderer.Create(actor, (JsonObject)interaction.DeepClone(), $"create-{localId}"),
token); token: token);
return; return;
} }
var instrument = (JsonObject)interaction.DeepClone(); var instrument = (JsonObject)interaction.DeepClone();
instrument.Remove("@context"); instrument.Remove("@context");
await _delivery.Enqueue(actor, new[] { author.InboxURL }, new JsonObject await deliveryService.Enqueue(actor, new[] { author.InboxURL }, new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
["id"] = actor.ActivityUri(Prefix(kind) + localId), ["id"] = actor.ActivityUri(Prefix(kind) + localId),
@@ -133,7 +122,7 @@ namespace PrivaPub.Domain.Statuses
["to"] = target.ActorURI, ["to"] = target.ActorURI,
["object"] = target.ObjectURI, ["object"] = target.ObjectURI,
["instrument"] = instrument ["instrument"] = instrument
}, token); }, token: token);
} }
// an author's answer to one of our requests (the request, or the interaction itself when it was sent unasked) // an author's answer to one of our requests (the request, or the interaction itself when it was sent unasked)
@@ -154,7 +143,7 @@ namespace PrivaPub.Domain.Statuses
if (kind == InteractionKind.Like) if (kind == InteractionKind.Like)
{ {
var like = await DB.Default.Find<Favourite>().OneAsync(localId, token); var like = await DB.Default.Find<Favourite>().OneAsync(localId, token);
var liked = like == default ? default : await _dbEntities.Posts.MatchID(like.PostId).ExecuteFirstAsync(token); var liked = like == default ? default : await dbEntities.Posts.MatchID(like.PostId).ExecuteFirstAsync(token);
if (like is not { Approval: ApprovalState.Pending } || liked?.ActorURI != actor.ActorURI) if (like is not { Approval: ApprovalState.Pending } || liked?.ActorURI != actor.ActorURI)
return true; return true;
if (!accepted) if (!accepted)
@@ -168,9 +157,9 @@ namespace PrivaPub.Domain.Statuses
return true; return true;
await DB.Default.Update<Favourite>().MatchID(like.ID).Modify(f => f.Approval, ApprovalState.Accepted).Modify(f => f.ApprovalURI, stamp) await DB.Default.Update<Favourite>().MatchID(like.ID).Modify(f => f.Approval, ApprovalState.Accepted).Modify(f => f.ApprovalURI, stamp)
.ExecuteAsync(token); .ExecuteAsync(token);
var liker = await _localActors.FindById(Models.Federation.LocalActorKind.Person, like.AccountId, token); var liker = await localActors.FindById(Models.Federation.LocalActorKind.Person, like.AccountId, token);
if (liker != default && !string.IsNullOrEmpty(actor.InboxURL)) if (liker != default && !string.IsNullOrEmpty(actor.InboxURL))
await _delivery.Enqueue(liker, new[] { actor.InboxURL }, new JsonObject await deliveryService.Enqueue(liker, new[] { actor.InboxURL }, new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
["id"] = like.ActivityURI, ["id"] = like.ActivityURI,
@@ -178,16 +167,16 @@ namespace PrivaPub.Domain.Statuses
["actor"] = liker.Uri, ["actor"] = liker.Uri,
["object"] = liked.ObjectURI, ["object"] = liked.ObjectURI,
["likeAuthorization"] = stamp ["likeAuthorization"] = stamp
}, token); }, token: token);
return true; return true;
} }
var post = await _dbEntities.Posts.Match(p => p.ID == localId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == localId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var target = post == default ? default : await _dbEntities.Posts.MatchID(kind == InteractionKind.Reply ? post.AnsweringToPostId : post.ReblogOfPostId) var target = post == default ? default : await dbEntities.Posts.MatchID(kind == InteractionKind.Reply ? post.AnsweringToPostId : post.ReblogOfPostId)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
if (post is not { Approval: ApprovalState.Pending } || target?.ActorURI != actor.ActorURI) if (post is not { Approval: ApprovalState.Pending } || target?.ActorURI != actor.ActorURI)
return true; return true;
var author = await _localActors.FindById(Models.Federation.LocalActorKind.Person, post.GroupUserId, token); var author = await localActors.FindById(Models.Federation.LocalActorKind.Person, post.GroupUserId, token);
if (author == default) if (author == default)
return true; return true;
if (!accepted) if (!accepted)
@@ -223,7 +212,7 @@ namespace PrivaPub.Domain.Statuses
if (kind == InteractionKind.Reply) if (kind == InteractionKind.Reply)
{ {
var create = ActivityPubRenderer.Create(author, ActivityPubRenderer.Note(post, author, default, post.InReplyToURI), $"create-{post.ID}"); var create = ActivityPubRenderer.Create(author, ActivityPubRenderer.Note(post, author, default, post.InReplyToURI), $"create-{post.ID}");
await _outbox.Publish(author, post, create, token); await outbox.Publish(author, post, create, token);
return true; return true;
} }
var announce = new JsonObject var announce = new JsonObject
@@ -238,13 +227,13 @@ namespace PrivaPub.Domain.Statuses
["object"] = target.ObjectURI, ["object"] = target.ObjectURI,
["announceAuthorization"] = post.ApprovalURI ["announceAuthorization"] = post.ApprovalURI
}; };
await _delivery.EnqueueToFollowers(author, announce, token, string.IsNullOrEmpty(actor.InboxURL) ? default : new[] { actor.InboxURL }); await deliveryService.EnqueueToFollowers(author, announce, string.IsNullOrEmpty(actor.InboxURL) ? default : new[] { actor.InboxURL }, token);
return true; return true;
} }
(InteractionKind Kind, string LocalId) Request(string requestId) (InteractionKind Kind, string LocalId) Request(string requestId)
{ {
if (requestId == default || !requestId.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (requestId == default || !requestId.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return default; return default;
foreach (var kind in new[] { InteractionKind.Reply, InteractionKind.Like, InteractionKind.Announce }) foreach (var kind in new[] { InteractionKind.Reply, InteractionKind.Like, InteractionKind.Announce })
{ {
@@ -258,11 +247,11 @@ namespace PrivaPub.Domain.Statuses
// an interaction of ours named by its own id, as an answer to one sent unasked names it // an interaction of ours named by its own id, as an answer to one sent unasked names it
async Task<(InteractionKind Kind, string LocalId)> Interaction(string uri, CancellationToken token) async Task<(InteractionKind Kind, string LocalId)> Interaction(string uri, CancellationToken token)
{ {
if (!uri.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (!uri.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return default; return default;
if (await DB.Default.Find<Favourite>().Match(f => f.ActivityURI == uri).ExecuteFirstAsync(token) is { } like) if (await DB.Default.Find<Favourite>().Match(f => f.ActivityURI == uri).ExecuteFirstAsync(token) is { } like)
return (InteractionKind.Like, like.ID); return (InteractionKind.Like, like.ID);
if (await _dbEntities.Posts.Match(p => (p.ObjectURI == uri || p.ActivityURI == uri) && !p.IsFederatedCopy).ExecuteFirstAsync(token) is { } post) if (await dbEntities.Posts.Match(p => (p.ObjectURI == uri || p.ActivityURI == uri) && !p.IsFederatedCopy).ExecuteFirstAsync(token) is { } post)
return (post.ReblogOfPostId != default ? InteractionKind.Announce : InteractionKind.Reply, post.ID); return (post.ReblogOfPostId != default ? InteractionKind.Announce : InteractionKind.Reply, post.ID);
return default; return default;
} }
@@ -272,7 +261,7 @@ namespace PrivaPub.Domain.Statuses
{ {
if (!Origin.Same(authorization, target.ActorURI)) if (!Origin.Same(authorization, target.ActorURI))
return false; return false;
using var fetched = await _remoteActors.FetchObject(authorization, token); using var fetched = await remoteActors.FetchObject(authorization, token);
if (fetched == default) if (fetched == default)
return false; return false;
var stamp = JsonNode.Parse(fetched.Root.GetRawText()); var stamp = JsonNode.Parse(fetched.Root.GetRawText());
@@ -288,7 +277,7 @@ namespace PrivaPub.Domain.Statuses
if (parent is not { IsFederatedCopy: true, ReplyPolicy: { } rule } || replier.ActorURI == parent.ActorURI) if (parent is not { IsFederatedCopy: true, ReplyPolicy: { } rule } || replier.ActorURI == parent.ActorURI)
return true; return true;
// anyone, the replier itself, or a collection (followers, following) whose members we cannot list from here // anyone, the replier itself, or a collection (followers, following) whose members we cannot list from here
var author = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == parent.ActorURI).ExecuteFirstAsync(token); var author = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == parent.ActorURI).ExecuteFirstAsync(token);
if (rule.Automatic.Any(Addressing.IsPublic) || rule.Automatic.Contains(replier.ActorURI) if (rule.Automatic.Any(Addressing.IsPublic) || rule.Automatic.Contains(replier.ActorURI)
|| author != default && (rule.Automatic.Contains(author.FollowersURL) || rule.Automatic.Contains(author.FollowingURL))) || author != default && (rule.Automatic.Contains(author.FollowersURL) || rule.Automatic.Contains(author.FollowingURL)))
return true; return true;
+9 -16
View File
@@ -29,24 +29,17 @@ namespace PrivaPub.Domain.Statuses
Task<bool> Answered(JsonNode answer, ForeignAvatar actor, bool accepted, CancellationToken token); Task<bool> Answered(JsonNode answer, ForeignAvatar actor, bool accepted, CancellationToken token);
} }
public class Participations : IParticipations public class Participations(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery) : IParticipations
{ {
const string JoinPrefix = "join-"; const string JoinPrefix = "join-";
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
public Participations(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery)
{
_dbEntities = dbEntities;
_localActors = localActors;
_delivery = delivery;
}
async Task<PostEntity> Event(LocalActor me, string postId, CancellationToken token) async Task<PostEntity> Event(LocalActor me, string postId, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == postId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == postId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return post is { IsFederatedCopy: true, Event: not null } && await VisibilityPolicy.CanSee(post, me.Id, token) ? post : default; return post is { IsFederatedCopy: true, Event: not null } && await VisibilityPolicy.CanSee(post, me.Id, token) ? post : default;
} }
@@ -105,10 +98,10 @@ namespace PrivaPub.Domain.Statuses
async Task Send(LocalActor me, PostEntity post, JsonObject activity, CancellationToken token) async Task Send(LocalActor me, PostEntity post, JsonObject activity, CancellationToken token)
{ {
var author = string.IsNullOrEmpty(post.AuthorAccountId) ? default : await _dbEntities.ForeignAvatars.MatchID(post.AuthorAccountId).ExecuteFirstAsync(token); var author = string.IsNullOrEmpty(post.AuthorAccountId) ? default : await dbEntities.ForeignAvatars.MatchID(post.AuthorAccountId).ExecuteFirstAsync(token);
var inbox = !string.IsNullOrEmpty(author?.SharedInboxURL) ? author.SharedInboxURL : author?.InboxURL; var inbox = !string.IsNullOrEmpty(author?.SharedInboxURL) ? author.SharedInboxURL : author?.InboxURL;
if (!string.IsNullOrEmpty(inbox)) if (!string.IsNullOrEmpty(inbox))
await _delivery.Enqueue(me, new[] { inbox }, activity, token); await delivery.Enqueue(me, new[] { inbox }, activity, token: token);
} }
// the event's server answering our Join: Accept or Reject, naming it or carrying it // the event's server answering our Join: Accept or Reject, naming it or carrying it
@@ -116,10 +109,10 @@ namespace PrivaPub.Domain.Statuses
{ {
var joinId = Id(answer["object"]); var joinId = Id(answer["object"]);
var marker = joinId?.LastIndexOf("/grunts/" + JoinPrefix, StringComparison.Ordinal) ?? -1; var marker = joinId?.LastIndexOf("/grunts/" + JoinPrefix, StringComparison.Ordinal) ?? -1;
if (marker < 0 || !joinId.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (marker < 0 || !joinId.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return false; return false;
var participation = await DB.Default.Find<Participation>().Match(p => p.ActivityURI == joinId).ExecuteFirstAsync(token); var participation = await DB.Default.Find<Participation>().Match(p => p.ActivityURI == joinId).ExecuteFirstAsync(token);
var post = participation == default ? default : await _dbEntities.Posts.MatchID(participation.PostId).ExecuteFirstAsync(token); var post = participation == default ? default : await dbEntities.Posts.MatchID(participation.PostId).ExecuteFirstAsync(token);
if (post == default || !Origin.Same(post.ObjectURI, actor.ActorURI)) if (post == default || !Origin.Same(post.ObjectURI, actor.ActorURI))
return true; return true;
await DB.Default.Update<Participation>().MatchID(participation.ID) await DB.Default.Update<Participation>().MatchID(participation.ID)
+28 -46
View File
@@ -33,7 +33,11 @@ namespace PrivaPub.Domain.Statuses
Task<HashSet<int>> OwnVotes(string postId, string avatarId, CancellationToken token); Task<HashSet<int>> OwnVotes(string postId, string avatarId, CancellationToken token);
} }
public class PollService : IPollService public class PollService(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery,
IJobQueue queue) : IPollService
{ {
public const int MaxOptions = 4; public const int MaxOptions = 4;
public const int MaxOptionLength = 50; public const int MaxOptionLength = 50;
@@ -41,18 +45,6 @@ namespace PrivaPub.Domain.Statuses
public const int MaxExpiration = 2_629_746; public const int MaxExpiration = 2_629_746;
static readonly TimeSpan RefreshEvery = TimeSpan.FromMinutes(3); static readonly TimeSpan RefreshEvery = TimeSpan.FromMinutes(3);
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
readonly IJobQueue _queue;
public PollService(DbEntities dbEntities, ILocalActorService localActors, IDeliveryService delivery, IJobQueue queue)
{
_dbEntities = dbEntities;
_localActors = localActors;
_delivery = delivery;
_queue = queue;
}
public string Invalid(PollDraft draft) public string Invalid(PollDraft draft)
{ {
@@ -81,7 +73,7 @@ namespace PrivaPub.Domain.Statuses
{ {
if (post.Poll?.ExpiresAt is not { } ends) if (post.Poll?.ExpiresAt is not { } ends)
return; return;
await _queue.EnqueueMany(new[] await queue.EnqueueMany(new[]
{ {
new Job { Kind = JobKind.PollClose, Payload = post.ID, Host = LocalHost, DedupeKey = $"poll-close|{post.ID}", RunAt = ends } new Job { Kind = JobKind.PollClose, Payload = post.ID, Host = LocalHost, DedupeKey = $"poll-close|{post.ID}", RunAt = ends }
}, token); }, token);
@@ -115,7 +107,7 @@ namespace PrivaPub.Domain.Statuses
else else
await Refreshed(post, token); await Refreshed(post, token);
await Scheduled(post, token); await Scheduled(post, token);
return new StatusOutcome(await _dbEntities.Posts.MatchID(post.ID).ExecuteFirstAsync(token)); return new StatusOutcome(await dbEntities.Posts.MatchID(post.ID).ExecuteFirstAsync(token));
} }
public async Task Receive(PostEntity post, ForeignAvatar voter, string choice, string activityId, CancellationToken token) public async Task Receive(PostEntity post, ForeignAvatar voter, string choice, string activityId, CancellationToken token)
@@ -164,13 +156,13 @@ namespace PrivaPub.Domain.Statuses
async Task SendVotes(LocalActor me, PostEntity post, IReadOnlyList<int> choices, CancellationToken token) async Task SendVotes(LocalActor me, PostEntity post, IReadOnlyList<int> choices, CancellationToken token)
{ {
var owner = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token); var owner = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
if (string.IsNullOrEmpty(owner?.InboxURL)) if (string.IsNullOrEmpty(owner?.InboxURL))
return; return;
foreach (var choice in choices) foreach (var choice in choices)
{ {
var voteId = me.Uri + $"#votes/{post.ID}/{choice}"; var voteId = me.Uri + $"#votes/{post.ID}/{choice}";
await _delivery.Enqueue(me, new[] { owner.InboxURL }, new JsonObject await delivery.Enqueue(me, new[] { owner.InboxURL }, new JsonObject
{ {
["@context"] = ActivityPubRenderer.ActivityStreams, ["@context"] = ActivityPubRenderer.ActivityStreams,
["id"] = voteId + "/activity", ["id"] = voteId + "/activity",
@@ -186,14 +178,14 @@ namespace PrivaPub.Domain.Statuses
["to"] = new JsonArray(owner.ActorURI), ["to"] = new JsonArray(owner.ActorURI),
["inReplyTo"] = post.ObjectURI ["inReplyTo"] = post.ObjectURI
} }
}, token); }, token: token);
} }
} }
async Task Refreshed(PostEntity post, CancellationToken token) async Task Refreshed(PostEntity post, CancellationToken token)
{ {
var bucket = DateTime.UtcNow.Ticks / RefreshEvery.Ticks; var bucket = DateTime.UtcNow.Ticks / RefreshEvery.Ticks;
await _queue.EnqueueMany(new[] await queue.EnqueueMany(new[]
{ {
new Job new Job
{ {
@@ -203,58 +195,48 @@ namespace PrivaPub.Domain.Statuses
}, token); }, token);
} }
string LocalHost => new Uri(_localActors.BaseAddress).Host; string LocalHost => new Uri(localActors.BaseAddress).Host;
} }
public class PollRefreshJob : IJobHandler public class PollRefreshJob(
DbEntities dbEntities,
ILocalActorService localActors,
IOutboxPublisher outbox) : IJobHandler
{ {
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IOutboxPublisher _outbox;
public PollRefreshJob(DbEntities dbEntities, ILocalActorService localActors, IOutboxPublisher outbox)
{
_dbEntities = dbEntities;
_localActors = localActors;
_outbox = outbox;
}
public virtual JobKind Kind => JobKind.PollRefresh; public virtual JobKind Kind => JobKind.PollRefresh;
public int Concurrency => 1; public int Concurrency => 1;
public int MaxAttempts => 3; public int MaxAttempts => 3;
public int PerHostLimit => 1; public int PerHostLimit => 1;
protected DbEntities Entities => dbEntities;
public virtual async Task<JobOutcome> Handle(Job job, CancellationToken token) public virtual async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var post = await _dbEntities.Posts.MatchID(job.Payload).ExecuteFirstAsync(token); var post = await dbEntities.Posts.MatchID(job.Payload).ExecuteFirstAsync(token);
if (post?.Poll == default || post.IsFederatedCopy || post.DeletedAt.HasValue) if (post?.Poll == default || post.IsFederatedCopy || post.DeletedAt.HasValue)
return JobOutcome.Done; return JobOutcome.Done;
var author = await _localActors.FindById(LocalActorKind.Person, post.GroupUserId, token); var author = await localActors.FindById(LocalActorKind.Person, post.GroupUserId, token);
if (author == default) if (author == default)
return JobOutcome.Done; return JobOutcome.Done;
await Closing(post, author, token); await Closing(post, author, token);
if (!post.IsLocalOnly) if (!post.IsLocalOnly)
await _outbox.PublishUpdate(author, post, $"poll-{DateTime.UtcNow.Ticks}", token); await outbox.PublishUpdate(author, post, $"poll-{DateTime.UtcNow.Ticks}", token);
return JobOutcome.Done; return JobOutcome.Done;
} }
protected virtual Task Closing(PostEntity post, LocalActor author, CancellationToken token) => Task.CompletedTask; protected virtual Task Closing(PostEntity post, LocalActor author, CancellationToken token) => Task.CompletedTask;
} }
public class PollCloseJob : PollRefreshJob public class PollCloseJob(
DbEntities dbEntities,
ILocalActorService localActors,
IOutboxPublisher outbox) : PollRefreshJob(dbEntities, localActors, outbox)
{ {
readonly DbEntities _posts;
public PollCloseJob(DbEntities dbEntities, ILocalActorService localActors, IOutboxPublisher outbox) : base(dbEntities, localActors, outbox)
{
_posts = dbEntities;
}
public override JobKind Kind => JobKind.PollClose; public override JobKind Kind => JobKind.PollClose;
public override async Task<JobOutcome> Handle(Job job, CancellationToken token) public override async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var post = await _posts.Posts.MatchID(job.Payload).ExecuteFirstAsync(token); var post = await Entities.Posts.MatchID(job.Payload).ExecuteFirstAsync(token);
if (post?.Poll == default || post.DeletedAt.HasValue) if (post?.Poll == default || post.DeletedAt.HasValue)
return JobOutcome.Done; return JobOutcome.Done;
if (!post.IsFederatedCopy) if (!post.IsFederatedCopy)
@@ -274,9 +256,9 @@ namespace PrivaPub.Domain.Statuses
{ {
var voters = await DB.Default.Find<PollVote>().Match(v => v.PostId == post.ID && v.IsLocalVoter).ExecuteAsync(token); var voters = await DB.Default.Find<PollVote>().Match(v => v.PostId == post.ID && v.IsLocalVoter).ExecuteAsync(token);
foreach (var voter in voters.Select(v => v.VoterAccountId).Distinct()) foreach (var voter in voters.Select(v => v.VoterAccountId).Distinct())
await Notifications.Add(voter, NotificationType.Poll, authorAccountId, authorUri, post.ID, token); await Notifications.Add(voter, NotificationType.Poll, authorAccountId, authorUri, post.ID, token: token);
if (!post.IsFederatedCopy) if (!post.IsFederatedCopy)
await Notifications.Add(post.GroupUserId, NotificationType.Poll, post.GroupUserId, authorUri, post.ID, token); await Notifications.Add(post.GroupUserId, NotificationType.Poll, post.GroupUserId, authorUri, post.ID, token: token);
} }
} }
} }
+32 -44
View File
@@ -40,26 +40,14 @@ namespace PrivaPub.Domain.Statuses
AskFirst AskFirst
} }
public class QuoteService : IQuoteService public class QuoteService(
DbEntities dbEntities,
IRemoteActorService remoteActors,
IRemotePosts remotePosts,
ILocalActorService localActors,
IDeliveryService delivery,
IOutboxPublisher outbox) : IQuoteService
{ {
readonly DbEntities _dbEntities;
readonly IRemoteActorService _remoteActors;
readonly IRemotePosts _remotePosts;
readonly ILocalActorService _localActors;
readonly IDeliveryService _delivery;
readonly IOutboxPublisher _outbox;
public QuoteService(DbEntities dbEntities, IRemoteActorService remoteActors, IRemotePosts remotePosts, ILocalActorService localActors,
IDeliveryService delivery, IOutboxPublisher outbox)
{
_dbEntities = dbEntities;
_remoteActors = remoteActors;
_remotePosts = remotePosts;
_localActors = localActors;
_delivery = delivery;
_outbox = outbox;
}
const string RequestPrefix = "quote-request-"; const string RequestPrefix = "quote-request-";
const string LicencePath = "/parrot-licences/"; const string LicencePath = "/parrot-licences/";
@@ -68,7 +56,7 @@ namespace PrivaPub.Domain.Statuses
async Task<bool> MayQuote(PostEntity quoted, string quoterUri, CancellationToken token) async Task<bool> MayQuote(PostEntity quoted, string quoterUri, CancellationToken token)
{ {
var author = await _localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token); var author = await localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token);
if (author == default) if (author == default)
return false; return false;
if (quoterUri == author.Uri) if (quoterUri == author.Uri)
@@ -83,11 +71,11 @@ namespace PrivaPub.Domain.Statuses
async Task<bool> Follows(string followerUri, LocalActor author, CancellationToken token) async Task<bool> Follows(string followerUri, LocalActor author, CancellationToken token)
{ {
if (await _dbEntities.Followers.Match(f => f.LocalActorId == author.Id && f.ActorURI == followerUri && f.IsAccepted).ExecuteAnyAsync(token)) if (await dbEntities.Followers.Match(f => f.LocalActorId == author.Id && f.ActorURI == followerUri && f.IsAccepted).ExecuteAnyAsync(token))
return true; return true;
var local = await _localActors.FindByUri(followerUri, token); var local = await localActors.FindByUri(followerUri, token);
return local != default return local != default
&& await _dbEntities.Followings.Match(f => f.AvatarId == local.Id && f.TargetActorURI == author.Uri && f.State == FollowState.Accepted).ExecuteAnyAsync(token); && await dbEntities.Followings.Match(f => f.AvatarId == local.Id && f.TargetActorURI == author.Uri && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
} }
public async Task<string> Grant(LocalActor author, PostEntity quoted, string quotingUri, string quoterUri, CancellationToken token) public async Task<string> Grant(LocalActor author, PostEntity quoted, string quotingUri, string quoterUri, CancellationToken token)
@@ -111,8 +99,8 @@ namespace PrivaPub.Domain.Statuses
Arrival.Drop("misattributed"); Arrival.Drop("misattributed");
return; return;
} }
var quoted = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var quoted = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var author = quoted == default ? default : await _localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token); var author = quoted == default ? default : await localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token);
if (author == default || string.IsNullOrEmpty(actor.InboxURL)) if (author == default || string.IsNullOrEmpty(actor.InboxURL))
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -139,22 +127,22 @@ namespace PrivaPub.Domain.Statuses
answer["type"] = "Reject"; answer["type"] = "Reject";
answer["id"] = author.ActivityUri($"reject-quote-{Guid.NewGuid():N}"); answer["id"] = author.ActivityUri($"reject-quote-{Guid.NewGuid():N}");
} }
await _delivery.Enqueue(author, new[] { actor.InboxURL }, answer, token); await delivery.Enqueue(author, new[] { actor.InboxURL }, answer, token: token);
} }
public async Task<bool> RevokeLicence(PostEntity quoted, PostEntity quoting, CancellationToken token) public async Task<bool> RevokeLicence(PostEntity quoted, PostEntity quoting, CancellationToken token)
{ {
var licence = await DB.Default.Find<QuoteLicence>().Match(l => l.PostId == quoted.ID && l.QuotingObjectURI == quoting.ObjectURI && l.RevokedAt == null).ExecuteFirstAsync(token); var licence = await DB.Default.Find<QuoteLicence>().Match(l => l.PostId == quoted.ID && l.QuotingObjectURI == quoting.ObjectURI && l.RevokedAt == null).ExecuteFirstAsync(token);
var author = licence == default ? default : await _localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token); var author = licence == default ? default : await localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token);
if (author == default) if (author == default)
return false; return false;
await DB.Default.Update<QuoteLicence>().MatchID(licence.ID).Modify(l => l.RevokedAt, DateTime.UtcNow).ExecuteAsync(token); await DB.Default.Update<QuoteLicence>().MatchID(licence.ID).Modify(l => l.RevokedAt, DateTime.UtcNow).ExecuteAsync(token);
var uri = LicenceUri(author, licence.ID); var uri = LicenceUri(author, licence.ID);
await Revoke(uri, token); await Revoke(uri, token);
var quoter = quoting.IsFederatedCopy ? await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == quoting.ActorURI).ExecuteFirstAsync(token) : default; var quoter = quoting.IsFederatedCopy ? await dbEntities.ForeignAvatars.Match(f => f.ActorURI == quoting.ActorURI).ExecuteFirstAsync(token) : default;
var inboxes = (await _delivery.FollowerInboxes(author, token)).Append(quoter?.InboxURL).Where(i => !string.IsNullOrEmpty(i)).Distinct().ToList(); var inboxes = (await delivery.FollowerInboxes(author, token)).Append(quoter?.InboxURL).Where(i => !string.IsNullOrEmpty(i)).Distinct().ToList();
if (inboxes.Count > 0) if (inboxes.Count > 0)
await _delivery.Enqueue(author, inboxes, new JsonObject await delivery.Enqueue(author, inboxes, new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
["id"] = author.ActivityUri($"revoke-quote-{licence.ID}"), ["id"] = author.ActivityUri($"revoke-quote-{licence.ID}"),
@@ -162,14 +150,14 @@ namespace PrivaPub.Domain.Statuses
["actor"] = author.Uri, ["actor"] = author.Uri,
["object"] = uri, ["object"] = uri,
["to"] = new JsonArray(Addressing.Public) ["to"] = new JsonArray(Addressing.Public)
}, token); }, token: token);
return true; return true;
} }
async Task<bool> OurLicence(string stampUri, PostEntity quoting, PostEntity quoted, CancellationToken token) async Task<bool> OurLicence(string stampUri, PostEntity quoting, PostEntity quoted, CancellationToken token)
{ {
var marker = stampUri?.LastIndexOf(LicencePath, StringComparison.Ordinal) ?? -1; var marker = stampUri?.LastIndexOf(LicencePath, StringComparison.Ordinal) ?? -1;
if (marker < 0 || !stampUri.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase)) if (marker < 0 || !stampUri.StartsWith(localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase))
return false; return false;
var id = stampUri[(marker + LicencePath.Length)..]; var id = stampUri[(marker + LicencePath.Length)..];
return await DB.Default.Find<QuoteLicence>().Match(l => l.ID == id && l.PostId == quoted.ID && l.QuotingObjectURI == quoting.ObjectURI && l.RevokedAt == null) return await DB.Default.Find<QuoteLicence>().Match(l => l.ID == id && l.PostId == quoted.ID && l.QuotingObjectURI == quoting.ObjectURI && l.RevokedAt == null)
@@ -191,10 +179,10 @@ namespace PrivaPub.Domain.Statuses
public async Task Request(LocalActor author, PostEntity post, PostEntity quoted, JsonObject note, CancellationToken token) public async Task Request(LocalActor author, PostEntity post, PostEntity quoted, JsonObject note, CancellationToken token)
{ {
var owner = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == quoted.ActorURI).ExecuteFirstAsync(token); var owner = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == quoted.ActorURI).ExecuteFirstAsync(token);
if (string.IsNullOrEmpty(owner?.InboxURL)) if (string.IsNullOrEmpty(owner?.InboxURL))
return; return;
await _delivery.Enqueue(author, new[] { owner.InboxURL }, new JsonObject await delivery.Enqueue(author, new[] { owner.InboxURL }, new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
["id"] = author.ActivityUri(RequestPrefix + post.ID), ["id"] = author.ActivityUri(RequestPrefix + post.ID),
@@ -203,7 +191,7 @@ namespace PrivaPub.Domain.Statuses
["object"] = quoted.ObjectURI, ["object"] = quoted.ObjectURI,
["instrument"] = note.DeepClone(), ["instrument"] = note.DeepClone(),
["to"] = new JsonArray(quoted.ActorURI) ["to"] = new JsonArray(quoted.ActorURI)
}, token); }, token: token);
} }
public async Task<bool> Answered(JsonNode answer, ForeignAvatar actor, bool accepted, CancellationToken token) public async Task<bool> Answered(JsonNode answer, ForeignAvatar actor, bool accepted, CancellationToken token)
@@ -216,11 +204,11 @@ namespace PrivaPub.Domain.Statuses
if (marker < 0) if (marker < 0)
return true; return true;
var postId = requestId[(marker + "/grunts/".Length + RequestPrefix.Length)..]; var postId = requestId[(marker + "/grunts/".Length + RequestPrefix.Length)..];
var post = await _dbEntities.Posts.Match(p => p.ID == postId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == postId && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var author = post == default ? default : await _localActors.FindById(LocalActorKind.Person, post.GroupUserId, token); var author = post == default ? default : await localActors.FindById(LocalActorKind.Person, post.GroupUserId, token);
if (author == default || author.ActivityUri(RequestPrefix + post.ID) != requestId || post.QuoteState != QuoteState.Pending) if (author == default || author.ActivityUri(RequestPrefix + post.ID) != requestId || post.QuoteState != QuoteState.Pending)
return true; return true;
var quoted = await _dbEntities.Posts.MatchID(post.QuotedPostId).ExecuteFirstAsync(token); var quoted = await dbEntities.Posts.MatchID(post.QuotedPostId).ExecuteFirstAsync(token);
if (quoted?.ActorURI != actor.ActorURI) if (quoted?.ActorURI != actor.ActorURI)
return true; return true;
if (!accepted) if (!accepted)
@@ -239,7 +227,7 @@ namespace PrivaPub.Domain.Statuses
.ExecuteAsync(token); .ExecuteAsync(token);
await DB.Default.Update<PostEntity>().MatchID(quoted.ID).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(quoted.ID).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token);
if (!post.IsLocalOnly) if (!post.IsLocalOnly)
await _outbox.PublishUpdate(author, post, $"quote-approved-{DateTime.UtcNow.Ticks}", token); await outbox.PublishUpdate(author, post, $"quote-approved-{DateTime.UtcNow.Ticks}", token);
return true; return true;
} }
@@ -249,8 +237,8 @@ namespace PrivaPub.Domain.Statuses
return; return;
var quoted = note.QuoteUri == default var quoted = note.QuoteUri == default
? default ? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == note.QuoteUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token) : await dbEntities.Posts.Match(p => p.ObjectURI == note.QuoteUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await _remotePosts.StoreContext(note.QuoteUri, RemotePosts.MaxDepth, token); ?? await remotePosts.StoreContext(note.QuoteUri, RemotePosts.MaxDepth, token);
var state = note.QuoteDeleted ? QuoteState.Deleted var state = note.QuoteDeleted ? QuoteState.Deleted
: quoted == default ? QuoteState.Pending : quoted == default ? QuoteState.Pending
@@ -281,13 +269,13 @@ namespace PrivaPub.Domain.Statuses
{ {
await DB.Default.Update<PostEntity>().MatchID(nowCounted).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(nowCounted).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token);
if (!quoted.IsFederatedCopy) if (!quoted.IsFederatedCopy)
await Notifications.Add(quoted.GroupUserId, NotificationType.Quote, post.AuthorAccountId, post.ActorURI, post.ID, token); await Notifications.Add(quoted.GroupUserId, NotificationType.Quote, post.AuthorAccountId, post.ActorURI, post.ID, token: token);
} }
} }
public async Task Revoke(string stampUri, CancellationToken token) public async Task Revoke(string stampUri, CancellationToken token)
{ {
var revoked = await _dbEntities.Posts.Match(p => p.QuoteAuthorizationURI == stampUri && p.QuoteState == QuoteState.Accepted).ExecuteAsync(token); var revoked = await dbEntities.Posts.Match(p => p.QuoteAuthorizationURI == stampUri && p.QuoteState == QuoteState.Accepted).ExecuteAsync(token);
foreach (var post in revoked) foreach (var post in revoked)
{ {
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.QuoteState, QuoteState.Revoked).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.QuoteState, QuoteState.Revoked).ExecuteAsync(token);
@@ -300,7 +288,7 @@ namespace PrivaPub.Domain.Statuses
{ {
if (!Origin.Same(stampUri, quoted.ActorURI)) if (!Origin.Same(stampUri, quoted.ActorURI))
return false; return false;
using var fetched = await _remoteActors.FetchObject(stampUri, token); using var fetched = await remoteActors.FetchObject(stampUri, token);
if (fetched == default) if (fetched == default)
return false; return false;
var stamp = JsonNode.Parse(fetched.Root.GetRawText()); var stamp = JsonNode.Parse(fetched.Root.GetRawText());
+5 -12
View File
@@ -83,17 +83,10 @@ namespace PrivaPub.Domain.Statuses
DB.Default.Update<MediaAttachment>().Match(m => m.ScheduledStatusId == scheduledId).Modify(m => m.ScheduledStatusId, null).ExecuteAsync(token); DB.Default.Update<MediaAttachment>().Match(m => m.ScheduledStatusId == scheduledId).Modify(m => m.ScheduledStatusId, null).ExecuteAsync(token);
} }
public class PublishScheduledJob : IJobHandler public class PublishScheduledJob(
IServiceScopeFactory scopes,
ILogger<PublishScheduledJob> logger) : IJobHandler
{ {
readonly IServiceScopeFactory _scopes;
readonly ILogger<PublishScheduledJob> _logger;
public PublishScheduledJob(IServiceScopeFactory scopes, ILogger<PublishScheduledJob> logger)
{
_scopes = scopes;
_logger = logger;
}
public JobKind Kind => JobKind.PublishScheduled; public JobKind Kind => JobKind.PublishScheduled;
public int Concurrency => 2; public int Concurrency => 2;
public int MaxAttempts => 3; public int MaxAttempts => 3;
@@ -104,7 +97,7 @@ namespace PrivaPub.Domain.Statuses
var scheduled = await DB.Default.Find<ScheduledStatus>().MatchID(job.Payload).ExecuteFirstAsync(token); var scheduled = await DB.Default.Find<ScheduledStatus>().MatchID(job.Payload).ExecuteFirstAsync(token);
if (scheduled == default || scheduled.ScheduledAt > DateTime.UtcNow.AddSeconds(30)) if (scheduled == default || scheduled.ScheduledAt > DateTime.UtcNow.AddSeconds(30))
return JobOutcome.Done;//dropped, or moved to a later time that has its own job return JobOutcome.Done;//dropped, or moved to a later time that has its own job
using var scope = _scopes.CreateScope(); using var scope = scopes.CreateScope();
// a persona suspended since, or whose login was banned, waits: lifting it publishes what came due meanwhile // a persona suspended since, or whose login was banned, waits: lifting it publishes what came due meanwhile
// (R6), unless that was a month ago // (R6), unless that was a month ago
if (Moderation.Restrictions.IsSuspended(scheduled.AvatarId) && scheduled.ScheduledAt > DateTime.UtcNow.AddDays(-30) if (Moderation.Restrictions.IsSuspended(scheduled.AvatarId) && scheduled.ScheduledAt > DateTime.UtcNow.AddDays(-30)
@@ -122,7 +115,7 @@ namespace PrivaPub.Domain.Statuses
{ {
var outcome = await scope.ServiceProvider.GetRequiredService<IStatusService>().Publish(author, ScheduledStatuses.Draft(scheduled.Params, scheduled.ID), token); var outcome = await scope.ServiceProvider.GetRequiredService<IStatusService>().Publish(author, ScheduledStatuses.Draft(scheduled.Params, scheduled.ID), token);
if (!outcome.Ok) if (!outcome.Ok)
_logger.LogWarning("Scheduled status {Id} of {Avatar} could not be published: {Error}", scheduled.ID, scheduled.AvatarId, outcome.Error); logger.LogWarning("Scheduled status {Id} of {Avatar} could not be published: {Error}", scheduled.ID, scheduled.AvatarId, outcome.Error);
} }
await ScheduledStatuses.Release(scheduled.ID, token); await ScheduledStatuses.Release(scheduled.ID, token);
await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID); await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID);
+83 -101
View File
@@ -40,6 +40,7 @@ namespace PrivaPub.Domain.Statuses
public string Language { get; init; } public string Language { get; init; }
public string ConversationId { get; init; } public string ConversationId { get; init; }
public IReadOnlyList<string> Recipients { get; init; } = Array.Empty<string>(); public IReadOnlyList<string> Recipients { get; init; } = Array.Empty<string>();
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "Null on an edit keeps the post's media; an empty list removes it, as on Mastodon.")]
public IReadOnlyList<string> MediaIds { get; init; } public IReadOnlyList<string> MediaIds { get; init; }
public IReadOnlyList<MediaChange> MediaChanges { get; init; } = Array.Empty<MediaChange>(); public IReadOnlyList<MediaChange> MediaChanges { get; init; } = Array.Empty<MediaChange>();
// the scheduled post being published, whose media are reserved for it alone // the scheduled post being published, whose media are reserved for it alone
@@ -68,42 +69,23 @@ namespace PrivaPub.Domain.Statuses
Task<StatusOutcome> Reblog(LocalActor me, string postId, bool on, PostVisibility visibility, CancellationToken token); Task<StatusOutcome> Reblog(LocalActor me, string postId, bool on, PostVisibility visibility, CancellationToken token);
} }
public class StatusService : IStatusService public class StatusService(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IDeliveryService deliveryService,
IContentRenderer content,
IOutboxPublisher outbox,
IFanout fanout,
IMediaService mediaService,
IGroupDistributor groupDistributor,
IPollService polls,
ILinkPreviews previews,
IQuoteService quotes,
IInteractionApprovals approvals = default) : IStatusService
{ {
const int MaxRevisions = 20; const int MaxRevisions = 20;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDeliveryService _delivery;
readonly IContentRenderer _content;
readonly IOutboxPublisher _outbox;
readonly IFanout _fanout;
readonly IMediaService _media;
readonly IGroupDistributor _groups;
readonly IPollService _polls;
readonly ILinkPreviews _previews;
readonly IQuoteService _quotes;
readonly IInteractionApprovals _approvals;
public StatusService(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery,
IContentRenderer content, IOutboxPublisher outbox, IFanout fanout, IMediaService media, IGroupDistributor groups, IPollService polls,
ILinkPreviews previews, IQuoteService quotes, IInteractionApprovals approvals = default)
{
_approvals = approvals;
_previews = previews;
_quotes = quotes;
_polls = polls;
_media = media;
_groups = groups;
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_delivery = delivery;
_content = content;
_outbox = outbox;
_fanout = fanout;
}
public const int MaxCharacters = 5000;//what the instance API advertises as max_characters, and enforced here public const int MaxCharacters = 5000;//what the instance API advertises as max_characters, and enforced here
@@ -121,16 +103,16 @@ namespace PrivaPub.Domain.Statuses
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Media attachments are invalid"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Media attachments are invalid");
if (string.IsNullOrWhiteSpace(draft.Text) && media.Count == 0 && draft.Poll == default) if (string.IsNullOrWhiteSpace(draft.Text) && media.Count == 0 && draft.Poll == default)
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Text can't be blank"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Text can't be blank");
if (draft.Poll != default && _polls.Invalid(draft.Poll) is { } invalidPoll) if (draft.Poll != default && polls.Invalid(draft.Poll) is { } invalidPoll)
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, invalidPoll); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, invalidPoll);
LocalActor group = default; LocalActor group = default;
if (!string.IsNullOrEmpty(draft.GroupId)) if (!string.IsNullOrEmpty(draft.GroupId))
{ {
var groupEntity = await _dbEntities.Groups.MatchID(draft.GroupId).ExecuteFirstAsync(token); var groupEntity = await dbEntities.Groups.MatchID(draft.GroupId).ExecuteFirstAsync(token);
if (groupEntity == default || groupEntity.DeletionAt.HasValue || !await MayPost(groupEntity, author, token)) if (groupEntity == default || groupEntity.DeletionAt.HasValue || !await MayPost(groupEntity, author, token))
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Group not found"); return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Group not found");
group = _localActors.FromGroup(groupEntity); group = localActors.FromGroup(groupEntity);
} }
var parent = await Parent(draft.InReplyTo, token); var parent = await Parent(draft.InReplyTo, token);
@@ -147,18 +129,18 @@ namespace PrivaPub.Domain.Statuses
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Its author does not take replies from you"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Its author does not take replies from you");
// a reply in a circle stays in the circle, whichever client wrote it: Mastodon clients know nothing of groups // a reply in a circle stays in the circle, whichever client wrote it: Mastodon clients know nothing of groups
if (group == default && parent is { Visibility: PostVisibility.Circle } && !string.IsNullOrEmpty(parent.GroupId) if (group == default && parent is { Visibility: PostVisibility.Circle } && !string.IsNullOrEmpty(parent.GroupId)
&& await _dbEntities.Groups.MatchID(parent.GroupId).ExecuteFirstAsync(token) is { DeletionAt: null } parentCircle && await dbEntities.Groups.MatchID(parent.GroupId).ExecuteFirstAsync(token) is { DeletionAt: null } parentCircle
&& await MayPost(parentCircle, author, token)) && await MayPost(parentCircle, author, token))
group = _localActors.FromGroup(parentCircle); group = localActors.FromGroup(parentCircle);
PostEntity quoted = default; PostEntity quoted = default;
var quotePermission = QuotePermission.Denied; var quotePermission = QuotePermission.Denied;
if (!string.IsNullOrEmpty(draft.QuotedStatusId)) if (!string.IsNullOrEmpty(draft.QuotedStatusId))
{ {
quoted = await _dbEntities.Posts.Match(p => p.ID == draft.QuotedStatusId && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token); quoted = await dbEntities.Posts.Match(p => p.ID == draft.QuotedStatusId && !p.DeletedAt.HasValue && p.ReblogOfPostId == null).ExecuteFirstAsync(token);
if (quoted == default || !await VisibilityPolicy.CanSee(quoted, author.Id, token)) if (quoted == default || !await VisibilityPolicy.CanSee(quoted, author.Id, token))
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found"); return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found");
quotePermission = await _quotes.Permission(quoted, author, token); quotePermission = await quotes.Permission(quoted, author, token);
if (quotePermission == QuotePermission.Denied) if (quotePermission == QuotePermission.Denied)
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: This post cannot be quoted"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: This post cannot be quoted");
} }
@@ -168,21 +150,21 @@ namespace PrivaPub.Domain.Statuses
|| draft.Visibility == PostVisibility.Direct)) || draft.Visibility == PostVisibility.Direct))
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: A located post needs a valid position and no group or recipients"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: A located post needs a valid position and no group or recipients");
var rendered = draft.PlainText ? await _content.PlainText(draft.Text ?? string.Empty, token) : await _content.Markdown(draft.Text ?? string.Empty, token); var rendered = draft.PlainText ? await content.PlainText(draft.Text ?? string.Empty, token) : await content.Markdown(draft.Text ?? string.Empty, token);
string audienceUri = default; string audienceUri = default;
if (group == default && !located && draft.Visibility is PostVisibility.Public or PostVisibility.Unlisted) if (group == default && !located && draft.Visibility is PostVisibility.Public or PostVisibility.Unlisted)
foreach (var mention in rendered.Mentions) foreach (var mention in rendered.Mentions)
{ {
if (mention.IsLocal) if (mention.IsLocal)
{ {
var mentioned = await _dbEntities.Groups.MatchID(mention.AccountId).ExecuteFirstAsync(token); var mentioned = await dbEntities.Groups.MatchID(mention.AccountId).ExecuteFirstAsync(token);
if (mentioned is { DeletionAt: null, Kind: GroupKind.Community } && await MayPost(mentioned, author, token)) if (mentioned is { DeletionAt: null, Kind: GroupKind.Community } && await MayPost(mentioned, author, token))
{ {
group = _localActors.FromGroup(mentioned); group = localActors.FromGroup(mentioned);
break; break;
} }
} }
else if (await _dbEntities.ForeignAvatars.MatchID(mention.AccountId).ExecuteFirstAsync(token) is { AvatarType: Models.User.AvatarType.Group } remoteGroup) else if (await dbEntities.ForeignAvatars.MatchID(mention.AccountId).ExecuteFirstAsync(token) is { AvatarType: Models.User.AvatarType.Group } remoteGroup)
{ {
audienceUri = remoteGroup.ActorURI; audienceUri = remoteGroup.ActorURI;
break; break;
@@ -223,7 +205,7 @@ namespace PrivaPub.Domain.Statuses
InReplyToActorURI = parent is { IsFederatedCopy: true } ? parent.ActorURI : default, InReplyToActorURI = parent is { IsFederatedCopy: true } ? parent.ActorURI : default,
IsLocalOnly = isLocalOnly, IsLocalOnly = isLocalOnly,
ActorURI = author.Uri, ActorURI = author.Uri,
Poll = draft.Poll == default ? default : _polls.Create(draft.Poll), Poll = draft.Poll == default ? default : polls.Create(draft.Poll),
QuoteURI = quoted?.ObjectURI, QuoteURI = quoted?.ObjectURI,
QuotedPostId = quoted?.ID, QuotedPostId = quoted?.ID,
QuoteByConsent = quoted != default && (quoted.QuotePolicy != default || !quoted.IsFederatedCopy), QuoteByConsent = quoted != default && (quoted.QuotePolicy != default || !quoted.IsFederatedCopy),
@@ -239,8 +221,8 @@ namespace PrivaPub.Domain.Statuses
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Media attachments are invalid"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Media attachments are invalid");
post.LocalQuotePolicy = QuotePolicies.IsKnown(draft.QuotePolicy) ? draft.QuotePolicy : author.Settings.QuotePolicy ?? QuotePolicies.Public; post.LocalQuotePolicy = QuotePolicies.IsKnown(draft.QuotePolicy) ? draft.QuotePolicy : author.Settings.QuotePolicy ?? QuotePolicies.Public;
if (quoted is { IsFederatedCopy: false } && post.QuoteState == QuoteState.Accepted if (quoted is { IsFederatedCopy: false } && post.QuoteState == QuoteState.Accepted
&& await _localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token) is { } quotedAuthor) && await localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token) is { } quotedAuthor)
post.QuoteAuthorizationURI = await _quotes.Grant(quotedAuthor, quoted, post.ObjectURI, author.Uri, token); post.QuoteAuthorizationURI = await quotes.Grant(quotedAuthor, quoted, post.ObjectURI, author.Uri, token);
if (located) if (located)
{ {
post.Geo = new Coordinates2D(Math.Round(draft.Longitude.Value, 2), Math.Round(draft.Latitude.Value, 2)); post.Geo = new Coordinates2D(Math.Round(draft.Longitude.Value, 2), Math.Round(draft.Latitude.Value, 2));
@@ -263,7 +245,7 @@ namespace PrivaPub.Domain.Statuses
// to one account elsewhere, as a ChatMessage when it writes to us that way, or when its server takes a private message // to one account elsewhere, as a ChatMessage when it writes to us that way, or when its server takes a private message
// no other way (Lemmy 0.19 and Mbin) // no other way (Lemmy 0.19 and Mbin)
post.AsChatMessage = recipients is [{ LocalId: null } recipient] && (await TakesOnlyChatMessages(recipient.Uri, token) post.AsChatMessage = recipients is [{ LocalId: null } recipient] && (await TakesOnlyChatMessages(recipient.Uri, token)
|| await _dbEntities.Posts.Match(p => p.ActorURI == recipient.Uri && p.IsFederatedCopy && p.ObjectType == "ChatMessage").ExecuteAnyAsync(token)); || await dbEntities.Posts.Match(p => p.ActorURI == recipient.Uri && p.IsFederatedCopy && p.ObjectType == "ChatMessage").ExecuteAnyAsync(token));
var note = ActivityPubRenderer.DirectNote(post, author, recipients.Select(r => (r.Uri, r.Handle)).ToList(), dmGroup.ConversationURI); var note = ActivityPubRenderer.DirectNote(post, author, recipients.Select(r => (r.Uri, r.Handle)).ToList(), dmGroup.ConversationURI);
create = ActivityPubRenderer.Create(author, note, $"create-{post.ID}"); create = ActivityPubRenderer.Create(author, note, $"create-{post.ID}");
post.To = Strings(note["to"]); post.To = Strings(note["to"]);
@@ -284,22 +266,22 @@ namespace PrivaPub.Domain.Statuses
await DB.Default.SaveAsync(post, token); await DB.Default.SaveAsync(post, token);
if (parent != default && Counted.Reply(post)) if (parent != default && Counted.Reply(post))
await DB.Default.Update<PostEntity>().MatchID(parent.ID).Modify(b => b.Inc(p => p.RepliesCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(parent.ID).Modify(b => b.Inc(p => p.RepliesCount, 1)).ExecuteAsync(token);
await _fanout.Distribute(post, token); await fanout.Distribute(post, token);
if (post.Visibility == PostVisibility.Direct) if (post.Visibility == PostVisibility.Direct)
await Fanout.Conversation(post.ConversationId, token);//the `direct` streams (R8), now that it is saved await Fanout.Conversation(post.ConversationId, token);//the `direct` streams (R8), now that it is saved
await _polls.Scheduled(post, token); await polls.Scheduled(post, token);
if (post.QuoteState == QuoteState.Accepted) if (post.QuoteState == QuoteState.Accepted)
await DB.Default.Update<PostEntity>().MatchID(quoted.ID).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(quoted.ID).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token);
if (post.QuoteState == QuoteState.Pending && create?["object"] is JsonObject quotingNote) if (post.QuoteState == QuoteState.Pending && create?["object"] is JsonObject quotingNote)
await _quotes.Request(author, post, quoted, quotingNote, token); await quotes.Request(author, post, quoted, quotingNote, token);
await _previews.Wanted(post, token); await previews.Wanted(post, token);
// a reply its parent's author must approve goes to that author alone, as a request, until it is approved // a reply its parent's author must approve goes to that author alone, as a request, until it is approved
if (create != default && post.Approval == ApprovalState.Pending) if (create != default && post.Approval == ApprovalState.Pending)
await _approvals.Ask(author, parent, InteractionKind.Reply, create["object"].AsObject(), post.ID, token); await approvals.Ask(author, parent, InteractionKind.Reply, create["object"].AsObject(), post.ID, token);
else if (create != default) else if (create != default)
await _outbox.Publish(author, post, create, token); await outbox.Publish(author, post, create, token);
if (create != default && post.Approval != ApprovalState.Pending && group is { IsCircle: false } && visibility is PostVisibility.Public or PostVisibility.Unlisted) if (create != default && post.Approval != ApprovalState.Pending && group is { IsCircle: false } && visibility is PostVisibility.Public or PostVisibility.Unlisted)
await _groups.Announce(group, create, post.ObjectURI, isNewPost: true, token); await groupDistributor.Announce(group, create, post.ObjectURI, isNewPost: true, token);
return new StatusOutcome(post); return new StatusOutcome(post);
} }
@@ -333,7 +315,7 @@ namespace PrivaPub.Domain.Statuses
post.Revisions.RemoveRange(0, post.Revisions.Count - MaxRevisions); post.Revisions.RemoveRange(0, post.Revisions.Count - MaxRevisions);
var plain = draft.PlainText || post.ContentFormat == ContentFormat.Plain; var plain = draft.PlainText || post.ContentFormat == ContentFormat.Plain;
var rendered = plain ? await _content.PlainText(draft.Text ?? string.Empty, token) : await _content.Markdown(draft.Text ?? string.Empty, token); var rendered = plain ? await content.PlainText(draft.Text ?? string.Empty, token) : await content.Markdown(draft.Text ?? string.Empty, token);
// descriptions and focal points changed by the edit, on the media it keeps or those the post already has // descriptions and focal points changed by the edit, on the media it keeps or those the post already has
var described = media ?? (draft.MediaChanges.Count > 0 var described = media ?? (draft.MediaChanges.Count > 0
? await DB.Default.Find<MediaAttachment>().Match(m => m.PostId == post.ID && m.TrashedAt == null).ExecuteAsync(token) ? await DB.Default.Find<MediaAttachment>().Match(m => m.PostId == post.ID && m.TrashedAt == null).ExecuteAsync(token)
@@ -358,7 +340,7 @@ namespace PrivaPub.Domain.Statuses
post.Media = media.Select(ToPostMedia).ToList(); post.Media = media.Select(ToPostMedia).ToList();
// what the edit left out is no longer held by anything // what the edit left out is no longer held by anything
var kept = media.Select(m => m.ID).ToList(); var kept = media.Select(m => m.ID).ToList();
await _media.Trash(m => m.PostId == post.ID && !kept.Contains(m.ID), "edited out", token); await mediaService.Trash(m => m.PostId == post.ID && !kept.Contains(m.ID), "edited out", token);
} }
post.Title = draft.Title == default ? post.Title : Clean(draft.Title); post.Title = draft.Title == default ? post.Title : Clean(draft.Title);
// as on Mastodon, an edit sends the whole post: no warning sent is no warning (the language alone falls back) // as on Mastodon, an edit sends the whole post: no warning sent is no warning (the language alone falls back)
@@ -379,7 +361,7 @@ namespace PrivaPub.Domain.Statuses
if (!post.IsLocalOnly) if (!post.IsLocalOnly)
{ {
var group = string.IsNullOrEmpty(post.GroupId) ? default : await _localActors.FindById(LocalActorKind.Group, post.GroupId, token); var group = string.IsNullOrEmpty(post.GroupId) ? default : await localActors.FindById(LocalActorKind.Group, post.GroupId, token);
var note = post.Visibility == PostVisibility.Direct var note = post.Visibility == PostVisibility.Direct
? ActivityPubRenderer.DirectNote(post, author, Array.Empty<(string, string)>(), post.ContextURI) ? ActivityPubRenderer.DirectNote(post, author, Array.Empty<(string, string)>(), post.ContextURI)
: ActivityPubRenderer.Note(post, author, group, post.InReplyToURI); : ActivityPubRenderer.Note(post, author, group, post.InReplyToURI);
@@ -395,22 +377,22 @@ namespace PrivaPub.Domain.Statuses
["cc"] = note["cc"]!.DeepClone(), ["cc"] = note["cc"]!.DeepClone(),
["object"] = note ["object"] = note
}; };
await _outbox.Publish(author, post, update, token); await outbox.Publish(author, post, update, token);
if (group is { IsCircle: false }) if (group is { IsCircle: false })
await _groups.Announce(group, update, post.ObjectURI, isNewPost: false, token); await groupDistributor.Announce(group, update, post.ObjectURI, isNewPost: false, token);
} }
return new StatusOutcome(post); return new StatusOutcome(post);
} }
public async Task<StatusOutcome> Remove(LocalActor author, string postId, CancellationToken token) public async Task<StatusOutcome> Remove(LocalActor author, string postId, CancellationToken token)
{ {
var post = await _dbEntities.Posts.Match(p => p.ID == postId && p.GroupUserId == author.Id && !p.IsFederatedCopy).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == postId && p.GroupUserId == author.Id && !p.IsFederatedCopy).ExecuteFirstAsync(token);
if (post == default || post.DeletedAt.HasValue) if (post == default || post.DeletedAt.HasValue)
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found"); return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found");
if (post.ReblogOfPostId != default) if (post.ReblogOfPostId != default)
return await Reblog(author, post.ReblogOfPostId, false, post.Visibility, token); return await Reblog(author, post.ReblogOfPostId, false, post.Visibility, token);
var audience = await _outbox.Audience(author, post, token); var audience = await outbox.Audience(author, post, token);
await DB.Default.Update<PostEntity>().MatchID(post.ID) await DB.Default.Update<PostEntity>().MatchID(post.ID)
.Modify(p => p.DeletedAt, DateTime.UtcNow) .Modify(p => p.DeletedAt, DateTime.UtcNow)
.Modify(p => p.Text, null) .Modify(p => p.Text, null)
@@ -421,7 +403,7 @@ namespace PrivaPub.Domain.Statuses
.Modify(p => p.Revisions, new List<PostRevision>()) .Modify(p => p.Revisions, new List<PostRevision>())
.ExecuteAsync(token); .ExecuteAsync(token);
await Fanout.Deleting(post, token); await Fanout.Deleting(post, token);
await _media.Trash(m => m.PostId == post.ID, "post deleted", token); await mediaService.Trash(m => m.PostId == post.ID, "post deleted", token);
await DB.Default.DeleteAsync<TimelineEntry>(e => e.PostId == post.ID || e.ReblogOfPostId == post.ID); await DB.Default.DeleteAsync<TimelineEntry>(e => e.PostId == post.ID || e.ReblogOfPostId == post.ID);
// boosts of it end with it, as on Mastodon, so no count keeps them // boosts of it end with it, as on Mastodon, so no count keeps them
await DB.Default.Update<PostEntity>().Match(p => p.ReblogOfPostId == post.ID && !p.DeletedAt.HasValue) await DB.Default.Update<PostEntity>().Match(p => p.ReblogOfPostId == post.ID && !p.DeletedAt.HasValue)
@@ -433,10 +415,10 @@ namespace PrivaPub.Domain.Statuses
{ {
var delete = ActivityPubRenderer.Delete(author, post.ObjectURI, $"delete-{post.ID}", var delete = ActivityPubRenderer.Delete(author, post.ObjectURI, $"delete-{post.ID}",
new JsonArray(post.To.Select(t => (JsonNode)t).ToArray()), new JsonArray(post.Cc.Select(c => (JsonNode)c).ToArray())); new JsonArray(post.To.Select(t => (JsonNode)t).ToArray()), new JsonArray(post.Cc.Select(c => (JsonNode)c).ToArray()));
await _outbox.Publish(author, post, delete, token);//the post in hand still has its group and mentions await outbox.Publish(author, post, delete, token);//the post in hand still has its group and mentions
var group = string.IsNullOrEmpty(post.GroupId) ? default : await _localActors.FindById(LocalActorKind.Group, post.GroupId, token); var group = string.IsNullOrEmpty(post.GroupId) ? default : await localActors.FindById(LocalActorKind.Group, post.GroupId, token);
if (group is { IsCircle: false }) if (group is { IsCircle: false })
await _groups.Announce(group, delete, post.ObjectURI, isNewPost: false, token); await groupDistributor.Announce(group, delete, post.ObjectURI, isNewPost: false, token);
} }
return new StatusOutcome(post); return new StatusOutcome(post);
} }
@@ -475,7 +457,7 @@ namespace PrivaPub.Domain.Statuses
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(b => b.Inc(p => p.FavouritesCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(b => b.Inc(p => p.FavouritesCount, 1)).ExecuteAsync(token);
post.FavouritesCount++; post.FavouritesCount++;
if (!post.IsFederatedCopy) if (!post.IsFederatedCopy)
await Notifications.Add(post.GroupUserId, NotificationType.Favourite, me.Id, me.Uri, post.ID, token); await Notifications.Add(post.GroupUserId, NotificationType.Favourite, me.Id, me.Uri, post.ID, token: token);
} }
else else
{ {
@@ -497,9 +479,9 @@ namespace PrivaPub.Domain.Statuses
["object"] = post.ObjectURI ["object"] = post.ObjectURI
}; };
if (on && favourite.Approval == ApprovalState.Pending) if (on && favourite.Approval == ApprovalState.Pending)
await _approvals.Ask(me, post, InteractionKind.Like, like, favourite.ID, token); await approvals.Ask(me, post, InteractionKind.Like, like, favourite.ID, token);
else else
await _delivery.Enqueue(me, inboxes, on ? like : Undo(me, like, $"undo-like-{favourite.ID}"), token); await deliveryService.Enqueue(me, inboxes, on ? like : Undo(me, like, $"undo-like-{favourite.ID}"), token: token);
} }
return new StatusOutcome(post); return new StatusOutcome(post);
} }
@@ -517,7 +499,7 @@ namespace PrivaPub.Domain.Statuses
if (post == default) if (post == default)
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found"); return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found");
Downvote downvote; var downvote = default(Downvote);
if (on) if (on)
{ {
await Forget<Favourite>(f => f.AccountId == me.Id && f.PostId == post.ID, post, p => p.FavouritesCount, token); await Forget<Favourite>(f => f.AccountId == me.Id && f.PostId == post.ID, post, p => p.FavouritesCount, token);
@@ -553,7 +535,7 @@ namespace PrivaPub.Domain.Statuses
["actor"] = me.Uri, ["actor"] = me.Uri,
["object"] = post.ObjectURI ["object"] = post.ObjectURI
}; };
await _delivery.Enqueue(me, inboxes, on ? dislike : Undo(me, dislike, $"undo-dislike-{downvote.ID}"), token); await deliveryService.Enqueue(me, inboxes, on ? dislike : Undo(me, dislike, $"undo-dislike-{downvote.ID}"), token: token);
} }
return new StatusOutcome(post); return new StatusOutcome(post);
} }
@@ -578,11 +560,11 @@ namespace PrivaPub.Domain.Statuses
async Task<List<string>> VoteInboxes(PostEntity post, CancellationToken token) async Task<List<string>> VoteInboxes(PostEntity post, CancellationToken token)
{ {
var inboxes = new List<string>(); var inboxes = new List<string>();
if (await Federation.Inbox.Communities.Of(post, _dbEntities, token) is { } communityUri if (await Federation.Inbox.Communities.Of(post, dbEntities, token) is { } communityUri
&& await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == communityUri && f.AvatarType == AvatarType.Group).ExecuteFirstAsync(token) is { } community && await dbEntities.ForeignAvatars.Match(f => f.ActorURI == communityUri && f.AvatarType == AvatarType.Group).ExecuteFirstAsync(token) is { } community
&& !string.IsNullOrEmpty(community.InboxURL)) && !string.IsNullOrEmpty(community.InboxURL))
inboxes.Add(community.InboxURL); inboxes.Add(community.InboxURL);
if (await AuthorInbox(post, token) is { } author if (await AuthorInbox(post, token: token) is { } author
&& !inboxes.Any(i => string.Equals(new Uri(i).Authority, new Uri(author).Authority, StringComparison.OrdinalIgnoreCase))) && !inboxes.Any(i => string.Equals(new Uri(i).Authority, new Uri(author).Authority, StringComparison.OrdinalIgnoreCase)))
inboxes.Add(author); inboxes.Add(author);
return inboxes; return inboxes;
@@ -590,7 +572,7 @@ namespace PrivaPub.Domain.Statuses
// how a remote post's interaction policy takes an interaction of ours: at once, once asked, or not at all // how a remote post's interaction policy takes an interaction of ours: at once, once asked, or not at all
async Task<QuotePermission> Permission(PostEntity target, LocalActor actor, InteractionKind kind, CancellationToken token) => async Task<QuotePermission> Permission(PostEntity target, LocalActor actor, InteractionKind kind, CancellationToken token) =>
target is { IsFederatedCopy: true } && _approvals != default ? await _approvals.Judge(target, actor, kind, token) : QuotePermission.Granted; target is { IsFederatedCopy: true } && approvals != default ? await approvals.Judge(target, actor, kind, token) : QuotePermission.Granted;
public async Task<StatusOutcome> Reblog(LocalActor me, string postId, bool on, PostVisibility visibility, CancellationToken token) public async Task<StatusOutcome> Reblog(LocalActor me, string postId, bool on, PostVisibility visibility, CancellationToken token)
{ {
@@ -605,7 +587,7 @@ namespace PrivaPub.Domain.Statuses
if (announcePermission == QuotePermission.Denied) if (announcePermission == QuotePermission.Denied)
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Its author does not take boosts from you"); return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Its author does not take boosts from you");
var existing = await _dbEntities.Posts.Match(p => p.ReblogOfPostId == original.ID && p.AuthorAccountId == me.Id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var existing = await dbEntities.Posts.Match(p => p.ReblogOfPostId == original.ID && p.AuthorAccountId == me.Id && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
// each boost is an activity of its own, as Mastodon's are: a boost after an unboost is a new Announce, which no // each boost is an activity of its own, as Mastodon's are: a boost after an unboost is a new Announce, which no
// server (and no delivery queue) takes for the one already undone; an unboost undoes the boost it ends // server (and no delivery queue) takes for the one already undone; an unboost undoes the boost it ends
var reblogId = existing?.ID ?? ObjectId.GenerateNewId().ToString(); var reblogId = existing?.ID ?? ObjectId.GenerateNewId().ToString();
@@ -647,10 +629,10 @@ namespace PrivaPub.Domain.Statuses
} }
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
{ {
return new StatusOutcome(await _dbEntities.Posts.Match(p => p.ObjectURI == announceId).ExecuteFirstAsync(token)); return new StatusOutcome(await dbEntities.Posts.Match(p => p.ObjectURI == announceId).ExecuteFirstAsync(token));
} }
// two boosts at once: the first one saved stands, and the other goes // two boosts at once: the first one saved stands, and the other goes
var boosts = await _dbEntities.Posts.Match(p => p.ReblogOfPostId == original.ID && p.AuthorAccountId == me.Id && !p.DeletedAt.HasValue) var boosts = await dbEntities.Posts.Match(p => p.ReblogOfPostId == original.ID && p.AuthorAccountId == me.Id && !p.DeletedAt.HasValue)
.Sort(p => p.ID, Order.Ascending).ExecuteAsync(token); .Sort(p => p.ID, Order.Ascending).ExecuteAsync(token);
if (boosts.Count > 1 && boosts[0].ID != reblog.ID) if (boosts.Count > 1 && boosts[0].ID != reblog.ID)
{ {
@@ -659,12 +641,12 @@ namespace PrivaPub.Domain.Statuses
} }
await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, 1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, 1)).ExecuteAsync(token);
if (!original.IsFederatedCopy) if (!original.IsFederatedCopy)
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, me.Id, me.Uri, original.ID, token); await Notifications.Add(original.GroupUserId, NotificationType.Reblog, me.Id, me.Uri, original.ID, token: token);
await _fanout.Distribute(reblog, token); await fanout.Distribute(reblog, token);
if (reblog.Approval == ApprovalState.Pending) if (reblog.Approval == ApprovalState.Pending)
await _approvals.Ask(me, original, InteractionKind.Announce, announce, reblog.ID, token); await approvals.Ask(me, original, InteractionKind.Announce, announce, reblog.ID, token);
else else
await _delivery.EnqueueToFollowers(me, announce, token, await AuthorInbox(original, token, shared: true) is { } inbox ? new[] { inbox } : default); await deliveryService.EnqueueToFollowers(me, announce, await AuthorInbox(original, shared: true, token) is { } inbox ? new[] { inbox } : default, token);
return new StatusOutcome(reblog); return new StatusOutcome(reblog);
} }
@@ -674,8 +656,8 @@ namespace PrivaPub.Domain.Statuses
await DB.Default.DeleteAsync<PostEntity>(existing.ID); await DB.Default.DeleteAsync<PostEntity>(existing.ID);
await DB.Default.DeleteAsync<TimelineEntry>(e => e.PostId == existing.ID); await DB.Default.DeleteAsync<TimelineEntry>(e => e.PostId == existing.ID);
await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, -1)).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, -1)).ExecuteAsync(token);
await _delivery.EnqueueToFollowers(me, Undo(me, announce, $"undo-announce-{existing.ID}"), token, await deliveryService.EnqueueToFollowers(me, Undo(me, announce, $"undo-announce-{existing.ID}"),
await AuthorInbox(original, token, shared: true) is { } authorInbox ? new[] { authorInbox } : default); await AuthorInbox(original, shared: true, token) is { } authorInbox ? new[] { authorInbox } : default, token);
return new StatusOutcome(original); return new StatusOutcome(original);
} }
@@ -708,7 +690,7 @@ namespace PrivaPub.Domain.Statuses
DmGroup dmGroup = default; DmGroup dmGroup = default;
if (!string.IsNullOrEmpty(draft.ConversationId)) if (!string.IsNullOrEmpty(draft.ConversationId))
{ {
dmGroup = await _dbEntities.DmGroups.MatchID(draft.ConversationId).ExecuteFirstAsync(token); dmGroup = await dbEntities.DmGroups.MatchID(draft.ConversationId).ExecuteFirstAsync(token);
if (dmGroup == default || !dmGroup.Members.Any(m => !m.IsForeign && m.AvatarId == author.Id)) if (dmGroup == default || !dmGroup.Members.Any(m => !m.IsForeign && m.AvatarId == author.Id))
return new(default, default, StatusCodes.Status404NotFound, "Conversation not found"); return new(default, default, StatusCodes.Status404NotFound, "Conversation not found");
} }
@@ -733,7 +715,7 @@ namespace PrivaPub.Domain.Statuses
return new(default, default, StatusCodes.Status422UnprocessableEntity, "Validation failed: A direct message needs at least one recipient"); return new(default, default, StatusCodes.Status422UnprocessableEntity, "Validation failed: A direct message needs at least one recipient");
var key = DmGroup.KeyOf(members); var key = DmGroup.KeyOf(members);
dmGroup = await _dbEntities.DmGroups.Match(g => g.ParticipantsKey == key && !g.DeletionAt.HasValue).ExecuteFirstAsync(token); dmGroup = await dbEntities.DmGroups.Match(g => g.ParticipantsKey == key && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (dmGroup == default) if (dmGroup == default)
{ {
dmGroup = new DmGroup { Members = members, ParticipantsKey = key }; dmGroup = new DmGroup { Members = members, ParticipantsKey = key };
@@ -748,11 +730,11 @@ namespace PrivaPub.Domain.Statuses
{ {
if (member.IsForeign) if (member.IsForeign)
{ {
var foreign = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == member.AvatarId).ExecuteFirstAsync(token); var foreign = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == member.AvatarId).ExecuteFirstAsync(token);
if (foreign != default) if (foreign != default)
recipients.Add(new Recipient(foreign.ActorURI, $"{foreign.UserName}@{foreign.Domain}", default, foreign.ID, foreign.InboxURL)); recipients.Add(new Recipient(foreign.ActorURI, $"{foreign.UserName}@{foreign.Domain}", default, foreign.ID, foreign.InboxURL));
} }
else if (await _localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } local) else if (await localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } local)
recipients.Add(new Recipient(local.Uri, local.Handle, local.Id, default, default)); recipients.Add(new Recipient(local.Uri, local.Handle, local.Id, default, default));
} }
return new(dmGroup, recipients); return new(dmGroup, recipients);
@@ -761,13 +743,13 @@ namespace PrivaPub.Domain.Statuses
async Task<GroupMember> ResolveRecipient(string recipient, CancellationToken token) async Task<GroupMember> ResolveRecipient(string recipient, CancellationToken token)
{ {
var handle = recipient.Trim().TrimStart('@'); var handle = recipient.Trim().TrimStart('@');
if (!handle.Contains('@') || handle.EndsWith("@" + new Uri(_localActors.BaseAddress).Authority, StringComparison.OrdinalIgnoreCase)) if (!handle.Contains('@') || handle.EndsWith("@" + new Uri(localActors.BaseAddress).Authority, StringComparison.OrdinalIgnoreCase))
{ {
var local = await _localActors.FindByUserName(handle.Split('@')[0], token); var local = await localActors.FindByUserName(handle.Split('@')[0], token);
return local is { Kind: LocalActorKind.Person } ? new GroupMember { AvatarId = local.Id } : default; return local is { Kind: LocalActorKind.Person } ? new GroupMember { AvatarId = local.Id } : default;
} }
var actorUri = await _remoteActors.ResolveHandle(handle, token); var actorUri = await remoteActors.ResolveHandle(handle, token);
var foreign = actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token); var foreign = actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token);
return foreign == default ? default : new GroupMember { AvatarId = foreign.ActorURI, IsForeign = true }; return foreign == default ? default : new GroupMember { AvatarId = foreign.ActorURI, IsForeign = true };
} }
@@ -776,27 +758,27 @@ namespace PrivaPub.Domain.Statuses
if (string.IsNullOrEmpty(reference)) if (string.IsNullOrEmpty(reference))
return default; return default;
return IsRemoteUri(reference) return IsRemoteUri(reference)
? await _dbEntities.Posts.Match(p => p.ObjectURI == reference && !p.DeletedAt.HasValue).ExecuteFirstAsync(token) ? await dbEntities.Posts.Match(p => p.ObjectURI == reference && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
: await _dbEntities.Posts.Match(p => p.ID == reference && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); : await dbEntities.Posts.Match(p => p.ID == reference && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
} }
async Task<PostEntity> Own(LocalActor author, string postId, CancellationToken token) => async Task<PostEntity> Own(LocalActor author, string postId, CancellationToken token) =>
await _dbEntities.Posts.Match(p => p.ID == postId && p.GroupUserId == author.Id && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null) await dbEntities.Posts.Match(p => p.ID == postId && p.GroupUserId == author.Id && !p.IsFederatedCopy && !p.DeletedAt.HasValue && p.ReblogOfPostId == null)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
async Task<PostEntity> Visible(LocalActor me, string postId, CancellationToken token) async Task<PostEntity> Visible(LocalActor me, string postId, CancellationToken token)
{ {
var post = string.IsNullOrEmpty(postId) ? default : await _dbEntities.Posts.Match(p => p.ID == postId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var post = string.IsNullOrEmpty(postId) ? default : await dbEntities.Posts.Match(p => p.ID == postId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return post != default && await VisibilityPolicy.CanSee(post, me.Id, token) ? post : default; return post != default && await VisibilityPolicy.CanSee(post, me.Id, token) ? post : default;
} }
// shared: what goes to the author's followers too (a boost) goes to its server's shared inbox, so the server gets // shared: what goes to the author's followers too (a boost) goes to its server's shared inbox, so the server gets
// one copy, as Mastodon sends it; two copies at once race in servers that count as they process (Misskey) // one copy, as Mastodon sends it; two copies at once race in servers that count as they process (Misskey)
async Task<string> AuthorInbox(PostEntity post, CancellationToken token, bool shared = false) async Task<string> AuthorInbox(PostEntity post, bool shared = false, CancellationToken token = default)
{ {
if (!post.IsFederatedCopy || string.IsNullOrEmpty(post.AuthorAccountId)) if (!post.IsFederatedCopy || string.IsNullOrEmpty(post.AuthorAccountId))
return default; return default;
var author = await _dbEntities.ForeignAvatars.MatchID(post.AuthorAccountId).ExecuteFirstAsync(token); var author = await dbEntities.ForeignAvatars.MatchID(post.AuthorAccountId).ExecuteFirstAsync(token);
return shared && !string.IsNullOrEmpty(author?.SharedInboxURL) ? author.SharedInboxURL : author?.InboxURL; return shared && !string.IsNullOrEmpty(author?.SharedInboxURL) ? author.SharedInboxURL : author?.InboxURL;
} }
@@ -809,7 +791,7 @@ namespace PrivaPub.Domain.Statuses
{ {
PostingPolicy.Anyone => true, PostingPolicy.Anyone => true,
PostingPolicy.Moderators => member?.Role is GroupRole.Owner or GroupRole.Moderator, PostingPolicy.Moderators => member?.Role is GroupRole.Owner or GroupRole.Moderator,
_ => member != default || await _dbEntities.Followings _ => member != default || await dbEntities.Followings
.Match(f => f.AvatarId == author.Id && f.TargetAccountId == group.ID && f.State == FollowState.Accepted).ExecuteAnyAsync(token) .Match(f => f.AvatarId == author.Id && f.TargetAccountId == group.ID && f.State == FollowState.Accepted).ExecuteAnyAsync(token)
}; };
} }
@@ -855,8 +837,8 @@ namespace PrivaPub.Domain.Statuses
ContentType = attachment.ContentType, ContentType = attachment.ContentType,
Kind = attachment.Kind, Kind = attachment.Kind,
DurationSeconds = attachment.DurationSeconds, DurationSeconds = attachment.DurationSeconds,
URL = _media.Url(attachment.FilePath), URL = mediaService.Url(attachment.FilePath),
PreviewURL = _media.Url(attachment.PreviewPath ?? attachment.FilePath), PreviewURL = mediaService.Url(attachment.PreviewPath ?? attachment.FilePath),
Description = attachment.Description, Description = attachment.Description,
Blurhash = attachment.Blurhash, Blurhash = attachment.Blurhash,
Width = attachment.Width, Width = attachment.Width,
+11 -17
View File
@@ -16,15 +16,9 @@ namespace PrivaPub.Domain.Timelines
Task Distribute(Post post, CancellationToken token); Task Distribute(Post post, CancellationToken token);
} }
public class Fanout : IFanout public class Fanout(
DbEntities dbEntities) : IFanout
{ {
readonly DbEntities _dbEntities;
public Fanout(DbEntities dbEntities)
{
_dbEntities = dbEntities;
}
public async Task Distribute(Post post, CancellationToken token) public async Task Distribute(Post post, CancellationToken token)
{ {
// a located post is read only through /clientapi/post/nearby: the Mastodon API looks past it everywhere, so in a // a located post is read only through /clientapi/post/nearby: the Mastodon API looks past it everywhere, so in a
@@ -42,8 +36,8 @@ namespace PrivaPub.Domain.Timelines
{ {
case PostVisibility.Public or PostVisibility.Unlisted or PostVisibility.FollowersOnly: case PostVisibility.Public or PostVisibility.Unlisted or PostVisibility.FollowersOnly:
var followers = post.IsFederatedCopy var followers = post.IsFederatedCopy
? await _dbEntities.Followings.Match(f => f.TargetActorURI == post.ActorURI && f.State == FollowState.Accepted && f.FollowerKind == null).ExecuteAsync(token) ? await dbEntities.Followings.Match(f => f.TargetActorURI == post.ActorURI && f.State == FollowState.Accepted && f.FollowerKind == null).ExecuteAsync(token)
: await _dbEntities.Followings.Match(f => f.TargetAccountId == post.GroupUserId && f.TargetIsLocal && f.State == FollowState.Accepted).ExecuteAsync(token); : await dbEntities.Followings.Match(f => f.TargetAccountId == post.GroupUserId && f.TargetIsLocal && f.State == FollowState.Accepted).ExecuteAsync(token);
foreach (var following in followers) foreach (var following in followers)
if (await Shows(following, post, token)) if (await Shows(following, post, token))
{ {
@@ -53,14 +47,14 @@ namespace PrivaPub.Domain.Timelines
} }
if (!string.IsNullOrEmpty(post.AudienceURI)) if (!string.IsNullOrEmpty(post.AudienceURI))
// (the server's reader of feeds follows communities for nobody's home) // (the server's reader of feeds follows communities for nobody's home)
foreach (var member in await _dbEntities.Followings.Match(f => f.TargetActorURI == post.AudienceURI && f.State == FollowState.Accepted && f.FollowerKind == null).ExecuteAsync(token)) foreach (var member in await dbEntities.Followings.Match(f => f.TargetActorURI == post.AudienceURI && f.State == FollowState.Accepted && f.FollowerKind == null).ExecuteAsync(token))
recipients.Add(member.AvatarId); recipients.Add(member.AvatarId);
// a post on a wall (FEP-400e): its owner, when a persona, and those following the owner // a post on a wall (FEP-400e): its owner, when a persona, and those following the owner
if (!string.IsNullOrEmpty(post.WallOwnerURI)) if (!string.IsNullOrEmpty(post.WallOwnerURI))
{ {
if (await _dbEntities.Avatars.MatchID(post.WallOwnerAccountId).ExecuteAnyAsync(token)) if (await dbEntities.Avatars.MatchID(post.WallOwnerAccountId).ExecuteAnyAsync(token))
recipients.Add(post.WallOwnerAccountId); recipients.Add(post.WallOwnerAccountId);
foreach (var follower in await _dbEntities.Followings.Match(f => f.TargetActorURI == post.WallOwnerURI && f.State == FollowState.Accepted).ExecuteAsync(token)) foreach (var follower in await dbEntities.Followings.Match(f => f.TargetActorURI == post.WallOwnerURI && f.State == FollowState.Accepted).ExecuteAsync(token))
recipients.Add(follower.AvatarId); recipients.Add(follower.AvatarId);
} }
// a public post (not a boost, not a reply) comes to those following one of its hashtags, as on Mastodon, // a public post (not a boost, not a reply) comes to those following one of its hashtags, as on Mastodon,
@@ -74,7 +68,7 @@ namespace PrivaPub.Domain.Timelines
} }
break; break;
case PostVisibility.Direct when !string.IsNullOrEmpty(post.ConversationId): case PostVisibility.Direct when !string.IsNullOrEmpty(post.ConversationId):
var conversation = await _dbEntities.DmGroups.MatchID(post.ConversationId).ExecuteFirstAsync(token); var conversation = await dbEntities.DmGroups.MatchID(post.ConversationId).ExecuteFirstAsync(token);
foreach (var member in conversation?.Members.Where(m => !m.IsForeign) ?? Enumerable.Empty<GroupMember>()) foreach (var member in conversation?.Members.Where(m => !m.IsForeign) ?? Enumerable.Empty<GroupMember>())
recipients.Add(member.AvatarId); recipients.Add(member.AvatarId);
break; break;
@@ -105,9 +99,9 @@ namespace PrivaPub.Domain.Timelines
if (string.IsNullOrEmpty(post.ReblogOfPostId)) if (string.IsNullOrEmpty(post.ReblogOfPostId))
foreach (var mention in post.Mentions.Where(m => m.IsLocal && !string.IsNullOrEmpty(m.AccountId))) foreach (var mention in post.Mentions.Where(m => m.IsLocal && !string.IsNullOrEmpty(m.AccountId)))
await Notifications.Add(mention.AccountId, NotificationType.Mention, post.AuthorAccountId ?? post.GroupUserId, post.ActorURI, post.ID, token); await Notifications.Add(mention.AccountId, NotificationType.Mention, post.AuthorAccountId ?? post.GroupUserId, post.ActorURI, post.ID, token: token);
foreach (var avatarId in notifying.Where(recipients.Contains).Distinct()) foreach (var avatarId in notifying.Where(recipients.Contains).Distinct())
await Notifications.Add(avatarId, NotificationType.Status, post.AuthorAccountId ?? post.GroupUserId, post.ActorURI, post.ID, token); await Notifications.Add(avatarId, NotificationType.Status, post.AuthorAccountId ?? post.GroupUserId, post.ActorURI, post.ID, token: token);
if (Streams.Anyone) if (Streams.Anyone)
await Stream(post, recipients, token); await Stream(post, recipients, token);
} }
@@ -230,7 +224,7 @@ namespace PrivaPub.Domain.Timelines
return true; return true;
if (string.IsNullOrEmpty(repliedTo)) if (string.IsNullOrEmpty(repliedTo))
return false; return false;
return await _dbEntities.Followings return await dbEntities.Followings
.Match(f => f.AvatarId == following.AvatarId && f.TargetAccountId == repliedTo && f.State == FollowState.Accepted) .Match(f => f.AvatarId == following.AvatarId && f.TargetAccountId == repliedTo && f.State == FollowState.Accepted)
.ExecuteAnyAsync(token); .ExecuteAnyAsync(token);
} }
+10 -16
View File
@@ -20,26 +20,20 @@ namespace PrivaPub.Domain.Timelines
Task<WebResult> MarkNotificationsRead(string rootUserId, string avatarId, CancellationToken token); Task<WebResult> MarkNotificationsRead(string rootUserId, string avatarId, CancellationToken token);
} }
public class TimelineService : ITimelineService public class TimelineService(
DbEntities dbEntities,
IStringLocalizer<GenericRes> localizer) : ITimelineService
{ {
const int MaxLimit = 40; const int MaxLimit = 40;
readonly DbEntities _dbEntities;
readonly IStringLocalizer<GenericRes> _localizer;
public TimelineService(DbEntities dbEntities, IStringLocalizer<GenericRes> localizer)
{
_dbEntities = dbEntities;
_localizer = localizer;
}
public async Task<WebResult> Home(string rootUserId, string avatarId, string maxId, int limit, CancellationToken token) public async Task<WebResult> Home(string rootUserId, string avatarId, string maxId, int limit, CancellationToken token)
{ {
var result = new WebResult(); var result = new WebResult();
if (!await Owns(rootUserId, avatarId, token)) if (!await Owns(rootUserId, avatarId, token))
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
var query = _dbEntities.TimelineEntries.Match(e => e.AvatarId == avatarId); var query = dbEntities.TimelineEntries.Match(e => e.AvatarId == avatarId);
if (!string.IsNullOrEmpty(maxId)) if (!string.IsNullOrEmpty(maxId))
query.Match(f => f.Lt(e => e.PostId, maxId)); query.Match(f => f.Lt(e => e.PostId, maxId));
var entries = await query.Sort(e => e.PostId, Order.Descending).Limit(Math.Clamp(limit, 1, MaxLimit)).ExecuteAsync(token); var entries = await query.Sort(e => e.PostId, Order.Descending).Limit(Math.Clamp(limit, 1, MaxLimit)).ExecuteAsync(token);
@@ -47,7 +41,7 @@ namespace PrivaPub.Domain.Timelines
var ids = entries.Select(e => e.PostId).Concat(entries.Where(e => e.ReblogOfPostId != default).Select(e => e.ReblogOfPostId)).Distinct().ToList(); var ids = entries.Select(e => e.PostId).Concat(entries.Where(e => e.ReblogOfPostId != default).Select(e => e.ReblogOfPostId)).Distinct().ToList();
var posts = ids.Count == 0 var posts = ids.Count == 0
? new Dictionary<string, Post>() ? new Dictionary<string, Post>()
: (await _dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID); : (await dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID);
result.Data = entries result.Data = entries
.Where(e => posts.ContainsKey(e.PostId) && (e.ReblogOfPostId == default || posts.ContainsKey(e.ReblogOfPostId))) .Where(e => posts.ContainsKey(e.PostId) && (e.ReblogOfPostId == default || posts.ContainsKey(e.ReblogOfPostId)))
@@ -66,9 +60,9 @@ namespace PrivaPub.Domain.Timelines
{ {
var result = new WebResult(); var result = new WebResult();
if (!await Owns(rootUserId, avatarId, token)) if (!await Owns(rootUserId, avatarId, token))
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
var query = _dbEntities.Notifications.Match(n => n.AvatarId == avatarId); var query = dbEntities.Notifications.Match(n => n.AvatarId == avatarId);
if (!string.IsNullOrEmpty(maxId)) if (!string.IsNullOrEmpty(maxId))
query.Match(f => f.Lt(n => n.ID, maxId)); query.Match(f => f.Lt(n => n.ID, maxId));
result.Data = (await query.Sort(n => n.ID, Order.Descending).Limit(Math.Clamp(limit, 1, MaxLimit)).ExecuteAsync(token)) result.Data = (await query.Sort(n => n.ID, Order.Descending).Limit(Math.Clamp(limit, 1, MaxLimit)).ExecuteAsync(token))
@@ -90,14 +84,14 @@ namespace PrivaPub.Domain.Timelines
{ {
var result = new WebResult(); var result = new WebResult();
if (!await Owns(rootUserId, avatarId, token)) if (!await Owns(rootUserId, avatarId, token))
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound); return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
await DB.Default.Update<Notification>().Match(n => n.AvatarId == avatarId && !n.IsRead).Modify(n => n.IsRead, true).ExecuteAsync(token); await DB.Default.Update<Notification>().Match(n => n.AvatarId == avatarId && !n.IsRead).Modify(n => n.IsRead, true).ExecuteAsync(token);
return result; return result;
} }
async Task<bool> Owns(string rootUserId, string avatarId, CancellationToken token) => async Task<bool> Owns(string rootUserId, string avatarId, CancellationToken token) =>
!string.IsNullOrEmpty(rootUserId) && !string.IsNullOrEmpty(avatarId) !string.IsNullOrEmpty(rootUserId) && !string.IsNullOrEmpty(avatarId)
&& await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token); && await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token);
static ViewPost ToView(Post post) => new() static ViewPost ToView(Post post) => new()
{ {
+18 -30
View File
@@ -14,28 +14,16 @@ namespace PrivaPub.Federation.Actors
// once a day, never when someone looks at it; a hidden or missing collection leaves its count unknown. Mastodon and // once a day, never when someone looks at it; a hidden or missing collection leaves its count unknown. Mastodon and
// GoToSocial do the same. A feed's following is its communities: they are kept, and read in turn, so its list shows. // GoToSocial do the same. A feed's following is its communities: they are kept, and read in turn, so its list shows.
// Its featured hashtags (its featuredTags collection, R8) are read with them. // Its featured hashtags (its featuredTags collection, R8) are read with them.
public class AccountCountsJob : IJobHandler public class AccountCountsJob(
IRemoteActorService remoteActors,
DbEntities dbEntities,
IFeaturedPosts featured = default,
ILocalActorService localActors = default,
IJobQueue jobs = default,
Domain.Social.IFeaturedTags featuredTags = default) : IJobHandler
{ {
readonly IRemoteActorService _remoteActors;
readonly DbEntities _dbEntities;
readonly IFeaturedPosts _featured;
readonly ILocalActorService _localActors;
readonly IJobQueue _jobs;
readonly Domain.Social.IFeaturedTags _featuredTags;
public const int MaxFeedCommunities = 50; public const int MaxFeedCommunities = 50;
public AccountCountsJob(IRemoteActorService remoteActors, DbEntities dbEntities, IFeaturedPosts featured = default,
ILocalActorService localActors = default, IJobQueue jobs = default, Domain.Social.IFeaturedTags featuredTags = default)
{
_featuredTags = featuredTags;
_remoteActors = remoteActors;
_dbEntities = dbEntities;
_featured = featured;
_localActors = localActors;
_jobs = jobs;
}
public JobKind Kind => JobKind.CountAccount; public JobKind Kind => JobKind.CountAccount;
public int Concurrency => 2; public int Concurrency => 2;
public int MaxAttempts => 2; public int MaxAttempts => 2;
@@ -45,7 +33,7 @@ namespace PrivaPub.Federation.Actors
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var actor = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == job.Payload && !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var actor = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == job.Payload && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (actor == default) if (actor == default)
return JobOutcome.Done; return JobOutcome.Done;
var feed = actor.AvatarType == AvatarType.Feed; var feed = actor.AvatarType == AvatarType.Feed;
@@ -62,15 +50,15 @@ namespace PrivaPub.Federation.Actors
if (feed && listed) if (feed && listed)
{ {
foreach (var community in communities) foreach (var community in communities)
if (_localActors == default || !community.StartsWith(_localActors.BaseAddress + "/", StringComparison.Ordinal)) if (localActors == default || !community.StartsWith(localActors.BaseAddress + "/", StringComparison.Ordinal))
await _remoteActors.GetActor(community, refresh: false, token); await remoteActors.GetActor(community, refresh: false, token);
if (_jobs != default && await DB.Default.Find<Models.Social.FeedSubscription>().Match(s => s.FeedActorURI == actor.ActorURI).ExecuteAnyAsync(token)) if (jobs != default && await DB.Default.Find<Models.Social.FeedSubscription>().Match(s => s.FeedActorURI == actor.ActorURI).ExecuteAnyAsync(token))
await Domain.Social.FeedFollows.Sync(_jobs, token); await Domain.Social.FeedFollows.Sync(jobs, token);
} }
if (_featured != default) if (featured != default)
await _featured.Sync(actor, token); await featured.Sync(actor, token);
if (_featuredTags != default) if (featuredTags != default)
await _featuredTags.Sync(actor, token); await featuredTags.Sync(actor, token);
return JobOutcome.Done; return JobOutcome.Done;
} }
@@ -82,7 +70,7 @@ namespace PrivaPub.Federation.Actors
if (string.IsNullOrEmpty(collection) || !Origin.Same(collection, actor.ActorURI)) if (string.IsNullOrEmpty(collection) || !Origin.Same(collection, actor.ActorURI))
return (default, listed, false); return (default, listed, false);
using var scope = HttpScope.For("collection"); using var scope = HttpScope.For("collection");
using var fetched = await _remoteActors.FetchObject(collection, token); using var fetched = await remoteActors.FetchObject(collection, token);
if (fetched == default || fetched.Root.ValueKind != System.Text.Json.JsonValueKind.Object) if (fetched == default || fetched.Root.ValueKind != System.Text.Json.JsonValueKind.Object)
return (default, listed, false); return (default, listed, false);
int? total = fetched.Root.TryGetProperty("totalItems", out var counted) && counted.TryGetInt32(out var count) && count >= 0 ? count : default; int? total = fetched.Root.TryGetProperty("totalItems", out var counted) && counted.TryGetInt32(out var count) && count >= 0 ? count : default;
@@ -92,7 +80,7 @@ namespace PrivaPub.Federation.Actors
var page = document["orderedItems"] ?? document["items"] ?? document["first"]?["orderedItems"] ?? document["first"]?["items"]; var page = document["orderedItems"] ?? document["items"] ?? document["first"]?["orderedItems"] ?? document["first"]?["items"];
if (page == default && ActivityJson.Id(document["first"]) is { } first && Origin.Same(first, actor.ActorURI)) if (page == default && ActivityJson.Id(document["first"]) is { } first && Origin.Same(first, actor.ActorURI))
{ {
using var next = await _remoteActors.FetchObject(first, token); using var next = await remoteActors.FetchObject(first, token);
if (next == default) if (next == default)
return (total, listed, false); return (total, listed, false);
var nextPage = System.Text.Json.Nodes.JsonNode.Parse(next.Root.GetRawText()); var nextPage = System.Text.Json.Nodes.JsonNode.Parse(next.Root.GetRawText());
@@ -39,6 +39,7 @@ namespace PrivaPub.Federation.Actors
public string MovedTo { get; init; } public string MovedTo { get; init; }
public string Moderators { get; init; } public string Moderators { get; init; }
public List<PostFlair> Flairs { get; init; } = new(); public List<PostFlair> Flairs { get; init; } = new();
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0006", Justification = "Null when the document does not state searchableBy (FEP-268d), which is not the same as an empty list.")]
public List<string> SearchableBy { get; init; } public List<string> SearchableBy { get; init; }
public List<string> AlsoKnownAs { get; init; } = new();//the accounts it says it also is (a Move's target names the moved one) public List<string> AlsoKnownAs { get; init; } = new();//the accounts it says it also is (a Move's target names the moved one)
public DateTime? Published { get; init; } public DateTime? Published { get; init; }
+8 -15
View File
@@ -26,20 +26,13 @@ namespace PrivaPub.Federation.Actors
// What an account elsewhere features (pins): its `featured` collection, read with its counts at most once a day, and // What an account elsewhere features (pins): its `featured` collection, read with its counts at most once a day, and
// the Add and Remove it sends when it pins or unpins. An account features only its own posts; a community (Lemmy's, // the Add and Remove it sends when it pins or unpins. An account features only its own posts; a community (Lemmy's,
// inside its announce) features posts made in it. Shown first on its profile here, as Mastodon shows them. // inside its announce) features posts made in it. Shown first on its profile here, as Mastodon shows them.
public class FeaturedPosts : IFeaturedPosts public class FeaturedPosts(
DbEntities dbEntities,
IRemoteActorService remoteActors,
IRemotePosts remotePosts) : IFeaturedPosts
{ {
public const int MaxFeatured = 20; public const int MaxFeatured = 20;
readonly DbEntities _dbEntities;
readonly IRemoteActorService _remoteActors;
readonly IRemotePosts _remotePosts;
public FeaturedPosts(DbEntities dbEntities, IRemoteActorService remoteActors, IRemotePosts remotePosts)
{
_dbEntities = dbEntities;
_remoteActors = remoteActors;
_remotePosts = remotePosts;
}
public async Task Receive(JsonNode activity, ForeignAvatar owner, bool add, CancellationToken token) public async Task Receive(JsonNode activity, ForeignAvatar owner, bool add, CancellationToken token)
{ {
@@ -110,8 +103,8 @@ namespace PrivaPub.Federation.Actors
var isGroup = owner.AvatarType is AvatarType.Group; var isGroup = owner.AvatarType is AvatarType.Group;
if (!isGroup && !Origin.Same(objectUri, owner.ActorURI)) if (!isGroup && !Origin.Same(objectUri, owner.ActorURI))
return default; return default;
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token) var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await _remotePosts.StoreContext(objectUri, 0, token); ?? await remotePosts.StoreContext(objectUri, 0, token);
return post switch return post switch
{ {
null => default, null => default,
@@ -125,7 +118,7 @@ namespace PrivaPub.Federation.Actors
async Task<List<string>> Items(ForeignAvatar owner, CancellationToken token) async Task<List<string>> Items(ForeignAvatar owner, CancellationToken token)
{ {
using var scope = HttpScope.For("collection"); using var scope = HttpScope.For("collection");
using var collection = await _remoteActors.FetchObject(owner.FeaturedURL, token); using var collection = await remoteActors.FetchObject(owner.FeaturedURL, token);
if (collection == default || collection.Root.ValueKind != JsonValueKind.Object) if (collection == default || collection.Root.ValueKind != JsonValueKind.Object)
return default; return default;
var items = ItemsOf(collection.Root); var items = ItemsOf(collection.Root);
@@ -136,7 +129,7 @@ namespace PrivaPub.Federation.Actors
var page = first.ValueKind == JsonValueKind.String ? first.GetString() : default; var page = first.ValueKind == JsonValueKind.String ? first.GetString() : default;
if (page == default || !Origin.Same(page, owner.ActorURI)) if (page == default || !Origin.Same(page, owner.ActorURI))
return items; return items;
using var fetched = await _remoteActors.FetchObject(page, token); using var fetched = await remoteActors.FetchObject(page, token);
return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? items : ItemsOf(fetched.Root); return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? items : ItemsOf(fetched.Root);
} }
@@ -23,25 +23,15 @@ namespace PrivaPub.Federation.Actors
// only PrivaPub remembers ends, a request it answered without our knowing is accepted, and a follow only it remembers // only PrivaPub remembers ends, a request it answered without our knowing is accepted, and a follow only it remembers
// is undone by the persona, as Mastodon does, or kept within RestoreRecord.FollowersGrace of a restore, which may have // is undone by the persona, as Mastodon does, or kept within RestoreRecord.FollowersGrace of a restore, which may have
// lost it. A follow ends only when the list is the one the digest describes. // lost it. A follow ends only when the list is the one the digest describes.
public class FollowingSynchronization : IJobHandler public class FollowingSynchronization(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IFollowService follows,
IDeliveryService deliveryService) : IJobHandler
{ {
const int MaxPages = 10; const int MaxPages = 10;
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IFollowService _follows;
readonly IDeliveryService _delivery;
public FollowingSynchronization(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IFollowService follows,
IDeliveryService delivery)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_follows = follows;
_delivery = delivery;
}
public JobKind Kind => JobKind.SynchronizeFollowing; public JobKind Kind => JobKind.SynchronizeFollowing;
public int Concurrency => 1; public int Concurrency => 1;
@@ -55,14 +45,14 @@ namespace PrivaPub.Federation.Actors
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var claim = JsonSerializer.Deserialize<SynchronizationClaim>(job.Payload); var claim = JsonSerializer.Deserialize<SynchronizationClaim>(job.Payload);
var actor = claim == default ? default : await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == claim.Actor && !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var actor = claim == default ? default : await dbEntities.ForeignAvatars.Match(a => a.ActorURI == claim.Actor && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (actor == default || string.IsNullOrEmpty(actor.FollowersURL) || claim.CollectionId != actor.FollowersURL || !Origin.Same(claim.Url, actor.ActorURI)) if (actor == default || string.IsNullOrEmpty(actor.FollowersURL) || claim.CollectionId != actor.FollowersURL || !Origin.Same(claim.Url, actor.ActorURI))
return JobOutcome.Done; return JobOutcome.Done;
var followings = await _dbEntities.Followings.Match(f => f.TargetActorURI == actor.ActorURI && !f.TargetIsLocal).ExecuteAsync(token); var followings = await dbEntities.Followings.Match(f => f.TargetActorURI == actor.ActorURI && !f.TargetIsLocal).ExecuteAsync(token);
var personas = new Dictionary<string, (LocalActor Persona, Following Following)>(StringComparer.Ordinal); var personas = new Dictionary<string, (LocalActor Persona, Following Following)>(StringComparer.Ordinal);
foreach (var following in followings) foreach (var following in followings)
if (await _localActors.FindById(LocalActorKind.Person, following.AvatarId, token) is { } persona) if (await localActors.FindById(LocalActorKind.Person, following.AvatarId, token) is { } persona)
personas[persona.Uri] = (persona, following); personas[persona.Uri] = (persona, following);
var accepted = personas.Values.Where(p => p.Following.State == FollowState.Accepted).Select(p => p.Persona.Uri).ToList(); var accepted = personas.Values.Where(p => p.Following.State == FollowState.Accepted).Select(p => p.Persona.Uri).ToList();
if (FollowersSynchronization.Digest(accepted) == claim.Digest) if (FollowersSynchronization.Digest(accepted) == claim.Digest)
@@ -76,7 +66,7 @@ namespace PrivaPub.Federation.Actors
var named = listed.ToHashSet(StringComparer.Ordinal); var named = listed.ToHashSet(StringComparer.Ordinal);
if (complete) if (complete)
foreach (var uri in accepted.Where(uri => !named.Contains(uri))) foreach (var uri in accepted.Where(uri => !named.Contains(uri)))
await _follows.UnfollowAs(personas[uri].Persona, actor.ActorURI, token); await follows.UnfollowAs(personas[uri].Persona, actor.ActorURI, token);
foreach (var uri in named) foreach (var uri in named)
{ {
@@ -86,7 +76,7 @@ namespace PrivaPub.Federation.Actors
await DB.Default.Update<Following>().MatchID(known.Following.ID).Modify(f => f.State, FollowState.Accepted).ExecuteAsync(token); await DB.Default.Update<Following>().MatchID(known.Following.ID).Modify(f => f.State, FollowState.Accepted).ExecuteAsync(token);
continue; continue;
} }
if (await _localActors.FindByUri(uri, token) is not { Kind: LocalActorKind.Person } stranger) if (await localActors.FindByUri(uri, token) is not { Kind: LocalActorKind.Person } stranger)
continue; continue;
// a follow the restore lost: kept, not undone // a follow the restore lost: kept, not undone
if (await Infrastructure.Backup.RestoreRecord.InFollowersGrace(token)) if (await Infrastructure.Backup.RestoreRecord.InFollowersGrace(token))
@@ -110,7 +100,7 @@ namespace PrivaPub.Federation.Actors
["actor"] = stranger.Uri, ["actor"] = stranger.Uri,
["object"] = new JsonObject { ["type"] = "Follow", ["actor"] = stranger.Uri, ["object"] = actor.ActorURI } ["object"] = new JsonObject { ["type"] = "Follow", ["actor"] = stranger.Uri, ["object"] = actor.ActorURI }
}; };
await _delivery.Enqueue(stranger, new[] { string.IsNullOrEmpty(actor.InboxURL) ? actor.SharedInboxURL : actor.InboxURL }, undo, token); await deliveryService.Enqueue(stranger, new[] { string.IsNullOrEmpty(actor.InboxURL) ? actor.SharedInboxURL : actor.InboxURL }, undo, token: token);
} }
return JobOutcome.Done; return JobOutcome.Done;
} }
@@ -123,7 +113,7 @@ namespace PrivaPub.Federation.Actors
var next = url; var next = url;
for (var page = 0; page < MaxPages && next != default; page++) for (var page = 0; page < MaxPages && next != default; page++)
{ {
using var fetched = await _remoteActors.FetchObject(next, token); using var fetched = await remoteActors.FetchObject(next, token);
if (fetched == default || fetched.Root.ValueKind != JsonValueKind.Object) if (fetched == default || fetched.Root.ValueKind != JsonValueKind.Object)
return page == 0 ? default : items; return page == 0 ? default : items;
var root = fetched.Root; var root = fetched.Root;
+15 -22
View File
@@ -91,7 +91,10 @@ namespace PrivaPub.Federation.Actors
// a persona or group that was deleted: its name stays reserved, and its documents answer 410 with this // a persona or group that was deleted: its name stays reserved, and its documents answer 410 with this
public sealed record GoneActor(string Uri, string FormerType, DateTime DeletedAt); public sealed record GoneActor(string Uri, string FormerType, DateTime DeletedAt);
public class LocalActorService : ILocalActorService public class LocalActorService(
DbEntities dbEntities,
IOptionsMonitor<AppConfiguration> appConfiguration,
Domain.Instance.IInstanceSettings instanceSettings) : ILocalActorService
{ {
public const string InstanceUserName = "privapub"; public const string InstanceUserName = "privapub";
// the anonymous Service that carries this server's reports to Lemmy, which takes no report from an Application // the anonymous Service that carries this server's reports to Lemmy, which takes no report from an Application
@@ -114,21 +117,11 @@ namespace PrivaPub.Federation.Actors
// what the instance actor says of itself until the administrator describes the server (ServerSettings) // what the instance actor says of itself until the administrator describes the server (ServerSettings)
const string InstanceSummary = "The instance actor of this PrivaPub server; it signs the requests no other actor speaks for."; const string InstanceSummary = "The instance actor of this PrivaPub server; it signs the requests no other actor speaks for.";
readonly DbEntities _dbEntities;
readonly IOptionsMonitor<AppConfiguration> _appConfiguration;
readonly Domain.Instance.IInstanceSettings _settings;
InstanceActor _instanceActor; InstanceActor _instanceActor;
ReporterActor _reporterActor; ReporterActor _reporterActor;
ReaderActor _readerActor; ReaderActor _readerActor;
public LocalActorService(DbEntities dbEntities, IOptionsMonitor<AppConfiguration> appConfiguration, Domain.Instance.IInstanceSettings settings) public string BaseAddress => appConfiguration.CurrentValue.BackendBaseAddress?.TrimEnd('/');
{
_dbEntities = dbEntities;
_appConfiguration = appConfiguration;
_settings = settings;
}
public string BaseAddress => _appConfiguration.CurrentValue.BackendBaseAddress?.TrimEnd('/');
public async Task<LocalActor> FindByUserName(string userName, CancellationToken token) public async Task<LocalActor> FindByUserName(string userName, CancellationToken token)
{ {
@@ -142,13 +135,13 @@ namespace PrivaPub.Federation.Actors
if (userName == ReaderUserName) if (userName == ReaderUserName)
return await GetReaderActor(token); return await GetReaderActor(token);
var avatar = await _dbEntities.Avatars var avatar = await dbEntities.Avatars
.Match(a => a.UserName == userName && !a.DeletionAt.HasValue) .Match(a => a.UserName == userName && !a.DeletionAt.HasValue)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
return FromAvatar(avatar); return FromAvatar(avatar);
var group = await _dbEntities.Groups var group = await dbEntities.Groups
.Match(g => g.UserName == userName && !g.DeletionAt.HasValue) .Match(g => g.UserName == userName && !g.DeletionAt.HasValue)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
return group == default ? default : FromGroup(group); return group == default ? default : FromGroup(group);
@@ -159,10 +152,10 @@ namespace PrivaPub.Federation.Actors
if (string.IsNullOrEmpty(userName)) if (string.IsNullOrEmpty(userName))
return default; return default;
userName = userName.ToLowerInvariant(); userName = userName.ToLowerInvariant();
var avatar = await _dbEntities.Avatars.Match(a => a.UserName == userName && a.DeletionAt.HasValue).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.Match(a => a.UserName == userName && a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (avatar != default) if (avatar != default)
return new GoneActor($"{BaseAddress}/peasants/{avatar.UserName}", "Person", avatar.DeletionAt.Value); return new GoneActor($"{BaseAddress}/peasants/{avatar.UserName}", "Person", avatar.DeletionAt.Value);
var group = await _dbEntities.Groups.Match(g => g.UserName == userName && g.DeletionAt.HasValue).ExecuteFirstAsync(token); var group = await dbEntities.Groups.Match(g => g.UserName == userName && g.DeletionAt.HasValue).ExecuteFirstAsync(token);
return group == default ? default : new GoneActor($"{BaseAddress}/peasants/{group.UserName}", "Group", group.DeletionAt.Value); return group == default ? default : new GoneActor($"{BaseAddress}/peasants/{group.UserName}", "Group", group.DeletionAt.Value);
} }
@@ -171,10 +164,10 @@ namespace PrivaPub.Federation.Actors
switch (kind) switch (kind)
{ {
case LocalActorKind.Person: case LocalActorKind.Person:
var avatar = await _dbEntities.Avatars.MatchID(id).ExecuteFirstAsync(token); var avatar = await dbEntities.Avatars.MatchID(id).ExecuteFirstAsync(token);
return avatar == default ? default : FromAvatar(avatar); return avatar == default ? default : FromAvatar(avatar);
case LocalActorKind.Group: case LocalActorKind.Group:
var group = await _dbEntities.Groups.MatchID(id).ExecuteFirstAsync(token); var group = await dbEntities.Groups.MatchID(id).ExecuteFirstAsync(token);
return group == default ? default : FromGroup(group); return group == default ? default : FromGroup(group);
case LocalActorKind.Reporter: case LocalActorKind.Reporter:
return await GetReporterActor(token); return await GetReporterActor(token);
@@ -208,7 +201,7 @@ namespace PrivaPub.Federation.Actors
{ {
var instance = _instanceActor ??= await LoadInstanceActor(token); var instance = _instanceActor ??= await LoadInstanceActor(token);
// the server's name, and its short description once the administrator wrote one of their own // the server's name, and its short description once the administrator wrote one of their own
var settings = _settings.Current; var settings = instanceSettings.Current;
return new LocalActor return new LocalActor
{ {
@@ -268,7 +261,7 @@ namespace PrivaPub.Federation.Actors
async Task<ReaderActor> LoadReaderActor(CancellationToken token) async Task<ReaderActor> LoadReaderActor(CancellationToken token)
{ {
var reader = await _dbEntities.ReaderActors.Sort(r => r.CreationDate, Order.Ascending).ExecuteFirstAsync(token); var reader = await dbEntities.ReaderActors.Sort(r => r.CreationDate, Order.Ascending).ExecuteFirstAsync(token);
if (reader != default) if (reader != default)
return reader; return reader;
var (privateKey, publicKey) = Keys.NewKeyPair(); var (privateKey, publicKey) = Keys.NewKeyPair();
@@ -279,7 +272,7 @@ namespace PrivaPub.Federation.Actors
async Task<ReporterActor> LoadReporterActor(CancellationToken token) async Task<ReporterActor> LoadReporterActor(CancellationToken token)
{ {
var reporter = await _dbEntities.ReporterActors.Sort(r => r.CreationDate, Order.Ascending).ExecuteFirstAsync(token); var reporter = await dbEntities.ReporterActors.Sort(r => r.CreationDate, Order.Ascending).ExecuteFirstAsync(token);
if (reporter != default) if (reporter != default)
return reporter; return reporter;
var (privateKey, publicKey) = Keys.NewKeyPair(); var (privateKey, publicKey) = Keys.NewKeyPair();
@@ -290,7 +283,7 @@ namespace PrivaPub.Federation.Actors
async Task<InstanceActor> LoadInstanceActor(CancellationToken token) async Task<InstanceActor> LoadInstanceActor(CancellationToken token)
{ {
var instance = await _dbEntities.InstanceActors.Sort(i => i.CreationDate, Order.Ascending).ExecuteFirstAsync(token); var instance = await dbEntities.InstanceActors.Sort(i => i.CreationDate, Order.Ascending).ExecuteFirstAsync(token);
if (instance != default) if (instance != default)
return instance; return instance;
var (privateKey, publicKey) = Keys.NewKeyPair(); var (privateKey, publicKey) = Keys.NewKeyPair();
+8 -15
View File
@@ -14,20 +14,13 @@ namespace PrivaPub.Federation.Actors
// The latest public posts of an account a persona has just followed, read from the first page of its outbox (at most // The latest public posts of an account a persona has just followed, read from the first page of its outbox (at most
// twenty, once a day) and kept as any fetched post: its profile shows them and threads find them at once, instead of // twenty, once a day) and kept as any fetched post: its profile shows them and threads find them at once, instead of
// only what it posts from then on. Homes still get only what arrives from now on, as on Mastodon. // only what it posts from then on. Homes still get only what arrives from now on, as on Mastodon.
public class OutboxBackfill : IJobHandler public class OutboxBackfill(
DbEntities dbEntities,
IRemoteActorService remoteActors,
IRemotePosts remotePosts) : IJobHandler
{ {
public const int MaxPosts = 20; public const int MaxPosts = 20;
readonly DbEntities _dbEntities;
readonly IRemoteActorService _remoteActors;
readonly IRemotePosts _remotePosts;
public OutboxBackfill(DbEntities dbEntities, IRemoteActorService remoteActors, IRemotePosts remotePosts)
{
_dbEntities = dbEntities;
_remoteActors = remoteActors;
_remotePosts = remotePosts;
}
public JobKind Kind => JobKind.BackfillOutbox; public JobKind Kind => JobKind.BackfillOutbox;
public int Concurrency => 1; public int Concurrency => 1;
@@ -38,11 +31,11 @@ namespace PrivaPub.Federation.Actors
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var actor = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == job.Payload && !a.DeletionAt.HasValue).ExecuteFirstAsync(token); var actor = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == job.Payload && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (actor == default || string.IsNullOrEmpty(actor.OutboxURL) || !Origin.Same(actor.OutboxURL, actor.ActorURI)) if (actor == default || string.IsNullOrEmpty(actor.OutboxURL) || !Origin.Same(actor.OutboxURL, actor.ActorURI))
return JobOutcome.Done; return JobOutcome.Done;
foreach (var objectUri in (await Items(actor, token)).Take(MaxPosts)) foreach (var objectUri in (await Items(actor, token)).Take(MaxPosts))
await _remotePosts.StoreContext(objectUri, 0, token); await remotePosts.StoreContext(objectUri, 0, token);
return JobOutcome.Done; return JobOutcome.Done;
} }
@@ -51,7 +44,7 @@ namespace PrivaPub.Federation.Actors
async Task<List<string>> Items(Models.User.ForeignAvatar actor, CancellationToken token) async Task<List<string>> Items(Models.User.ForeignAvatar actor, CancellationToken token)
{ {
using var scope = HttpScope.For("outbox"); using var scope = HttpScope.For("outbox");
using var outbox = await _remoteActors.FetchObject(actor.OutboxURL, token); using var outbox = await remoteActors.FetchObject(actor.OutboxURL, token);
if (outbox == default || outbox.Root.ValueKind != JsonValueKind.Object) if (outbox == default || outbox.Root.ValueKind != JsonValueKind.Object)
return new(); return new();
var page = ItemsOf(outbox.Root, actor); var page = ItemsOf(outbox.Root, actor);
@@ -62,7 +55,7 @@ namespace PrivaPub.Federation.Actors
var pageUri = first.ValueKind == JsonValueKind.String ? first.GetString() : default; var pageUri = first.ValueKind == JsonValueKind.String ? first.GetString() : default;
if (pageUri == default || !Origin.Same(pageUri, actor.ActorURI)) if (pageUri == default || !Origin.Same(pageUri, actor.ActorURI))
return page; return page;
using var fetched = await _remoteActors.FetchObject(pageUri, token); using var fetched = await remoteActors.FetchObject(pageUri, token);
return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? page : ItemsOf(fetched.Root, actor); return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? page : ItemsOf(fetched.Root, actor);
} }
@@ -26,41 +26,30 @@ namespace PrivaPub.Federation.Actors
Task<string> ResolveHandle(string handle, CancellationToken token); Task<string> ResolveHandle(string handle, CancellationToken token);
} }
public class RemoteActorService : IRemoteActorService public class RemoteActorService(
IFederationHttp federationHttp,
ILocalActorService localActors,
IMemoryCache cache,
DbEntities dbEntities,
IOptionsMonitor<FederationOptions> options = default,
Infrastructure.Jobs.IJobQueue jobs = default) : IRemoteActorService
{ {
public const string ActivityJson = "application/activity+json"; public const string ActivityJson = "application/activity+json";
const string Accept = "application/activity+json, application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\""; const string Accept = "application/activity+json, application/ld+json; profile=\"https://www.w3.org/ns/activitystreams\"";
static readonly TimeSpan CacheLifetime = TimeSpan.FromDays(1); static readonly TimeSpan CacheLifetime = TimeSpan.FromDays(1);
static readonly TimeSpan RefetchInterval = TimeSpan.FromMinutes(5); static readonly TimeSpan RefetchInterval = TimeSpan.FromMinutes(5);
readonly IFederationHttp _http;
readonly ILocalActorService _localActors;
readonly IMemoryCache _cache;
readonly DbEntities _dbEntities;
readonly IOptionsMonitor<FederationOptions> _options;
readonly Infrastructure.Jobs.IJobQueue _jobs;
public RemoteActorService(IFederationHttp http, ILocalActorService localActors, IMemoryCache cache, DbEntities dbEntities,
IOptionsMonitor<FederationOptions> options = default, Infrastructure.Jobs.IJobQueue jobs = default)
{
_jobs = jobs;
_http = http;
_localActors = localActors;
_cache = cache;
_dbEntities = dbEntities;
_options = options;
}
public Task<FetchedJson> FetchObject(string uri, CancellationToken token) => FetchObject(uri, default, token); public Task<FetchedJson> FetchObject(string uri, CancellationToken token) => FetchObject(uri, default, token);
public async Task<FetchedJson> FetchObject(string uri, string etag, CancellationToken token) public async Task<FetchedJson> FetchObject(string uri, string etag, CancellationToken token)
{ {
using var scope = HttpScope.Default("object"); using var scope = HttpScope.Default("object");
var signer = await _localActors.GetInstanceActor(token); var signer = await localActors.GetInstanceActor(token);
var fetched = string.IsNullOrEmpty(etag) var fetched = string.IsNullOrEmpty(etag)
? await Get(uri, signer, token) ? await Get(uri, signer, token)
: await _http.GetJsonIfChanged(uri, Accept, etag, request => HttpSignatures.Sign(request, signer, body: null), token); : await federationHttp.GetJsonIfChanged(uri, Accept, etag, request => HttpSignatures.Sign(request, signer, body: null), token);
if (fetched == default || fetched.NotModified) if (fetched == default || fetched.NotModified)
return fetched; return fetched;
@@ -86,7 +75,7 @@ namespace PrivaPub.Federation.Actors
return default; return default;
actorUri = StripFragment(actorUri); actorUri = StripFragment(actorUri);
var cached = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == actorUri).ExecuteFirstAsync(token); var cached = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == actorUri).ExecuteFirstAsync(token);
if (cached != default && !refresh && DateTime.UtcNow - cached.UpdatedAt < CacheLifetime) if (cached != default && !refresh && DateTime.UtcNow - cached.UpdatedAt < CacheLifetime)
return cached; return cached;
if (!MayFetch(actorUri)) if (!MayFetch(actorUri))
@@ -105,8 +94,8 @@ namespace PrivaPub.Federation.Actors
// its counts are read once a day, after it was fetched (AccountCountsJob) // its counts are read once a day, after it was fetched (AccountCountsJob)
async Task<ForeignAvatar> Counted(ForeignAvatar stored, CancellationToken token) async Task<ForeignAvatar> Counted(ForeignAvatar stored, CancellationToken token)
{ {
if (_jobs != default && stored is { DeletionAt: null } && Uri.TryCreate(stored.ActorURI, UriKind.Absolute, out var uri)) if (jobs != default && stored is { DeletionAt: null } && Uri.TryCreate(stored.ActorURI, UriKind.Absolute, out var uri))
await _jobs.Enqueue(Models.Jobs.JobKind.CountAccount, stored.ActorURI, uri.Host.ToLowerInvariant(), await jobs.Enqueue(Models.Jobs.JobKind.CountAccount, stored.ActorURI, uri.Host.ToLowerInvariant(),
AccountCountsJob.DedupeKey(stored.ActorURI, DateTime.UtcNow), token); AccountCountsJob.DedupeKey(stored.ActorURI, DateTime.UtcNow), token);
return stored; return stored;
} }
@@ -116,7 +105,7 @@ namespace PrivaPub.Federation.Actors
if (Origin.Of(keyId) == default) if (Origin.Of(keyId) == default)
return default; return default;
var cached = await _dbEntities.ForeignAvatars.Match(a => a.PublicKeyId == keyId).ExecuteFirstAsync(token); var cached = await dbEntities.ForeignAvatars.Match(a => a.PublicKeyId == keyId).ExecuteFirstAsync(token);
if (cached != default && !string.IsNullOrEmpty(cached.PublicKey) && !refresh) if (cached != default && !string.IsNullOrEmpty(cached.PublicKey) && !refresh)
return cached; return cached;
if (!MayFetch(keyId)) if (!MayFetch(keyId))
@@ -143,7 +132,7 @@ namespace PrivaPub.Federation.Actors
return await Counted(await Upsert(actor, key, token), token); return await Counted(await Upsert(actor, key, token), token);
} }
public bool KeyTemporarilyUnavailable(string keyId) => Origin.Of(keyId) != default && _http.FailedTemporarily(StripFragment(keyId)); public bool KeyTemporarilyUnavailable(string keyId) => Origin.Of(keyId) != default && federationHttp.FailedTemporarily(StripFragment(keyId));
// whether an object's origin says it is gone: 404 or 410 to our instance actor, or a Tombstone in its place // whether an object's origin says it is gone: 404 or 410 to our instance actor, or a Tombstone in its place
public async Task<bool> IsGone(string uri, CancellationToken token) public async Task<bool> IsGone(string uri, CancellationToken token)
@@ -151,8 +140,8 @@ namespace PrivaPub.Federation.Actors
if (Origin.Of(uri) == default) if (Origin.Of(uri) == default)
return false; return false;
using var scope = HttpScope.Default("object"); using var scope = HttpScope.Default("object");
var signer = await _localActors.GetInstanceActor(token); var signer = await localActors.GetInstanceActor(token);
var (status, fetched) = await _http.GetJsonStatus(uri, Accept, request => HttpSignatures.Sign(request, signer, body: null), token); var (status, fetched) = await federationHttp.GetJsonStatus(uri, Accept, request => HttpSignatures.Sign(request, signer, body: null), token);
using (fetched) using (fetched)
return status is StatusCodes.Status404NotFound or StatusCodes.Status410Gone || fetched != default && Text(fetched.Root, "type") == "Tombstone"; return status is StatusCodes.Status404NotFound or StatusCodes.Status410Gone || fetched != default && Text(fetched.Root, "type") == "Tombstone";
} }
@@ -165,9 +154,9 @@ namespace PrivaPub.Federation.Actors
using var scope = HttpScope.For("webfinger"); using var scope = HttpScope.For("webfinger");
var query = $"/.well-known/webfinger?resource={Uri.EscapeDataString($"acct:{parts[0]}@{parts[1]}")}"; var query = $"/.well-known/webfinger?resource={Uri.EscapeDataString($"acct:{parts[0]}@{parts[1]}")}";
using var fetched = await _http.GetJson($"https://{parts[1]}{query}", "application/jrd+json, application/json", sign: default, token) using var fetched = await federationHttp.GetJson($"https://{parts[1]}{query}", "application/jrd+json, application/json", sign: default, token)
?? (_options?.CurrentValue.AllowPlainHttp == true ?? (options?.CurrentValue.AllowPlainHttp == true
? await _http.GetJson($"http://{parts[1]}{query}", "application/jrd+json, application/json", sign: default, token) ? await federationHttp.GetJson($"http://{parts[1]}{query}", "application/jrd+json, application/json", sign: default, token)
: default); : default);
if (fetched == default) if (fetched == default)
return default; return default;
@@ -185,14 +174,14 @@ namespace PrivaPub.Federation.Actors
} }
async Task<FetchedJson> Get(string uri, LocalActor signer, CancellationToken token) => async Task<FetchedJson> Get(string uri, LocalActor signer, CancellationToken token) =>
await _http.GetJson(uri, Accept, request => HttpSignatures.Sign(request, signer, body: null), token); await federationHttp.GetJson(uri, Accept, request => HttpSignatures.Sign(request, signer, body: null), token);
bool MayFetch(string uri) bool MayFetch(string uri)
{ {
var key = "remote-actor:fetched:" + uri; var key = "remote-actor:fetched:" + uri;
if (_cache.TryGetValue(key, out _)) if (cache.TryGetValue(key, out _))
return false; return false;
_cache.Set(key, true, RefetchInterval); cache.Set(key, true, RefetchInterval);
return true; return true;
} }
@@ -206,7 +195,7 @@ namespace PrivaPub.Federation.Actors
if (named is not { Length: 2 } || named[0].Length == 0 || named[1].Length == 0 || named[1].Equals(host, StringComparison.OrdinalIgnoreCase)) if (named is not { Length: 2 } || named[0].Length == 0 || named[1].Length == 0 || named[1].Equals(host, StringComparison.OrdinalIgnoreCase))
return host; return host;
var domain = named[1].ToLowerInvariant(); var domain = named[1].ToLowerInvariant();
var stored = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == actor.Id).ExecuteFirstAsync(token); var stored = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == actor.Id).ExecuteFirstAsync(token);
if (stored?.Domain == domain && stored.UserName == actor.PreferredUsername) if (stored?.Domain == domain && stored.UserName == actor.PreferredUsername)
return domain; return domain;
return await ResolveHandle($"{named[0]}@{domain}", token) == actor.Id ? domain : host; return await ResolveHandle($"{named[0]}@{domain}", token) == actor.Id ? domain : host;
+16 -25
View File
@@ -32,42 +32,33 @@ namespace PrivaPub.Federation.Actors
// the persona and its followers, and told to its followers' servers with Add{Note}. The persona may take it off again // the persona and its followers, and told to its followers' servers with Add{Note}. The persona may take it off again
// (Remove, which Smithereen takes for a deletion, as it is on its walls). Another server's account that tells its // (Remove, which Smithereen takes for a deletion, as it is on its walls). Another server's account that tells its
// followers here of a post on its wall (Add) has it shown to them as on its wall. // followers here of a post on its wall (Add) has it shown to them as on its wall.
public class Walls : IWalls public class Walls(
DbEntities dbEntities,
ILocalActorService localActors,
IRemotePosts remotePosts,
IDeliveryService delivery,
IFanout fanout) : IWalls
{ {
public const string Path = "graffiti"; public const string Path = "graffiti";
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemotePosts _remotePosts;
readonly IDeliveryService _delivery;
readonly IFanout _fanout;
public Walls(DbEntities dbEntities, ILocalActorService localActors, IRemotePosts remotePosts, IDeliveryService delivery, IFanout fanout)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remotePosts = remotePosts;
_delivery = delivery;
_fanout = fanout;
}
public async Task<LocalActor> OwnerOf(string wallUri, CancellationToken token) public async Task<LocalActor> OwnerOf(string wallUri, CancellationToken token)
{ {
if (string.IsNullOrEmpty(wallUri) || !wallUri.EndsWith("/" + Path, StringComparison.Ordinal)) if (string.IsNullOrEmpty(wallUri) || !wallUri.EndsWith("/" + Path, StringComparison.Ordinal))
return default; return default;
var owner = await _localActors.FindByUri(wallUri[..^(Path.Length + 1)], token); var owner = await localActors.FindByUri(wallUri[..^(Path.Length + 1)], token);
return owner is { HasWall: true } && owner.Wall == wallUri ? owner : default; return owner is { HasWall: true } && owner.Wall == wallUri ? owner : default;
} }
// its followers, as the actor says to Smithereen (wallPosting), unless the persona hides them // its followers, as the actor says to Smithereen (wallPosting), unless the persona hides them
public async Task<bool> MayWrite(LocalActor owner, ForeignAvatar author, CancellationToken token) => public async Task<bool> MayWrite(LocalActor owner, ForeignAvatar author, CancellationToken token) =>
await _dbEntities.Followers.Match(f => f.LocalActorId == owner.Id && f.LocalActorKind == owner.Kind && f.ActorURI == author.ActorURI && f.IsAccepted) await dbEntities.Followers.Match(f => f.LocalActorId == owner.Id && f.LocalActorKind == owner.Kind && f.ActorURI == author.ActorURI && f.IsAccepted)
.ExecuteAnyAsync(token) .ExecuteAnyAsync(token)
&& !(await Domain.Relationships.Hidden.RecipientsHiding(new[] { owner.Id }, author.ActorURI, token)).Contains(owner.Id); && !(await Domain.Relationships.Hidden.RecipientsHiding(new[] { owner.Id }, author.ActorURI, token)).Contains(owner.Id);
public async Task Hosted(PostEntity post, LocalActor owner, CancellationToken token) public async Task Hosted(PostEntity post, LocalActor owner, CancellationToken token)
{ {
await Notifications.Add(owner.Id, NotificationType.Mention, post.AuthorAccountId, post.ActorURI, post.ID, token); await Notifications.Add(owner.Id, NotificationType.Mention, post.AuthorAccountId, post.ActorURI, post.ID, token: token);
var add = new JsonObject var add = new JsonObject
{ {
["@context"] = ActivityPubRenderer.Context(), ["@context"] = ActivityPubRenderer.Context(),
@@ -78,7 +69,7 @@ namespace PrivaPub.Federation.Actors
["target"] = new JsonObject { ["type"] = "OrderedCollection", ["id"] = owner.Wall, ["attributedTo"] = owner.Uri }, ["target"] = new JsonObject { ["type"] = "OrderedCollection", ["id"] = owner.Wall, ["attributedTo"] = owner.Uri },
["to"] = new JsonArray(ActivityPubRenderer.Public, owner.Followers, post.ActorURI) ["to"] = new JsonArray(ActivityPubRenderer.Public, owner.Followers, post.ActorURI)
}; };
await _delivery.EnqueueToFollowers(owner, add, token, await AuthorInbox(post, token)); await delivery.EnqueueToFollowers(owner, add, await AuthorInbox(post, token), token);
} }
public async Task Receive(JsonNode activity, ForeignAvatar owner, bool add, CancellationToken token) public async Task Receive(JsonNode activity, ForeignAvatar owner, bool add, CancellationToken token)
@@ -91,7 +82,7 @@ namespace PrivaPub.Federation.Actors
} }
if (!add) if (!add)
{ {
var walled = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.WallOwnerURI == owner.ActorURI).ExecuteFirstAsync(token); var walled = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && p.WallOwnerURI == owner.ActorURI).ExecuteFirstAsync(token);
if (walled == default) if (walled == default)
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -102,8 +93,8 @@ namespace PrivaPub.Federation.Actors
return; return;
} }
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token) var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await _remotePosts.StoreContext(objectUri, 0, token); ?? await remotePosts.StoreContext(objectUri, 0, token);
if (post is not { IsFederatedCopy: true, ReblogOfPostId: null, Visibility: PostVisibility.Public or PostVisibility.Unlisted } || !string.IsNullOrEmpty(post.InReplyToURI)) if (post is not { IsFederatedCopy: true, ReblogOfPostId: null, Visibility: PostVisibility.Public or PostVisibility.Unlisted } || !string.IsNullOrEmpty(post.InReplyToURI))
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -123,7 +114,7 @@ namespace PrivaPub.Federation.Actors
.Modify(p => p.WallOwnerURI, post.WallOwnerURI) .Modify(p => p.WallOwnerURI, post.WallOwnerURI)
.Modify(p => p.WallOwnerAccountId, post.WallOwnerAccountId) .Modify(p => p.WallOwnerAccountId, post.WallOwnerAccountId)
.ExecuteAsync(token); .ExecuteAsync(token);
await _fanout.Distribute(post, token); await fanout.Distribute(post, token);
Arrival.Accept("walled"); Arrival.Accept("walled");
} }
@@ -142,14 +133,14 @@ namespace PrivaPub.Federation.Actors
["target"] = owner.Wall, ["target"] = owner.Wall,
["to"] = new JsonArray(ActivityPubRenderer.Public, owner.Followers, post.ActorURI) ["to"] = new JsonArray(ActivityPubRenderer.Public, owner.Followers, post.ActorURI)
}; };
await _delivery.EnqueueToFollowers(owner, remove, token, await AuthorInbox(post, token)); await delivery.EnqueueToFollowers(owner, remove, await AuthorInbox(post, token), token);
await RemoteDeletes.Remove(post, post.ObjectURI, token); await RemoteDeletes.Remove(post, post.ObjectURI, token);
return true; return true;
} }
async Task<IEnumerable<string>> AuthorInbox(PostEntity post, CancellationToken token) async Task<IEnumerable<string>> AuthorInbox(PostEntity post, CancellationToken token)
{ {
var author = await _dbEntities.ForeignAvatars.Match(a => a.ActorURI == post.ActorURI).ExecuteFirstAsync(token); var author = await dbEntities.ForeignAvatars.Match(a => a.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
var inbox = string.IsNullOrEmpty(author?.SharedInboxURL) ? author?.InboxURL : author.SharedInboxURL; var inbox = string.IsNullOrEmpty(author?.SharedInboxURL) ? author?.InboxURL : author.SharedInboxURL;
return inbox == default ? Array.Empty<string>() : new[] { inbox }; return inbox == default ? Array.Empty<string>() : new[] { inbox };
} }
@@ -17,16 +17,11 @@ namespace PrivaPub.Federation.Controllers
// answers 410 with a Tombstone. An emoji tells nothing about anyone, so it is served unsigned under SecureMode too, as the // answers 410 with a Tombstone. An emoji tells nothing about anyone, so it is served unsigned under SecureMode too, as the
// server's own actors are; a browser is sent to the picture. // server's own actors are; a browser is sent to the picture.
[ApiController] [ApiController]
public class EmojisController : ControllerBase public class EmojisController(
ILocalActorService localActors) : ControllerBase
{ {
const string ActivityContentType = "application/activity+json; charset=utf-8"; const string ActivityContentType = "application/activity+json; charset=utf-8";
readonly ILocalActorService _localActors;
public EmojisController(ILocalActorService localActors)
{
_localActors = localActors;
}
[HttpGet, Route("/" + LocalEmojis.Path + "/{shortcode}")] [HttpGet, Route("/" + LocalEmojis.Path + "/{shortcode}")]
public async Task<IActionResult> Get(string shortcode, CancellationToken token) public async Task<IActionResult> Get(string shortcode, CancellationToken token)
@@ -44,7 +39,7 @@ namespace PrivaPub.Federation.Controllers
Content = new JsonObject Content = new JsonObject
{ {
["@context"] = ActivityPubRenderer.ActivityStreams, ["@context"] = ActivityPubRenderer.ActivityStreams,
["id"] = LocalEmojis.Uri(_localActors.BaseAddress, emoji.Shortcode), ["id"] = LocalEmojis.Uri(localActors.BaseAddress, emoji.Shortcode),
["type"] = "Tombstone", ["type"] = "Tombstone",
["formerType"] = "Emoji", ["formerType"] = "Emoji",
["deleted"] = ActivityPubRenderer.Timestamp(deleted) ["deleted"] = ActivityPubRenderer.Timestamp(deleted)
@@ -60,7 +55,7 @@ namespace PrivaPub.Federation.Controllers
emoji.ImageUpdatedAt, emoji.Category, emoji.VisibleInPicker); emoji.ImageUpdatedAt, emoji.Category, emoji.VisibleInPicker);
return new ContentResult return new ContentResult
{ {
Content = LocalEmojis.Document(live, _localActors.BaseAddress).ToJsonString(), Content = LocalEmojis.Document(live, localActors.BaseAddress).ToJsonString(),
ContentType = ActivityContentType, ContentType = ActivityContentType,
StatusCode = StatusCodes.Status200OK StatusCode = StatusCodes.Status200OK
}; };
@@ -26,34 +26,23 @@ using PrivaPub.Infrastructure;
namespace PrivaPub.Federation.Controllers namespace PrivaPub.Federation.Controllers
{ {
[ApiController, Route("peasants")] [ApiController, Route("peasants")]
public class PeasantsController : ControllerBase, IAsyncActionFilter public class PeasantsController(
ILocalActorService localActors,
IInboxReceiver inboxReceiver,
DbEntities dbEntities,
ILogger<PeasantsController> logger,
ISignedFetchAuthorizer fetches,
IOptionsMonitor<FederationOptions> federation) : ControllerBase, IAsyncActionFilter
{ {
const string ActivityContentType = "application/activity+json; charset=utf-8"; const string ActivityContentType = "application/activity+json; charset=utf-8";
const int OutboxSize = 20; const int OutboxSize = 20;
readonly ILocalActorService _localActors;
readonly IInboxReceiver _inbox;
readonly DbEntities _dbEntities;
readonly ILogger<PeasantsController> _logger;
readonly ISignedFetchAuthorizer _fetches;
readonly IOptionsMonitor<FederationOptions> _federation;
public PeasantsController(ILocalActorService localActors, IInboxReceiver inbox, DbEntities dbEntities,
ILogger<PeasantsController> logger, ISignedFetchAuthorizer fetches, IOptionsMonitor<FederationOptions> federation)
{
_fetches = fetches;
_federation = federation;
_localActors = localActors;
_inbox = inbox;
_dbEntities = dbEntities;
_logger = logger;
}
[HttpGet, Route("{actor}")] [HttpGet, Route("{actor}")]
public async Task<IActionResult> GetActor(string actor, CancellationToken token) public async Task<IActionResult> GetActor(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local == default && await _localActors.Gone(actor, token) is { } gone) if (local == default && await localActors.Gone(actor, token) is { } gone)
return new ContentResult return new ContentResult
{ {
Content = new JsonObject Content = new JsonObject
@@ -82,14 +71,14 @@ namespace PrivaPub.Federation.Controllers
var accept = Request.Headers.Accept.ToString(); var accept = Request.Headers.Accept.ToString();
if (!accept.Contains("activity+json", StringComparison.OrdinalIgnoreCase) && !accept.Contains("ld+json", StringComparison.OrdinalIgnoreCase)) if (!accept.Contains("activity+json", StringComparison.OrdinalIgnoreCase) && !accept.Contains("ld+json", StringComparison.OrdinalIgnoreCase))
return NotFound(); return NotFound();
return Activity(ActivityPubRenderer.Actor(await _localActors.GetInstanceActor(token))); return Activity(ActivityPubRenderer.Actor(await localActors.GetInstanceActor(token)));
} }
[HttpGet, Route("{actor}/anus")] [HttpGet, Route("{actor}/anus")]
public async Task<IActionResult> Outbox(string actor, [FromQuery] bool page, [FromQuery(Name = "max_id")] string maxId, public async Task<IActionResult> Outbox(string actor, [FromQuery] bool page, [FromQuery(Name = "max_id")] string maxId,
CancellationToken token) CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return NotFound(); return NotFound();
@@ -101,8 +90,8 @@ namespace PrivaPub.Federation.Controllers
} }
var query = local.Kind == LocalActorKind.Group var query = local.Kind == LocalActorKind.Group
? _dbEntities.Posts.Match(p => p.GroupId == local.Id).Match(VisibilityPolicy.IsPublic) ? dbEntities.Posts.Match(p => p.GroupId == local.Id).Match(VisibilityPolicy.IsPublic)
: _dbEntities.Posts.Match(p => p.GroupUserId == local.Id && !p.IsFederatedCopy).Match(VisibilityPolicy.IsPublic); : dbEntities.Posts.Match(p => p.GroupUserId == local.Id && !p.IsFederatedCopy).Match(VisibilityPolicy.IsPublic);
if (!string.IsNullOrEmpty(maxId)) if (!string.IsNullOrEmpty(maxId))
query.Match(f => f.Lt(p => p.ID, maxId)); query.Match(f => f.Lt(p => p.ID, maxId));
var latest = await query.Sort(p => p.ID, Order.Descending).Limit(OutboxSize).ExecuteAsync(token); var latest = await query.Sort(p => p.ID, Order.Descending).Limit(OutboxSize).ExecuteAsync(token);
@@ -134,11 +123,11 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/groupies")] [HttpGet, Route("{actor}/groupies")]
public async Task<IActionResult> Followers(string actor, CancellationToken token) public async Task<IActionResult> Followers(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return NotFound(); return NotFound();
if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(await _dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token), if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(await dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token),
await _fetches.Requester(Request, token))) await fetches.Requester(Request, token)))
return NotFound(); return NotFound();
var count = await DB.Default.CountAsync<Follower>( var count = await DB.Default.CountAsync<Follower>(
f => f.LocalActorId == local.Id && f.LocalActorKind == local.Kind && f.IsAccepted, token); f => f.LocalActorId == local.Id && f.LocalActorKind == local.Kind && f.IsAccepted, token);
@@ -150,7 +139,7 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/" + Walls.Path)] [HttpGet, Route("{actor}/" + Walls.Path)]
public async Task<IActionResult> Wall(string actor, [FromQuery] bool page, [FromQuery(Name = "max_id")] string maxId, CancellationToken token) public async Task<IActionResult> Wall(string actor, [FromQuery] bool page, [FromQuery(Name = "max_id")] string maxId, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { HasWall: true }) if (local is not { HasWall: true })
return NotFound(); return NotFound();
var wall = local.Wall; var wall = local.Wall;
@@ -161,7 +150,7 @@ namespace PrivaPub.Federation.Controllers
|| p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null && p.AnsweringToPostId == null && p.InReplyToURI == null && p.GroupId == null); || p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null && p.AnsweringToPostId == null && p.InReplyToURI == null && p.GroupId == null);
if (!page) if (!page)
return Activity(ActivityPubRenderer.OrderedCollection(wall, (int)await DB.Default.CountAsync(onWall, token), default, $"{wall}?page=true")); return Activity(ActivityPubRenderer.OrderedCollection(wall, (int)await DB.Default.CountAsync(onWall, token), default, $"{wall}?page=true"));
var query = _dbEntities.Posts.Match(onWall); var query = dbEntities.Posts.Match(onWall);
if (!string.IsNullOrEmpty(maxId)) if (!string.IsNullOrEmpty(maxId))
query.Match(f => f.Lt(p => p.ID, maxId)); query.Match(f => f.Lt(p => p.ID, maxId));
var latest = await query.Sort(p => p.ID, Order.Descending).Limit(OutboxSize).ExecuteAsync(token); var latest = await query.Sort(p => p.ID, Order.Descending).Limit(OutboxSize).ExecuteAsync(token);
@@ -174,10 +163,10 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/groupies/roll-call")] [HttpGet, Route("{actor}/groupies/roll-call")]
public async Task<IActionResult> RollCall(string actor, CancellationToken token) public async Task<IActionResult> RollCall(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true } || !FollowersSynchronization.Synchronizes(local)) if (local is not { IsFederated: true } || !FollowersSynchronization.Synchronizes(local))
return NotFound(); return NotFound();
var requester = await _fetches.Requester(Request, token); var requester = await fetches.Requester(Request, token);
if (requester == default) if (requester == default)
return StatusCode(StatusCodes.Status401Unauthorized); return StatusCode(StatusCodes.Status401Unauthorized);
var there = await FollowersSynchronization.On(local, FollowersSynchronization.Origin(requester.ActorURI), token); var there = await FollowersSynchronization.On(local, FollowersSynchronization.Origin(requester.ActorURI), token);
@@ -187,7 +176,7 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/stalking")] [HttpGet, Route("{actor}/stalking")]
public async Task<IActionResult> Following(string actor, CancellationToken token) public async Task<IActionResult> Following(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return NotFound(); return NotFound();
// the count, as following_count says it; who is followed is never listed (FEDERATION.md) // the count, as following_count says it; who is followed is never listed (FEDERATION.md)
@@ -200,11 +189,11 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/flock")] [HttpGet, Route("{actor}/flock")]
public async Task<IActionResult> Members(string actor, CancellationToken token) public async Task<IActionResult> Members(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Group }) if (local is not { IsFederated: true, Kind: LocalActorKind.Group })
return NotFound(); return NotFound();
var group = await _dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token); var group = await dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token);
if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(group, await _fetches.Requester(Request, token))) if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(group, await fetches.Requester(Request, token)))
return NotFound(); return NotFound();
return Activity(ActivityPubRenderer.OrderedCollection(local.Flock, group.Members.Count, default)); return Activity(ActivityPubRenderer.OrderedCollection(local.Flock, group.Members.Count, default));
} }
@@ -212,15 +201,15 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/wardens")] [HttpGet, Route("{actor}/wardens")]
public async Task<IActionResult> Moderators(string actor, CancellationToken token) public async Task<IActionResult> Moderators(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Group }) if (local is not { IsFederated: true, Kind: LocalActorKind.Group })
return NotFound(); return NotFound();
var group = await _dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token); var group = await dbEntities.Groups.MatchID(local.Id).ExecuteFirstAsync(token);
if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(group, await _fetches.Requester(Request, token))) if (local.IsCircle && !SignedFetchAuthorizer.MayReadCircle(group, await fetches.Requester(Request, token)))
return NotFound(); return NotFound();
var moderators = new List<JsonNode>(); var moderators = new List<JsonNode>();
foreach (var member in group.Members.Where(m => !m.IsForeign && m.Role is GroupRole.Owner or GroupRole.Moderator)) foreach (var member in group.Members.Where(m => !m.IsForeign && m.Role is GroupRole.Owner or GroupRole.Moderator))
if (await _localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } moderator) if (await localActors.FindById(LocalActorKind.Person, member.AvatarId, token) is { } moderator)
moderators.Add(moderator.Uri); moderators.Add(moderator.Uri);
return Activity(ActivityPubRenderer.OrderedCollection(local.Wardens, moderators.Count, moderators)); return Activity(ActivityPubRenderer.OrderedCollection(local.Wardens, moderators.Count, moderators));
} }
@@ -228,14 +217,14 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/trophies")] [HttpGet, Route("{actor}/trophies")]
public async Task<IActionResult> Featured(string actor, CancellationToken token) public async Task<IActionResult> Featured(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return NotFound(); return NotFound();
var pinIds = (await DB.Default.Find<Pin>().Match(p => p.AvatarId == local.Id).Sort(p => p.ID, Order.Descending).ExecuteAsync(token)) var pinIds = (await DB.Default.Find<Pin>().Match(p => p.AvatarId == local.Id).Sort(p => p.ID, Order.Descending).ExecuteAsync(token))
.Select(p => p.PostId).ToList(); .Select(p => p.PostId).ToList();
var posts = pinIds.Count == 0 var posts = pinIds.Count == 0
? new List<PostEntity>() ? new List<PostEntity>()
: await _dbEntities.Posts.Match(p => pinIds.Contains(p.ID) && p.GroupUserId == local.Id && p.ReblogOfPostId == null) : await dbEntities.Posts.Match(p => pinIds.Contains(p.ID) && p.GroupUserId == local.Id && p.ReblogOfPostId == null)
.Match(VisibilityPolicy.IsPublic).ExecuteAsync(token); .Match(VisibilityPolicy.IsPublic).ExecuteAsync(token);
var notes = new List<JsonNode>(); var notes = new List<JsonNode>();
foreach (var id in pinIds) foreach (var id in pinIds)
@@ -249,7 +238,7 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/tattoos")] [HttpGet, Route("{actor}/tattoos")]
public async Task<IActionResult> FeaturedTags(string actor, CancellationToken token) public async Task<IActionResult> FeaturedTags(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return NotFound(); return NotFound();
var tags = local.Kind == LocalActorKind.Person var tags = local.Kind == LocalActorKind.Person
@@ -278,7 +267,7 @@ namespace PrivaPub.Federation.Controllers
if (WantsHtml()) if (WantsHtml())
return Redirect(local.PostHtmlUrl(post.ID)); return Redirect(local.PostHtmlUrl(post.ID));
var group = string.IsNullOrEmpty(post.GroupId) ? default : await _localActors.FindById(LocalActorKind.Group, post.GroupId, token); var group = string.IsNullOrEmpty(post.GroupId) ? default : await localActors.FindById(LocalActorKind.Group, post.GroupId, token);
var note = ActivityPubRenderer.Note(post, local, group, post.InReplyToURI); var note = ActivityPubRenderer.Note(post, local, group, post.InReplyToURI);
note["@context"] = ActivityPubRenderer.Context(); note["@context"] = ActivityPubRenderer.Context();
return Activity(note); return Activity(note);
@@ -291,7 +280,7 @@ namespace PrivaPub.Federation.Controllers
var (local, post) = await PublicPost(actor, postId, token); var (local, post) = await PublicPost(actor, postId, token);
if (post == default || post.IsLocalOnly || !string.IsNullOrEmpty(post.GroupId)) if (post == default || post.IsLocalOnly || !string.IsNullOrEmpty(post.GroupId))
return NotFound(); return NotFound();
var replies = await _dbEntities.Posts.Match(p => p.AnsweringToPostId == post.ID && !p.IsLocalOnly && p.ReblogOfPostId == null) var replies = await dbEntities.Posts.Match(p => p.AnsweringToPostId == post.ID && !p.IsLocalOnly && p.ReblogOfPostId == null)
.Match(VisibilityPolicy.IsPublic).Sort(p => p.CreationDate, Order.Ascending).Limit(MaxThread).ExecuteAsync(token); .Match(VisibilityPolicy.IsPublic).Sort(p => p.CreationDate, Order.Ascending).Limit(MaxThread).ExecuteAsync(token);
replies.RemoveAll(VisibilityPolicy.Barred); replies.RemoveAll(VisibilityPolicy.Barred);
return Activity(ActivityPubRenderer.OrderedCollection(local.PostUri(post.ID) + "/replies", replies.Count, return Activity(ActivityPubRenderer.OrderedCollection(local.PostUri(post.ID) + "/replies", replies.Count,
@@ -309,7 +298,7 @@ namespace PrivaPub.Federation.Controllers
var level = new List<string> { root.ID }; var level = new List<string> { root.ID };
for (var depth = 0; depth < PrivaPub.Federation.Inbox.RemotePosts.MaxDepth && level.Count > 0 && thread.Count < MaxThread; depth++) for (var depth = 0; depth < PrivaPub.Federation.Inbox.RemotePosts.MaxDepth && level.Count > 0 && thread.Count < MaxThread; depth++)
{ {
var next = await _dbEntities.Posts.Match(p => level.Contains(p.AnsweringToPostId) && !p.IsLocalOnly && p.ReblogOfPostId == null) var next = await dbEntities.Posts.Match(p => level.Contains(p.AnsweringToPostId) && !p.IsLocalOnly && p.ReblogOfPostId == null)
.Match(VisibilityPolicy.IsPublic).Sort(p => p.CreationDate, Order.Ascending).Limit(MaxThread - thread.Count).ExecuteAsync(token); .Match(VisibilityPolicy.IsPublic).Sort(p => p.CreationDate, Order.Ascending).Limit(MaxThread - thread.Count).ExecuteAsync(token);
thread.AddRange(next.Where(p => !VisibilityPolicy.Barred(p))); thread.AddRange(next.Where(p => !VisibilityPolicy.Barred(p)));
level = next.Select(p => p.ID).ToList(); level = next.Select(p => p.ID).ToList();
@@ -324,9 +313,9 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/parrot-licences/{licenceId}")] [HttpGet, Route("{actor}/parrot-licences/{licenceId}")]
public async Task<IActionResult> ParrotLicence(string actor, string licenceId, CancellationToken token) public async Task<IActionResult> ParrotLicence(string actor, string licenceId, CancellationToken token)
{ {
var author = await _localActors.FindByUserName(actor, token); var author = await localActors.FindByUserName(actor, token);
var licence = author == default ? default : await DB.Default.Find<QuoteLicence>().Match(l => l.ID == licenceId && l.AuthorAvatarId == author.Id).ExecuteFirstAsync(token); var licence = author == default ? default : await DB.Default.Find<QuoteLicence>().Match(l => l.ID == licenceId && l.AuthorAvatarId == author.Id).ExecuteFirstAsync(token);
var quoted = licence == default ? default : await _dbEntities.Posts.MatchID(licence.PostId).ExecuteFirstAsync(token); var quoted = licence == default ? default : await dbEntities.Posts.MatchID(licence.PostId).ExecuteFirstAsync(token);
if (quoted == default) if (quoted == default)
return NotFound(); return NotFound();
var uri = Domain.Statuses.QuoteService.LicenceUri(author, licence.ID); var uri = Domain.Statuses.QuoteService.LicenceUri(author, licence.ID);
@@ -353,13 +342,13 @@ namespace PrivaPub.Federation.Controllers
{ {
if (activityId.StartsWith("announce-", StringComparison.Ordinal)) if (activityId.StartsWith("announce-", StringComparison.Ordinal))
{ {
var booster = await _localActors.FindByUserName(actor, token); var booster = await localActors.FindByUserName(actor, token);
var uri = booster?.ActivityUri(activityId); var uri = booster?.ActivityUri(activityId);
if (booster is { Kind: LocalActorKind.Group, IsCircle: false }) if (booster is { Kind: LocalActorKind.Group, IsCircle: false })
return await GroupAnnounce(booster, activityId, uri, token); return await GroupAnnounce(booster, activityId, uri, token);
var reblog = uri == default ? default : await _dbEntities.Posts.Match(p => p.ObjectURI == uri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); var reblog = uri == default ? default : await dbEntities.Posts.Match(p => p.ObjectURI == uri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
var rendered = reblog == default ? default : await AnnounceFor(reblog, token); var rendered = reblog == default ? default : await AnnounceFor(reblog, token);
if (rendered != default && WantsHtml() && await _dbEntities.Posts.MatchID(reblog.ReblogOfPostId).ExecuteFirstAsync(token) is { } boosted) if (rendered != default && WantsHtml() && await dbEntities.Posts.MatchID(reblog.ReblogOfPostId).ExecuteFirstAsync(token) is { } boosted)
return Redirect(boosted.Url ?? boosted.ObjectURI);//a boost has no page of its own: the boosted post's return Redirect(boosted.Url ?? boosted.ObjectURI);//a boost has no page of its own: the boosted post's
return rendered == default ? NotFound() : Activity(rendered); return rendered == default ? NotFound() : Activity(rendered);
} }
@@ -377,14 +366,14 @@ namespace PrivaPub.Federation.Controllers
[HttpGet, Route("{actor}/whispers/{conversationId}")] [HttpGet, Route("{actor}/whispers/{conversationId}")]
public async Task<IActionResult> Whispers(string actor, string conversationId, CancellationToken token) public async Task<IActionResult> Whispers(string actor, string conversationId, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Person }) if (local is not { IsFederated: true, Kind: LocalActorKind.Person })
return NotFound(); return NotFound();
var uri = local.ConversationUri(conversationId); var uri = local.ConversationUri(conversationId);
var conversation = await _dbEntities.DmGroups.Match(g => g.ID == conversationId && g.ConversationURI == uri && !g.DeletionAt.HasValue).ExecuteFirstAsync(token); var conversation = await dbEntities.DmGroups.Match(g => g.ID == conversationId && g.ConversationURI == uri && !g.DeletionAt.HasValue).ExecuteFirstAsync(token);
if (conversation == default || !SignedFetchAuthorizer.MayReadConversation(conversation, await _fetches.Requester(Request, token))) if (conversation == default || !SignedFetchAuthorizer.MayReadConversation(conversation, await fetches.Requester(Request, token)))
return NotFound(); return NotFound();
var posts = await _dbEntities.Posts var posts = await dbEntities.Posts
.Match(p => p.ConversationId == conversationId && p.Visibility == PostVisibility.Direct && !p.DeletedAt.HasValue) .Match(p => p.ConversationId == conversationId && p.Visibility == PostVisibility.Direct && !p.DeletedAt.HasValue)
.Sort(p => p.CreationDate, Order.Ascending) .Sort(p => p.CreationDate, Order.Ascending)
.ExecuteAsync(token); .ExecuteAsync(token);
@@ -401,28 +390,28 @@ namespace PrivaPub.Federation.Controllers
[HttpPost, Route("{actor}/mouth"), EnableRateLimiting(RateLimiting.Inbox)] [HttpPost, Route("{actor}/mouth"), EnableRateLimiting(RateLimiting.Inbox)]
public async Task<IActionResult> Inbox(string actor, CancellationToken token) public async Task<IActionResult> Inbox(string actor, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local == default && await _localActors.Gone(actor, token) != default) if (local == default && await localActors.Gone(actor, token) != default)
return StatusCode(StatusCodes.Status410Gone); return StatusCode(StatusCodes.Status410Gone);
if (local is not { IsFederated: true }) if (local is not { IsFederated: true })
return Answer(_inbox.NoSuchRecipient(Request)); return Answer(inboxReceiver.NoSuchRecipient(Request));
return Answer(await _inbox.Receive(Request, local, token)); return Answer(await inboxReceiver.Receive(Request, local, token));
} }
[HttpPost, Route("{actor}/human-centipede"), EnableRateLimiting(RateLimiting.Inbox)] [HttpPost, Route("{actor}/human-centipede"), EnableRateLimiting(RateLimiting.Inbox)]
public async Task<IActionResult> ActorSharedInbox(string actor, CancellationToken token) => public async Task<IActionResult> ActorSharedInbox(string actor, CancellationToken token) =>
Answer(await _inbox.Receive(Request, default, token)); Answer(await inboxReceiver.Receive(Request, default, token));
[HttpPost, Route("/human-centipede"), EnableRateLimiting(RateLimiting.Inbox)] [HttpPost, Route("/human-centipede"), EnableRateLimiting(RateLimiting.Inbox)]
public async Task<IActionResult> SharedInbox(CancellationToken token) => public async Task<IActionResult> SharedInbox(CancellationToken token) =>
Answer(await _inbox.Receive(Request, default, token)); Answer(await inboxReceiver.Receive(Request, default, token));
async Task<(LocalActor Actor, PostEntity Post)> PublicPost(string actor, string postId, CancellationToken token) async Task<(LocalActor Actor, PostEntity Post)> PublicPost(string actor, string postId, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Person }) if (local is not { IsFederated: true, Kind: LocalActorKind.Person })
return default; return default;
var post = await _dbEntities.Posts var post = await dbEntities.Posts
.Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null) .Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null)
.Match(VisibilityPolicy.IsPublic) .Match(VisibilityPolicy.IsPublic)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
@@ -434,24 +423,24 @@ namespace PrivaPub.Federation.Controllers
// member, or the members on the requesting instance actor's server. // member, or the members on the requesting instance actor's server.
async Task<(LocalActor Author, PostEntity Post, JsonObject Note)?> SignedPost(string actor, string postId, CancellationToken token) async Task<(LocalActor Author, PostEntity Post, JsonObject Note)?> SignedPost(string actor, string postId, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Person }) if (local is not { IsFederated: true, Kind: LocalActorKind.Person })
return default; return default;
var post = await _dbEntities.Posts var post = await dbEntities.Posts
.Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null .Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.ReblogOfPostId == null
&& (p.Visibility == PostVisibility.FollowersOnly || p.Visibility == PostVisibility.Direct || p.Visibility == PostVisibility.Circle)) && (p.Visibility == PostVisibility.FollowersOnly || p.Visibility == PostVisibility.Direct || p.Visibility == PostVisibility.Circle))
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
if (post == default) if (post == default)
return default; return default;
var requester = await _fetches.Requester(Request, token); var requester = await fetches.Requester(Request, token);
if (!await _fetches.MayRead(post, requester, token)) if (!await fetches.MayRead(post, requester, token))
return default; return default;
if (post.Visibility == PostVisibility.Circle) if (post.Visibility == PostVisibility.Circle)
{ {
var circle = await _dbEntities.Groups.MatchID(post.GroupId).ExecuteFirstAsync(token); var circle = await dbEntities.Groups.MatchID(post.GroupId).ExecuteFirstAsync(token);
var note = ActivityPubRenderer.Note(post, local, _localActors.FromGroup(circle), post.InReplyToURI); var note = ActivityPubRenderer.Note(post, local, localActors.FromGroup(circle), post.InReplyToURI);
var readers = SignedFetchAuthorizer.CircleReaders(circle, requester); var readers = SignedFetchAuthorizer.CircleReaders(circle, requester);
var named = readers.Count == 0 ? new List<Models.User.ForeignAvatar>() : await _dbEntities.ForeignAvatars.Match(a => readers.Contains(a.ActorURI)).ExecuteAsync(token); var named = readers.Count == 0 ? new List<Models.User.ForeignAvatar>() : await dbEntities.ForeignAvatars.Match(a => readers.Contains(a.ActorURI)).ExecuteAsync(token);
return (local, post, OutboxPublisher.Naming(note, named)); return (local, post, OutboxPublisher.Naming(note, named));
} }
var rendered = post.Visibility == PostVisibility.Direct var rendered = post.Visibility == PostVisibility.Direct
@@ -464,10 +453,10 @@ namespace PrivaPub.Federation.Controllers
async Task<IActionResult> Tombstone(string actor, string postId, CancellationToken token) async Task<IActionResult> Tombstone(string actor, string postId, CancellationToken token)
{ {
var local = await _localActors.FindByUserName(actor, token); var local = await localActors.FindByUserName(actor, token);
if (local is not { IsFederated: true, Kind: LocalActorKind.Person }) if (local is not { IsFederated: true, Kind: LocalActorKind.Person })
return default; return default;
var deleted = await _dbEntities.Posts var deleted = await dbEntities.Posts
.Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.DeletedAt.HasValue .Match(p => p.ID == postId && p.GroupUserId == local.Id && !p.IsFederatedCopy && p.DeletedAt.HasValue
&& (p.Visibility == PostVisibility.Public || p.Visibility == PostVisibility.Unlisted)) && (p.Visibility == PostVisibility.Public || p.Visibility == PostVisibility.Unlisted))
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
@@ -493,7 +482,7 @@ namespace PrivaPub.Federation.Controllers
{ {
if (await DB.Default.Find<GroupAnnouncement>().Match(a => a.ActivityURI == uri && a.GroupId == group.Id).ExecuteFirstAsync(token) is { } kept) if (await DB.Default.Find<GroupAnnouncement>().Match(a => a.ActivityURI == uri && a.GroupId == group.Id).ExecuteFirstAsync(token) is { } kept)
{ {
var about = await _dbEntities.Posts.Match(p => p.ObjectURI == kept.ObjectURI).ExecuteFirstAsync(token); var about = await dbEntities.Posts.Match(p => p.ObjectURI == kept.ObjectURI).ExecuteFirstAsync(token);
if (!VisibilityPolicy.Shown(about) || about.Visibility is not (PostVisibility.Public or PostVisibility.Unlisted)) if (!VisibilityPolicy.Shown(about) || about.Visibility is not (PostVisibility.Public or PostVisibility.Unlisted))
return StatusCode(StatusCodes.Status410Gone); return StatusCode(StatusCodes.Status410Gone);
var body = JsonNode.Parse(kept.Body)!.AsObject(); var body = JsonNode.Parse(kept.Body)!.AsObject();
@@ -501,13 +490,13 @@ namespace PrivaPub.Federation.Controllers
return Activity(body); return Activity(body);
} }
var postId = activityId["announce-".Length..]; var postId = activityId["announce-".Length..];
var post = await _dbEntities.Posts.Match(p => p.ID == postId && p.GroupId == group.Id).Match(VisibilityPolicy.IsPublic).ExecuteFirstAsync(token); var post = await dbEntities.Posts.Match(p => p.ID == postId && p.GroupId == group.Id).Match(VisibilityPolicy.IsPublic).ExecuteFirstAsync(token);
return post == default ? NotFound() : Activity(ActivityPubRenderer.Announce(group, post.ObjectURI, activityId, post.CreationDate)); return post == default ? NotFound() : Activity(ActivityPubRenderer.Announce(group, post.ObjectURI, activityId, post.CreationDate));
} }
async Task<JsonObject> AnnounceFor(PostEntity reblog, CancellationToken token) async Task<JsonObject> AnnounceFor(PostEntity reblog, CancellationToken token)
{ {
var original = await _dbEntities.Posts.MatchID(reblog.ReblogOfPostId).ExecuteFirstAsync(token); var original = await dbEntities.Posts.MatchID(reblog.ReblogOfPostId).ExecuteFirstAsync(token);
if (!VisibilityPolicy.Shown(original)) if (!VisibilityPolicy.Shown(original))
return default; return default;
return new JsonObject return new JsonObject
@@ -525,7 +514,7 @@ namespace PrivaPub.Federation.Controllers
async Task<JsonObject> CreateFor(PostEntity post, LocalActor author, CancellationToken token) async Task<JsonObject> CreateFor(PostEntity post, LocalActor author, CancellationToken token)
{ {
var group = string.IsNullOrEmpty(post.GroupId) ? default : await _localActors.FindById(LocalActorKind.Group, post.GroupId, token); var group = string.IsNullOrEmpty(post.GroupId) ? default : await localActors.FindById(LocalActorKind.Group, post.GroupId, token);
var note = ActivityPubRenderer.Note(post, author, group, post.InReplyToURI); var note = ActivityPubRenderer.Note(post, author, group, post.InReplyToURI);
return ActivityPubRenderer.Create(author, note, $"create-{post.ID}"); return ActivityPubRenderer.Create(author, note, $"create-{post.ID}");
} }
@@ -546,9 +535,9 @@ namespace PrivaPub.Federation.Controllers
// SecureMode asks every reader of ActivityPub documents for a signature, except for the server's own actors (the // SecureMode asks every reader of ActivityPub documents for a signature, except for the server's own actors (the
// instance actor, the reporter, the reader of feeds), whose keys peers need first, and except for browsers, which // instance actor, the reporter, the reader of feeds), whose keys peers need first, and except for browsers, which
// only get redirected to the public pages // only get redirected to the public pages
if (_federation.CurrentValue.SecureMode && HttpMethods.IsGet(Request.Method) && !WantsHtml() && Request.Path.Value != "/" if (federation.CurrentValue.SecureMode && HttpMethods.IsGet(Request.Method) && !WantsHtml() && Request.Path.Value != "/"
&& !LocalActorService.IsServerActorName(context.RouteData.Values["actor"] as string) && !LocalActorService.IsServerActorName(context.RouteData.Values["actor"] as string)
&& await _fetches.Requester(Request, HttpContext.RequestAborted) == default) && await fetches.Requester(Request, HttpContext.RequestAborted) == default)
{ {
context.Result = StatusCode(StatusCodes.Status401Unauthorized); context.Result = StatusCode(StatusCodes.Status401Unauthorized);
return; return;
@@ -557,7 +546,7 @@ namespace PrivaPub.Federation.Controllers
// nothing new is told of it, and lifting the suspension serves it all again (owner decision 2026-10-17) // nothing new is told of it, and lifting the suspension serves it all again (owner decision 2026-10-17)
if (HttpMethods.IsGet(Request.Method) && context.RouteData.Values["actor"] is string name if (HttpMethods.IsGet(Request.Method) && context.RouteData.Values["actor"] is string name
&& context.ActionDescriptor is Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor { ActionName: not nameof(GetActor) } && context.ActionDescriptor is Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor { ActionName: not nameof(GetActor) }
&& await _localActors.FindByUserName(name, HttpContext.RequestAborted) is { Kind: LocalActorKind.Person, Suspended: true }) && await localActors.FindByUserName(name, HttpContext.RequestAborted) is { Kind: LocalActorKind.Person, Suspended: true })
{ {
context.Result = NotFound(); context.Result = NotFound();
return; return;
@@ -568,7 +557,7 @@ namespace PrivaPub.Federation.Controllers
IActionResult Answer(InboxResult result) IActionResult Answer(InboxResult result)
{ {
if (result.Error != default) if (result.Error != default)
_logger.LogInformation("Inbox refused with {Status} ({Reason}): {Error}", result.StatusCode, result.Reason, result.Error); logger.LogInformation("Inbox refused with {Status} ({Reason}): {Error}", result.StatusCode, result.Reason, result.Error);
if (result.RetryAfterSeconds is { } seconds) if (result.RetryAfterSeconds is { } seconds)
Response.Headers.RetryAfter = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture); Response.Headers.RetryAfter = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
return result.Error == default ? StatusCode(result.StatusCode) : StatusCode(result.StatusCode, result.Error); return result.Error == default ? StatusCode(result.StatusCode) : StatusCode(result.StatusCode, result.Error);
@@ -18,31 +18,20 @@ using PrivaPub.Infrastructure;
namespace PrivaPub.Federation.Controllers namespace PrivaPub.Federation.Controllers
{ {
[ApiController] [ApiController]
public class WellKnownController : ControllerBase public class WellKnownController(
ILocalActorService localActors,
IOptionsMonitor<RegistrationOptions> registrations,
Domain.Instance.IInstanceSettings settings) : ControllerBase
{ {
readonly ILocalActorService _localActors;
readonly DbEntities _dbEntities;
readonly IOptionsMonitor<RegistrationOptions> _registrations;
readonly Domain.Instance.IInstanceSettings _settings;
public WellKnownController(ILocalActorService localActors, DbEntities dbEntities, IOptionsMonitor<RegistrationOptions> registrations,
Domain.Instance.IInstanceSettings settings)
{
_registrations = registrations;
_settings = settings;
_localActors = localActors;
_dbEntities = dbEntities;
}
[HttpGet, Route("/.well-known/webfinger")] [HttpGet, Route("/.well-known/webfinger")]
public async Task<IActionResult> WebFinger([FromQuery] string resource, CancellationToken token) public async Task<IActionResult> WebFinger([FromQuery] string resource, CancellationToken token)
{ {
if (string.IsNullOrEmpty(resource)) if (string.IsNullOrEmpty(resource))
return BadRequest(); return BadRequest();
// the server itself (FEP-d556): its instance actor // the server itself (FEP-d556): its instance actor
if (resource.TrimEnd('/') == _localActors.BaseAddress) if (resource.TrimEnd('/') == localActors.BaseAddress)
{ {
var instance = await _localActors.GetInstanceActor(token); var instance = await localActors.GetInstanceActor(token);
return Content(new JsonObject return Content(new JsonObject
{ {
["subject"] = resource, ["subject"] = resource,
@@ -53,7 +42,7 @@ namespace PrivaPub.Federation.Controllers
}.ToJsonString(), "application/jrd+json; charset=utf-8"); }.ToJsonString(), "application/jrd+json; charset=utf-8");
} }
LocalActor actor; var actor = default(LocalActor);
// Mastodon, GoToSocial and Pleroma also take a bare user@domain or @user@domain, so we do too. // Mastodon, GoToSocial and Pleroma also take a bare user@domain or @user@domain, so we do too.
var acct = resource.StartsWith("acct:", StringComparison.OrdinalIgnoreCase) ? resource[5..] var acct = resource.StartsWith("acct:", StringComparison.OrdinalIgnoreCase) ? resource[5..]
: !resource.Contains("://", StringComparison.Ordinal) && resource.Contains('@') ? resource : !resource.Contains("://", StringComparison.Ordinal) && resource.Contains('@') ? resource
@@ -61,15 +50,15 @@ namespace PrivaPub.Federation.Controllers
if (acct != default) if (acct != default)
{ {
var parts = acct.TrimStart('@').Split('@'); var parts = acct.TrimStart('@').Split('@');
var domain = new Uri(_localActors.BaseAddress).Authority; var domain = new Uri(localActors.BaseAddress).Authority;
if (parts.Length != 2 || !parts[1].Equals(domain, StringComparison.OrdinalIgnoreCase)) if (parts.Length != 2 || !parts[1].Equals(domain, StringComparison.OrdinalIgnoreCase))
return NotFound(); return NotFound();
actor = await _localActors.FindByUserName(parts[0], token); actor = await localActors.FindByUserName(parts[0], token);
if (actor == default && await _localActors.Gone(parts[0], token) != default) if (actor == default && await localActors.Gone(parts[0], token) != default)
return StatusCode(StatusCodes.Status410Gone); return StatusCode(StatusCodes.Status410Gone);
} }
else else
actor = await _localActors.FindByUri(resource, token); actor = await localActors.FindByUri(resource, token);
if (actor is not { IsFederated: true }) if (actor is not { IsFederated: true })
return NotFound(); return NotFound();
@@ -96,18 +85,18 @@ namespace PrivaPub.Federation.Controllers
new JsonObject new JsonObject
{ {
["rel"] = "http://nodeinfo.diaspora.software/ns/schema/2.1", ["rel"] = "http://nodeinfo.diaspora.software/ns/schema/2.1",
["href"] = $"{_localActors.BaseAddress}/nodeinfo/2.1" ["href"] = $"{localActors.BaseAddress}/nodeinfo/2.1"
}, },
new JsonObject new JsonObject
{ {
["rel"] = "http://nodeinfo.diaspora.software/ns/schema/2.0", ["rel"] = "http://nodeinfo.diaspora.software/ns/schema/2.0",
["href"] = $"{_localActors.BaseAddress}/nodeinfo/2.0" ["href"] = $"{localActors.BaseAddress}/nodeinfo/2.0"
}, },
// the application actor (FEP-2677) // the application actor (FEP-2677)
new JsonObject new JsonObject
{ {
["rel"] = "https://www.w3.org/ns/activitystreams#Application", ["rel"] = "https://www.w3.org/ns/activitystreams#Application",
["href"] = (await _localActors.GetInstanceActor(token)).Uri ["href"] = (await localActors.GetInstanceActor(token)).Uri
}) })
}; };
return Content(document.ToJsonString(), "application/json; charset=utf-8"); return Content(document.ToJsonString(), "application/json; charset=utf-8");
@@ -130,7 +119,7 @@ namespace PrivaPub.Federation.Controllers
["software"] = software, ["software"] = software,
["protocols"] = new JsonArray("activitypub"), ["protocols"] = new JsonArray("activitypub"),
["services"] = new JsonObject { ["inbound"] = new JsonArray(), ["outbound"] = new JsonArray() }, ["services"] = new JsonObject { ["inbound"] = new JsonArray(), ["outbound"] = new JsonArray() },
["openRegistrations"] = _registrations.CurrentValue.IsOpen, ["openRegistrations"] = registrations.CurrentValue.IsOpen,
["usage"] = new JsonObject ["usage"] = new JsonObject
{ {
["users"] = new JsonObject ["users"] = new JsonObject
@@ -144,8 +133,8 @@ namespace PrivaPub.Federation.Controllers
["metadata"] = new JsonObject ["metadata"] = new JsonObject
{ {
// the server's name and short description, as its administrator set them (IInstanceSettings) // the server's name and short description, as its administrator set them (IInstanceSettings)
["nodeName"] = _settings.Current.Title, ["nodeName"] = settings.Current.Title,
["nodeDescription"] = _settings.Current.ShortDescription ?? string.Empty, ["nodeDescription"] = settings.Current.ShortDescription ?? string.Empty,
["federation"] = new JsonObject { ["document"] = "https://git.thepra.dev/thepra/SocialPub/src/branch/master/FEDERATION.md" } ["federation"] = new JsonObject { ["document"] = "https://git.thepra.dev/thepra/SocialPub/src/branch/master/FEDERATION.md" }
} }
}; };
+28 -49
View File
@@ -23,21 +23,12 @@ namespace PrivaPub.Federation.Crawler
} }
//each hour, the servers due for a visit, spread across the hour so the crawler reaches one at a time //each hour, the servers due for a visit, spread across the hour so the crawler reaches one at a time
public class CrawlPlanner : IJobHandler public class CrawlPlanner(
IJobQueue queue,
IDomainBlocks blocks,
IOptionsMonitor<StatisticsOptions> options,
IOptionsMonitor<FederationOptions> federation = default) : IJobHandler
{ {
readonly IJobQueue _queue;
readonly IDomainBlocks _blocks;
readonly IOptionsMonitor<StatisticsOptions> _options;
readonly IOptionsMonitor<FederationOptions> _federation;
public CrawlPlanner(IJobQueue queue, IDomainBlocks blocks, IOptionsMonitor<StatisticsOptions> options, IOptionsMonitor<FederationOptions> federation = default)
{
_queue = queue;
_blocks = blocks;
_options = options;
_federation = federation;
}
public JobKind Kind => JobKind.CrawlPlan; public JobKind Kind => JobKind.CrawlPlan;
public int Concurrency => 1; public int Concurrency => 1;
public int MaxAttempts => 1; public int MaxAttempts => 1;
@@ -53,11 +44,11 @@ namespace PrivaPub.Federation.Crawler
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var crawler = _options.CurrentValue.Crawler; var crawler = options.CurrentValue.Crawler;
if (!crawler.Enabled) if (!crawler.Enabled)
return JobOutcome.Done; return JobOutcome.Done;
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
foreach (var seed in PeerHosts.Filter(crawler.Seeds ?? new(), host => !_blocks.IsSuspended(host), _federation?.CurrentValue.AllowPrivateNetworks == true)) foreach (var seed in PeerHosts.Filter(crawler.Seeds ?? new(), host => !blocks.IsSuspended(host), federation?.CurrentValue.AllowPrivateNetworks == true))
await DB.Default.Update<RemoteInstance>() await DB.Default.Update<RemoteInstance>()
.Match(i => i.Host == seed) .Match(i => i.Host == seed)
.Modify(b => b.SetOnInsert(i => i.Seen, "crawled")) .Modify(b => b.SetOnInsert(i => i.Seen, "crawled"))
@@ -73,7 +64,7 @@ namespace PrivaPub.Federation.Crawler
.Limit(perHour * 3) .Limit(perHour * 3)
.ExecuteAsync(token); .ExecuteAsync(token);
var week = InstanceDescriber.Week(now); var week = InstanceDescriber.Week(now);
var jobs = candidates.Where(i => _blocks.Find(i.Host) == default && PeerHosts.Normalise(i.Host) != default) var jobs = candidates.Where(i => blocks.Find(i.Host) == default && PeerHosts.Normalise(i.Host) != default)
.Take(perHour) .Take(perHour)
.Select((instance, index) => new Job .Select((instance, index) => new Job
{ {
@@ -83,36 +74,24 @@ namespace PrivaPub.Federation.Crawler
DedupeKey = $"crawl|{instance.Host}|{week}", DedupeKey = $"crawl|{instance.Host}|{week}",
RunAt = now.AddSeconds(index * 3600.0 / perHour) RunAt = now.AddSeconds(index * 3600.0 / perHour)
}); });
await _queue.EnqueueMany(jobs, token); await queue.EnqueueMany(jobs, token);
return JobOutcome.Done; return JobOutcome.Done;
} }
} }
//one server: its robots.txt, a description if only crawling ever found it, then the servers its peers list names //one server: its robots.txt, a description if only crawling ever found it, then the servers its peers list names
public class InstanceCrawler : IJobHandler public class InstanceCrawler(
IFederationHttp http,
InstanceDescriber describer,
IDomainBlocks blocks,
IOptionsMonitor<StatisticsOptions> options,
IOptionsMonitor<AppConfiguration> app,
IOptionsMonitor<FederationOptions> federation,
IInteractionLedger ledger = default) : IJobHandler
{ {
const int MaxPeers = 20_000; const int MaxPeers = 20_000;
const int MaxRobotsBytes = 64 * 1024; const int MaxRobotsBytes = 64 * 1024;
readonly IFederationHttp _http;
readonly InstanceDescriber _describer;
readonly IDomainBlocks _blocks;
readonly IOptionsMonitor<StatisticsOptions> _options;
readonly IOptionsMonitor<AppConfiguration> _app;
readonly IOptionsMonitor<FederationOptions> _federation;
readonly IInteractionLedger _ledger;
public InstanceCrawler(IFederationHttp http, InstanceDescriber describer, IDomainBlocks blocks, IOptionsMonitor<StatisticsOptions> options,
IOptionsMonitor<AppConfiguration> app, IOptionsMonitor<FederationOptions> federation, IInteractionLedger ledger = default)
{
_http = http;
_describer = describer;
_blocks = blocks;
_options = options;
_app = app;
_federation = federation;
_ledger = ledger;
}
public JobKind Kind => JobKind.CrawlInstance; public JobKind Kind => JobKind.CrawlInstance;
public int Concurrency => 1; public int Concurrency => 1;
@@ -123,16 +102,16 @@ namespace PrivaPub.Federation.Crawler
public async Task<JobOutcome> Handle(Job job, CancellationToken token) public async Task<JobOutcome> Handle(Job job, CancellationToken token)
{ {
var crawler = _options.CurrentValue.Crawler; var crawler = options.CurrentValue.Crawler;
var host = job.Payload; var host = job.Payload;
if (!crawler.Enabled || _blocks.Find(host) != default) if (!crawler.Enabled || blocks.Find(host) != default)
return JobOutcome.Done; return JobOutcome.Done;
using var crawl = HttpScope.Crawl(Stargazer.UserAgent(_app.CurrentValue.BackendBaseAddress)); using var crawl = HttpScope.Crawl(Stargazer.UserAgent(app.CurrentValue.BackendBaseAddress));
RobotsTxt robots; var robots = default(RobotsTxt);
using (HttpScope.For("robots")) using (HttpScope.For("robots"))
{ {
var (status, text) = await _http.GetText(Address($"https://{host}/robots.txt"), MaxRobotsBytes, token); var (status, text) = await http.GetText(Address($"https://{host}/robots.txt"), MaxRobotsBytes, token);
robots = RobotsTxt.From(status, text, Stargazer.Token, "PrivaPub"); robots = RobotsTxt.From(status, text, Stargazer.Token, "PrivaPub");
} }
var instance = await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteFirstAsync(token); var instance = await DB.Default.Find<RemoteInstance>().Match(i => i.Host == host).ExecuteFirstAsync(token);
@@ -146,14 +125,14 @@ namespace PrivaPub.Federation.Crawler
var reachable = true; var reachable = true;
if (instance?.Seen != "touched") if (instance?.Seen != "touched")
reachable = await _describer.Describe(host, crawled: true, robots.Allows, token); reachable = await describer.Describe(host, crawled: true, robots.Allows, token);
int? peersCount = default; int? peersCount = default;
if (robots.Allows("/api/v1/instance/peers")) if (robots.Allows("/api/v1/instance/peers"))
{ {
IReadOnlyList<string> peers; var peers = default(IReadOnlyList<string>);
using (HttpScope.For("peers")) using (HttpScope.For("peers"))
peers = await _http.GetStringArray(Address($"https://{host}/api/v1/instance/peers"), MaxPeers, token); peers = await http.GetStringArray(Address($"https://{host}/api/v1/instance/peers"), MaxPeers, token);
peersCount = peers.Count; peersCount = peers.Count;
await Discover(peers, crawler, token); await Discover(peers, crawler, token);
} }
@@ -167,8 +146,8 @@ namespace PrivaPub.Federation.Crawler
var room = Math.Min(crawler.MaxNewHostsPerCrawl, crawler.MaxHosts - (int)await DB.Default.CountAsync<RemoteInstance>(i => i.Seen == "crawled", token)); var room = Math.Min(crawler.MaxNewHostsPerCrawl, crawler.MaxHosts - (int)await DB.Default.CountAsync<RemoteInstance>(i => i.Seen == "crawled", token));
if (room <= 0) if (room <= 0)
return; return;
var candidates = PeerHosts.Filter(peers, host => _http.IsAllowed(new Uri($"https://{host}/")) && _blocks.Find(host) == default, var candidates = PeerHosts.Filter(peers, host => http.IsAllowed(new Uri($"https://{host}/")) && blocks.Find(host) == default,
_federation.CurrentValue.AllowPrivateNetworks).ToList(); federation.CurrentValue.AllowPrivateNetworks).ToList();
var now = DateTime.UtcNow; var now = DateTime.UtcNow;
foreach (var batch in candidates.Chunk(500)) foreach (var batch in candidates.Chunk(500))
{ {
@@ -203,6 +182,6 @@ namespace PrivaPub.Federation.Crawler
} }
void Record(string host, string outcome, string reason) => void Record(string host, string outcome, string reason) =>
_ledger?.Record(new InteractionEvent { Channel = Interactions.Crawl, Host = host, Outcome = outcome, Reason = reason, Crawl = true }); ledger?.Record(new InteractionEvent { Channel = Interactions.Crawl, Host = host, Outcome = outcome, Reason = reason, Crawl = true });
} }
} }
@@ -12,53 +12,40 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers 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 virtual string Type => "Accept";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) 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"); Arrival.Accept("quote-answer");
return; 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"); Arrival.Accept("interaction-answer");
return; 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"); Arrival.Accept("participation-answer");
return; 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"); Arrival.Accept("relay-answer");
return; return;
} }
var following = await FindFollowing(activity["object"], actor, _dbEntities, _localActors, token); var following = await FindFollowing(activity["object"], actor, db, localActorService, token);
if (following == default) if (following == default)
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -73,8 +60,8 @@ namespace PrivaPub.Federation.Inbox.Handlers
protected virtual async Task Apply(Following following, CancellationToken token) 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); await DB.Default.Update<Following>().MatchID(following.ID).Modify(f => f.State, FollowState.Accepted).ExecuteAsync(token);
if (_queue != default) if (queue != default)
await _queue.Enqueue(Models.Jobs.JobKind.BackfillOutbox, following.TargetActorURI, new Uri(following.TargetActorURI).Host, await queue.Enqueue(Models.Jobs.JobKind.BackfillOutbox, following.TargetActorURI, new Uri(following.TargetActorURI).Host,
Actors.OutboxBackfill.DedupeKey(following.TargetActorURI, DateTime.UtcNow), token); Actors.OutboxBackfill.DedupeKey(following.TargetActorURI, DateTime.UtcNow), token);
} }
@@ -22,40 +22,23 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers 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 // 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 // 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; } 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"; public string Type => "Announce";
@@ -74,27 +57,27 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop("unparseable"); Arrival.Drop("unparseable");
return; 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"); Arrival.Drop("duplicate");
return; return;
} }
if (_relayService != default && await _relayService.Passes(actor.ActorURI, token)) if (relays != default && await relays.Passes(actor.ActorURI, token))
{ {
await FromRelay(objectUri, token); await FromRelay(objectUri, token);
return; return;
} }
var isLocal = objectUri.StartsWith(_localActors.BaseAddress + "/", StringComparison.OrdinalIgnoreCase); 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 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 followed = await dbEntities.Followings.Match(f => f.TargetActorURI == actor.ActorURI && f.State == FollowState.Accepted).ExecuteAnyAsync(token);
if (original is not { IsFederatedCopy: false } && !followed) if (original is not { IsFederatedCopy: false } && !followed)
{ {
Arrival.Drop("not-followed"); Arrival.Drop("not-followed");
return; return;
} }
if (original == default && !isLocal) if (original == default && !isLocal)
original = await _remotePosts.StoreContext(objectUri, 0, token); original = await remotePosts.StoreContext(objectUri, 0, token);
if (original == default) if (original == default)
{ {
Arrival.Drop("fetch-failed"); Arrival.Drop("fetch-failed");
@@ -125,7 +108,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
Cc = cc, Cc = cc,
IsFederatedCopy = true, IsFederatedCopy = true,
AuthorSuspended = actor.SuspendedAt.HasValue, AuthorSuspended = actor.SuspendedAt.HasValue,
AuthorLimited = RemotePosts.Limited(actor, _domainBlocks), AuthorLimited = RemotePosts.Limited(actor, domainBlocks),
CreationDate = published, CreationDate = published,
UpdateDate = published UpdateDate = published
}; };
@@ -144,20 +127,20 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
Arrival.Accept("stored"); 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); await DB.Default.Update<PostEntity>().MatchID(original.ID).Modify(b => b.Inc(p => p.ReblogsCount, 1)).ExecuteAsync(token);
if (!original.IsFederatedCopy) if (!original.IsFederatedCopy)
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, actor.ID, actor.ActorURI, original.ID, token); await Notifications.Add(original.GroupUserId, NotificationType.Reblog, actor.ID, actor.ActorURI, original.ID, token: token);
await _fanout.Distribute(reblog, 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 // 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) // boost (Mastodon unwraps them the same way)
async Task FromRelay(string objectUri, CancellationToken token) async Task FromRelay(string objectUri, CancellationToken token)
{ {
var held = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token); var held = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = held ?? await _remotePosts.StoreContext(objectUri, 0, token); var post = held ?? await remotePosts.StoreContext(objectUri, 0, token);
if (post == default) if (post == default)
{ {
Arrival.Drop("fetch-failed"); Arrival.Drop("fetch-failed");
@@ -170,14 +153,14 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
Arrival.Accept("relayed"); Arrival.Accept("relayed");
await _fanout.Distribute(post, token); await fanout.Distribute(post, token);
} }
async Task GroupActivity(JsonNode inner, ForeignAvatar group, CancellationToken token) async Task GroupActivity(JsonNode inner, ForeignAvatar group, CancellationToken token)
{ {
Arrival.About(Value(inner, "type")); Arrival.About(Value(inner, "type"));
if (group.AvatarType != AvatarType.Group 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)) && !await OurPostInItsThread(inner, group, token))
{ {
Arrival.Drop("not-followed"); Arrival.Drop("not-followed");
@@ -187,12 +170,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
switch (Value(inner, "type")) switch (Value(inner, "type"))
{ {
case "Create" when objectUri != default: 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"); Arrival.Drop("duplicate");
return; return;
} }
var post = await _remotePosts.StoreContext(objectUri, 0, token); var post = await remotePosts.StoreContext(objectUri, 0, token);
if (post == default) if (post == default)
{ {
Arrival.Drop("fetch-failed"); Arrival.Drop("fetch-failed");
@@ -202,10 +185,10 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.About(visibility: post.Visibility); Arrival.About(visibility: post.Visibility);
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.AudienceURI, group.ActorURI).ExecuteAsync(token); await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.AudienceURI, group.ActorURI).ExecuteAsync(token);
post.AudienceURI = group.ActorURI; post.AudienceURI = group.ActorURI;
await _fanout.Distribute(post, token); await fanout.Distribute(post, token);
break; break;
case "Update" when objectUri != default: 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); .ExecuteFirstAsync(token);
if (stored == default) if (stored == default)
{ {
@@ -213,7 +196,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
Arrival.About(visibility: stored.Visibility, created: stored.CreationDate); 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())); var note = fetched == default ? default : NoteParser.Parse(System.Text.Json.Nodes.JsonNode.Parse(fetched.Root.GetRawText()));
if (note == default || note.AttributedTo != stored.ActorURI) if (note == default || note.AttributedTo != stored.ActorURI)
@@ -221,11 +204,11 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop(note == default ? "fetch-failed" : "misattributed"); Arrival.Drop(note == default ? "fetch-failed" : "misattributed");
return; 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; break;
case "Delete" when objectUri != default: 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) if (deleted == default)
{ {
Arrival.Drop("unknown-object"); 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. // 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 // One elsewhere is believed once the post's server says it is gone
if (!Origin.Same(objectUri, group.ActorURI)) 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") if (check != default && Value(System.Text.Json.Nodes.JsonNode.Parse(check.Root.GetRawText()), "type") != "Tombstone")
{ {
Arrival.Drop("not-deleted"); Arrival.Drop("not-deleted");
@@ -257,7 +240,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
await Ban(inner, group, token); await Ban(inner, group, token);
break; break;
case "Undo" when Value(inner["object"], "type") == "Block" && Id(inner["object"]?["target"]) == group.ActorURI: 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"); Arrival.Accept("unbanned");
else else
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -267,7 +250,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
break; break;
// a moderator features a post in the community, or no longer: the community's own pins // 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: 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")); ?.FirstOrDefault(h => h.Type == Value(inner, "type"));
if (featured == default) if (featured == default)
Arrival.Drop("unsupported"); Arrival.Drop("unsupported");
@@ -292,8 +275,8 @@ namespace PrivaPub.Federation.Inbox.Handlers
}; };
var post = target == default var post = target == default
? default ? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == target && !p.IsFederatedCopy && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); : 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; 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 // 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 var post = objectUri == default
? 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) if (post == default)
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -318,7 +301,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
// host is not taken: it would be ours to announce. // host is not taken: it would be ours to announce.
async Task Move(string objectUri, string targetUri, ForeignAvatar group, CancellationToken token) 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); .ExecuteFirstAsync(token);
if (post == default) if (post == default)
{ {
@@ -326,9 +309,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
Arrival.About(visibility: post.Visibility, created: post.CreationDate); 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 ? default
: await _remoteActors.GetActor(targetUri, refresh: false, token); : await remoteActors.GetActor(targetUri, refresh: false, token);
if (target is not { AvatarType: AvatarType.Group }) if (target is not { AvatarType: AvatarType.Group })
{ {
Arrival.Drop("unknown-target"); Arrival.Drop("unknown-target");
@@ -339,7 +322,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
while (level.Count > 0 && thread.Count < MaxMoved) while (level.Count > 0 && thread.Count < MaxMoved)
{ {
var parents = level; 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(); .Project(p => new PostEntity { ID = p.ID }).ExecuteAsync(token)).Select(p => p.ID).ToList();
thread.AddRange(level); 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. // Undo. A ban of someone from another server is no business of ours.
async Task Ban(JsonNode inner, ForeignAvatar group, CancellationToken token) 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"); Arrival.Drop("not-ours");
return; return;
@@ -378,7 +361,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
{ {
var actorUri = Id(inner["actor"]); var actorUri = Id(inner["actor"]);
var type = Value(inner, "type"); 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); var handler = handlers?.FirstOrDefault(h => h.Type == type);
if (actorUri == default || handler == default) if (actorUri == default || handler == default)
{ {
@@ -388,7 +371,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var activity = inner; var activity = inner;
var target = Id(Value(inner, "type") == "Undo" ? (inner["object"] as JsonObject)?["object"] : inner["object"]); var target = Id(Value(inner, "type") == "Undo" ? (inner["object"] as JsonObject)?["object"] : inner["object"]);
var ownPost = target != default 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) if (!Origin.Same(actorUri, group.ActorURI) && !ownPost)
{ {
var id = Id(inner); var id = Id(inner);
@@ -397,7 +380,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.Drop("misattributed"); Arrival.Drop("misattributed");
return; 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()); activity = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
if (activity == default || Value(activity, "type") != type || Id(activity["actor"]) != actorUri) if (activity == default || Value(activity, "type") != type || Id(activity["actor"]) != actorUri)
{ {
@@ -405,7 +388,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
} }
var actor = await _remoteActors.GetActor(actorUri, refresh: false, token); var actor = await remoteActors.GetActor(actorUri, refresh: false, token);
if (actor == default) if (actor == default)
{ {
Arrival.Drop("unknown-actor"); 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 // 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 // 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. // 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 string Type => "Block";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) 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 }) if (target is not { Kind: LocalActorKind.Person })
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -70,7 +63,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
async Task Ban(JsonNode activity, LocalActor persona, string communityUri, CancellationToken token) 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) if (community == default)
{ {
Arrival.Drop("unknown-community"); Arrival.Drop("unknown-community");
@@ -26,45 +26,22 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers 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 string Type => "Create";
public async Task Handle(JsonNode activity, ForeignAvatar author, CancellationToken token) 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); var refetched = node is not JsonObject || !Origin.Same(Id(node), author.ActorURI);
if (refetched) 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()); node = fetched == default ? default : JsonNode.Parse(fetched.Root.GetRawText());
if (node == default) if (node == default)
Arrival.Drop("fetch-failed"); Arrival.Drop("fetch-failed");
@@ -85,11 +62,11 @@ namespace PrivaPub.Federation.Inbox.Handlers
{ {
if (!refetched) 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())); note = fetched == default ? default : NoteParser.Parse(JsonNode.Parse(fetched.Root.GetRawText()));
refetched = true; 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) if (author == default)
{ {
Arrival.Drop(note == default ? "fetch-failed" : "author-unavailable"); Arrival.Drop(note == default ? "fetch-failed" : "author-unavailable");
@@ -104,16 +81,16 @@ namespace PrivaPub.Federation.Inbox.Handlers
Arrival.About(note.Type); Arrival.About(note.Type);
if (note.Title != default && note.InReplyTo != default && ObjectShapes.Text(note.ContentHtml, 1) == default) 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) 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.Accept("poll-vote");
Arrival.About(visibility: question.Visibility); Arrival.About(visibility: question.Visibility);
return; 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"); Arrival.Drop("duplicate");
return; return;
@@ -146,7 +123,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var localTargets = new List<LocalActor>(); var localTargets = new List<LocalActor>();
for (var i = 0; i < addressed.Count; i++) 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) if (local == default)
continue; continue;
addressed[i] = local.Uri; addressed[i] = local.Uri;
@@ -158,9 +135,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
var parent = string.IsNullOrEmpty(note.InReplyTo) var parent = string.IsNullOrEmpty(note.InReplyTo)
? default ? 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 // 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"); Arrival.Drop("reply-not-authorized");
return; return;
@@ -183,26 +160,26 @@ namespace PrivaPub.Federation.Inbox.Handlers
group = default; group = default;
var repliesToLocal = parent is { IsFederatedCopy: false } && visibility != PostVisibility.Direct; 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) .Match(f => f.TargetActorURI == author.ActorURI && f.State == FollowState.Accepted)
.ExecuteAnyAsync(token); .ExecuteAnyAsync(token);
// a reply in the thread of someone followed here, as Mastodon keeps them: what the thread's server forwards // 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 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 // 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 // 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 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) && 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 // a public post a relay we subscribe to passes on, for the federated timeline (read again from its origin, as any
// forwarded post) // forwarded post)
var relayed = !followed && visibility == PostVisibility.Public && _relays != default var relayed = !followed && visibility == PostVisibility.Public && relays != default
&& await _relays.Passes(Arrival.Current?.ForwardedBy, token); && 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 // written on a persona's wall (FEP-400e): public, not a reply, by an account following the persona, as its actor
// tells Smithereen // 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) 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"); Arrival.Drop("wall-refused");
return; return;
@@ -214,7 +191,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
return; return;
} }
if (parent == default && visibility != PostVisibility.Direct) 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; DmGroup conversation = default;
if (visibility == PostVisibility.Direct) 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); 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.ActivityURI = Id(activity);
post.GroupId = group?.Id; post.GroupId = group?.Id;
post.ConversationId = conversation?.ID; post.ConversationId = conversation?.ID;
@@ -247,31 +224,31 @@ namespace PrivaPub.Federation.Inbox.Handlers
} }
Arrival.Accept("stored"); Arrival.Accept("stored");
Arrival.About(local: group ?? persons.FirstOrDefault()); Arrival.About(local: group ?? persons.FirstOrDefault());
await _records.Record(note, post, ObjectPath.Delivered, refetched, token); await records.Record(note, post, ObjectPath.Delivered, refetched, token);
await _previews.Wanted(post, token); await previews.Wanted(post, token);
await _quotes.Resolve(post, note, token); await quotes.Resolve(post, note, token);
if (parent != default && Domain.Privacy.Counted.Reply(post)) 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 DB.Default.Update<PostEntity>().MatchID(parent.ID).Modify(b => b.Inc(p => p.RepliesCount, 1)).ExecuteAsync(token);
await _fanout.Distribute(post, token); await fanout.Distribute(post, token);
await ReplyRelay.Pass(post, _dbEntities, _localActors, _delivery, token); await ReplyRelay.Pass(post, dbEntities, localActors, delivery, token);
if (conversation != default) if (conversation != default)
{ {
await Domain.Statuses.ConversationStates.Posted(conversation.ID, post.ID, default, token); 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 await Domain.Timelines.Fanout.Conversation(conversation.ID, token);//the `direct` streams (R8), once it is the newest
} }
if (group is { IsCircle: false }) 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) 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) => 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) 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 return entity?.PostingPolicy switch
{ {
PostingPolicy.Anyone => true, PostingPolicy.Anyone => true,
@@ -285,7 +262,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var members = new List<GroupMember>(); var members = new List<GroupMember>();
foreach (var uri in participantUris.Distinct(StringComparer.Ordinal)) 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 var member = local != default && local.Kind == LocalActorKind.Person
? new GroupMember { AvatarId = local.Id } ? new GroupMember { AvatarId = local.Id }
: new GroupMember { AvatarId = uri, IsForeign = true }; : new GroupMember { AvatarId = uri, IsForeign = true };
@@ -294,7 +271,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
} }
var key = DmGroup.KeyOf(members); 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) if (match != default)
return match; return match;
@@ -21,26 +21,14 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers 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"; public string Type => "Delete";
const int MaxObjects = 50; const int MaxObjects = 50;
@@ -70,7 +58,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
actor.DeletionAt = DateTime.UtcNow; actor.DeletionAt = DateTime.UtcNow;
actor.AccountState = AvatarAccountState.Deleted; actor.AccountState = AvatarAccountState.Deleted;
await DB.Default.SaveAsync(actor, token); 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) foreach (var follower in followers)
{ {
await DB.Default.DeleteAsync<Follower>(follower.ID); await DB.Default.DeleteAsync<Follower>(follower.ID);
@@ -85,24 +73,24 @@ namespace PrivaPub.Federation.Inbox.Handlers
} }
await RemoteDeletes.Tombstone(objectUri, token); 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 // deleted by another account of its author's server (Mobilizon's organiser deletes the group's event): once
// that server says it is gone // that server says it is gone
if (post == default && await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token) is { } held 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)) && held.ActorURI != actor.ActorURI && Origin.Same(held.ActorURI, actor.ActorURI) && await remoteActors.IsGone(objectUri, token))
post = held; post = held;
if (post == default) if (post == default)
{ {
Arrival.Accept("tombstone-only"); Arrival.Accept("tombstone-only");
await _quotes.Revoke(objectUri, token); await quotes.Revoke(objectUri, token);
return; return;
} }
Arrival.Accept("removed"); Arrival.Accept("removed");
Arrival.About(post.ObjectType, post.Visibility, post.CreationDate); 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); await RemoteDeletes.Remove(post, objectUri, token);
if (!string.IsNullOrEmpty(post.GroupId) && await _localActors.FindById(LocalActorKind.Group, post.GroupId, token) is { IsCircle: false } community) 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); 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 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 string Type => "Dislike";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) 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 objectUri = Id(activity["object"]);
var post = objectUri == default var post = objectUri == default
? 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)) if (post == default || !await VisibilityPolicy.RemoteCanSee(post, actor, token))
{ {
Arrival.Drop(post == default ? "unknown-object" : "not-visible"); Arrival.Drop(post == default ? "unknown-object" : "not-visible");
@@ -8,17 +8,10 @@ using static PrivaPub.Federation.Objects.ActivityJson;
namespace PrivaPub.Federation.Inbox.Handlers 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 string Type => "EmojiReact";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) 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 objectUri = Id(activity["object"]);
var post = objectUri == default var post = objectUri == default
? 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) if (post == default)
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
return; return;
} }
Arrival.About(post.ObjectType ?? "Note", post.Visibility, post.CreationDate); 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 // 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 // (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. // 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; public string Type => add ? "Add" : "Remove";
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 async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) 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; return;
var target = Objects.ActivityJson.Id(activity["target"]); 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 // 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) // 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)) && 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 // 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 (Objects.ActivityJson.Value(activity["object"], "type") == "Hashtag")
{ {
if (_tags != default && target != default && (target == actor.FeaturedURL || target == actor.FeaturedTagsURL)) if (tags != default && target != default && (target == actor.FeaturedURL || target == actor.FeaturedTagsURL))
await _tags.Receive(activity, actor, _add, token); await tags.Receive(activity, actor, add, token);
else else
Arrival.Drop("unknown-target"); Arrival.Drop("unknown-target");
return; return;
} }
if (_walls != default && !string.IsNullOrEmpty(actor.WallURL) && target == actor.WallURL) if (walls != default && !string.IsNullOrEmpty(actor.WallURL) && target == actor.WallURL)
await _walls.Receive(activity, actor, _add, token); await walls.Receive(activity, actor, add, token);
else 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 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 string Type => "Flag";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -38,7 +31,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var postUris = new List<string>(); var postUris = new List<string>();
foreach (var uri in objects.Take(50)) 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) if (local is { Kind: LocalActorKind.Person } && uri.TrimEnd('/') == local.Uri)
target ??= local; target ??= local;
else else
@@ -46,9 +39,9 @@ namespace PrivaPub.Federation.Inbox.Handlers
} }
var posts = postUris.Count == 0 var posts = postUris.Count == 0
? new List<Models.Post.Post>() ? 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) 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) if (target == default)
{ {
Arrival.Drop("unknown-object"); Arrival.Drop("unknown-object");
@@ -21,21 +21,11 @@ using PostEntity = PrivaPub.Models.Post.Post;
namespace PrivaPub.Federation.Inbox.Handlers 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 string Type => "Follow";
public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token) public async Task Handle(JsonNode activity, ForeignAvatar actor, CancellationToken token)
@@ -43,7 +33,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
var follow = activity; var follow = activity;
var follower = actor; 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) if (target is not { IsFederated: true } || target.IsServerActor)
{ {
Arrival.Drop("unknown-recipient"); Arrival.Drop("unknown-recipient");
@@ -67,12 +57,12 @@ namespace PrivaPub.Federation.Inbox.Handlers
["actor"] = target.Uri, ["actor"] = target.Uri,
["object"] = follow.DeepClone() ["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"); Arrival.Reject("blocked");
return; 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) .Match(f => f.LocalActorId == target.Id && f.LocalActorKind == target.Kind && f.ActorURI == follower.ActorURI)
.ExecuteFirstAsync(token); .ExecuteFirstAsync(token);
var record = existing ?? new Follower var record = existing ?? new Follower
@@ -90,7 +80,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
if (target.Kind == LocalActorKind.Person) if (target.Kind == LocalActorKind.Person)
await Notifications.Add(target.Id, record.IsAccepted ? NotificationType.Follow : NotificationType.FollowRequest, 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) if (!record.IsAccepted)
return; return;
@@ -98,7 +88,7 @@ namespace PrivaPub.Federation.Inbox.Handlers
await AddForeignMember(target.Id, follower.ActorURI, token); await AddForeignMember(target.Id, follower.ActorURI, token);
var accept = ActivityPubRenderer.Accept(target, follow, $"accept-{record.ID}-{DateTime.UtcNow.Ticks}"); 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; return;
} }
} }
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more