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

+8 -14
View File
@@ -26,22 +26,16 @@ namespace PrivaPub.Domain.Content
string TagUrl(string tag);
}
public partial class ContentRenderer : IContentRenderer
public partial class ContentRenderer(
ILocalActorService localActors,
IRemoteActorService remoteActors) : IContentRenderer
{
const int MaxMentions = 20;
static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().DisableHtml().UseAutoLinks().UseEmphasisExtras().Build();
static readonly HtmlParser Parser = new();
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
public ContentRenderer(ILocalActorService localActors, IRemoteActorService remoteActors)
{
_localActors = localActors;
_remoteActors = remoteActors;
}
public string TagUrl(string tag) => $"{_localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}";
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
/// 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)
{
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))
{
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 }
? new ResolvedMention(local.Uri, local.UserName, local.Domain, local.Uri, true, local.Id, local.Inbox)
: default;
}
var actorUri = await _remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
var actor = actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token);
var actorUri = await remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
var actor = actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token);
return actor == default
? default
: 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);
}
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;
static readonly TimeSpan Freshness = TimeSpan.FromDays(7);
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 int Concurrency => 2;
@@ -69,12 +58,12 @@ namespace PrivaPub.Domain.Content
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;
var url = post.Link?.Href ?? FirstLink(post, _localActors.BaseAddress);
var url = post.Link?.Href ?? FirstLink(post, localActors.BaseAddress);
if (url == default)
return;
await _queue.EnqueueMany(new[]
await queue.EnqueueMany(new[]
{
new Job
{
@@ -86,10 +75,10 @@ namespace PrivaPub.Domain.Content
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))
return JobOutcome.Done;
var url = post.Link?.Href ?? FirstLink(post, _localActors.BaseAddress);
var url = post.Link?.Href ?? FirstLink(post, localActors.BaseAddress);
if (url == default)
return JobOutcome.Done;
@@ -110,9 +99,9 @@ namespace PrivaPub.Domain.Content
async Task<LinkPreview> Fetch(string url, CancellationToken token)
{
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);
_ledger?.Record(new InteractionEvent
ledger?.Record(new InteractionEvent
{
Channel = Interactions.Preview,
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
// 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.
public class InstanceSettings : IInstanceSettings
public class InstanceSettings(
ILogger<InstanceSettings> logger) : IInstanceSettings
{
readonly ILogger<InstanceSettings> _logger;
readonly SemaphoreSlim _saving = new(1, 1);
volatile ServerSettings _current = ServerSettings.Defaults();
volatile bool _stored;//whether Current came from the document (or is the defaults)
CancellationTokenSource _changed = new();
public InstanceSettings(ILogger<InstanceSettings> logger)
{
_logger = logger;
}
public ServerSettings Current => _current;
public IChangeToken ChangeToken() => new CancellationChangeToken(Volatile.Read(ref _changed).Token);
@@ -85,7 +80,7 @@ namespace PrivaPub.Domain.Instance
}
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)
}
+1 -1
View File
@@ -36,7 +36,7 @@ namespace PrivaPub.Domain.Media
if (i != 0 || j != 0)
for (var c = 0; c < 3; c++)
maximum = Math.Max(maximum, Math.Abs(factors[j, i, c]));
double maximumValue;
var maximumValue = default(double);
if (componentsX * componentsY > 1)
{
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;
// - 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.
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 FailedFor = TimeSpan.FromMinutes(5);
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
readonly ConcurrentDictionary<string, Lazy<Task<(ProxyOutcome, string, string)>>> _inFlight = 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
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
{
get
@@ -87,15 +77,15 @@ namespace PrivaPub.Domain.Media
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;
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)
{
string url;
var url = default(string);
try
{
url = Encoding.UTF8.GetString(FromBase64Url(encodedUrl));
@@ -109,9 +99,9 @@ namespace PrivaPub.Domain.Media
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;
var block = _domainBlocks.Find(target.Host);
var block = domainBlocks.Find(target.Host);
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) =>
_http.OpenMedia(url, range, token);
http.OpenMedia(url, range, 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();
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
// cached by a download that ended just before this one began
if (Cached(url) is { Path: not null } done)
@@ -182,16 +172,17 @@ namespace PrivaPub.Domain.Media
try
{
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))
(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)
{
var outcome = refusal == "too-large" ? ProxyOutcome.TooBig : ProxyOutcome.Failed;
_refused[url] = (outcome, DateTime.UtcNow + (outcome == ProxyOutcome.TooBig ? TooBigFor : FailedFor));
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;
File.Move(part, path, overwrite: true);
Grew(size);
@@ -209,7 +200,7 @@ namespace PrivaPub.Domain.Media
{
if (Interlocked.Read(ref _bytes) < 0)
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);
}
@@ -219,7 +210,7 @@ namespace PrivaPub.Domain.Media
return;
try
{
Interlocked.Exchange(ref _bytes, TrimDirectory(_media.ProxyRoot, _options.CurrentValue.ProxyCacheBytes));
Interlocked.Exchange(ref _bytes, TrimDirectory(mediaService.ProxyRoot, options.CurrentValue.ProxyCacheBytes));
}
finally
{
@@ -229,7 +220,7 @@ namespace PrivaPub.Domain.Media
public int Purge(string domain)
{
var directory = new DirectoryInfo(_media.ProxyRoot);
var directory = new DirectoryInfo(mediaService.ProxyRoot);
if (string.IsNullOrEmpty(domain) || !directory.Exists)
return 0;
var purged = 0;
@@ -256,7 +247,7 @@ namespace PrivaPub.Domain.Media
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;
}
@@ -290,7 +281,7 @@ namespace PrivaPub.Domain.Media
(string Path, string TypePath) CachePaths(string 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");
}
@@ -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 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
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)
{
@@ -353,7 +337,7 @@ namespace PrivaPub.Domain.Media
}
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)
{
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);
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)
{
await _media.Purge(row, token);
await mediaService.Purge(row, token);
purged++;
}
else
_media.Hide(row);
mediaService.Hide(row);
}
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);
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);
}
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
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
@@ -94,22 +100,7 @@ namespace PrivaPub.Domain.Media
Cache.Max = 0;//an upload is decoded once: nothing to keep between operations
}
readonly IOptionsMonitor<MediaOptions> _options;
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 Root => Path.GetFullPath(mediaOptions.CurrentValue.Root ?? Path.Combine(environment.ContentRootPath, "media-store"));
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");
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)
{
if (file == default || file.Length == 0)
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();
if (await OverQuota(owner.Id, file.Length, token) is { } full)
return full;
@@ -168,7 +159,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
finally
@@ -210,15 +201,16 @@ namespace PrivaPub.Domain.Media
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank");
if (!ImageTypes.Contains(contentType))
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");
if (await OverQuota(avatarId, file.Length, token) is { } full)
return full;
var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused)
if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused;
byte[] bytes;
int outWidth, outHeight;
var bytes = default(byte[]);
var outWidth = default(int);
var outHeight = default(int);
await _processing.WaitAsync(token);
try
{
@@ -229,7 +221,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
finally
@@ -264,13 +256,14 @@ namespace PrivaPub.Domain.Media
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: File can't be blank");
if (!ImageTypes.Contains(contentType))
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");
var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused)
if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused;
byte[] bytes;
int outWidth, outHeight;
var bytes = default(byte[]);
var outWidth = default(int);
var outHeight = default(int);
await _processing.WaitAsync(token);
try
{
@@ -281,7 +274,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
finally
@@ -327,11 +320,13 @@ namespace PrivaPub.Domain.Media
if (file.Length > EmojiMaxUploadBytes)
return MediaOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: An emoji's image is at most 256 KB");
var input = await Read(file, token);
if (Refusal(input, _options.CurrentValue) is { } refused)
if (Refusal(input, mediaOptions.CurrentValue) is { } refused)
return refused;
byte[] bytes, still = default;
int width, height;
bool animated;
var bytes = default(byte[]);
var still = default(byte[]);
var width = default(int);
var height = default(int);
var animated = default(bool);
await _processing.WaitAsync(token);
try
{
@@ -342,7 +337,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
finally
@@ -408,7 +403,7 @@ namespace PrivaPub.Domain.Media
// a login over its quota (Media:QuotaBytesPerRoot; none when 0) uploads nothing more
async Task<MediaOutcome> OverQuota(string avatarId, long incoming, CancellationToken token)
{
var quota = _options.CurrentValue.QuotaBytesPerRoot;
var quota = mediaOptions.CurrentValue.QuotaBytesPerRoot;
if (quota <= 0)
return default;
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
static MediaOutcome Refusal(byte[] input, MediaOptions options)
{
ImageHeader header;
var header = default(ImageHeader);
try
{
header = Inspect(input);
@@ -511,7 +506,7 @@ namespace PrivaPub.Domain.Media
// its first frame the poster
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 gif = temp + ".gif";
var mp4 = temp + ".mp4";
@@ -538,7 +533,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
finally
@@ -598,7 +593,7 @@ namespace PrivaPub.Domain.Media
// saved until everything succeeded, and every temporary file goes, the stored upload too.
async Task<MediaOutcome> ProcessIncoming(MediaAttachment attachment, CancellationToken token)
{
var options = _options.CurrentValue;
var options = mediaOptions.CurrentValue;
var input = Incoming(attachment.ID);
var temp = Path.Combine(Path.GetTempPath(), $"privapub-{Guid.NewGuid():N}");
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");
var extension = AvTypes[attachment.ContentType];
var format = probe.Format.FormatName.Split(',')[0];
string arguments;
var arguments = default(string);
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);
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.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);
poster = still.Preview;
attachment.Blurhash = still.Blurhash;
@@ -668,7 +663,7 @@ namespace PrivaPub.Domain.Media
}
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");
}
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
// 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 int Concurrency => 1;
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);
if (pending == default)
return JobOutcome.Done;//processed already, or trashed meanwhile
if (!await _media.ProcessPending(pending, token))
_logger.LogInformation("Upload {Id} could not be processed", pending.ID);
if (!await mediaService.ProcessPending(pending, token))
logger.LogInformation("Upload {Id} could not be processed", pending.ID);
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.
//
// 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,
CancellationToken token)
{
var result = new WebResult();
if (!ModerationActions.IsAccountAction(action))
return result.Invalidate(_localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity);
return result.Invalidate(localizer["Unknown moderation action."], StatusCodes.Status422UnprocessableEntity);
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)
{
result.Data = await Persona(byRootId, avatar, action, note, warning, reportId, token);
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)
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);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, "{Service}.{Method}({Action})", nameof(AccountModeration), nameof(Moderate), action);
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
logger.LogError(ex, "{Service}.{Method}({Action})", nameof(AccountModeration), nameof(Moderate), action);
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -148,18 +132,18 @@ namespace PrivaPub.Domain.Moderation
.Modify(p => p.AuthorLimited, silenced.HasValue)
.ExecuteAsync(CancellationToken.None);
await Restrictions.Reload(CancellationToken.None);
var persona = _localActors.FromAvatar(avatar);
var persona = localActors.FromAvatar(avatar);
if (action == ModerationActions.Suspend)
{
// nothing acts as it from now on: its Mastodon tokens end and its open streams close
await _tokens.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 openIddictTokenManager.RevokeBySubjectAsync(avatar.ID, CancellationToken.None);
await authorizations.RevokeBySubjectAsync(avatar.ID, CancellationToken.None);
await Social.WebPush.Forget(new[] { avatar.ID }, token);//and its Web Push subscriptions with them (R9): it is pushed nothing
Streams.CloseFor(avatar.ID);
}
if (action is ModerationActions.Silence or ModerationActions.Suspend)
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.Unsilence => AdminActions.PersonaUnsilence,
@@ -212,7 +196,7 @@ namespace PrivaPub.Domain.Moderation
.Modify(p => p.AuthorLimited, limited)
.ExecuteAsync(CancellationToken.None);
await Restrictions.Reload(CancellationToken.None);
await _log.Write(byRootId, action switch
await log.Write(byRootId, action switch
{
ModerationActions.Silence => AdminActions.AccountSilence,
ModerationActions.Unsilence => AdminActions.AccountUnsilence,
@@ -227,22 +211,22 @@ namespace PrivaPub.Domain.Moderation
var result = new WebResult();
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)
return result.Invalidate(_localizer["Post not found."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["Post not found."], StatusCodes.Status404NotFound);
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)
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
// 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)
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 _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);
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
await DB.Default.Update<PostEntity>().MatchID(post.ID).Modify(p => p.ModeratedAt, DateTime.UtcNow).ExecuteAsync(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;
}
catch (Exception ex)
{
_logger.LogError(ex, "{Service}.{Method}()", nameof(AccountModeration), nameof(RemovePost));
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
logger.LogError(ex, "{Service}.{Method}()", nameof(AccountModeration), nameof(RemovePost));
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -265,7 +249,7 @@ namespace PrivaPub.Domain.Moderation
domain = DomainBlocks.Normalise(domain);
if (string.IsNullOrEmpty(domain))
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
var pattern = ModerationFlags.OfDomain(domain);
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) =>
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)
{
var avatar = await _dbEntities.Avatars.MatchID(accountId).ExecuteFirstAsync(token);
var avatar = await dbEntities.Avatars.MatchID(accountId).ExecuteFirstAsync(token);
if (avatar != default)
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);
}
// a persona as moderators see it: never its login
public ViewModeratedAccount View(Avatar avatar)
{
var persona = _localActors.FromAvatar(avatar);
var persona = localActors.FromAvatar(avatar);
return new ViewModeratedAccount
{
Id = avatar.ID,
@@ -315,7 +299,7 @@ namespace PrivaPub.Domain.Moderation
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
{
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
// 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.
public class ModerationLog : IModerationLog
public class ModerationLog(
ILogger<ModerationLog> logger) : IModerationLog
{
const int MaxLabel = 200;
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,
string note = default, CancellationToken token = default)
@@ -49,7 +44,7 @@ namespace PrivaPub.Domain.Moderation
}
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.ImportSameActor = run.SameActor;
state.ImportCounts = [];
await Save(run, token, force: true);
await Save(run, force: true, token);
var parts = state.ImportParts.ToHashSet(StringComparer.Ordinal);
var privapub = Text((archive.Json("privapub/archive.json") as JsonObject)?["software"]) == "privapub";
@@ -185,7 +185,7 @@ namespace PrivaPub.Domain.Portability
.ExecuteAsync(token);
// 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))
return;
@@ -199,7 +199,7 @@ namespace PrivaPub.Domain.Portability
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);
}
@@ -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)
var notify = cells.Length >= 3 && cells[2].Trim().Equals("true", StringComparison.OrdinalIgnoreCase);
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
+1 -1
View File
@@ -29,7 +29,7 @@ namespace PrivaPub.Domain.Portability
public static (SafeArchive Archive, string Error) Open(string path)
{
ZipArchive zip;
var zip = default(ZipArchive);
try
{
zip = ZipFile.OpenRead(path);
@@ -25,19 +25,11 @@ namespace PrivaPub.Domain.Relationships
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)
{
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);
}
await _follows.UnfollowAs(me, targetActorUri, token);
await follows.UnfollowAs(me, targetActorUri, token);
await RemoveFollower(me, targetActorUri, targetAccountId, token);
await Forget(me, targetAccountId, token);
if (block != default)
@@ -59,7 +51,7 @@ namespace PrivaPub.Domain.Relationships
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)
return;
await DB.Default.DeleteAsync<Follower>(follower.ID);
@@ -73,7 +65,7 @@ namespace PrivaPub.Domain.Relationships
["actor"] = 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
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))
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))
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)
@@ -142,12 +134,12 @@ namespace PrivaPub.Domain.Relationships
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 followers = await _dbEntities.Followers.Match(f => f.LocalActorId == me.Id).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 handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token);
foreach (var following in followings)
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)
if (Hidden.Blocks(domain, follower.ActorURI, handles.GetValueOrDefault(follower.ActorURI)))
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);
}
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,
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
// 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();
if (rules.Count > 0 && string.IsNullOrEmpty(category))
category = "violation";
@@ -46,14 +37,14 @@ namespace PrivaPub.Domain.Relationships
if (category != "violation")
rules.Clear();
var localTarget = await _dbEntities.Avatars.MatchID(targetAccountId).ExecuteFirstAsync(token);
var remoteTarget = localTarget == default ? await _dbEntities.ForeignAvatars.MatchID(targetAccountId).ExecuteFirstAsync(token) : default;
var localTarget = await dbEntities.Avatars.MatchID(targetAccountId).ExecuteFirstAsync(token);
var remoteTarget = localTarget == default ? await dbEntities.ForeignAvatars.MatchID(targetAccountId).ExecuteFirstAsync(token) : default;
if (localTarget == default && remoteTarget == 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
? 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
{
@@ -75,15 +66,15 @@ namespace PrivaPub.Domain.Relationships
var reason = string.IsNullOrEmpty(report.Comment) ? report.Category : report.Comment;
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))
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;
if (string.IsNullOrEmpty(inbox))
continue;
var serviceReporter = await _localActors.GetReporterActor(token);
await _delivery.Enqueue(serviceReporter, new[] { inbox }, new JsonObject
var serviceReporter = await localActors.GetReporterActor(token);
await delivery.Enqueue(serviceReporter, new[] { inbox }, new JsonObject
{
["@context"] = ActivityPubRenderer.ActivityStreams,
["id"] = serviceReporter.ActivityUri($"flag-{report.ID}-{++flagged}"),
@@ -94,13 +85,13 @@ namespace PrivaPub.Domain.Relationships
["object"] = post.ObjectURI,
["summary"] = 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
// the author's server takes reports only in Lemmy's shape
if (!await TakesServiceReports(targetUri, token))
{
var instance = await _localActors.GetInstanceActor(token);
var instance = await localActors.GetInstanceActor(token);
var flag = new JsonObject
{
["@context"] = ActivityPubRenderer.ActivityStreams,
@@ -110,7 +101,7 @@ namespace PrivaPub.Domain.Relationships
["content"] = report.Comment ?? string.Empty,
["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++;
}
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
// Mastodon sends them (its AddHashtagSerializer), and the only target Mastodon takes a Hashtag from. Received the same
// way, with either collection as the target, and read from an account's featuredTags collection with its counts.
public class FeaturedTags : IFeaturedTags
public class FeaturedTags(
IDeliveryService delivery,
IRemoteActorService remoteActors) : IFeaturedTags
{
public const int MaxFeatured = 10;//the instance API's max_featured_tags, Mastodon's FeaturedTag::LIMIT
public const int MaxRemote = 20;//what we keep of an account elsewhere, whatever its server allows
readonly IDeliveryService _delivery;
readonly IRemoteActorService _remoteActors;
public FeaturedTags(IDeliveryService delivery, IRemoteActorService remoteActors)
{
_delivery = delivery;
_remoteActors = remoteActors;
}
// a featured hashtag as Mastodon renders it (its HashtagSerializer): the link to this server's page of the tag, which
// is what our posts' Hashtag tags link to, and the name as the persona wrote it
@@ -119,7 +113,7 @@ namespace PrivaPub.Domain.Social
{
if (persona is not { IsFederated: true, Kind: Models.Federation.LocalActorKind.Person })
return;
await _delivery.EnqueueToFollowers(persona, new JsonObject
await delivery.EnqueueToFollowers(persona, new JsonObject
{
["@context"] = ActivityPubRenderer.Context(),
["id"] = persona.ActivityUri($"{(add ? "feature" : "unfeature")}-tag-{tag.ID}-{DateTime.UtcNow.Ticks}"),
@@ -129,7 +123,7 @@ namespace PrivaPub.Domain.Social
["target"] = persona.Featured,
["to"] = new JsonArray(ActivityPubRenderer.Public),
["cc"] = new JsonArray(persona.Followers)
}, token);
}, token: token);
}
// what posts carry the tag: a persona's own public and unlisted posts, or the public and unlisted posts we hold of an
@@ -257,7 +251,7 @@ namespace PrivaPub.Domain.Social
async Task<JsonObject> Fetch(string uri, CancellationToken token)
{
using var fetched = await _remoteActors.FetchObject(uri, token);
using var fetched = await remoteActors.FetchObject(uri, token);
return fetched == default || fetched.Root.ValueKind != JsonValueKind.Object ? default : JsonNode.Parse(fetched.Root.GetRawText()) as JsonObject;
}
}
+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
// follower of multi-communities does, and stops following one no feed holds any more. What it follows arrives as any
// community's posts do; nobody's home shows them, the feed's timeline does.
public class FeedFollows : IFeedFollows
public class FeedFollows(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IFollowService followService,
IJobQueue jobQueue) : IFeedFollows
{
public const int MaxCommunities = 500;
static readonly TimeSpan Stale = TimeSpan.FromDays(1);
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IFollowService _follows;
readonly IJobQueue _jobs;
public FeedFollows(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IFollowService follows, IJobQueue jobs)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_follows = follows;
_jobs = jobs;
}
public static Task<bool> Sync(IJobQueue jobs, CancellationToken token) =>
jobs.Enqueue(JobKind.SyncFeeds, string.Empty, default, $"feeds|{Guid.NewGuid():N}", token);
@@ -59,7 +50,7 @@ namespace PrivaPub.Domain.Social
}
else if ((await DB.Default.DeleteAsync<FeedSubscription>(s => s.AvatarId == me.Id && s.FeedActorURI == feed.ActorURI)).DeletedCount == 0)
return true;
await Sync(_jobs, token);
await Sync(jobQueue, token);
return true;
}
@@ -69,26 +60,26 @@ namespace PrivaPub.Domain.Social
public async Task Reconcile(CancellationToken token)
{
var read = (await DB.Default.Find<FeedSubscription, string>().Project(s => s.FeedActorURI).ExecuteAsync(token)).Distinct().ToList();
var feeds = await _dbEntities.ForeignAvatars.Match(a => read.Contains(a.ActorURI) && a.AvatarType == AvatarType.Feed && !a.DeletionAt.HasValue)
var feeds = await dbEntities.ForeignAvatars.Match(a => read.Contains(a.ActorURI) && a.AvatarType == AvatarType.Feed && !a.DeletionAt.HasValue)
.ExecuteAsync(token);
// a feed's communities are as its server listed them a day ago at most (AccountCountsJob reads them, then asks
// for this again)
foreach (var stale in feeds.Where(f => !(DateTime.UtcNow - f.CountedAt < Stale)))
if (Uri.TryCreate(stale.ActorURI, UriKind.Absolute, out var uri))
await _jobs.Enqueue(JobKind.CountAccount, stale.ActorURI, uri.Host.ToLowerInvariant(), AccountCountsJob.DedupeKey(stale.ActorURI, DateTime.UtcNow), token);
await jobQueue.Enqueue(JobKind.CountAccount, stale.ActorURI, uri.Host.ToLowerInvariant(), AccountCountsJob.DedupeKey(stale.ActorURI, DateTime.UtcNow), token);
var ours = _localActors.BaseAddress + "/";
var ours = localActors.BaseAddress + "/";
var wanted = feeds.SelectMany(f => f.FeedCommunities).Where(c => !c.StartsWith(ours, StringComparison.Ordinal))
.Distinct(StringComparer.Ordinal).Take(MaxCommunities).ToHashSet(StringComparer.Ordinal);
var reader = await _localActors.GetReaderActor(token);
var following = await _dbEntities.Followings.Match(f => f.AvatarId == reader.Id).ExecuteAsync(token);
var reader = await localActors.GetReaderActor(token);
var following = await dbEntities.Followings.Match(f => f.AvatarId == reader.Id).ExecuteAsync(token);
foreach (var gone in following.Where(f => !wanted.Contains(f.TargetActorURI)))
await _follows.UnfollowAs(reader, gone.TargetActorURI, token);
await followService.UnfollowAs(reader, gone.TargetActorURI, token);
var followed = following.Select(f => f.TargetActorURI).ToHashSet(StringComparer.Ordinal);
foreach (var community in wanted.Where(c => !followed.Contains(c)))
// only a community: a feed lists nothing else, and the reader follows nothing else
if (await _remoteActors.GetActor(community, refresh: false, token) is { AvatarType: AvatarType.Group })
await _follows.FollowAs(reader, community, showReblogs: false, token);
if (await remoteActors.GetActor(community, refresh: false, token) is { AvatarType: AvatarType.Group })
await followService.FollowAs(reader, community, showReblogs: false, token: token);
}
}
+49 -59
View File
@@ -28,8 +28,9 @@ namespace PrivaPub.Domain.Social
Task<WebResult> Followings(string rootUserId, string avatarId, CancellationToken token);
/// <summary>Follows an account, or changes how a follow already made shows it: notify and languages (R8) change only
/// when given (languages empty: every language).</summary>
Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default,
IReadOnlyList<string> languages = default);
Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
IReadOnlyList<string> languages = default,
CancellationToken token = default);
Task UnfollowAs(LocalActor follower, string target, CancellationToken token);
Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token);
Task<int> ResendPending(DateTime now, CancellationToken token);
@@ -37,26 +38,14 @@ namespace PrivaPub.Domain.Social
Task<(LocalActor Local, ForeignAvatar Remote)> Resolve(string target, CancellationToken token);
}
public class FollowService : IFollowService
public class FollowService(
DbEntities dbEntities,
ILocalActorService localActors,
IRemoteActorService remoteActors,
IDeliveryService delivery,
IStringLocalizer<GenericRes> localizer,
ILogger<FollowService> logger) : IFollowService
{
readonly DbEntities _dbEntities;
readonly ILocalActorService _localActors;
readonly IRemoteActorService _remoteActors;
readonly IDeliveryService _delivery;
readonly IStringLocalizer<GenericRes> _localizer;
readonly ILogger<FollowService> _logger;
public FollowService(DbEntities dbEntities, ILocalActorService localActors, IRemoteActorService remoteActors, IDeliveryService delivery,
IStringLocalizer<GenericRes> localizer, ILogger<FollowService> logger)
{
_dbEntities = dbEntities;
_localActors = localActors;
_remoteActors = remoteActors;
_delivery = delivery;
_localizer = localizer;
_logger = logger;
}
public async Task<WebResult> Follow(string rootUserId, FollowForm form, CancellationToken token)
{
var result = new WebResult();
@@ -64,17 +53,17 @@ namespace PrivaPub.Domain.Social
{
var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
if (follower == default)
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
var following = await FollowAs(follower, form.Target, true, token);
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
var following = await FollowAs(follower, form.Target, true, token: token);
if (following == default)
return result.Invalidate(_localizer["Account not found."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["Account not found."], StatusCodes.Status404NotFound);
result.Data = ToView(following);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}");
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Follow)}");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -85,14 +74,14 @@ namespace PrivaPub.Domain.Social
{
var follower = await OwnedAvatar(rootUserId, form.AvatarId, token);
if (follower == default)
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
await UnfollowAs(follower, form.Target, token);
return result;
}
catch (Exception ex)
{
_logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}");
return result.Invalidate(_localizer["Something went wrong."], exception: ex);
logger.LogError(ex, $"{nameof(FollowService)}.{nameof(Unfollow)}");
return result.Invalidate(localizer["Something went wrong."], exception: ex);
}
}
@@ -106,8 +95,9 @@ namespace PrivaPub.Domain.Social
return kept.Count == 0 ? null : kept;
}
public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, CancellationToken token, bool? notify = default,
IReadOnlyList<string> languages = default)
public async Task<Following> FollowAs(LocalActor follower, string target, bool showReblogs, bool? notify = default,
IReadOnlyList<string> languages = default,
CancellationToken token = default)
{
var (local, remote) = await ResolveTarget(target, token);
if (local == default && remote == default)
@@ -116,7 +106,7 @@ namespace PrivaPub.Domain.Social
return default;
var targetUri = local?.Uri ?? remote.ActorURI;
var existing = await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
var existing = await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
if (existing != default)
{
if (existing.ShowReblogs != showReblogs)
@@ -136,8 +126,8 @@ namespace PrivaPub.Domain.Social
// a request still unanswered is sent again, at most once an hour: a server can take a Follow (202) and
// drop it later, as one that cannot yet read our actor does; one that holds it already ignores the copy
if (existing.State == FollowState.Requested && remote != default)
await _delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing), token,
again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture));
await delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, existing),
again: "again-" + DateTime.UtcNow.ToString("yyyyMMddHH", System.Globalization.CultureInfo.InvariantCulture), token);
return existing;
}
@@ -162,7 +152,7 @@ namespace PrivaPub.Domain.Social
}
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
{
return await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
return await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
}
//a new follow starts in no list, whatever lists the account was in before a follow that ended without passing here
await DB.Default.DeleteAsync<PersonaListMember>(m => m.AvatarId == follower.Id && m.AccountId == following.TargetAccountId);
@@ -170,7 +160,7 @@ namespace PrivaPub.Domain.Social
if (local != default)
await FollowLocally(follower, local, following, token);
else
await _delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, following), token);
await delivery.Enqueue(follower, new[] { remote.InboxURL }, FollowActivity(follower, following), token: token);
return following;
}
@@ -178,7 +168,7 @@ namespace PrivaPub.Domain.Social
{
var (local, remote) = await ResolveTarget(target, token);
var targetUri = local?.Uri ?? remote?.ActorURI ?? target;
var following = await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
var following = await dbEntities.Followings.Match(f => f.AvatarId == follower.Id && f.TargetActorURI == targetUri).ExecuteFirstAsync(token);
if (following == default)
return;
@@ -202,17 +192,17 @@ namespace PrivaPub.Domain.Social
["actor"] = follower.Uri,
["object"] = FollowActivity(follower, following)
};
await _delivery.Enqueue(follower, new[] { following.TargetInboxURL }, undo, token);
await delivery.Enqueue(follower, new[] { following.TargetInboxURL }, undo, token: token);
}
public async Task<bool> Decide(LocalActor me, string followerAccountId, bool accept, CancellationToken token)
{
var localFollower = await _localActors.FindById(LocalActorKind.Person, followerAccountId, token);
var remoteFollower = localFollower == default ? await _dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default;
var localFollower = await localActors.FindById(LocalActorKind.Person, followerAccountId, token);
var remoteFollower = localFollower == default ? await dbEntities.ForeignAvatars.MatchID(followerAccountId).ExecuteFirstAsync(token) : default;
var followerUri = localFollower?.Uri ?? remoteFollower?.ActorURI;
if (followerUri == default)
return false;
var request = await _dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.LocalActorKind == me.Kind && f.ActorURI == followerUri && !f.IsAccepted)
var request = await dbEntities.Followers.Match(f => f.LocalActorId == me.Id && f.LocalActorKind == me.Kind && f.ActorURI == followerUri && !f.IsAccepted)
.ExecuteFirstAsync(token);
if (request == default)
return false;
@@ -249,10 +239,10 @@ namespace PrivaPub.Domain.Social
["actor"] = me.Uri,
["object"] = follow
};
await _delivery.Enqueue(me, new[] { request.InboxURL }, answer, token);
await delivery.Enqueue(me, new[] { request.InboxURL }, answer, token: token);
}
if (accept)
await Notifications.Add(me.Id, NotificationType.Follow, followerAccountId, followerUri, default, token);
await Notifications.Add(me.Id, NotificationType.Follow, followerAccountId, followerUri, default, token: token);
return true;
}
@@ -261,8 +251,8 @@ namespace PrivaPub.Domain.Social
var result = new WebResult();
var follower = await OwnedAvatar(rootUserId, avatarId, token);
if (follower == default)
return result.Invalidate(_localizer["Avatar not found."], StatusCodes.Status404NotFound);
result.Data = (await _dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token))
return result.Invalidate(localizer["Avatar not found."], StatusCodes.Status404NotFound);
result.Data = (await dbEntities.Followings.Match(f => f.AvatarId == follower.Id).Sort(f => f.ID, Order.Descending).ExecuteAsync(token))
.Select(ToView).ToList();
return result;
}
@@ -286,7 +276,7 @@ namespace PrivaPub.Domain.Social
.ExecuteAsync(token);
if (target.Kind == LocalActorKind.Person)
await Notifications.Add(target.Id, following.State == FollowState.Accepted ? NotificationType.Follow : NotificationType.FollowRequest,
follower.Id, follower.Uri, default, token);
follower.Id, follower.Uri, default, token: token);
}
public Task<(LocalActor Local, ForeignAvatar Remote)> Resolve(string target, CancellationToken token) => ResolveTarget(target, token);
@@ -298,17 +288,17 @@ namespace PrivaPub.Domain.Social
return default;
if (target.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || target.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
{
var byUri = await _localActors.FindByUri(target, token);
return byUri != default ? (byUri, default) : (default, await _remoteActors.GetActor(target, refresh: false, token));
var byUri = await localActors.FindByUri(target, token);
return byUri != default ? (byUri, default) : (default, await remoteActors.GetActor(target, refresh: false, token));
}
var parts = target.TrimStart('@').Split('@');
var localDomain = new Uri(_localActors.BaseAddress).Authority;
var localDomain = new Uri(localActors.BaseAddress).Authority;
if (parts.Length == 1 || parts[1].Equals(localDomain, StringComparison.OrdinalIgnoreCase))
return (await _localActors.FindByUserName(parts[0], token), default);
return (await localActors.FindByUserName(parts[0], token), default);
var actorUri = await _remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
return (default, actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token));
var actorUri = await remoteActors.ResolveHandle($"{parts[0]}@{parts[1]}", token);
return (default, actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token));
}
// how long after it was made, or last sent again, a request still unanswered is sent again: a server can take a Follow and
@@ -324,19 +314,19 @@ namespace PrivaPub.Domain.Social
{
var sent = 0;
// (a request older than the count has no Resent yet: "not at least" matches it, "less than" would not)
var pending = await _dbEntities.Followings.Match(f => f.State == FollowState.Requested && !f.TargetIsLocal && !(f.Resent >= ResendAfter.Length))
var pending = await dbEntities.Followings.Match(f => f.State == FollowState.Requested && !f.TargetIsLocal && !(f.Resent >= ResendAfter.Length))
.ExecuteAsync(token);
foreach (var following in pending.Where(f => (f.ResentAt ?? f.CreatedAt) + ResendAfter[f.Resent] <= now))
{
var follower = await _localActors.FindById(following.FollowerKind ?? LocalActorKind.Person, following.AvatarId, token);
var inbox = following.TargetInboxURL ?? (await _remoteActors.GetActor(following.TargetActorURI, refresh: false, token))?.InboxURL;
var follower = await localActors.FindById(following.FollowerKind ?? LocalActorKind.Person, following.AvatarId, token);
var inbox = following.TargetInboxURL ?? (await remoteActors.GetActor(following.TargetActorURI, refresh: false, token))?.InboxURL;
if (follower != default && !string.IsNullOrEmpty(inbox))
{
// under a new id each time: Lemmy keeps the ids it received and never answers one again
var again = FollowActivity(follower, following);
again["id"] = AgainId(following.FollowActivityURI, following.Resent + 1);
await _delivery.Enqueue(follower, new[] { inbox }, again, token,
again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture));
await delivery.Enqueue(follower, new[] { inbox }, again,
again: "resend-" + now.ToString("yyyyMMddHHmm", System.Globalization.CultureInfo.InvariantCulture), token);
sent++;
}
await DB.Default.Update<Following>().MatchID(following.ID).Modify(b => b.Inc(f => f.Resent, 1)).Modify(f => f.ResentAt, now)
@@ -363,10 +353,10 @@ namespace PrivaPub.Domain.Social
{
if (string.IsNullOrEmpty(rootUserId) || string.IsNullOrEmpty(avatarId))
return default;
if (!await _dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootUserId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
return default;
// a suspended persona does nothing through the client API either (R6)
return await _localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
return await localActors.FindById(LocalActorKind.Person, avatarId, token) is { Suspended: false } persona ? persona : default;
}
static ViewFollowing ToView(Following following) => new()
+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,
CancellationToken token, string emoji = default, string emojiUrl = default, string text = default)
public static async Task Add(string avatarId, NotificationType type, string fromAccountId, string fromActorUri, string postId, string emoji = default, string emojiUrl = default, string text = default, CancellationToken token = default)
{
if (string.IsNullOrEmpty(avatarId) || avatarId == fromAccountId && type != NotificationType.Poll)
return;
+8 -14
View File
@@ -27,18 +27,12 @@ namespace PrivaPub.Domain.Social
Task<bool> Unreact(LocalActor me, PostEntity post, string emoji, CancellationToken token);
}
public class Reactions : IReactions
public class Reactions(
DbEntities dbEntities,
IDeliveryService delivery) : IReactions
{
static readonly string[] Hearts = { "❤", "❤️", "♥", "♥️" };
readonly DbEntities _dbEntities;
readonly IDeliveryService _delivery;
public Reactions(DbEntities dbEntities, IDeliveryService delivery)
{
_dbEntities = dbEntities;
_delivery = delivery;
}
public static bool IsHeart(string content) => content == default || Hearts.Contains(content.Trim());
@@ -64,7 +58,7 @@ namespace PrivaPub.Domain.Social
}
Arrival.Accept("reaction");
if (!post.IsFederatedCopy)
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, actor.ID, actor.ActorURI, post.ID, token, emoji.Name, emoji.Url);
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, actor.ID, actor.ActorURI, post.ID, emoji.Name, emoji.Url, token: token);
}
public async Task<bool> Withdraw(ForeignAvatar actor, string activityId, string objectUri, string content, CancellationToken token)
@@ -74,7 +68,7 @@ namespace PrivaPub.Domain.Social
: await DB.Default.Find<Reaction>().Match(r => r.ActivityURI == activityId && r.ActorURI == actor.ActorURI).ExecuteFirstAsync(token);
if (reaction == default && objectUri != default && Normalise(content, new()) is { } emoji)
{
var post = await _dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
var post = await dbEntities.Posts.Match(p => p.ObjectURI == objectUri).ExecuteFirstAsync(token);
reaction = post == default
? default
: await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID && r.ActorURI == actor.ActorURI && r.Emoji == emoji.Name).ExecuteFirstAsync(token);
@@ -114,7 +108,7 @@ namespace PrivaPub.Domain.Social
return true;
}
if (!post.IsFederatedCopy)
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, me.Id, me.Uri, post.ID, token, picked.Name, picked.Url);
await Notifications.Add(post.GroupUserId, NotificationType.Reaction, me.Id, me.Uri, post.ID, picked.Name, picked.Url, token: token);
else
await Tell(me, post, Activity(me, post, reaction), token);
return true;
@@ -169,9 +163,9 @@ namespace PrivaPub.Domain.Social
async Task Tell(LocalActor me, PostEntity post, JsonObject activity, CancellationToken token)
{
var author = await _dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
var author = await dbEntities.ForeignAvatars.Match(f => f.ActorURI == post.ActorURI).ExecuteFirstAsync(token);
if (!string.IsNullOrEmpty(author?.InboxURL))
await _delivery.Enqueue(me, new[] { author.InboxURL }, activity, token);
await delivery.Enqueue(me, new[] { author.InboxURL }, activity, token: token);
}
public sealed record Picked(string Name, string Url);
+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
// week before; posts with their favourites, boosts and replies, halving every twelve hours. A post trends only if its
// author is discoverable, and nothing warned about (content warning) trends. Computed at most every ten minutes.
public sealed class Trends
public sealed class Trends(
DbEntities dbEntities,
IMemoryCache cache)
{
public static readonly TimeSpan Fresh = TimeSpan.FromMinutes(10);
const int MinAuthors = 2;//one account alone never makes a trend
const int Kept = 40;
readonly DbEntities _dbEntities;
readonly IMemoryCache _cache;
public Trends(DbEntities dbEntities, IMemoryCache cache)
{
_dbEntities = dbEntities;
_cache = cache;
}
// what is computed is forgotten: the next read computes it again
public void Forget()
{
foreach (var key in new[] { "trends:tags", "trends:links", "trends:statuses" })
_cache.Remove(key);
cache.Remove(key);
}
public sealed record DayUse(DateTime Day, int Uses, int Accounts);
@@ -40,7 +34,7 @@ namespace PrivaPub.Domain.Social
public sealed record Trend(string Key, List<DayUse> History, string SamplePostId);
public Task<List<Trend>> Tags(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:tags", async entry =>
cache.GetOrCreateAsync("trends:tags", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = Fresh;
var posts = await Week(p => p.Tags.Count > 0, token);
@@ -48,7 +42,7 @@ namespace PrivaPub.Domain.Social
});
public Task<List<Trend>> Links(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:links", async entry =>
cache.GetOrCreateAsync("trends:links", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = Fresh;
var posts = await Week(p => p.Link != null, token);
@@ -58,12 +52,12 @@ namespace PrivaPub.Domain.Social
// the ids of the trending posts, best first
public Task<List<string>> Statuses(CancellationToken token) =>
_cache.GetOrCreateAsync("trends:statuses", async entry =>
cache.GetOrCreateAsync("trends:statuses", async entry =>
{
entry.AbsoluteExpirationRelativeToNow = Fresh;
var now = DateTime.UtcNow;
var since = now.AddHours(-48);
var posts = await _dbEntities.Posts
var posts = await dbEntities.Posts
.Match(p => p.Visibility == PostVisibility.Public && !p.DeletedAt.HasValue && !p.AuthorGone && !p.HasContentWarning && !p.IsLocalOnly
&& p.ReblogOfPostId == null && p.InReplyToURI == null && p.AnsweringToPostId == null && p.CreationDate >= since
&& p.FavouritesCount + p.ReblogsCount + p.RepliesCount > 0)
@@ -78,7 +72,7 @@ namespace PrivaPub.Domain.Social
Task<List<Post>> Week(System.Linq.Expressions.Expression<Func<Post, bool>> with, CancellationToken token)
{
var since = DateTime.UtcNow.Date.AddDays(-6);
return _dbEntities.Posts
return dbEntities.Posts
.Match(p => p.Visibility == PostVisibility.Public && !p.DeletedAt.HasValue && !p.AuthorGone && !p.HasContentWarning && !p.IsLocalOnly
&& p.ReblogOfPostId == null && p.CreationDate >= since)
.Match(Privacy.VisibilityPolicy.IsPublic).Match(Privacy.VisibilityPolicy.IsListed)
+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>
public static async Task Forget(IReadOnlyCollection<string> avatarIds)
public static async Task Forget(IReadOnlyCollection<string> avatarIds, CancellationToken token = default)
{
var ids = avatarIds?.Where(id => !string.IsNullOrEmpty(id)).Distinct().ToList() ?? new List<string>();
if (ids.Count > 0)
@@ -91,7 +91,7 @@ namespace PrivaPub.Domain.Social
}
/// <summary>The subscription made with this token goes (the token was revoked).</summary>
public static async Task ForgetToken(string tokenId)
public static async Task ForgetToken(string tokenId, CancellationToken token = default)
{
if (!string.IsNullOrEmpty(tokenId))
await DB.Default.DeleteAsync<PushSubscription>(s => s.TokenId == tokenId);
@@ -100,17 +100,10 @@ namespace PrivaPub.Domain.Social
// Hangs on Notifications.Told while the host runs and queues one SendPush job per subscription the notification goes to
// (WebPushJob sends it, encrypted). Queueing is a few indexed reads and inserts; nothing leaves the server here.
public class WebPushDispatcher : IHostedService
public class WebPushDispatcher(
IJobQueue jobQueue,
ILogger<WebPushDispatcher> logger) : IHostedService
{
readonly IJobQueue _jobs;
readonly ILogger<WebPushDispatcher> _logger;
public WebPushDispatcher(IJobQueue jobs, ILogger<WebPushDispatcher> logger)
{
_jobs = jobs;
_logger = logger;
}
public Task StartAsync(CancellationToken cancellationToken)
{
Notifications.Told = Dispatch;
@@ -145,11 +138,11 @@ namespace PrivaPub.Domain.Social
DedupeKey = $"push|{subscription.ID}|{notification.ID}"
});
if (jobs.Count > 0)
await _jobs.EnqueueMany(jobs, token);
await jobQueue.EnqueueMany(jobs, token);
}
catch (Exception ex) when (ex is not OperationCanceledException || !token.IsCancellationRequested)
{
_logger.LogWarning(ex, "{Service} could not queue the pushes of a notification", nameof(WebPushDispatcher));
logger.LogWarning(ex, "{Service} could not queue the pushes of a notification", nameof(WebPushDispatcher));
}
}
}
+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,
// 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.
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);
readonly IGeoLocator _geo;
readonly ICdnRanges _cdnRanges;
readonly IOptionsMonitor<StatisticsOptions> _options;
readonly IOptionsMonitor<AppConfiguration> _app;
readonly ILogger<SelfLocation> _logger;
readonly SemaphoreSlim _gate = new(1, 1);
InstanceGeo _located;
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)
{
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
{
Country = self.Country,
@@ -77,12 +67,12 @@ namespace PrivaPub.Domain.Statistics
{
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;
var addresses = await Dns.GetHostAddressesAsync(self.Host, token);
var address = addresses.FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork) ?? addresses.FirstOrDefault();
var fix = address == default ? default : _geo.Locate(address);
var (cdn, cdnSource) = Federation.Objects.InstanceDescriber.Cdn(address, self.Host, fix?.Asn, _cdnRanges, default);
var fix = address == default ? default : geo.Locate(address);
var (cdn, cdnSource) = Federation.Objects.InstanceDescriber.Cdn(address, self.Host, fix?.Asn, cdnRanges, default);
return fix == default ? default : new InstanceGeo
{
Country = fix.Country,
@@ -95,13 +85,13 @@ namespace PrivaPub.Domain.Statistics
CdnDomain = cdn?.Domain,
CdnSource = cdnSource,
Ipv6 = address.AddressFamily == AddressFamily.InterNetworkV6,
Source = _geo.Source,
Source = geo.Source,
LocatedAt = DateTime.UtcNow
};
}
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;
}
}
+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
// 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.
public class ServerPlaces : IServerPlaces
public class ServerPlaces(
ICdnRanges cdnRanges,
IMemoryCache cache) : IServerPlaces
{
public const int MaxHosts = 500;
const int MaxChanges = 50;
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
public static string KeyOf(InstanceGeo geo) =>
@@ -75,7 +69,7 @@ namespace PrivaPub.Domain.Statistics
public async Task<List<CdnGroup>> Cdns(CancellationToken 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);
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();
if (string.IsNullOrEmpty(key) || key.Length > 100)
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;
var fronted = await Fronted(token);
var provider = CdnCatalog.ByKey(key);
if (provider == default && fronted.All(i => KeyOf(i.Geo) != key))
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();
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);
}
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
{
InteractionKind.Reply => "reply-request-",
@@ -98,33 +87,33 @@ namespace PrivaPub.Domain.Statuses
return false;
if (who.Any(Addressing.IsPublic) || who.Contains(actor.Uri))
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)
return false;
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))
return true;
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
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))
return;
// FEP-5624: the reply itself is the question, to the author alone
if (ApprovesReplies(target, kind))
{
await _delivery.Enqueue(actor, new[] { author.InboxURL }, ActivityPubRenderer.Create(actor, (JsonObject)interaction.DeepClone(), $"create-{localId}"),
token);
await deliveryService.Enqueue(actor, new[] { author.InboxURL }, ActivityPubRenderer.Create(actor, (JsonObject)interaction.DeepClone(), $"create-{localId}"),
token: token);
return;
}
var instrument = (JsonObject)interaction.DeepClone();
instrument.Remove("@context");
await _delivery.Enqueue(actor, new[] { author.InboxURL }, new JsonObject
await deliveryService.Enqueue(actor, new[] { author.InboxURL }, new JsonObject
{
["@context"] = ActivityPubRenderer.Context(),
["id"] = actor.ActivityUri(Prefix(kind) + localId),
@@ -133,7 +122,7 @@ namespace PrivaPub.Domain.Statuses
["to"] = target.ActorURI,
["object"] = target.ObjectURI,
["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)
@@ -154,7 +143,7 @@ namespace PrivaPub.Domain.Statuses
if (kind == InteractionKind.Like)
{
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)
return true;
if (!accepted)
@@ -168,9 +157,9 @@ namespace PrivaPub.Domain.Statuses
return true;
await DB.Default.Update<Favourite>().MatchID(like.ID).Modify(f => f.Approval, ApprovalState.Accepted).Modify(f => f.ApprovalURI, stamp)
.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))
await _delivery.Enqueue(liker, new[] { actor.InboxURL }, new JsonObject
await deliveryService.Enqueue(liker, new[] { actor.InboxURL }, new JsonObject
{
["@context"] = ActivityPubRenderer.Context(),
["id"] = like.ActivityURI,
@@ -178,16 +167,16 @@ namespace PrivaPub.Domain.Statuses
["actor"] = liker.Uri,
["object"] = liked.ObjectURI,
["likeAuthorization"] = stamp
}, token);
}, token: token);
return true;
}
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 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)
.ExecuteFirstAsync(token);
if (post is not { Approval: ApprovalState.Pending } || target?.ActorURI != actor.ActorURI)
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)
return true;
if (!accepted)
@@ -223,7 +212,7 @@ namespace PrivaPub.Domain.Statuses
if (kind == InteractionKind.Reply)
{
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;
}
var announce = new JsonObject
@@ -238,13 +227,13 @@ namespace PrivaPub.Domain.Statuses
["object"] = target.ObjectURI,
["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;
}
(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;
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
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;
if (await DB.Default.Find<Favourite>().Match(f => f.ActivityURI == uri).ExecuteFirstAsync(token) is { } like)
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 default;
}
@@ -272,7 +261,7 @@ namespace PrivaPub.Domain.Statuses
{
if (!Origin.Same(authorization, target.ActorURI))
return false;
using var fetched = await _remoteActors.FetchObject(authorization, token);
using var fetched = await remoteActors.FetchObject(authorization, token);
if (fetched == default)
return false;
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)
return true;
// 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)
|| author != default && (rule.Automatic.Contains(author.FollowersURL) || rule.Automatic.Contains(author.FollowingURL)))
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);
}
public class Participations : IParticipations
public class Participations(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery) : IParticipations
{
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)
{
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;
}
@@ -105,10 +98,10 @@ namespace PrivaPub.Domain.Statuses
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;
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
@@ -116,10 +109,10 @@ namespace PrivaPub.Domain.Statuses
{
var joinId = Id(answer["object"]);
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;
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))
return true;
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);
}
public class PollService : IPollService
public class PollService(
DbEntities dbEntities,
ILocalActorService localActors,
IDeliveryService delivery,
IJobQueue queue) : IPollService
{
public const int MaxOptions = 4;
public const int MaxOptionLength = 50;
@@ -41,18 +45,6 @@ namespace PrivaPub.Domain.Statuses
public const int MaxExpiration = 2_629_746;
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)
{
@@ -81,7 +73,7 @@ namespace PrivaPub.Domain.Statuses
{
if (post.Poll?.ExpiresAt is not { } ends)
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 }
}, token);
@@ -115,7 +107,7 @@ namespace PrivaPub.Domain.Statuses
else
await Refreshed(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)
@@ -164,13 +156,13 @@ namespace PrivaPub.Domain.Statuses
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))
return;
foreach (var choice in choices)
{
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,
["id"] = voteId + "/activity",
@@ -186,14 +178,14 @@ namespace PrivaPub.Domain.Statuses
["to"] = new JsonArray(owner.ActorURI),
["inReplyTo"] = post.ObjectURI
}
}, token);
}, token: token);
}
}
async Task Refreshed(PostEntity post, CancellationToken token)
{
var bucket = DateTime.UtcNow.Ticks / RefreshEvery.Ticks;
await _queue.EnqueueMany(new[]
await queue.EnqueueMany(new[]
{
new Job
{
@@ -203,58 +195,48 @@ namespace PrivaPub.Domain.Statuses
}, 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 int Concurrency => 1;
public int MaxAttempts => 3;
public int PerHostLimit => 1;
protected DbEntities Entities => dbEntities;
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)
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)
return JobOutcome.Done;
await Closing(post, author, token);
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;
}
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 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)
return JobOutcome.Done;
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);
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)
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
}
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 LicencePath = "/parrot-licences/";
@@ -68,7 +56,7 @@ namespace PrivaPub.Domain.Statuses
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)
return false;
if (quoterUri == author.Uri)
@@ -83,11 +71,11 @@ namespace PrivaPub.Domain.Statuses
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;
var local = await _localActors.FindByUri(followerUri, token);
var local = await localActors.FindByUri(followerUri, token);
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)
@@ -111,8 +99,8 @@ namespace PrivaPub.Domain.Statuses
Arrival.Drop("misattributed");
return;
}
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 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);
if (author == default || string.IsNullOrEmpty(actor.InboxURL))
{
Arrival.Drop("unknown-object");
@@ -139,22 +127,22 @@ namespace PrivaPub.Domain.Statuses
answer["type"] = "Reject";
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)
{
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)
return false;
await DB.Default.Update<QuoteLicence>().MatchID(licence.ID).Modify(l => l.RevokedAt, DateTime.UtcNow).ExecuteAsync(token);
var uri = LicenceUri(author, licence.ID);
await Revoke(uri, token);
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 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();
if (inboxes.Count > 0)
await _delivery.Enqueue(author, inboxes, new JsonObject
await delivery.Enqueue(author, inboxes, new JsonObject
{
["@context"] = ActivityPubRenderer.Context(),
["id"] = author.ActivityUri($"revoke-quote-{licence.ID}"),
@@ -162,14 +150,14 @@ namespace PrivaPub.Domain.Statuses
["actor"] = author.Uri,
["object"] = uri,
["to"] = new JsonArray(Addressing.Public)
}, token);
}, token: token);
return true;
}
async Task<bool> OurLicence(string stampUri, PostEntity quoting, PostEntity quoted, CancellationToken token)
{
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;
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)
@@ -191,10 +179,10 @@ namespace PrivaPub.Domain.Statuses
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))
return;
await _delivery.Enqueue(author, new[] { owner.InboxURL }, new JsonObject
await delivery.Enqueue(author, new[] { owner.InboxURL }, new JsonObject
{
["@context"] = ActivityPubRenderer.Context(),
["id"] = author.ActivityUri(RequestPrefix + post.ID),
@@ -203,7 +191,7 @@ namespace PrivaPub.Domain.Statuses
["object"] = quoted.ObjectURI,
["instrument"] = note.DeepClone(),
["to"] = new JsonArray(quoted.ActorURI)
}, token);
}, token: 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)
return true;
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 author = post == default ? default : await _localActors.FindById(LocalActorKind.Person, post.GroupUserId, 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);
if (author == default || author.ActivityUri(RequestPrefix + post.ID) != requestId || post.QuoteState != QuoteState.Pending)
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)
return true;
if (!accepted)
@@ -239,7 +227,7 @@ namespace PrivaPub.Domain.Statuses
.ExecuteAsync(token);
await DB.Default.Update<PostEntity>().MatchID(quoted.ID).Modify(b => b.Inc(p => p.QuotesCount, 1)).ExecuteAsync(token);
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;
}
@@ -249,8 +237,8 @@ namespace PrivaPub.Domain.Statuses
return;
var quoted = note.QuoteUri == default
? default
: await _dbEntities.Posts.Match(p => p.ObjectURI == note.QuoteUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await _remotePosts.StoreContext(note.QuoteUri, RemotePosts.MaxDepth, token);
: await dbEntities.Posts.Match(p => p.ObjectURI == note.QuoteUri && !p.DeletedAt.HasValue).ExecuteFirstAsync(token)
?? await remotePosts.StoreContext(note.QuoteUri, RemotePosts.MaxDepth, token);
var state = note.QuoteDeleted ? QuoteState.Deleted
: 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);
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)
{
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)
{
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))
return false;
using var fetched = await _remoteActors.FetchObject(stampUri, token);
using var fetched = await remoteActors.FetchObject(stampUri, token);
if (fetched == default)
return false;
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);
}
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 int Concurrency => 2;
public int MaxAttempts => 3;
@@ -104,7 +97,7 @@ namespace PrivaPub.Domain.Statuses
var scheduled = await DB.Default.Find<ScheduledStatus>().MatchID(job.Payload).ExecuteFirstAsync(token);
if (scheduled == default || scheduled.ScheduledAt > DateTime.UtcNow.AddSeconds(30))
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
// (R6), unless that was a month ago
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);
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 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 ConversationId { get; init; }
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<MediaChange> MediaChanges { get; init; } = Array.Empty<MediaChange>();
// 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);
}
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;
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
@@ -121,16 +103,16 @@ namespace PrivaPub.Domain.Statuses
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: Media attachments are invalid");
if (string.IsNullOrWhiteSpace(draft.Text) && media.Count == 0 && draft.Poll == default)
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);
LocalActor group = default;
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))
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Group not found");
group = _localActors.FromGroup(groupEntity);
group = localActors.FromGroup(groupEntity);
}
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");
// 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)
&& 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))
group = _localActors.FromGroup(parentCircle);
group = localActors.FromGroup(parentCircle);
PostEntity quoted = default;
var quotePermission = QuotePermission.Denied;
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))
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)
return StatusOutcome.Fail(StatusCodes.Status422UnprocessableEntity, "Validation failed: This post cannot be quoted");
}
@@ -168,21 +150,21 @@ namespace PrivaPub.Domain.Statuses
|| draft.Visibility == PostVisibility.Direct))
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;
if (group == default && !located && draft.Visibility is PostVisibility.Public or PostVisibility.Unlisted)
foreach (var mention in rendered.Mentions)
{
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))
{
group = _localActors.FromGroup(mentioned);
group = localActors.FromGroup(mentioned);
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;
break;
@@ -223,7 +205,7 @@ namespace PrivaPub.Domain.Statuses
InReplyToActorURI = parent is { IsFederatedCopy: true } ? parent.ActorURI : default,
IsLocalOnly = isLocalOnly,
ActorURI = author.Uri,
Poll = draft.Poll == default ? default : _polls.Create(draft.Poll),
Poll = draft.Poll == default ? default : polls.Create(draft.Poll),
QuoteURI = quoted?.ObjectURI,
QuotedPostId = quoted?.ID,
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");
post.LocalQuotePolicy = QuotePolicies.IsKnown(draft.QuotePolicy) ? draft.QuotePolicy : author.Settings.QuotePolicy ?? QuotePolicies.Public;
if (quoted is { IsFederatedCopy: false } && post.QuoteState == QuoteState.Accepted
&& await _localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token) is { } quotedAuthor)
post.QuoteAuthorizationURI = await _quotes.Grant(quotedAuthor, quoted, post.ObjectURI, author.Uri, token);
&& await localActors.FindById(LocalActorKind.Person, quoted.GroupUserId, token) is { } quotedAuthor)
post.QuoteAuthorizationURI = await quotes.Grant(quotedAuthor, quoted, post.ObjectURI, author.Uri, token);
if (located)
{
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
// no other way (Lemmy 0.19 and Mbin)
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);
create = ActivityPubRenderer.Create(author, note, $"create-{post.ID}");
post.To = Strings(note["to"]);
@@ -284,22 +266,22 @@ namespace PrivaPub.Domain.Statuses
await DB.Default.SaveAsync(post, token);
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 _fanout.Distribute(post, token);
await fanout.Distribute(post, token);
if (post.Visibility == PostVisibility.Direct)
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)
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)
await _quotes.Request(author, post, quoted, quotingNote, token);
await _previews.Wanted(post, token);
await quotes.Request(author, post, quoted, quotingNote, 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
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)
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)
await _groups.Announce(group, create, post.ObjectURI, isNewPost: true, token);
await groupDistributor.Announce(group, create, post.ObjectURI, isNewPost: true, token);
return new StatusOutcome(post);
}
@@ -333,7 +315,7 @@ namespace PrivaPub.Domain.Statuses
post.Revisions.RemoveRange(0, post.Revisions.Count - MaxRevisions);
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
var described = media ?? (draft.MediaChanges.Count > 0
? 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();
// what the edit left out is no longer held by anything
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);
// 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)
{
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
? ActivityPubRenderer.DirectNote(post, author, Array.Empty<(string, string)>(), post.ContextURI)
: ActivityPubRenderer.Note(post, author, group, post.InReplyToURI);
@@ -395,22 +377,22 @@ namespace PrivaPub.Domain.Statuses
["cc"] = note["cc"]!.DeepClone(),
["object"] = note
};
await _outbox.Publish(author, post, update, token);
await outbox.Publish(author, post, update, token);
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);
}
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)
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found");
if (post.ReblogOfPostId != default)
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)
.Modify(p => p.DeletedAt, DateTime.UtcNow)
.Modify(p => p.Text, null)
@@ -421,7 +403,7 @@ namespace PrivaPub.Domain.Statuses
.Modify(p => p.Revisions, new List<PostRevision>())
.ExecuteAsync(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);
// 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)
@@ -433,10 +415,10 @@ namespace PrivaPub.Domain.Statuses
{
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()));
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);
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);
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);
}
@@ -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);
post.FavouritesCount++;
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
{
@@ -497,9 +479,9 @@ namespace PrivaPub.Domain.Statuses
["object"] = post.ObjectURI
};
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
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);
}
@@ -517,7 +499,7 @@ namespace PrivaPub.Domain.Statuses
if (post == default)
return StatusOutcome.Fail(StatusCodes.Status404NotFound, "Record not found");
Downvote downvote;
var downvote = default(Downvote);
if (on)
{
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,
["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);
}
@@ -578,11 +560,11 @@ namespace PrivaPub.Domain.Statuses
async Task<List<string>> VoteInboxes(PostEntity post, CancellationToken token)
{
var inboxes = new List<string>();
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
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
&& !string.IsNullOrEmpty(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.Add(author);
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
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)
{
@@ -605,7 +587,7 @@ namespace PrivaPub.Domain.Statuses
if (announcePermission == QuotePermission.Denied)
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
// 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();
@@ -647,10 +629,10 @@ namespace PrivaPub.Domain.Statuses
}
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
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);
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);
if (!original.IsFederatedCopy)
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, me.Id, me.Uri, original.ID, token);
await _fanout.Distribute(reblog, token);
await Notifications.Add(original.GroupUserId, NotificationType.Reblog, me.Id, me.Uri, original.ID, token: token);
await fanout.Distribute(reblog, token);
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
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);
}
@@ -674,8 +656,8 @@ namespace PrivaPub.Domain.Statuses
await DB.Default.DeleteAsync<PostEntity>(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 _delivery.EnqueueToFollowers(me, Undo(me, announce, $"undo-announce-{existing.ID}"), token,
await AuthorInbox(original, token, shared: true) is { } authorInbox ? new[] { authorInbox } : default);
await deliveryService.EnqueueToFollowers(me, Undo(me, announce, $"undo-announce-{existing.ID}"),
await AuthorInbox(original, shared: true, token) is { } authorInbox ? new[] { authorInbox } : default, token);
return new StatusOutcome(original);
}
@@ -708,7 +690,7 @@ namespace PrivaPub.Domain.Statuses
DmGroup dmGroup = default;
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))
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");
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)
{
dmGroup = new DmGroup { Members = members, ParticipantsKey = key };
@@ -748,11 +730,11 @@ namespace PrivaPub.Domain.Statuses
{
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)
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));
}
return new(dmGroup, recipients);
@@ -761,13 +743,13 @@ namespace PrivaPub.Domain.Statuses
async Task<GroupMember> ResolveRecipient(string recipient, CancellationToken token)
{
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;
}
var actorUri = await _remoteActors.ResolveHandle(handle, token);
var foreign = actorUri == default ? default : await _remoteActors.GetActor(actorUri, refresh: false, token);
var actorUri = await remoteActors.ResolveHandle(handle, token);
var foreign = actorUri == default ? default : await remoteActors.GetActor(actorUri, refresh: false, token);
return foreign == default ? default : new GroupMember { AvatarId = foreign.ActorURI, IsForeign = true };
}
@@ -776,27 +758,27 @@ namespace PrivaPub.Domain.Statuses
if (string.IsNullOrEmpty(reference))
return default;
return IsRemoteUri(reference)
? 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.ObjectURI == 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) =>
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);
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;
}
// 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)
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))
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;
}
@@ -809,7 +791,7 @@ namespace PrivaPub.Domain.Statuses
{
PostingPolicy.Anyone => true,
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)
};
}
@@ -855,8 +837,8 @@ namespace PrivaPub.Domain.Statuses
ContentType = attachment.ContentType,
Kind = attachment.Kind,
DurationSeconds = attachment.DurationSeconds,
URL = _media.Url(attachment.FilePath),
PreviewURL = _media.Url(attachment.PreviewPath ?? attachment.FilePath),
URL = mediaService.Url(attachment.FilePath),
PreviewURL = mediaService.Url(attachment.PreviewPath ?? attachment.FilePath),
Description = attachment.Description,
Blurhash = attachment.Blurhash,
Width = attachment.Width,
+11 -17
View File
@@ -16,15 +16,9 @@ namespace PrivaPub.Domain.Timelines
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)
{
// 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:
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.TargetAccountId == post.GroupUserId && f.TargetIsLocal && f.State == FollowState.Accepted).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);
foreach (var following in followers)
if (await Shows(following, post, token))
{
@@ -53,14 +47,14 @@ namespace PrivaPub.Domain.Timelines
}
if (!string.IsNullOrEmpty(post.AudienceURI))
// (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);
// a post on a wall (FEP-400e): its owner, when a persona, and those following the owner
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);
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);
}
// 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;
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>())
recipients.Add(member.AvatarId);
break;
@@ -105,9 +99,9 @@ namespace PrivaPub.Domain.Timelines
if (string.IsNullOrEmpty(post.ReblogOfPostId))
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())
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)
await Stream(post, recipients, token);
}
@@ -230,7 +224,7 @@ namespace PrivaPub.Domain.Timelines
return true;
if (string.IsNullOrEmpty(repliedTo))
return false;
return await _dbEntities.Followings
return await dbEntities.Followings
.Match(f => f.AvatarId == following.AvatarId && f.TargetAccountId == repliedTo && f.State == FollowState.Accepted)
.ExecuteAnyAsync(token);
}
+10 -16
View File
@@ -20,26 +20,20 @@ namespace PrivaPub.Domain.Timelines
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;
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)
{
var result = new WebResult();
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))
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);
@@ -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 posts = ids.Count == 0
? 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
.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();
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))
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))
@@ -90,14 +84,14 @@ namespace PrivaPub.Domain.Timelines
{
var result = new WebResult();
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);
return result;
}
async Task<bool> Owns(string rootUserId, string avatarId, CancellationToken token) =>
!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()
{