Build / Build (push) Successful in 35s
All 384 routes, the Mastodon API, the client API and the frozen federation paths, are read from one class with one nested class per controller. Their values are unchanged, checked one by one against the old literals; decePubClient keeps its own APIs class. 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
189 lines
11 KiB
C#
189 lines
11 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
|
|
using PrivaPub.Api.Mastodon.Entities;
|
|
using PrivaPub.Api.Mastodon.Infrastructure;
|
|
using PrivaPub.Api.Mastodon.Mappers;
|
|
using PrivaPub.Domain.Privacy;
|
|
using PrivaPub.Federation.Actors;
|
|
using PrivaPub.Federation.Inbox;
|
|
using PrivaPub.Federation.Outbox;
|
|
using PrivaPub.Domain.Social;
|
|
using PrivaPub.Models.Post;
|
|
using PrivaPub.StaticServices;
|
|
|
|
using PostEntity = PrivaPub.Models.Post.Post;
|
|
|
|
namespace PrivaPub.Api.Mastodon.Controllers
|
|
{
|
|
public partial class SearchController(
|
|
MastodonMapper mapper,
|
|
DbEntities dbEntities,
|
|
ILocalActorService localActors,
|
|
IRemoteActorService remoteActors,
|
|
IRemotePosts remotePosts,
|
|
AccountSearch accountSearch) : MastodonController
|
|
{
|
|
// Anyone may search, as on Mastodon; only resolving (which fetches from other servers) and paging need a sign-in.
|
|
[HttpGet(ApiPaths.Search.GET_Search), Scope("read:search", requiresUser: false), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public async Task<IActionResult> Search(CancellationToken token)
|
|
{
|
|
var q = Params.Get("q")?.Trim();
|
|
var type = Params.Get("type");
|
|
var offset = Params.Int("offset") ?? 0;
|
|
if (MyId == default && (Params.Bool("resolve") == true || offset > 0))
|
|
return Error(StatusCodes.Status401Unauthorized, "Search queries that resolve uris or use offset require the read:search scope");
|
|
var resolve = Params.Bool("resolve") == true && MyId != default;
|
|
var results = new SearchResults();
|
|
if (string.IsNullOrEmpty(q))
|
|
return Json(results);
|
|
|
|
if (q.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var post = await dbEntities.Posts.Match(p => (p.ObjectURI == q || p.Url == q) && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
|
|
if (post == default && resolve && type is null or "statuses")
|
|
post = await remotePosts.StoreContext(q, 0, token);
|
|
if (post != default && type is null or "statuses" && await VisibilityPolicy.CanSee(post, MyId, token))
|
|
if (await mapper.Status(post, MyId, token) is { } status)
|
|
results.Statuses.Add(status);
|
|
if (results.Statuses.Count == 0 && type is null or "accounts")
|
|
{
|
|
var local = await localActors.FindByUri(q, token);
|
|
var foreign = local == default ? (resolve ? await remoteActors.GetActor(q, refresh: false, token) : default) : default;
|
|
if (local is { IsFederated: true, IsCircle: false })
|
|
results.Accounts.Add(await mapper.Local(local, false, token));
|
|
else if (foreign != default)
|
|
results.Accounts.Add(mapper.Foreign(foreign));
|
|
}
|
|
return Json(results);
|
|
}
|
|
|
|
if (type is null or "accounts")
|
|
{
|
|
results.Accounts = await accountSearch.Find(q, resolve, Limit(), Math.Max(0, offset), token);
|
|
}
|
|
// an account's handle asks for the account, never for posts that happen to share its words
|
|
if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q))
|
|
results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token);
|
|
if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag))
|
|
results.Hashtags.Add(new { name = tag, url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", history = await TagsController.History(dbEntities, tag, token) });
|
|
return Json(results);
|
|
}
|
|
}
|
|
|
|
public partial class SearchController
|
|
{
|
|
const int WordCandidates = 400;
|
|
|
|
[System.Text.RegularExpressions.GeneratedRegex(@"^@?[^\s@]+@[^\s@]+$|^@[^\s@]+$")]
|
|
private static partial System.Text.RegularExpressions.Regex Handle();
|
|
|
|
// Posts by their words, as Mastodon searches them: those the persona wrote, boosted, favourited, bookmarked or was
|
|
// named in, and public posts of authors who let themselves be indexed; newest first, what the persona may see only
|
|
async Task<List<Status>> Words(string q, int offset, int limit, CancellationToken token)
|
|
{
|
|
var candidates = await dbEntities.Posts.Match(f => f.Text(q)).Match(p => p.ReblogOfPostId == null).Match(VisibilityPolicy.IsShown)
|
|
.Sort(p => p.ID, MongoDB.Entities.Order.Descending).Limit(WordCandidates).ExecuteAsync(token);
|
|
if (candidates.Count == 0)
|
|
return new List<Status>();
|
|
var ids = candidates.Select(p => p.ID).ToList();
|
|
var mine = new HashSet<string>();
|
|
mine.UnionWith((await dbEntities.Favourites.Match(f => f.AccountId == MyId && ids.Contains(f.PostId)).ExecuteAsync(token)).Select(f => f.PostId));
|
|
mine.UnionWith((await MongoDB.Entities.DB.Default.Find<Models.Social.Bookmark>().Match(b => b.AvatarId == MyId && ids.Contains(b.PostId)).ExecuteAsync(token))
|
|
.Select(b => b.PostId));
|
|
mine.UnionWith((await dbEntities.Posts.Match(p => p.AuthorAccountId == MyId && ids.Contains(p.ReblogOfPostId) && !p.DeletedAt.HasValue).ExecuteAsync(token))
|
|
.Select(p => p.ReblogOfPostId));
|
|
var authors = candidates.Select(p => p.AuthorAccountId ?? p.GroupUserId).Where(a => a != default).Distinct().ToList();
|
|
var indexable = (await dbEntities.Avatars.Match(a => authors.Contains(a.ID) && a.Settings.IsIndexable).ExecuteAsync(token)).Select(a => a.ID).ToHashSet();
|
|
// a remote author's searchableBy (FEP-268d) outranks its indexable, and a post's own outranks both
|
|
var remoteAuthors = (await dbEntities.ForeignAvatars.Match(f => authors.Contains(f.ID)).ExecuteAsync(token)).ToDictionary(f => f.ID);
|
|
var stating = remoteAuthors.Values.Where(f => f.SearchableBy != default).Select(f => f.ActorURI)
|
|
.Concat(candidates.Where(p => p.SearchableBy != default).Select(p => p.ActorURI))
|
|
.Where(uri => uri != default).Distinct().ToList();
|
|
var followed = stating.Count == 0
|
|
? new HashSet<string>()
|
|
: (await dbEntities.Followings.Match(f => f.AvatarId == MyId && stating.Contains(f.TargetActorURI) && f.State == Models.Social.FollowState.Accepted)
|
|
.ExecuteAsync(token)).Select(f => f.TargetActorURI).ToHashSet();
|
|
bool Searchable(PostEntity post, string author)
|
|
{
|
|
var remote = remoteAuthors.GetValueOrDefault(author);
|
|
var rule = post.SearchableBy ?? remote?.SearchableBy;
|
|
if (rule != default)
|
|
return Federation.Objects.ObjectShapes.Searchable(rule, remote?.FollowersURL, followed.Contains(post.ActorURI ?? string.Empty));
|
|
return remote?.IsIndexable == true || indexable.Contains(author);
|
|
}
|
|
var found = new List<PostEntity>();
|
|
foreach (var post in candidates)
|
|
{
|
|
var author = post.AuthorAccountId ?? post.GroupUserId;
|
|
var reachable = author == MyId && !post.IsFederatedCopy || mine.Contains(post.ID) || post.Mentions.Any(m => m.AccountId == MyId)
|
|
|| post.Visibility == PostVisibility.Public && !post.AuthorLimited && Searchable(post, author);//a silenced author's only to who met it (R6)
|
|
if (reachable && await VisibilityPolicy.CanSee(post, MyId, token))
|
|
found.Add(post);
|
|
if (found.Count >= offset + limit)
|
|
break;
|
|
}
|
|
return await mapper.Statuses(found.Skip(offset).Take(limit).ToList(), MyId, token);
|
|
}
|
|
}
|
|
|
|
public class StubsController : MastodonController
|
|
{
|
|
// Routes Mastodon answers that we have nothing behind: an empty or default answer lets clients degrade, where a
|
|
// 404 breaks some of them (Mastodon invariant 5)
|
|
[HttpGet(ApiPaths.Stubs.GET_LinkTimeline), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult LinkTimeline() => Json(Array.Empty<object>());
|
|
|
|
[HttpGet(ApiPaths.Stubs.GET_M_IdentityProofs), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult IdentityProofs(string id) => Json(Array.Empty<object>());
|
|
|
|
[HttpGet(ApiPaths.Stubs.GET_Languages), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult Languages() => Json(InstanceController.LanguageCodes(HttpContext.RequestServices)
|
|
.Select(code => new { code, name = System.Globalization.CultureInfo.GetCultureInfo(code).EnglishName }));
|
|
|
|
[HttpGet(ApiPaths.Stubs.GET_TranslationLanguages), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult TranslationLanguages() => Json(new { });
|
|
|
|
// translation is cut (owner decision 2026-10-17): no language offers any (translation_languages), and a client that
|
|
// asks anyway is told so, as Mastodon tells it when it can't translate
|
|
[HttpPost(ApiPaths.Stubs.POST_M_Translate), Scope("read:statuses")]
|
|
public IActionResult Translate(string id) => Error(StatusCodes.Status422UnprocessableEntity, "Translation is not available on this server");
|
|
|
|
// Mastodon 4.3's yearly reports (Wrapstodon): none are made here, so there are never any to show, for any year (4.4's
|
|
// show), and marking one read changes nothing
|
|
[HttpGet(ApiPaths.Stubs.GET_AnnualReports), HttpGet(ApiPaths.Stubs.GET_M_AnnualReports), Scope("read:accounts")]
|
|
public IActionResult AnnualReports(string year) => Json(new { annual_reports = Array.Empty<object>(), accounts = Array.Empty<object>(), statuses = Array.Empty<object>() });
|
|
|
|
[HttpPost(ApiPaths.Stubs.POST_M_ReadAnnualReport), Scope("write:accounts")]
|
|
public IActionResult ReadAnnualReport(string year) => Json(new { });
|
|
|
|
// Registration through the API is cut (owner decision 2026-10-17): a login is made by setup or an invitation, on
|
|
// /clientapi. Mastodon answers this when its registrations are closed; its e-mail confirmation routes follow, since no
|
|
// account here waits for one
|
|
[HttpPost(ApiPaths.Stubs.POST_Register), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult Register() => Error(StatusCodes.Status403Forbidden, "This action is not allowed");
|
|
|
|
[HttpPost(ApiPaths.Stubs.POST_ResendConfirmation), Scope("write:accounts")]
|
|
public IActionResult ResendConfirmation() =>
|
|
Error(StatusCodes.Status403Forbidden, "This method is only available while the e-mail is awaiting confirmation");
|
|
|
|
[HttpGet(ApiPaths.Stubs.GET_CheckConfirmation), Scope("read:accounts")]
|
|
public IActionResult CheckConfirmation() => Json(true);
|
|
|
|
// the peers' names are not published (/instance/peers stays empty), so a search of them finds none
|
|
[HttpGet(ApiPaths.Stubs.GET_SearchPeers), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult SearchPeers() => Json(Array.Empty<string>());
|
|
|
|
// Mastodon 4.4's asynchronous refreshes are announced by a Mastodon-Async-Refresh header, which PrivaPub never sends
|
|
// (a thread's replies are read again in the background and simply show up): there is never one to ask about
|
|
[HttpGet(ApiPaths.Stubs.GET_M_AsyncRefresh), Scope("read")]
|
|
public IActionResult AsyncRefresh(string id) => NotFoundError();
|
|
|
|
// the Mastodon admin API is cut: moderation stays on /clientapi (ModeratorController, AdminController), so every
|
|
// admin route answers as Mastodon answers an account that may not use it, whoever asks
|
|
[HttpGet(ApiPaths.Stubs.GET_M_Admin), HttpPost(ApiPaths.Stubs.POST_M_Admin), HttpPut(ApiPaths.Stubs.PUT_M_Admin), HttpPatch(ApiPaths.Stubs.PATCH_M_Admin),
|
|
HttpDelete(ApiPaths.Stubs.DELETE_M_Admin), HttpGet(ApiPaths.Stubs.GET_M_AdminV2), HttpPost(ApiPaths.Stubs.POST_M_AdminV2),
|
|
ApiExplorerSettings(IgnoreApi = true), Microsoft.AspNetCore.Authorization.AllowAnonymous]
|
|
public IActionResult Admin(string rest) => Error(StatusCodes.Status403Forbidden, "This action is not allowed");
|
|
}
|
|
}
|