Files
SocialPub/PrivaPub/Api/Mastodon/Controllers/TrendsController.cs
T
thepraandClaude Opus 5.5 f3fdeaf038
Build / Build (push) Successful in 36s
The API's JSON is generated at build time, and no answer is an anonymous object
Every answer of the Mastodon API and the client API now has its JSON shape generated when the server is built, instead
of worked out by reflection while it runs; the bytes sent are unchanged. The small answers that were anonymous objects
(the instance documents, notification policies, reports, lists, tags, trends, errors and the empty answers) are named
types. A type without generated metadata fails at once in development and on the pasture, and in production is logged
and still answered. Three lists that were sent as lazy sequences (moderation reports, the published domain blocks and
the languages) are now built first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
2026-11-10 07:28:02 +01:00

153 lines
8.2 KiB
C#

using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Privacy;
using PrivaPub.Domain.Social;
using PrivaPub.Federation.Actors;
using PrivaPub.Models.User;
using PrivaPub.StaticServices;
namespace PrivaPub.Api.Mastodon.Controllers
{
// Trends and the directory (owner decision 2026-10-04, back from the cut list), from what PrivaPub already holds
// (Trends). The directory lists only accounts that let themselves be discovered.
public class TrendsController(
Trends trendService,
MastodonMapper mapper,
DbEntities dbEntities,
ILocalActorService localActors) : MastodonController
{
static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new TagHistoryEntity
{
Day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(),
Uses = h.Uses.ToString(),
Accounts = h.Accounts.ToString()
}).ToList();
IEnumerable<T> Window<T>(IEnumerable<T> items, int fallback, int max) =>
items.Skip(Math.Max(0, Params.Int("offset") ?? 0)).Take(Limit(fallback, max));
[HttpGet(ApiPaths.Trends.GET_Tags), HttpGet(ApiPaths.Trends.GET_TagsV1), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Tags(CancellationToken token)
{
var followed = MyId == default
? new HashSet<string>()
: (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet();
return Json(Window(await trendService.Tags(token), 10, 20).Select(t => new TrendTagEntity
{
Name = t.Key,
Url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}",
History = History(t),
Following = MyId == default ? default(bool?) : followed.Contains(t.Key)
}).ToList());
}
[HttpGet(ApiPaths.Trends.GET_Statuses), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Statuses(CancellationToken token)
{
var ids = Window(await trendService.Statuses(token), 20, 40).ToList();
var posts = (await dbEntities.Posts.Match(p => ids.Contains(p.ID)).Match(VisibilityPolicy.IsShown).ExecuteAsync(token)).ToDictionary(p => p.ID);
return Json(await mapper.Statuses(ids.Where(posts.ContainsKey).Select(id => posts[id]).ToList(), MyId, token));
}
[HttpGet(ApiPaths.Trends.GET_Links), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Links(CancellationToken token)
{
var trends = Window(await trendService.Links(token), 10, 20).ToList();
var sampleIds = trends.Select(t => t.SamplePostId).ToList();
var samples = (await dbEntities.Posts.Match(p => sampleIds.Contains(p.ID)).ExecuteAsync(token)).ToDictionary(p => p.ID);
return Json(trends.Where(t => samples.ContainsKey(t.SamplePostId)).Select(t =>
{
var link = samples[t.SamplePostId].Link;
var card = mapper.LinkCard(t.Key, link.Title, link.Description, link.ImageURL);
return card == default ? default : (object)new TrendLinkEntity
{
Url = card.Url, Title = card.Title, Description = card.Description, Type = card.Type, AuthorName = card.AuthorName, AuthorUrl = card.AuthorUrl, ProviderName = card.ProviderName, ProviderUrl = card.ProviderUrl,
Html = card.Html, Width = card.Width, Height = card.Height, Image = card.Image, ImageDescription = card.ImageDescription, EmbedUrl = card.EmbedUrl, Blurhash = card.Blurhash, Language = card.Language,
PublishedAt = card.PublishedAt, Authors = card.Authors, History = History(t)
};
}).Where(c => c != default).ToList());
}
// order=active: by their latest public post PrivaPub holds; order=new: by when they say they joined, which for a
// persona is its published day (never its creation, so personas made together are not told apart by their order)
[HttpGet(ApiPaths.Trends.GET_Directory), Scope("read", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public async Task<IActionResult> Directory(CancellationToken token)
{
var offset = Math.Max(0, Params.Int("offset") ?? 0);
var limit = Limit(40, 80);
var localOnly = Params.Bool("local") == true;
var barred = await Counted.HeldBackPersonas(token);
var wanted = offset + limit;
var ordered = new List<string>();
if (Params.Get("order") == "new")
{
// many share a day: the first `wanted` are read with every other of the last one's day, so each page is cut the same way
var personas = await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue)
.Sort(a => a.PublishedOn, Order.Descending).Limit(wanted).ExecuteAsync(token);
if (personas.Count == wanted)
{
var edge = personas[^1].PublishedOn;
var known = personas.Select(a => a.ID).ToList();
personas.AddRange(await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue
&& a.PublishedOn == edge && !known.Contains(a.ID)).ExecuteAsync(token));
}
var remote = localOnly
? new List<ForeignAvatar>()
: await dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue && f.Published != null)
.Sort(f => f.Published, Order.Descending).Limit(wanted).ExecuteAsync(token);
if (remote.Count == wanted)
{
var edge = remote[^1].Published;
var known = remote.Select(f => f.ID).ToList();
remote.AddRange(await dbEntities.ForeignAvatars.Match(f => f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue
&& f.Published == edge && !known.Contains(f.ID)).ExecuteAsync(token));
}
ordered = personas.Select(a => (a.ID, Joined: a.PublishedOn, Tie: Tie(a.UserName)))
.Concat(remote.Select(f => (f.ID, Joined: f.Published.Value, Tie: Tie(f.ActorURI))))
.OrderByDescending(a => a.Joined).ThenBy(a => a.Tie, StringComparer.Ordinal)
.Select(a => a.ID).Skip(offset).Take(limit).ToList();
}
else
{
var discoverableLocal = (await dbEntities.Avatars.Match(a => a.Settings.IsDiscoverable && !a.DeletionAt.HasValue && !barred.Contains(a.ID) && !a.SilencedAt.HasValue)
.Project(a => a.Include(x => x.ID)).ExecuteAsync(token)).Select(a => a.ID).ToHashSet();
var seen = new HashSet<string>();
var maxId = default(string);
for (var round = 0; round < 20 && ordered.Count < wanted; round++)
{
var page = dbEntities.Posts.Match(p => p.Visibility == Models.Post.PostVisibility.Public && !p.DeletedAt.HasValue && p.ReblogOfPostId == null);
if (maxId != default)
page.Match(f => f.Lt(p => p.ID, maxId));
if (localOnly)
page.Match(p => !p.IsFederatedCopy);
var batch = await page.Sort(p => p.ID, Order.Descending).Limit(500)
.Project(p => p.Include(x => x.ID).Include(x => x.AuthorAccountId).Include(x => x.GroupUserId).Include(x => x.IsFederatedCopy))
.ExecuteAsync(token);
if (batch.Count == 0)
break;
maxId = batch[^1].ID;
var fresh = batch.Select(p => (Id: p.AuthorAccountId ?? p.GroupUserId, p.IsFederatedCopy)).Where(a => a.Id != default && seen.Add(a.Id)).ToList();
var remoteIds = fresh.Where(a => a.IsFederatedCopy).Select(a => a.Id).ToList();
var discoverableRemote = remoteIds.Count == 0
? new HashSet<string>()
: (await dbEntities.ForeignAvatars.Match(f => remoteIds.Contains(f.ID) && f.IsDiscoverable && !f.DeletionAt.HasValue && !f.SuspendedAt.HasValue && !f.SilencedAt.HasValue)
.Project(f => f.Include(x => x.ID)).ExecuteAsync(token)).Select(f => f.ID).ToHashSet();
ordered.AddRange(fresh.Where(a => a.IsFederatedCopy ? discoverableRemote.Contains(a.Id) : discoverableLocal.Contains(a.Id)).Select(a => a.Id));
}
ordered = ordered.Skip(offset).Take(limit).ToList();
}
var accounts = await mapper.Accounts(ordered, token);
return Json(ordered.Where(accounts.ContainsKey).Select(id => accounts[id]).ToList());
}
static string Tie(string name) =>
Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(name ?? string.Empty)));
}
}