House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- Services, controllers and jobs take their dependencies through primary constructors and use them directly; where a method already named a local after a dependency, the dependency takes its type's name. - Every async method takes a CancellationToken last and passes it down to MongoDB, HTTP and the job queue. The setup claim is still given back when a request is cancelled. - The federation and media options are read through IOptionsMonitor. - The Mastodon entities keep sending "" for empty strings, and every model field where null means something says so. - The inbox's 503 with Retry-After, which other servers retry, is the one server error left, and says why. - Arasaka.HouseRules.Analyzers checks all of this in every build, here and in PrivaPub.ClientModels as decePubClient builds it. Checked against GoToSocial in the pasture: 64 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -17,32 +17,22 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
[ApiController,
|
||||
Route("clientapi/moderator"),
|
||||
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 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")]
|
||||
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))
|
||||
.Select(r => new ViewReport
|
||||
{
|
||||
@@ -77,7 +67,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
form ??= new ResolveReportForm();
|
||||
var action = string.IsNullOrWhiteSpace(form.Action) ? ModerationActions.None : form.Action.Trim().ToLowerInvariant();
|
||||
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 report = await DB.Default.Find<Report>().MatchID(id).ExecuteFirstAsync(token);
|
||||
if (report == default)
|
||||
@@ -85,16 +75,16 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
switch (action)
|
||||
{
|
||||
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)
|
||||
return StatusCode(moderated.StatusCode, moderated);
|
||||
break;
|
||||
case ModerationActions.RemovePosts:
|
||||
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)
|
||||
{
|
||||
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
|
||||
return StatusCode(removed.StatusCode, removed);
|
||||
}
|
||||
@@ -107,7 +97,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
.Modify(r => r.Resolution, action)
|
||||
.Modify(r => r.ResolutionNote, string.IsNullOrWhiteSpace(form.Note) ? null : form.Note.Trim())
|
||||
.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()}",
|
||||
token: CancellationToken.None);
|
||||
return Ok();
|
||||
@@ -125,21 +115,21 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
return Ok(new ViewModeratedAccountsPage { Items = items });
|
||||
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)
|
||||
items.Add(_moderation.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.Add(accountModeration.View(persona));
|
||||
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() });
|
||||
}
|
||||
var parts = q.Split('@', 2);
|
||||
var name = parts[0];
|
||||
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)
|
||||
{
|
||||
var lowered = name.ToLowerInvariant();
|
||||
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)
|
||||
{
|
||||
@@ -148,7 +138,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
if (domain != default)
|
||||
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))
|
||||
.Select(_moderation.View));
|
||||
.Select(accountModeration.View));
|
||||
}
|
||||
return Ok(new ViewModeratedAccountsPage { Items = items });
|
||||
}
|
||||
@@ -162,7 +152,7 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
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 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();
|
||||
return Ok(new ViewModeratedAccountsPage
|
||||
{
|
||||
@@ -175,15 +165,15 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
|
||||
[HttpGet, Route("/clientapi/moderator/accounts/{id}")]
|
||||
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
|
||||
[HttpPost, Route("/clientapi/moderator/accounts/moderate")]
|
||||
public async Task<IActionResult> Moderate(ModerateAccountForm form, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
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);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -192,8 +182,8 @@ namespace PrivaPub.Controllers.ClientToServer
|
||||
public async Task<IActionResult> RemovePost(RemovePostForm form, CancellationToken token)
|
||||
{
|
||||
if (!ModelState.IsValid)
|
||||
return BadRequest(new WebResult().Invalidate(_localizer["Invalid model."]));
|
||||
var result = await _moderation.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token);
|
||||
return BadRequest(new WebResult().Invalidate(localizer["Invalid model."]));
|
||||
var result = await accountModeration.RemovePost(User.GetUserId(), form.PostId, form.Note, form.Warning, default, token);
|
||||
return result.IsValid ? Ok() : StatusCode(result.StatusCode, result);
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user