The API's JSON is generated at build time, and no answer is an anonymous object
Build / Build (push) Successful in 36s

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
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-11-10 07:28:02 +01:00
1 parent 8a1e4e419b
commit f3fdeaf038
41 files changed
+1333 -266

No files matched your search

+20 -2
View File
@@ -93,6 +93,7 @@ PrivaPub/ ASP.NET Core Web API, net10.0
Infrastructure/ Infrastructure/
Http/ FederationHttp + SafeHttpHandlerFactory + IpRangeGuard: the only way out Http/ FederationHttp + SafeHttpHandlerFactory + IpRangeGuard: the only way out
Jobs/ JobQueue (leases), JobWorker, Backoff, HostCircuitBreaker Jobs/ JobQueue (leases), JobWorker, Backoff, HostCircuitBreaker
Json/ ServerJsonContext, PrivaPubJson (the serializer chains), UnregisteredJson, ViewBuild
Push/ Web Push (R9): Vapid (the server's key, ES256 JWTs), WebPushCrypto (aes128gcm, aesgcm), Push/ Web Push (R9): Vapid (the server's key, ES256 JWTs), WebPushCrypto (aes128gcm, aesgcm),
WebPushJob (SendPush, through the `push` client) WebPushJob (SendPush, through the `push` client)
Ids/ PrivacyIds (day-only ids for personas and groups, arrival-ordered ids for remote posts) Ids/ PrivacyIds (day-only ids for personas and groups, arrival-ordered ids for remote posts)
@@ -144,7 +145,8 @@ PrivaPub/ ASP.NET Core Web API, net10.0
Participations: a persona's Join and Leave of a remote event, and the organiser's answer Participations: a persona's Join and Leave of a remote event, and the organiser's answer
Api/Mastodon/ Api/Mastodon/
Auth/ OpenIddict setup (keys in Mongo), MastodonScopes, TokenController, OAuthPruner Auth/ OpenIddict setup (keys in Mongo), MastodonScopes, TokenController, OAuthPruner
Infrastructure/ MastodonController (avatar context, scopes, errors, Link), MastodonParams, MastodonJson, Page Infrastructure/ MastodonController (avatar context, scopes, errors, Link), MastodonParams, MastodonJson,
MastodonJsonContext, Page
Entities/ Mappers/ Mastodon entities; MastodonMapper (Account, Status), AccountSearch Entities/ Mappers/ Mastodon entities; MastodonMapper (Account, Status), AccountSearch
Controllers/ apps, instance, accounts, statuses, timelines, notifications, search, lists, filters, Controllers/ apps, instance, accounts, statuses, timelines, notifications, search, lists, filters,
media, polls, reactions, reports, scheduled statuses, streaming, tags, trends, cdns, media, polls, reactions, reports, scheduled statuses, streaming, tags, trends, cdns,
@@ -1106,7 +1108,23 @@ same rules. Applied to PrivaPub:
- **Routes** are constants in `PrivaPub/ApiPaths.cs` (HR0305): one nested class per controller, `GET_`/`POST_`/…, - **Routes** are constants in `PrivaPub/ApiPaths.cs` (HR0305): one nested class per controller, `GET_`/`POST_`/…,
`_M_` when the template has parameters, `Prefix` for a controller's own `[Route]`. The values are the frozen routes `_M_` when the template has parameters, `Prefix` for a controller's own `[Route]`. The values are the frozen routes
above, never changed by a rename. decePubClient keeps its own `APIs` class (owner, 2026-11-10: kept separate). above, never changed by a rename. decePubClient keeps its own `APIs` class (owner, 2026-11-10: kept separate).
- **Still open:** source-generated JSON contexts (HR0306). - **JSON (HR0306):** everything that crosses HTTP has source-generated metadata, and no response is an anonymous object.
- `PrivaPub.ClientModels/ClientModelsJsonContext` holds every `/clientapi` DTO, shared with decePubClient.
`Infrastructure/Json/ServerJsonContext` holds the server-only ones: problem details, `/build.json` and the Web Push
and VAPID dictionaries. Both are chained into MVC's and the minimal APIs' options, `PrivaPubJson.Web` and
`PrivaPubJson.Plain` (`PrivaPubJson.Chain`).
- `Api/Mastodon/Infrastructure/MastodonJsonContext` holds every Mastodon entity (`Entities/Entities.cs` and
`Entities/Documents.cs`, the named shapes of instance, policy, report and the other small answers), with `List<T>` of
each and the boxed values the `object` members carry. It is chained into `MastodonJson.Options`, which the API,
streaming and error bodies use.
- An answer is a list or an array, never a lazy `Select`: an iterator's type has no metadata.
- The last resolver of each chain is `UnregisteredJson`. In Development and the pasture an unregistered type throws.
In Production it is logged as an error once and still serialized, so a gap never takes the server down.
`PrivaPubJson.Check` fails startup outside Production when a class in `PrivaPub.ClientModels` or
`Api/Mastodon/Entities` has no metadata.
- The documented exceptions: ActivityPub documents are built and read as `JsonNode` (`ActivityPubRenderer`,
`ActivityJson`). Job payloads, backup manifests, restore markers and archive exports are stored, not sent, and keep
the default options. OpenIddict writes its own token responses.
## Verifying ## Verifying
@@ -0,0 +1,187 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using PrivaPub.ClientModels.Admin;
using PrivaPub.ClientModels.Data;
using PrivaPub.ClientModels.Group;
using PrivaPub.ClientModels.Post;
using PrivaPub.ClientModels.Social;
using PrivaPub.ClientModels.User;
using PrivaPub.ClientModels.User.Avatar;
namespace PrivaPub.ClientModels
{
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(AdminPasswordForm))]
[JsonSerializable(typeof(AnnouncementForm))]
[JsonSerializable(typeof(BackupPasswordForm))]
[JsonSerializable(typeof(DeleteGroupForm))]
[JsonSerializable(typeof(DeletePersonaForm))]
[JsonSerializable(typeof(DeletePostForm))]
[JsonSerializable(typeof(DomainBlockForm))]
[JsonSerializable(typeof(EmailChangeForm))]
[JsonSerializable(typeof(EmailCodeForm))]
[JsonSerializable(typeof(FollowForm))]
[JsonSerializable(typeof(GroupMembershipForm))]
[JsonSerializable(typeof(ImportPersonaArchiveForm))]
[JsonSerializable(typeof(InsertAvatarForm))]
[JsonSerializable(typeof(InsertDmForm))]
[JsonSerializable(typeof(InsertGroupForm))]
[JsonSerializable(typeof(InsertPostForm))]
[JsonSerializable(typeof(InvitationLoginForm))]
[JsonSerializable(typeof(JoinGroupForm))]
[JsonSerializable(typeof(JwtUser))]
[JsonSerializable(typeof(LocalEmojiForm))]
[JsonSerializable(typeof(LoginForm))]
[JsonSerializable(typeof(ModerateAccountForm))]
[JsonSerializable(typeof(NewPasswordForm))]
[JsonSerializable(typeof(PasswordForm))]
[JsonSerializable(typeof(PasswordRecoveryForm))]
[JsonSerializable(typeof(PersonaPreferencesForm))]
[JsonSerializable(typeof(RelayForm))]
[JsonSerializable(typeof(RemovePostForm))]
[JsonSerializable(typeof(RemoveSelfForm))]
[JsonSerializable(typeof(ResolveReportForm))]
[JsonSerializable(typeof(RestoreBackupForm))]
[JsonSerializable(typeof(RootRoleForm))]
[JsonSerializable(typeof(ServerMediaLimitsForm))]
[JsonSerializable(typeof(ServerRuleForm))]
[JsonSerializable(typeof(ServerSettingsForm))]
[JsonSerializable(typeof(SetupForm))]
[JsonSerializable(typeof(StaffPickForm))]
[JsonSerializable(typeof(TotpCodeForm))]
[JsonSerializable(typeof(TotpDisableForm))]
[JsonSerializable(typeof(UpdateAvatarForm))]
[JsonSerializable(typeof(UpdateGroupForm))]
[JsonSerializable(typeof(UpdatePostForm))]
[JsonSerializable(typeof(UserForm))]
[JsonSerializable(typeof(UserPasswordForm))]
[JsonSerializable(typeof(UsersIds))]
[JsonSerializable(typeof(ViewAccount))]
[JsonSerializable(typeof(List<ViewAccount>))]
[JsonSerializable(typeof(ViewAdminAction))]
[JsonSerializable(typeof(List<ViewAdminAction>))]
[JsonSerializable(typeof(ViewAdminActionsPage))]
[JsonSerializable(typeof(List<ViewAdminActionsPage>))]
[JsonSerializable(typeof(ViewAdminGroup))]
[JsonSerializable(typeof(List<ViewAdminGroup>))]
[JsonSerializable(typeof(ViewAdminPersona))]
[JsonSerializable(typeof(List<ViewAdminPersona>))]
[JsonSerializable(typeof(ViewAdminRoot))]
[JsonSerializable(typeof(List<ViewAdminRoot>))]
[JsonSerializable(typeof(ViewAdminRootsPage))]
[JsonSerializable(typeof(List<ViewAdminRootsPage>))]
[JsonSerializable(typeof(ViewAnnouncement))]
[JsonSerializable(typeof(List<ViewAnnouncement>))]
[JsonSerializable(typeof(ViewAnnouncementReaction))]
[JsonSerializable(typeof(List<ViewAnnouncementReaction>))]
[JsonSerializable(typeof(ViewArchiveTicket))]
[JsonSerializable(typeof(List<ViewArchiveTicket>))]
[JsonSerializable(typeof(ViewArchiveUpload))]
[JsonSerializable(typeof(List<ViewArchiveUpload>))]
[JsonSerializable(typeof(ViewAvatar))]
[JsonSerializable(typeof(List<ViewAvatar>))]
[JsonSerializable(typeof(ViewAvatarSettings))]
[JsonSerializable(typeof(List<ViewAvatarSettings>))]
[JsonSerializable(typeof(ViewBackup))]
[JsonSerializable(typeof(List<ViewBackup>))]
[JsonSerializable(typeof(ViewBackupTicket))]
[JsonSerializable(typeof(List<ViewBackupTicket>))]
[JsonSerializable(typeof(ViewBackupUpload))]
[JsonSerializable(typeof(List<ViewBackupUpload>))]
[JsonSerializable(typeof(ViewBackups))]
[JsonSerializable(typeof(List<ViewBackups>))]
[JsonSerializable(typeof(ViewContactAccount))]
[JsonSerializable(typeof(List<ViewContactAccount>))]
[JsonSerializable(typeof(ViewCrawledHost))]
[JsonSerializable(typeof(List<ViewCrawledHost>))]
[JsonSerializable(typeof(ViewCrawler))]
[JsonSerializable(typeof(List<ViewCrawler>))]
[JsonSerializable(typeof(ViewDmGroup))]
[JsonSerializable(typeof(List<ViewDmGroup>))]
[JsonSerializable(typeof(ViewDomainBlock))]
[JsonSerializable(typeof(List<ViewDomainBlock>))]
[JsonSerializable(typeof(ViewFollowing))]
[JsonSerializable(typeof(List<ViewFollowing>))]
[JsonSerializable(typeof(ViewGroup))]
[JsonSerializable(typeof(List<ViewGroup>))]
[JsonSerializable(typeof(ViewGroupMember))]
[JsonSerializable(typeof(List<ViewGroupMember>))]
[JsonSerializable(typeof(ViewHostCounts))]
[JsonSerializable(typeof(List<ViewHostCounts>))]
[JsonSerializable(typeof(ViewHostDay))]
[JsonSerializable(typeof(List<ViewHostDay>))]
[JsonSerializable(typeof(ViewHostDelivery))]
[JsonSerializable(typeof(List<ViewHostDelivery>))]
[JsonSerializable(typeof(ViewHostDetail))]
[JsonSerializable(typeof(List<ViewHostDetail>))]
[JsonSerializable(typeof(ViewHostInstance))]
[JsonSerializable(typeof(List<ViewHostInstance>))]
[JsonSerializable(typeof(ViewHostRow))]
[JsonSerializable(typeof(List<ViewHostRow>))]
[JsonSerializable(typeof(ViewHostsPage))]
[JsonSerializable(typeof(List<ViewHostsPage>))]
[JsonSerializable(typeof(ViewInteractionEvent))]
[JsonSerializable(typeof(List<ViewInteractionEvent>))]
[JsonSerializable(typeof(ViewLanguage))]
[JsonSerializable(typeof(List<ViewLanguage>))]
[JsonSerializable(typeof(ViewLatency))]
[JsonSerializable(typeof(List<ViewLatency>))]
[JsonSerializable(typeof(ViewLedgerCounts))]
[JsonSerializable(typeof(List<ViewLedgerCounts>))]
[JsonSerializable(typeof(ViewLocalEmoji))]
[JsonSerializable(typeof(List<ViewLocalEmoji>))]
[JsonSerializable(typeof(ViewMediaLimits))]
[JsonSerializable(typeof(List<ViewMediaLimits>))]
[JsonSerializable(typeof(ViewMediaTotals))]
[JsonSerializable(typeof(List<ViewMediaTotals>))]
[JsonSerializable(typeof(ViewModeratedAccount))]
[JsonSerializable(typeof(List<ViewModeratedAccount>))]
[JsonSerializable(typeof(ViewModeratedAccountsPage))]
[JsonSerializable(typeof(List<ViewModeratedAccountsPage>))]
[JsonSerializable(typeof(ViewNotification))]
[JsonSerializable(typeof(List<ViewNotification>))]
[JsonSerializable(typeof(ViewPersonaArchive))]
[JsonSerializable(typeof(List<ViewPersonaArchive>))]
[JsonSerializable(typeof(ViewPersonaPreferences))]
[JsonSerializable(typeof(List<ViewPersonaPreferences>))]
[JsonSerializable(typeof(ViewPost))]
[JsonSerializable(typeof(List<ViewPost>))]
[JsonSerializable(typeof(ViewRelay))]
[JsonSerializable(typeof(List<ViewRelay>))]
[JsonSerializable(typeof(ViewReport))]
[JsonSerializable(typeof(List<ViewReport>))]
[JsonSerializable(typeof(ViewRestore))]
[JsonSerializable(typeof(List<ViewRestore>))]
[JsonSerializable(typeof(ViewRestoreWaiting))]
[JsonSerializable(typeof(List<ViewRestoreWaiting>))]
[JsonSerializable(typeof(ViewServerDay))]
[JsonSerializable(typeof(List<ViewServerDay>))]
[JsonSerializable(typeof(ViewServerRule))]
[JsonSerializable(typeof(List<ViewServerRule>))]
[JsonSerializable(typeof(ViewServerSettings))]
[JsonSerializable(typeof(List<ViewServerSettings>))]
[JsonSerializable(typeof(ViewServerSetup))]
[JsonSerializable(typeof(List<ViewServerSetup>))]
[JsonSerializable(typeof(ViewStaffPick))]
[JsonSerializable(typeof(List<ViewStaffPick>))]
[JsonSerializable(typeof(ViewStatisticsOverview))]
[JsonSerializable(typeof(List<ViewStatisticsOverview>))]
[JsonSerializable(typeof(ViewStorage))]
[JsonSerializable(typeof(List<ViewStorage>))]
[JsonSerializable(typeof(ViewTotpEnabled))]
[JsonSerializable(typeof(List<ViewTotpEnabled>))]
[JsonSerializable(typeof(ViewTotpSetup))]
[JsonSerializable(typeof(List<ViewTotpSetup>))]
[JsonSerializable(typeof(ViewUserSettings))]
[JsonSerializable(typeof(List<ViewUserSettings>))]
[JsonSerializable(typeof(WebResult))]
[JsonSerializable(typeof(List<string>))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(bool))]
[JsonSerializable(typeof(int))]
[JsonSerializable(typeof(long))]
public partial class ClientModelsJsonContext : JsonSerializerContext
{
}
}
@@ -7,7 +7,6 @@ using System.Xml.Linq;
namespace PrivaPub.ClientModels.User.Avatar namespace PrivaPub.ClientModels.User.Avatar
{ {
[JsonSerializable(typeof(InsertAvatarForm))]
public class InsertAvatarForm public class InsertAvatarForm
{ {
[JsonIgnore] [JsonIgnore]
@@ -5,7 +5,6 @@ using System.Text.Json.Serialization;
namespace PrivaPub.ClientModels.User.Avatar namespace PrivaPub.ClientModels.User.Avatar
{ {
[JsonSerializable(typeof(UpdateAvatarForm))]
public class UpdateAvatarForm public class UpdateAvatarForm
{ {
[JsonIgnore] [JsonIgnore]
@@ -1,8 +1,6 @@
using System.Text.Json.Serialization;
namespace PrivaPub.ClientModels.User.Avatar namespace PrivaPub.ClientModels.User.Avatar
{ {
[JsonSerializable(typeof(ViewAvatar))]
public class ViewAvatar public class ViewAvatar
{ {
public string Id { get; set; } public string Id { get; set; }
@@ -1,11 +1,9 @@
using PrivaPub.ClientModels.Resources; using PrivaPub.ClientModels.Resources;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
namespace PrivaPub.ClientModels.User.Avatar namespace PrivaPub.ClientModels.User.Avatar
{ {
[JsonSerializable(typeof(ViewAvatarSettings))]
public class ViewAvatarSettings public class ViewAvatarSettings
{ {
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)), [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)),
@@ -399,10 +399,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
.ExecuteAsync(token); .ExecuteAsync(token);
var followers = await dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.IsAccepted).ExecuteAsync(token); var followers = await dbEntities.Followers.Match(f => f.LocalActorId == MyId && f.IsAccepted).ExecuteAsync(token);
var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token); var handles = await Hidden.HandleDomains(followings.Select(f => f.TargetActorURI).Concat(followers.Select(f => f.ActorURI)).ToList(), token);
return Json(new return Json(new DomainBlockPreviewEntity
{ {
following_count = followings.Count(f => Hidden.Blocks(domain, f.TargetActorURI, handles.GetValueOrDefault(f.TargetActorURI))), FollowingCount = followings.Count(f => Hidden.Blocks(domain, f.TargetActorURI, handles.GetValueOrDefault(f.TargetActorURI))),
followers_count = followers.Count(f => Hidden.Blocks(domain, f.ActorURI, handles.GetValueOrDefault(f.ActorURI))) FollowersCount = followers.Count(f => Hidden.Blocks(domain, f.ActorURI, handles.GetValueOrDefault(f.ActorURI)))
}); });
} }
@@ -410,14 +410,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> BlockDomain(CancellationToken token) public async Task<IActionResult> BlockDomain(CancellationToken token)
{ {
await relationshipService.BlockDomain(Me, Params.Get("domain"), token); await relationshipService.BlockDomain(Me, Params.Get("domain"), token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpDelete(ApiPaths.Accounts.DELETE_UnblockDomain), Scope("write:blocks")] [HttpDelete(ApiPaths.Accounts.DELETE_UnblockDomain), Scope("write:blocks")]
public async Task<IActionResult> UnblockDomain(CancellationToken token) public async Task<IActionResult> UnblockDomain(CancellationToken token)
{ {
await relationshipService.UnblockDomain(Me, Params.Get("domain"), token); await relationshipService.UnblockDomain(Me, Params.Get("domain"), token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Accounts.GET_FollowRequests), Scope("read:follows")] [HttpGet(ApiPaths.Accounts.GET_FollowRequests), Scope("read:follows")]
@@ -440,7 +440,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
// tell who follows whom among the personas here (and their followers lists are never shown, hide_collections), so // tell who follows whom among the personas here (and their followers lists are never shown, hide_collections), so
// every account answers none // every account answers none
[HttpGet(ApiPaths.Accounts.GET_FamiliarFollowers), Scope("read:follows")] [HttpGet(ApiPaths.Accounts.GET_FamiliarFollowers), Scope("read:follows")]
public IActionResult FamiliarFollowers() => Json(Params.List("id").Select(id => new { id, accounts = Array.Empty<Account>() }).ToList()); public IActionResult FamiliarFollowers() => Json(Params.List("id").Select(id => new FamiliarFollowersEntity { Id = id, Accounts = Array.Empty<Account>() }).ToList());
// Endorsements (R8): Mastodon's account pins under their old names (pin, unpin) and 4.4's (endorse, unendorse). Only an // Endorsements (R8): Mastodon's account pins under their old names (pin, unpin) and 4.4's (endorse, unendorse). Only an
// account the persona follows may be endorsed, as Mastodon requires; they are the persona's alone, never federated as // account the persona follows may be endorsed, as Mastodon requires; they are the persona's alone, never federated as
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Domain.Content; using PrivaPub.Domain.Content;
using PrivaPub.Domain.Social; using PrivaPub.Domain.Social;
@@ -21,7 +22,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpPost(ApiPaths.Announcements.POST_M_Dismiss), Scope("write:accounts")] [HttpPost(ApiPaths.Announcements.POST_M_Dismiss), Scope("write:accounts")]
public async Task<IActionResult> Dismiss(string id, CancellationToken token) => public async Task<IActionResult> Dismiss(string id, CancellationToken token) =>
await announcementService.Dismiss(id, MyId, token) ? Json(new { }) : NotFoundError(); await announcementService.Dismiss(id, MyId, token) ? Json(new EmptyEntity()) : NotFoundError();
[HttpPut(ApiPaths.Announcements.PUT_M_React), Scope("write:favourites")] [HttpPut(ApiPaths.Announcements.PUT_M_React), Scope("write:favourites")]
public Task<IActionResult> React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token); public Task<IActionResult> React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token);
@@ -32,7 +33,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
async Task<IActionResult> Reaction(string id, string name, bool add, CancellationToken token) async Task<IActionResult> Reaction(string id, string name, bool add, CancellationToken token)
{ {
var (status, error) = await announcementService.React(id, MyId, name, add, token); var (status, error) = await announcementService.React(id, MyId, name, add, token);
return error == default ? Json(new { }) : Error(status, error); return error == default ? Json(new EmptyEntity()) : Error(status, error);
} }
/// <summary>Mastodon's Announcement entities, as the viewer (a persona, or nobody) sees them.</summary> /// <summary>Mastodon's Announcement entities, as the viewer (a persona, or nobody) sees them.</summary>
@@ -77,14 +77,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (application == default) if (application == default)
return Error(StatusCodes.Status401Unauthorized, "The access token is invalid"); return Error(StatusCodes.Status401Unauthorized, "The access token is invalid");
var properties = await applications.GetPropertiesAsync(application, token); var properties = await applications.GetPropertiesAsync(application, token);
return Json(new return Json(new AppCredentialsEntity
{ {
id = await applications.GetIdAsync(application, token), Id = await applications.GetIdAsync(application, token),
name = await applications.GetDisplayNameAsync(application, token), Name = await applications.GetDisplayNameAsync(application, token),
website = properties.TryGetValue("website", out var website) ? website.GetString() : default, Website = properties.TryGetValue("website", out var website) ? website.GetString() : default,
scopes = User.GetScopes().ToList(), Scopes = User.GetScopes().ToList(),
redirect_uris = (await applications.GetRedirectUrisAsync(application, token)).ToList(), RedirectUris = (await applications.GetRedirectUrisAsync(application, token)).ToList(),
vapid_key = (await vapid.Key(token)).ForApi VapidKey = (await vapid.Key(token)).ForApi
}); });
} }
@@ -37,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpDelete(ApiPaths.FeaturedTags.DELETE_M_Unfeature), Scope("write:accounts")] [HttpDelete(ApiPaths.FeaturedTags.DELETE_M_Unfeature), Scope("write:accounts")]
public async Task<IActionResult> Unfeature(string id, CancellationToken token) => public async Task<IActionResult> Unfeature(string id, CancellationToken token) =>
await featuredTags.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new { }); await featuredTags.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new EmptyEntity());
// the tags the persona used lately and does not feature yet, the most used first, as Mastodon's Tag // the tags the persona used lately and does not feature yet, the most used first, as Mastodon's Tag
[HttpGet(ApiPaths.FeaturedTags.GET_Suggestions), Scope("read:accounts")] [HttpGet(ApiPaths.FeaturedTags.GET_Suggestions), Scope("read:accounts")]
@@ -177,7 +177,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (await Mine(id, token) is not { } filter) if (await Mine(id, token) is not { } filter)
return NotFoundError(); return NotFoundError();
await DB.Default.DeleteAsync<PersonaFilter>(filter.ID); await DB.Default.DeleteAsync<PersonaFilter>(filter.ID);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Filters.GET_M_Keywords), Scope("read:filters")] [HttpGet(ApiPaths.Filters.GET_M_Keywords), Scope("read:filters")]
@@ -223,7 +223,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
filter.Keywords.RemoveAll(k => k.Id == id); filter.Keywords.RemoveAll(k => k.Id == id);
await DB.Default.SaveAsync(filter, token); await DB.Default.SaveAsync(filter, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Filters.GET_M_Statuses), Scope("read:filters")] [HttpGet(ApiPaths.Filters.GET_M_Statuses), Scope("read:filters")]
@@ -261,7 +261,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
filter.Statuses.RemoveAll(s => s.Id == id); filter.Statuses.RemoveAll(s => s.Id == id);
await DB.Default.SaveAsync(filter, token); await DB.Default.SaveAsync(filter, token);
return Json(new { }); return Json(new EmptyEntity());
} }
// -- v1: each keyword is a filter of its own, with its parent's context, action and expiry // -- v1: each keyword is a filter of its own, with its parent's context, action and expiry
@@ -351,7 +351,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
await DB.Default.DeleteAsync<PersonaFilter>(filter.ID); await DB.Default.DeleteAsync<PersonaFilter>(filter.ID);
else else
await DB.Default.SaveAsync(filter, token); await DB.Default.SaveAsync(filter, token);
return Json(new { }); return Json(new EmptyEntity());
} }
} }
} }
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Options;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Content; using PrivaPub.Domain.Content;
@@ -60,7 +61,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
string Thumbnail => Settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}"; string Thumbnail => Settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}";
static object Rules(ServerSettings settings) => static object Rules(ServerSettings settings) =>
settings.ListedRules().Select(r => new { id = r.Id, text = r.Text ?? string.Empty, hint = r.Hint ?? string.Empty }).ToList(); settings.ListedRules().Select(r => new RuleEntity { Id = r.Id, Text = r.Text ?? string.Empty, Hint = r.Hint ?? string.Empty }).ToList();
// the persona the administrator named as the server's contact, while it exists and its login may act // the persona the administrator named as the server's contact, while it exists and its login may act
async Task<object> ContactAccount(ServerSettings settings, CancellationToken token) async Task<object> ContactAccount(ServerSettings settings, CancellationToken token)
@@ -89,31 +90,31 @@ namespace PrivaPub.Api.Mastodon.Controllers
.Uri.GetLeftPart(UriPartial.Authority); .Uri.GetLeftPart(UriPartial.Authority);
// every limit is what the server enforces, read from where it is enforced // every limit is what the server enforces, read from where it is enforced
static object Statuses => new { max_characters = PrivaPub.Domain.Statuses.StatusService.MaxCharacters, max_media_attachments = 4, characters_reserved_per_url = 23 }; static object Statuses => new StatusLimitsEntity { MaxCharacters = PrivaPub.Domain.Statuses.StatusService.MaxCharacters, MaxMediaAttachments = 4, CharactersReservedPerUrl = 23 };
object MediaAttachments object MediaAttachments
{ {
get get
{ {
var media = HttpContext.RequestServices.GetRequiredService<IOptionsMonitor<PrivaPub.Domain.Media.MediaOptions>>().CurrentValue; var media = HttpContext.RequestServices.GetRequiredService<IOptionsMonitor<PrivaPub.Domain.Media.MediaOptions>>().CurrentValue;
return new return new MediaLimitsEntity
{ {
supported_mime_types = PrivaPub.Domain.Media.MediaService.SupportedTypes, SupportedMimeTypes = PrivaPub.Domain.Media.MediaService.SupportedTypes,
image_size_limit = media.MaxImageBytes, ImageSizeLimit = media.MaxImageBytes,
image_matrix_limit = media.MaxPixels, ImageMatrixLimit = media.MaxPixels,
video_size_limit = media.MaxVideoBytes, VideoSizeLimit = media.MaxVideoBytes,
video_frame_rate_limit = (int)media.MaxFrameRate, VideoFrameRateLimit = (int)media.MaxFrameRate,
video_matrix_limit = media.MaxVideoPixels VideoMatrixLimit = media.MaxVideoPixels
}; };
} }
} }
static object Polls => new static object Polls => new PollLimitsEntity
{ {
max_options = PrivaPub.Domain.Statuses.PollService.MaxOptions, MaxOptions = PrivaPub.Domain.Statuses.PollService.MaxOptions,
max_characters_per_option = PrivaPub.Domain.Statuses.PollService.MaxOptionLength, MaxCharactersPerOption = PrivaPub.Domain.Statuses.PollService.MaxOptionLength,
min_expiration = PrivaPub.Domain.Statuses.PollService.MinExpiration, MinExpiration = PrivaPub.Domain.Statuses.PollService.MinExpiration,
max_expiration = PrivaPub.Domain.Statuses.PollService.MaxExpiration MaxExpiration = PrivaPub.Domain.Statuses.PollService.MaxExpiration
}; };
[HttpGet(ApiPaths.Instance.GET_V1), AllowAnonymous] [HttpGet(ApiPaths.Instance.GET_V1), AllowAnonymous]
@@ -123,24 +124,24 @@ namespace PrivaPub.Api.Mastodon.Controllers
var users = await Counted.Users(token); var users = await Counted.Users(token);
var statuses = await Counted.LocalPosts(token); var statuses = await Counted.LocalPosts(token);
var domains = await KnownServers(token); var domains = await KnownServers(token);
return Json(new return Json(new InstanceV1Entity
{ {
uri = Domain, Uri = Domain,
title = settings.Title, Title = settings.Title,
short_description = settings.ShortDescription ?? string.Empty, ShortDescription = settings.ShortDescription ?? string.Empty,
description = settings.ShortDescription ?? string.Empty, Description = settings.ShortDescription ?? string.Empty,
email = settings.ContactEmail ?? string.Empty, Email = settings.ContactEmail ?? string.Empty,
version = Version, Version = Version,
urls = new { streaming_api = Streaming }, Urls = new InstanceV1UrlsEntity { StreamingApi = Streaming },
stats = new { user_count = users, status_count = statuses, domain_count = domains }, Stats = new InstanceV1StatsEntity { UserCount = users, StatusCount = statuses, DomainCount = domains },
thumbnail = Thumbnail, Thumbnail = Thumbnail,
languages = LanguageCodes(HttpContext.RequestServices), Languages = LanguageCodes(HttpContext.RequestServices),
registrations = Open, Registrations = Open,
approval_required = false, ApprovalRequired = false,
invites_enabled = true,//a group invitation always creates an account InvitesEnabled = true,//a group invitation always creates an account
configuration = new { accounts = new { max_featured_tags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured }, statuses = Statuses, media_attachments = MediaAttachments, polls = Polls }, Configuration = new InstanceV1ConfigurationEntity { Accounts = new InstanceV1ConfigurationAccountsEntity { MaxFeaturedTags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured }, Statuses = Statuses, MediaAttachments = MediaAttachments, Polls = Polls },
contact_account = await ContactAccount(settings, token), ContactAccount = await ContactAccount(settings, token),
rules = Rules(settings) Rules = Rules(settings)
}); });
} }
@@ -151,30 +152,30 @@ namespace PrivaPub.Api.Mastodon.Controllers
await DB.Default.CountAsync<Models.Jobs.RemoteInstance>(i => i.Seen == "touched", token); await DB.Default.CountAsync<Models.Jobs.RemoteInstance>(i => i.Seen == "touched", token);
[HttpGet(ApiPaths.Instance.GET_V2), AllowAnonymous] [HttpGet(ApiPaths.Instance.GET_V2), AllowAnonymous]
public async Task<IActionResult> V2(CancellationToken token) => Json(new public async Task<IActionResult> V2(CancellationToken token) => Json(new InstanceV2Entity
{ {
domain = Domain, Domain = Domain,
title = Settings.Title, Title = Settings.Title,
version = Version, Version = Version,
api_versions = new { mastodon = 7 }, ApiVersions = new InstanceV2ApiVersionsEntity { Mastodon = 7 },
source_url = "https://git.thepra.dev/thepra/SocialPub", SourceUrl = "https://git.thepra.dev/thepra/SocialPub",
description = Settings.ShortDescription ?? string.Empty, Description = Settings.ShortDescription ?? string.Empty,
usage = new { users = new { active_month = await Counted.ActiveUsers(30, token) } }, Usage = new InstanceV2UsageEntity { Users = new InstanceV2UsageUsersEntity { ActiveMonth = await Counted.ActiveUsers(30, token) } },
thumbnail = new { url = Thumbnail }, Thumbnail = new InstanceV2ThumbnailEntity { Url = Thumbnail },
languages = LanguageCodes(HttpContext.RequestServices), Languages = LanguageCodes(HttpContext.RequestServices),
configuration = new Configuration = new InstanceV2ConfigurationEntity
{ {
urls = new { streaming = Streaming }, Urls = new InstanceV2ConfigurationUrlsEntity { Streaming = Streaming },
accounts = new { max_featured_tags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured, max_pinned_statuses = StatusesController.MaxPins }, Accounts = new InstanceV2ConfigurationAccountsEntity { MaxFeaturedTags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured, MaxPinnedStatuses = StatusesController.MaxPins },
statuses = Statuses, Statuses = Statuses,
media_attachments = MediaAttachments, MediaAttachments = MediaAttachments,
polls = Polls, Polls = Polls,
translation = new { enabled = false }, Translation = new InstanceV2ConfigurationTranslationEntity { Enabled = false },
vapid = new { public_key = (await vapidKeys.Key(token)).ForApi }//Web Push (R9): the key every push is signed with Vapid = new InstanceV2ConfigurationVapidEntity { PublicKey = (await vapidKeys.Key(token)).ForApi }//Web Push (R9): the key every push is signed with
}, },
registrations = new { enabled = Open, approval_required = false, message = Open ? default : RegistrationOptions.ClosedMessage }, Registrations = new InstanceV2RegistrationsEntity { Enabled = Open, ApprovalRequired = false, Message = Open ? default : RegistrationOptions.ClosedMessage },
contact = new { email = Settings.ContactEmail ?? string.Empty, account = await ContactAccount(Settings, token) }, Contact = new InstanceV2ContactEntity { Email = Settings.ContactEmail ?? string.Empty, Account = await ContactAccount(Settings, token) },
rules = Rules(Settings) Rules = Rules(Settings)
}); });
[HttpGet(ApiPaths.Instance.GET_Peers), AllowAnonymous] [HttpGet(ApiPaths.Instance.GET_Peers), AllowAnonymous]
@@ -190,12 +191,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Json(Array.Empty<object>()); return Json(Array.Empty<object>());
if (_activity is { } cached && DateTime.UtcNow - cached.At < ActivityLifetime) if (_activity is { } cached && DateTime.UtcNow - cached.At < ActivityLifetime)
return Json(cached.Weeks); return Json(cached.Weeks);
var weeks = (await Counted.Weekly(ActivityWeeks, token)).Select(w => new var weeks = (await Counted.Weekly(ActivityWeeks, token)).Select(w => new ActivityWeekEntity
{ {
week = new DateTimeOffset(w.Week, TimeSpan.Zero).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), Week = new DateTimeOffset(w.Week, TimeSpan.Zero).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture),
statuses = w.Posts.ToString(CultureInfo.InvariantCulture), Statuses = w.Posts.ToString(CultureInfo.InvariantCulture),
logins = "0", Logins = "0",
registrations = w.Registrations.ToString(CultureInfo.InvariantCulture) Registrations = w.Registrations.ToString(CultureInfo.InvariantCulture)
}).ToList(); }).ToList();
_activity = new CachedActivity(DateTime.UtcNow, weeks); _activity = new CachedActivity(DateTime.UtcNow, weeks);
return Json(weeks); return Json(weeks);
@@ -208,10 +209,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
public IActionResult ExtendedDescription() public IActionResult ExtendedDescription()
{ {
var settings = Settings; var settings = Settings;
return Json(new return Json(new InstanceDocumentEntity
{ {
updated_at = settings.DescriptionUpdatedAt is { } updated ? MastodonJson.Time(updated) : MastodonJson.Day(DateTime.UtcNow), UpdatedAt = settings.DescriptionUpdatedAt is { } updated ? MastodonJson.Time(updated) : MastodonJson.Day(DateTime.UtcNow),
content = ContentRenderer.Document(settings.Description) Content = ContentRenderer.Document(settings.Description)
}); });
} }
@@ -219,10 +220,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
public IActionResult PrivacyPolicy() public IActionResult PrivacyPolicy()
{ {
var settings = Settings; var settings = Settings;
return Json(new return Json(new InstanceDocumentEntity
{ {
updated_at = MastodonJson.Time(settings.PrivacyPolicyUpdatedAt ?? ServerSettings.DefaultPrivacyPolicyUpdatedAt), UpdatedAt = MastodonJson.Time(settings.PrivacyPolicyUpdatedAt ?? ServerSettings.DefaultPrivacyPolicyUpdatedAt),
content = ContentRenderer.Document(settings.PrivacyPolicy) Content = ContentRenderer.Document(settings.PrivacyPolicy)
}); });
} }
@@ -244,12 +245,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
var effective = (settings.TermsEffectiveAt ?? settings.UpdatedAt ?? DateTime.UtcNow).Date; var effective = (settings.TermsEffectiveAt ?? settings.UpdatedAt ?? DateTime.UtcNow).Date;
if (on != default && on.Value != effective) if (on != default && on.Value != effective)
return NotFoundError(); return NotFoundError();
return Json(new return Json(new TermsOfServiceEntity
{ {
effective_date = effective.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), EffectiveDate = effective.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
effective = effective <= DateTime.UtcNow.Date, Effective = effective <= DateTime.UtcNow.Date,
content = ContentRenderer.Document(settings.TermsOfService), Content = ContentRenderer.Document(settings.TermsOfService),
succeeded_by = default(string) SucceededBy = default(string)
}); });
} }
@@ -258,13 +259,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet(ApiPaths.Instance.GET_DomainBlocks), AllowAnonymous] [HttpGet(ApiPaths.Instance.GET_DomainBlocks), AllowAnonymous]
public async Task<IActionResult> DomainBlocks(CancellationToken token) => public async Task<IActionResult> DomainBlocks(CancellationToken token) =>
Json((await DB.Default.Find<DomainBlock>().Match(b => b.Published).Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token)) Json((await DB.Default.Find<DomainBlock>().Match(b => b.Published).Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token))
.Select(b => new .Select(b => new DomainBlockEntity
{ {
domain = b.Obfuscate ? Obfuscated(b.Domain) : b.Domain, Domain = b.Obfuscate ? Obfuscated(b.Domain) : b.Domain,
digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(b.Domain ?? string.Empty))), Digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(b.Domain ?? string.Empty))),
severity = b.Severity switch { DomainBlockSeverity.Suspend => "suspend", DomainBlockSeverity.Silence => "silence", _ => "noop" }, Severity = b.Severity switch { DomainBlockSeverity.Suspend => "suspend", DomainBlockSeverity.Silence => "silence", _ => "noop" },
comment = b.PublicComment Comment = b.PublicComment
})); }).ToList());
// Mastodon's DomainBlock#public_domain: a quarter of the name kept at each end, every other character but the dots a * // Mastodon's DomainBlock#public_domain: a quarter of the name kept at each end, every other character but the dots a *
public static string Obfuscated(string domain) public static string Obfuscated(string domain)
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Privacy; using PrivaPub.Domain.Privacy;
@@ -20,7 +21,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
const int MaxMembers = 500; const int MaxMembers = 500;
static object View(PersonaList list) => new { id = list.ID, title = list.Title, replies_policy = list.RepliesPolicy, exclusive = list.Exclusive }; static object View(PersonaList list) => new ListEntity { Id = list.ID, Title = list.Title, RepliesPolicy = list.RepliesPolicy, Exclusive = list.Exclusive };
Task<PersonaList> Mine(string id, CancellationToken token) => Task<PersonaList> Mine(string id, CancellationToken token) =>
DB.Default.Find<PersonaList>().Match(l => l.ID == id && l.AvatarId == MyId).ExecuteFirstAsync(token); DB.Default.Find<PersonaList>().Match(l => l.ID == id && l.AvatarId == MyId).ExecuteFirstAsync(token);
@@ -97,7 +98,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
await DB.Default.DeleteAsync<PersonaListMember>(m => m.ListId == list.ID); await DB.Default.DeleteAsync<PersonaListMember>(m => m.ListId == list.ID);
await DB.Default.DeleteAsync<PersonaList>(list.ID); await DB.Default.DeleteAsync<PersonaList>(list.ID);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Lists.GET_M_Accounts), Scope("read:lists")] [HttpGet(ApiPaths.Lists.GET_M_Accounts), Scope("read:lists")]
@@ -131,7 +132,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Too many accounts in the list"); return Error(StatusCodes.Status422UnprocessableEntity, "Validation failed: Too many accounts in the list");
foreach (var account in ids.Where(a => !present.Contains(a))) foreach (var account in ids.Where(a => !present.Contains(a)))
await DB.Default.SaveAsync(new PersonaListMember { ListId = list.ID, AvatarId = MyId, AccountId = account }, token); await DB.Default.SaveAsync(new PersonaListMember { ListId = list.ID, AvatarId = MyId, AccountId = account }, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpDelete(ApiPaths.Lists.DELETE_M_Remove), Scope("write:lists")] [HttpDelete(ApiPaths.Lists.DELETE_M_Remove), Scope("write:lists")]
@@ -141,7 +142,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
var ids = Params.List("account_ids"); var ids = Params.List("account_ids");
await DB.Default.DeleteAsync<PersonaListMember>(m => m.ListId == list.ID && ids.Contains(m.AccountId)); await DB.Default.DeleteAsync<PersonaListMember>(m => m.ListId == list.ID && ids.Contains(m.AccountId));
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Lists.GET_M_Containing), Scope("read:lists")] [HttpGet(ApiPaths.Lists.GET_M_Containing), Scope("read:lists")]
@@ -1,4 +1,9 @@
using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.RateLimiting;
using EmptyEntity = PrivaPub.Api.Mastodon.Entities.EmptyEntity;
using MediaUploadEntity = PrivaPub.Api.Mastodon.Entities.MediaUploadEntity;
using MediaUploadMetaEntity = PrivaPub.Api.Mastodon.Entities.MediaUploadMetaEntity;
using MediaUploadMetaFocusEntity = PrivaPub.Api.Mastodon.Entities.MediaUploadMetaFocusEntity;
using MediaUploadMetaOriginalEntity = PrivaPub.Api.Mastodon.Entities.MediaUploadMetaOriginalEntity;
using PrivaPub.Infrastructure.Statistics; using PrivaPub.Infrastructure.Statistics;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
@@ -67,7 +72,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (attachment.PostId != null || attachment.ScheduledStatusId != null) if (attachment.PostId != null || attachment.ScheduledStatusId != null)
return Error(StatusCodes.Status422UnprocessableEntity, "Media attachment is currently used by a status"); return Error(StatusCodes.Status422UnprocessableEntity, "Media attachment is currently used by a status");
await mediaService.Trash(m => m.ID == attachment.ID && m.PostId == null && m.ScheduledStatusId == null, "deleted by its owner", token); await mediaService.Trash(m => m.ID == attachment.ID && m.PostId == null && m.ScheduledStatusId == null, "deleted by its owner", token);
return Json(new { }); return Json(new EmptyEntity());
} }
// as on Mastodon, only media not posted yet: a posted one's description and focus change by editing its post (media_attributes) // as on Mastodon, only media not posted yet: a posted one's description and focus change by editing its post (media_attributes)
@@ -147,23 +152,23 @@ namespace PrivaPub.Api.Mastodon.Controllers
object View(MediaAttachment attachment) => View(mediaService, attachment); object View(MediaAttachment attachment) => View(mediaService, attachment);
internal static object View(IMediaService media, MediaAttachment attachment) => new internal static object View(IMediaService media, MediaAttachment attachment) => new MediaUploadEntity
{ {
id = attachment.ID, Id = attachment.ID,
type = attachment.Kind, Type = attachment.Kind,
url = media.Url(attachment.FilePath), Url = media.Url(attachment.FilePath),
preview_url = media.Url(attachment.PreviewPath ?? attachment.FilePath), PreviewUrl = media.Url(attachment.PreviewPath ?? attachment.FilePath),
remote_url = default(string), RemoteUrl = default(string),
text_url = default(string), TextUrl = default(string),
meta = new Meta = new MediaUploadMetaEntity
{ {
original = attachment.Width.HasValue && attachment.Height > 0 Original = attachment.Width.HasValue && attachment.Height > 0
? new { width = attachment.Width, height = attachment.Height, size = $"{attachment.Width}x{attachment.Height}", aspect = (double)attachment.Width / attachment.Height.Value } ? new MediaUploadMetaOriginalEntity { Width = attachment.Width, Height = attachment.Height, Size = $"{attachment.Width}x{attachment.Height}", Aspect = (double)attachment.Width / attachment.Height.Value }
: default, : default,
focus = attachment.Focus is { Length: 2 } ? new { x = attachment.Focus[0], y = attachment.Focus[1] } : default Focus = attachment.Focus is { Length: 2 } ? new MediaUploadMetaFocusEntity { X = attachment.Focus[0], Y = attachment.Focus[1] } : default
}, },
description = attachment.Description, Description = attachment.Description,
blurhash = attachment.Blurhash Blurhash = attachment.Blurhash
}; };
} }
} }
@@ -3,6 +3,12 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver; using MongoDB.Driver;
using MongoDB.Entities; using MongoDB.Entities;
using EmptyEntity = PrivaPub.Api.Mastodon.Entities.EmptyEntity;
using MergedEntity = PrivaPub.Api.Mastodon.Entities.MergedEntity;
using NotificationPolicyEntity = PrivaPub.Api.Mastodon.Entities.NotificationPolicyEntity;
using NotificationPolicySummaryEntity = PrivaPub.Api.Mastodon.Entities.NotificationPolicySummaryEntity;
using NotificationPolicyV1Entity = PrivaPub.Api.Mastodon.Entities.NotificationPolicyV1Entity;
using NotificationRequestEntity = PrivaPub.Api.Mastodon.Entities.NotificationRequestEntity;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Social; using PrivaPub.Domain.Social;
@@ -33,30 +39,30 @@ namespace PrivaPub.Api.Mastodon.Controllers
_ => null _ => null
}; };
async Task<object> Summary(CancellationToken token) => new async Task<object> Summary(CancellationToken token) => new NotificationPolicySummaryEntity
{ {
pending_requests_count = await DB.Default.CountAsync<NotificationRequest>(r => r.AvatarId == MyId, token), PendingRequestsCount = await DB.Default.CountAsync<NotificationRequest>(r => r.AvatarId == MyId, token),
pending_notifications_count = await DB.Default.CountAsync<Notification>(n => n.AvatarId == MyId && n.Filtered, token) PendingNotificationsCount = await DB.Default.CountAsync<Notification>(n => n.AvatarId == MyId && n.Filtered, token)
}; };
async Task<object> V2(NotificationPolicy policy, CancellationToken token) => new async Task<object> V2(NotificationPolicy policy, CancellationToken token) => new NotificationPolicyEntity
{ {
for_not_following = Name(policy.ForNotFollowing), ForNotFollowing = Name(policy.ForNotFollowing),
for_not_followers = Name(policy.ForNotFollowers), ForNotFollowers = Name(policy.ForNotFollowers),
for_new_accounts = Name(policy.ForNewAccounts), ForNewAccounts = Name(policy.ForNewAccounts),
for_private_mentions = Name(policy.ForPrivateMentions), ForPrivateMentions = Name(policy.ForPrivateMentions),
for_limited_accounts = Name(policy.ForLimitedAccounts), ForLimitedAccounts = Name(policy.ForLimitedAccounts),
summary = await Summary(token) Summary = await Summary(token)
}; };
// the first version spoke of filtering only: dropped is filtered for it // the first version spoke of filtering only: dropped is filtered for it
async Task<object> V1(NotificationPolicy policy, CancellationToken token) => new async Task<object> V1(NotificationPolicy policy, CancellationToken token) => new NotificationPolicyV1Entity
{ {
filter_not_following = policy.ForNotFollowing != NotificationAction.Accept, FilterNotFollowing = policy.ForNotFollowing != NotificationAction.Accept,
filter_not_followers = policy.ForNotFollowers != NotificationAction.Accept, FilterNotFollowers = policy.ForNotFollowers != NotificationAction.Accept,
filter_new_accounts = policy.ForNewAccounts != NotificationAction.Accept, FilterNewAccounts = policy.ForNewAccounts != NotificationAction.Accept,
filter_private_mentions = policy.ForPrivateMentions != NotificationAction.Accept, FilterPrivateMentions = policy.ForPrivateMentions != NotificationAction.Accept,
summary = await Summary(token) Summary = await Summary(token)
}; };
[HttpGet(ApiPaths.NotificationRequests.GET_Policy), Scope("read:notifications")] [HttpGet(ApiPaths.NotificationRequests.GET_Policy), Scope("read:notifications")]
@@ -99,14 +105,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
return default; return default;
var post = string.IsNullOrEmpty(request.LastPostId) ? default var post = string.IsNullOrEmpty(request.LastPostId) ? default
: await dbEntities.Posts.Match(p => p.ID == request.LastPostId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); : await dbEntities.Posts.Match(p => p.ID == request.LastPostId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token);
return new return new NotificationRequestEntity
{ {
id = request.ID, Id = request.ID,
created_at = MastodonJson.Time(request.CreatedAt), CreatedAt = MastodonJson.Time(request.CreatedAt),
updated_at = MastodonJson.Time(request.UpdatedAt), UpdatedAt = MastodonJson.Time(request.UpdatedAt),
notifications_count = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture), NotificationsCount = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture),
account, Account = account,
last_status = post == default ? default : await mapper.Status(post, MyId, token) LastStatus = post == default ? default : await mapper.Status(post, MyId, token)
}; };
} }
@@ -126,7 +132,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
DB.Default.Find<NotificationRequest>().Match(r => r.ID == id && r.AvatarId == MyId).ExecuteFirstAsync(token); DB.Default.Find<NotificationRequest>().Match(r => r.ID == id && r.AvatarId == MyId).ExecuteFirstAsync(token);
[HttpGet(ApiPaths.NotificationRequests.GET_Merged), Scope("read:notifications")] [HttpGet(ApiPaths.NotificationRequests.GET_Merged), Scope("read:notifications")]
public IActionResult Merged() => Json(new { merged = true }); public IActionResult Merged() => Json(new MergedEntity { Merged = true });
[HttpGet(ApiPaths.NotificationRequests.GET_M_Request), Scope("read:notifications")] [HttpGet(ApiPaths.NotificationRequests.GET_M_Request), Scope("read:notifications")]
public async Task<IActionResult> Request(string id, CancellationToken token) => public async Task<IActionResult> Request(string id, CancellationToken token) =>
@@ -138,7 +144,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (await Mine(id, token) is not { } request) if (await Mine(id, token) is not { } request)
return NotFoundError(); return NotFoundError();
await NotificationPolicies.Accept(request, token); await NotificationPolicies.Accept(request, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpPost(ApiPaths.NotificationRequests.POST_M_Dismiss), Scope("write:notifications")] [HttpPost(ApiPaths.NotificationRequests.POST_M_Dismiss), Scope("write:notifications")]
@@ -147,7 +153,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (await Mine(id, token) is not { } request) if (await Mine(id, token) is not { } request)
return NotFoundError(); return NotFoundError();
await NotificationPolicies.Dismiss(request, token); await NotificationPolicies.Dismiss(request, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpPost(ApiPaths.NotificationRequests.POST_AcceptMany), Scope("write:notifications")] [HttpPost(ApiPaths.NotificationRequests.POST_AcceptMany), Scope("write:notifications")]
@@ -156,7 +162,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
foreach (var id in Params.List("id").Take(100)) foreach (var id in Params.List("id").Take(100))
if (await Mine(id, token) is { } request) if (await Mine(id, token) is { } request)
await NotificationPolicies.Accept(request, token); await NotificationPolicies.Accept(request, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpPost(ApiPaths.NotificationRequests.POST_DismissMany), Scope("write:notifications")] [HttpPost(ApiPaths.NotificationRequests.POST_DismissMany), Scope("write:notifications")]
@@ -165,7 +171,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
foreach (var id in Params.List("id").Take(100)) foreach (var id in Params.List("id").Take(100))
if (await Mine(id, token) is { } request) if (await Mine(id, token) is { } request)
await NotificationPolicies.Dismiss(request, token); await NotificationPolicies.Dismiss(request, token);
return Json(new { }); return Json(new EmptyEntity());
} }
} }
} }
@@ -8,6 +8,7 @@ using MongoDB.Entities;
using OpenIddict.Abstractions; using OpenIddict.Abstractions;
using OpenIddict.Validation.AspNetCore; using OpenIddict.Validation.AspNetCore;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Domain.Social; using PrivaPub.Domain.Social;
using PrivaPub.Infrastructure.Http; using PrivaPub.Infrastructure.Http;
@@ -111,7 +112,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Delete(CancellationToken token) public async Task<IActionResult> Delete(CancellationToken token)
{ {
await WebPush.ForgetToken(TokenId, token); await WebPush.ForgetToken(TokenId, token);
return Json(new { }); return Json(new EmptyEntity());
} }
async Task<PushSubscription> Mine(CancellationToken token) async Task<PushSubscription> Mine(CancellationToken token)
@@ -150,14 +151,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
} }
// Mastodon's WebPushSubscription // Mastodon's WebPushSubscription
async Task<object> View(PushSubscription subscription, CancellationToken token) => new async Task<object> View(PushSubscription subscription, CancellationToken token) => new WebPushSubscriptionEntity
{ {
id = subscription.ID, Id = subscription.ID,
endpoint = subscription.Endpoint, Endpoint = subscription.Endpoint,
standard = subscription.Standard, Standard = subscription.Standard,
alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)), Alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)),
server_key = (await vapid.Key(token)).ForApi, ServerKey = (await vapid.Key(token)).ForApi,
policy = WebPush.Name(subscription.Policy) Policy = WebPush.Name(subscription.Policy)
}; };
} }
} }
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Privacy; using PrivaPub.Domain.Privacy;
@@ -28,14 +29,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
var reactions = await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID).ExecuteAsync(token); var reactions = await DB.Default.Find<Reaction>().Match(r => r.PostId == post.ID).ExecuteAsync(token);
var accounts = await mapper.Accounts(reactions.Select(r => r.AccountId), token); var accounts = await mapper.Accounts(reactions.Select(r => r.AccountId), token);
return Json(reactions.GroupBy(r => r.Emoji).Select(group => new return Json(reactions.GroupBy(r => r.Emoji).Select(group => new PleromaReactionEntity
{ {
name = group.Key, Name = group.Key,
count = group.Count(), Count = group.Count(),
me = MyId != default && group.Any(r => r.AccountId == MyId), Me = MyId != default && group.Any(r => r.AccountId == MyId),
url = mapper.ProxiedUrl(group.First().EmojiURL), Url = mapper.ProxiedUrl(group.First().EmojiURL),
accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList() Accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList()
}).OrderByDescending(r => r.count).ToList()); }).OrderByDescending(r => r.Count).ToList());
} }
[HttpPut(ApiPaths.Reactions.PUT_M_React), Scope("write:favourites")] [HttpPut(ApiPaths.Reactions.PUT_M_React), Scope("write:favourites")]
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Relationships; using PrivaPub.Domain.Relationships;
@@ -17,18 +18,18 @@ namespace PrivaPub.Api.Mastodon.Controllers
Params.List("rule_ids"), Params.Bool("forward") == true, token); Params.List("rule_ids"), Params.Bool("forward") == true, token);
if (report == default) if (report == default)
return NotFoundError(); return NotFoundError();
return Json(new return Json(new ReportEntity
{ {
id = report.ID, Id = report.ID,
action_taken = false, ActionTaken = false,
action_taken_at = default(string), ActionTakenAt = default(string),
category = report.Category, Category = report.Category,
comment = report.Comment ?? string.Empty, Comment = report.Comment ?? string.Empty,
forwarded = report.Forwarded, Forwarded = report.Forwarded,
created_at = MastodonJson.Time(report.CreatedAt), CreatedAt = MastodonJson.Time(report.CreatedAt),
status_ids = report.PostIds, StatusIds = report.PostIds,
rule_ids = report.RuleIds, RuleIds = report.RuleIds,
target_account = await mapper.Account(report.TargetAccountId, token) TargetAccount = await mapper.Account(report.TargetAccountId, token)
}); });
} }
} }
@@ -2,6 +2,10 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Entities; using MongoDB.Entities;
using EmptyEntity = PrivaPub.Api.Mastodon.Entities.EmptyEntity;
using ScheduledStatusEntity = PrivaPub.Api.Mastodon.Entities.ScheduledStatusEntity;
using ScheduledStatusParamsEntity = PrivaPub.Api.Mastodon.Entities.ScheduledStatusParamsEntity;
using ScheduledStatusParamsPollEntity = PrivaPub.Api.Mastodon.Entities.ScheduledStatusParamsPollEntity;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Domain.Media; using PrivaPub.Domain.Media;
using PrivaPub.Domain.Statuses; using PrivaPub.Domain.Statuses;
@@ -24,27 +28,27 @@ namespace PrivaPub.Api.Mastodon.Controllers
var attachments = ids.Count == 0 var attachments = ids.Count == 0
? new List<MediaAttachment>() ? new List<MediaAttachment>()
: await DB.Default.Find<MediaAttachment>().Match(m => ids.Contains(m.ID)).ExecuteAsync(token); : await DB.Default.Find<MediaAttachment>().Match(m => ids.Contains(m.ID)).ExecuteAsync(token);
return new return new ScheduledStatusEntity
{ {
id = scheduled.ID, Id = scheduled.ID,
scheduled_at = MastodonJson.Time(scheduled.ScheduledAt), ScheduledAt = MastodonJson.Time(scheduled.ScheduledAt),
@params = new Params = new ScheduledStatusParamsEntity
{ {
text = p.Text, Text = p.Text,
poll = p.Poll == default ? default : new { options = p.Poll.Options, expires_in = p.Poll.ExpiresIn, multiple = p.Poll.Multiple, hide_totals = p.Poll.HideTotals }, Poll = p.Poll == default ? default : new ScheduledStatusParamsPollEntity { Options = p.Poll.Options, ExpiresIn = p.Poll.ExpiresIn, Multiple = p.Poll.Multiple, HideTotals = p.Poll.HideTotals },
media_ids = ids.Count == 0 ? default : ids, MediaIds = ids.Count == 0 ? default : ids,
sensitive = p.Sensitive, Sensitive = p.Sensitive,
spoiler_text = p.SpoilerText, SpoilerText = p.SpoilerText,
visibility = p.Visibility, Visibility = p.Visibility,
in_reply_to_id = p.InReplyToId, InReplyToId = p.InReplyToId,
language = p.Language, Language = p.Language,
application_id = default(string), ApplicationId = default(string),
scheduled_at = default(string), ScheduledAt = default(string),
idempotency = p.Idempotency, Idempotency = p.Idempotency,
with_rate_limit = false, WithRateLimit = false,
quoted_status_id = p.QuotedStatusId QuotedStatusId = p.QuotedStatusId
}, },
media_attachments = ids.Select(id => attachments.FirstOrDefault(m => m.ID == id)).Where(m => m != default) MediaAttachments = ids.Select(id => attachments.FirstOrDefault(m => m.ID == id)).Where(m => m != default)
.Select(m => MediaController.View(media, m)).ToList() .Select(m => MediaController.View(media, m)).ToList()
}; };
} }
@@ -91,7 +95,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID); await DB.Default.DeleteAsync<ScheduledStatus>(scheduled.ID);
// its media were the scheduled post's alone, never posted // its media were the scheduled post's alone, never posted
await mediaService.Trash(m => m.ScheduledStatusId == scheduled.ID, "scheduled post dropped", token); await mediaService.Trash(m => m.ScheduledStatusId == scheduled.ID, "scheduled post dropped", token);
return Json(new { }); return Json(new EmptyEntity());
} }
} }
} }
@@ -65,7 +65,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q)) if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q))
results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token); results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token);
if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag)) if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag))
results.Hashtags.Add(new { name = tag, url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", history = await TagsController.History(dbEntities, tag, token) }); results.Hashtags.Add(new SearchTagEntity { Name = tag, Url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", History = await TagsController.History(dbEntities, tag, token) });
return Json(results); return Json(results);
} }
} }
@@ -138,10 +138,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
[HttpGet(ApiPaths.Stubs.GET_Languages), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet(ApiPaths.Stubs.GET_Languages), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public IActionResult Languages() => Json(InstanceController.LanguageCodes(HttpContext.RequestServices) public IActionResult Languages() => Json(InstanceController.LanguageCodes(HttpContext.RequestServices)
.Select(code => new { code, name = System.Globalization.CultureInfo.GetCultureInfo(code).EnglishName })); .Select(code => new LanguageEntity { Code = code, Name = System.Globalization.CultureInfo.GetCultureInfo(code).EnglishName }).ToList());
[HttpGet(ApiPaths.Stubs.GET_TranslationLanguages), Microsoft.AspNetCore.Authorization.AllowAnonymous] [HttpGet(ApiPaths.Stubs.GET_TranslationLanguages), Microsoft.AspNetCore.Authorization.AllowAnonymous]
public IActionResult TranslationLanguages() => Json(new { }); public IActionResult TranslationLanguages() => Json(new EmptyEntity());
// translation is cut (owner decision 2026-10-17): no language offers any (translation_languages), and a client that // 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 // asks anyway is told so, as Mastodon tells it when it can't translate
@@ -151,10 +151,10 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Mastodon 4.3's yearly reports (Wrapstodon): none are made here, so there are never any to show, for any year (4.4's // 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 // show), and marking one read changes nothing
[HttpGet(ApiPaths.Stubs.GET_AnnualReports), HttpGet(ApiPaths.Stubs.GET_M_AnnualReports), Scope("read:accounts")] [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>() }); public IActionResult AnnualReports(string year) => Json(new AnnualReportsEntity { AnnualReports = Array.Empty<object>(), Accounts = Array.Empty<object>(), Statuses = Array.Empty<object>() });
[HttpPost(ApiPaths.Stubs.POST_M_ReadAnnualReport), Scope("write:accounts")] [HttpPost(ApiPaths.Stubs.POST_M_ReadAnnualReport), Scope("write:accounts")]
public IActionResult ReadAnnualReport(string year) => Json(new { }); public IActionResult ReadAnnualReport(string year) => Json(new EmptyEntity());
// Registration through the API is cut (owner decision 2026-10-17): a login is made by setup or an invitation, on // 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 // /clientapi. Mastodon answers this when its registrations are closed; its e-mail confirmation routes follow, since no
@@ -37,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey) catch (MongoWriteException ex) when (ex.WriteError?.Category == ServerErrorCategory.DuplicateKey)
{ {
} }
return Json(new { }); return Json(new EmptyEntity());
} }
// the candidates mapped a few at a time, until the page is full: an account no longer shown (deleted, suspended), one // the candidates mapped a few at a time, until the page is full: an account no longer shown (deleted, suspended), one
@@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver; using MongoDB.Driver;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Federation.Actors; using PrivaPub.Federation.Actors;
using PrivaPub.Models.Post; using PrivaPub.Models.Post;
@@ -44,11 +45,11 @@ namespace PrivaPub.Api.Mastodon.Controllers
return Enumerable.Range(0, 7).Select(back => today.AddDays(-back)).Select(day => return Enumerable.Range(0, 7).Select(back => today.AddDays(-back)).Select(day =>
{ {
var that = posts.Where(p => p.CreationDate >= day && p.CreationDate < day.AddDays(1)).ToList(); var that = posts.Where(p => p.CreationDate >= day && p.CreationDate < day.AddDays(1)).ToList();
return (object)new return (object)new TagHistoryEntity
{ {
day = new DateTimeOffset(day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), Day = new DateTimeOffset(day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(),
uses = that.Count.ToString(), Uses = that.Count.ToString(),
accounts = that.Select(p => p.AuthorAccountId ?? p.GroupUserId).Distinct().Count().ToString() Accounts = that.Select(p => p.AuthorAccountId ?? p.GroupUserId).Distinct().Count().ToString()
}; };
}).ToList(); }).ToList();
} }
@@ -58,13 +59,13 @@ namespace PrivaPub.Api.Mastodon.Controllers
// Mastodon's Tag: its week of use, and for a signed-in persona whether it follows it and (Mastodon 4.4) features it // Mastodon's Tag: its week of use, and for a signed-in persona whether it follows it and (Mastodon 4.4) features it
internal static async Task<object> TagView(DbEntities dbEntities, string baseAddress, string tag, string viewerId, bool? following, bool? featuring, internal static async Task<object> TagView(DbEntities dbEntities, string baseAddress, string tag, string viewerId, bool? following, bool? featuring,
CancellationToken token) => new CancellationToken token) => new TagEntity
{ {
name = tag, Name = tag,
url = $"{baseAddress}/tags/{Uri.EscapeDataString(tag)}", Url = $"{baseAddress}/tags/{Uri.EscapeDataString(tag)}",
history = await History(dbEntities, tag, token), History = await History(dbEntities, tag, token),
following = following ?? (viewerId != default && await DB.Default.Find<FollowedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)), Following = following ?? (viewerId != default && await DB.Default.Find<FollowedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)),
featuring = viewerId == default ? default(bool?) Featuring = viewerId == default ? default(bool?)
: featuring ?? await DB.Default.Find<FeaturedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token) : featuring ?? await DB.Default.Find<FeaturedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)
}; };
@@ -191,7 +191,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
return NotFoundError(); return NotFoundError();
await ConversationStates.Hide(MyId, group.ID, group.LastPostId, token); await ConversationStates.Hide(MyId, group.ID, group.LastPostId, token);
await ConversationStates.Read(MyId, group.ID, group.LastPostId, token); await ConversationStates.Read(MyId, group.ID, group.LastPostId, token);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Timelines.GET_Markers), Scope("read:statuses")] [HttpGet(ApiPaths.Timelines.GET_Markers), Scope("read:statuses")]
@@ -332,27 +332,27 @@ namespace PrivaPub.Api.Mastodon.Controllers
var newest = mapped[group.First().ID]; var newest = mapped[group.First().ID];
var total = group.Key.StartsWith("ungrouped-", StringComparison.Ordinal) ? 1 var total = group.Key.StartsWith("ungrouped-", StringComparison.Ordinal) ? 1
: await DB.Default.CountAsync(Builders<NotificationEntity>.Filter.And(Builders<NotificationEntity>.Filter.Where(InGroup(group.Key)), NotFiltered), token); : await DB.Default.CountAsync(Builders<NotificationEntity>.Filter.And(Builders<NotificationEntity>.Filter.Where(InGroup(group.Key)), NotFiltered), token);
groups.Add(new groups.Add(new NotificationGroupEntity
{ {
group_key = group.Key, GroupKey = group.Key,
notifications_count = Math.Max(total, group.Count()), NotificationsCount = Math.Max(total, group.Count()),
type = newest.Type, Type = newest.Type,
most_recent_notification_id = newest.Id, MostRecentNotificationId = newest.Id,
page_min_id = group.Last().ID, PageMinId = group.Last().ID,
page_max_id = group.First().ID, PageMaxId = group.First().ID,
latest_page_notification_at = newest.CreatedAt, LatestPageNotificationAt = newest.CreatedAt,
sample_account_ids = group.Select(n => mapped[n.ID].Account.Id).Distinct().Take(8).ToList(), SampleAccountIds = group.Select(n => mapped[n.ID].Account.Id).Distinct().Take(8).ToList(),
status_id = newest.Status?.Id, StatusId = newest.Status?.Id,
emoji = newest.Emoji, Emoji = newest.Emoji,
emoji_url = newest.EmojiUrl, EmojiUrl = newest.EmojiUrl,
moderation_warning = newest.ModerationWarning ModerationWarning = newest.ModerationWarning
}); });
} }
return new return new GroupedNotificationsEntity
{ {
accounts = mapped.Values.Select(n => n.Account).DistinctBy(a => a.Id).ToList(), Accounts = mapped.Values.Select(n => n.Account).DistinctBy(a => a.Id).ToList(),
statuses = mapped.Values.Where(n => n.Status != default).Select(n => n.Status).DistinctBy(s => s.Id).ToList(), Statuses = mapped.Values.Where(n => n.Status != default).Select(n => n.Status).DistinctBy(s => s.Id).ToList(),
notification_groups = groups NotificationGroups = groups
}; };
} }
@@ -371,7 +371,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
.Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token); .Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token);
var shown = (await Map(unread, token)).Select(n => n.Id).ToHashSet(); var shown = (await Map(unread, token)).Select(n => n.Id).ToHashSet();
var grouped = Grouped(); var grouped = Grouped();
return Json(new { count = unread.Where(n => shown.Contains(n.ID)).Select(n => GroupKey(n, grouped)).Distinct().Count() }); return Json(new UnreadCountEntity { Count = unread.Where(n => shown.Contains(n.ID)).Select(n => GroupKey(n, grouped)).Distinct().Count() });
} }
[HttpGet(ApiPaths.Notifications.GET_M_Group), Scope("read:notifications")] [HttpGet(ApiPaths.Notifications.GET_M_Group), Scope("read:notifications")]
@@ -398,7 +398,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
if (InGroup(groupKey) is not { } filter) if (InGroup(groupKey) is not { } filter)
return NotFoundError(); return NotFoundError();
await DB.Default.DeleteAsync(filter); await DB.Default.DeleteAsync(filter);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpGet(ApiPaths.Notifications.GET_M_Get), Scope("read:notifications")] [HttpGet(ApiPaths.Notifications.GET_M_Get), Scope("read:notifications")]
@@ -413,14 +413,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Clear(CancellationToken token) public async Task<IActionResult> Clear(CancellationToken token)
{ {
await DB.Default.DeleteAsync<NotificationEntity>(n => n.AvatarId == MyId); await DB.Default.DeleteAsync<NotificationEntity>(n => n.AvatarId == MyId);
return Json(new { }); return Json(new EmptyEntity());
} }
[HttpPost(ApiPaths.Notifications.POST_M_Dismiss), Scope("write:notifications")] [HttpPost(ApiPaths.Notifications.POST_M_Dismiss), Scope("write:notifications")]
public async Task<IActionResult> Dismiss(string id, CancellationToken token) public async Task<IActionResult> Dismiss(string id, CancellationToken token)
{ {
await DB.Default.DeleteAsync<NotificationEntity>(n => n.ID == id && n.AvatarId == MyId); await DB.Default.DeleteAsync<NotificationEntity>(n => n.ID == id && n.AvatarId == MyId);
return Json(new { }); return Json(new EmptyEntity());
} }
// counts what the list would show (Map drops notifications from gone accounts and about hidden posts), at most // counts what the list would show (Map drops notifications from gone accounts and about hidden posts), at most
@@ -430,7 +430,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var unread = await DB.Default.Find<NotificationEntity>().Match(n => n.AvatarId == MyId && !n.IsRead).Match(NotFiltered) var unread = await DB.Default.Find<NotificationEntity>().Match(n => n.AvatarId == MyId && !n.IsRead).Match(NotFiltered)
.Sort(n => n.ID, Order.Descending).Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token); .Sort(n => n.ID, Order.Descending).Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token);
return Json(new { count = (await Map(unread, token)).Count }); return Json(new UnreadCountEntity { Count = (await Map(unread, token)).Count });
} }
Task<List<Entities.Notification>> Map(List<NotificationEntity> notifications, CancellationToken token) => Task<List<Entities.Notification>> Map(List<NotificationEntity> notifications, CancellationToken token) =>
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver; using MongoDB.Driver;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Domain.Privacy; using PrivaPub.Domain.Privacy;
@@ -21,11 +22,11 @@ namespace PrivaPub.Api.Mastodon.Controllers
DbEntities dbEntities, DbEntities dbEntities,
ILocalActorService localActors) : MastodonController ILocalActorService localActors) : MastodonController
{ {
static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new TagHistoryEntity
{ {
day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), Day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(),
uses = h.Uses.ToString(), Uses = h.Uses.ToString(),
accounts = h.Accounts.ToString() Accounts = h.Accounts.ToString()
}).ToList(); }).ToList();
IEnumerable<T> Window<T>(IEnumerable<T> items, int fallback, int max) => IEnumerable<T> Window<T>(IEnumerable<T> items, int fallback, int max) =>
@@ -37,12 +38,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
var followed = MyId == default var followed = MyId == default
? new HashSet<string>() ? new HashSet<string>()
: (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet(); : (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet();
return Json(Window(await trendService.Tags(token), 10, 20).Select(t => new return Json(Window(await trendService.Tags(token), 10, 20).Select(t => new TrendTagEntity
{ {
name = t.Key, Name = t.Key,
url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}", Url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}",
history = History(t), History = History(t),
following = MyId == default ? default(bool?) : followed.Contains(t.Key) Following = MyId == default ? default(bool?) : followed.Contains(t.Key)
}).ToList()); }).ToList());
} }
@@ -64,11 +65,11 @@ namespace PrivaPub.Api.Mastodon.Controllers
{ {
var link = samples[t.SamplePostId].Link; var link = samples[t.SamplePostId].Link;
var card = mapper.LinkCard(t.Key, link.Title, link.Description, link.ImageURL); var card = mapper.LinkCard(t.Key, link.Title, link.Description, link.ImageURL);
return card == default ? default : (object)new return card == default ? default : (object)new TrendLinkEntity
{ {
card.Url, card.Title, card.Description, card.Type, card.AuthorName, card.AuthorUrl, card.ProviderName, card.ProviderUrl, Url = card.Url, Title = card.Title, Description = card.Description, Type = card.Type, AuthorName = card.AuthorName, AuthorUrl = card.AuthorUrl, ProviderName = card.ProviderName, ProviderUrl = card.ProviderUrl,
card.Html, card.Width, card.Height, card.Image, card.ImageDescription, card.EmbedUrl, card.Blurhash, card.Language, Html = card.Html, Width = card.Width, Height = card.Height, Image = card.Image, ImageDescription = card.ImageDescription, EmbedUrl = card.EmbedUrl, Blurhash = card.Blurhash, Language = card.Language,
card.PublishedAt, card.Authors, History = History(t) PublishedAt = card.PublishedAt, Authors = card.Authors, History = History(t)
}; };
}).Where(c => c != default).ToList()); }).Where(c => c != default).ToList());
} }
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Api.Mastodon.Mappers;
using PrivaPub.Federation.Actors; using PrivaPub.Federation.Actors;
@@ -20,14 +21,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
public async Task<IActionResult> Show(CancellationToken token) public async Task<IActionResult> Show(CancellationToken token)
{ {
var account = await mapper.Local(Me, false, token); var account = await mapper.Local(Me, false, token);
return Json(new return Json(new UserInfoEntity
{ {
iss = localActors.BaseAddress + "/", Iss = localActors.BaseAddress + "/",
sub = Me.Uri, Sub = Me.Uri,
name = account.DisplayName, Name = account.DisplayName,
preferred_username = account.Username, PreferredUsername = account.Username,
profile = account.Url, Profile = account.Url,
picture = account.Avatar Picture = account.Avatar
}); });
} }
} }
+474
View File
@@ -0,0 +1,474 @@
namespace PrivaPub.Api.Mastodon.Entities
{
public class ActivityWeekEntity
{
public string Week { get; set; }
public string Statuses { get; set; }
public string Logins { get; set; }
public string Registrations { get; set; }
}
public class AnnualReportsEntity
{
public object[] AnnualReports { get; set; } = [];
public object[] Accounts { get; set; } = [];
public object[] Statuses { get; set; } = [];
}
public class AppCredentialsEntity
{
public string Id { get; set; }
public string Name { get; set; }
public string Website { get; set; }
public List<string> Scopes { get; set; } = [];
public List<string> RedirectUris { get; set; } = [];
public string VapidKey { get; set; }
}
public class DomainBlockEntity
{
public string Domain { get; set; }
public string Digest { get; set; }
public string Severity { get; set; }
public string Comment { get; set; }
}
public class DomainBlockPreviewEntity
{
public int FollowingCount { get; set; }
public int FollowersCount { get; set; }
}
public class EmptyEntity
{
}
public class ErrorEntity
{
public string Error { get; set; }
}
public class FamiliarFollowersEntity
{
public string Id { get; set; }
public Account[] Accounts { get; set; } = [];
}
public class GroupedNotificationsEntity
{
public List<Account> Accounts { get; set; } = [];
public List<Status> Statuses { get; set; } = [];
public List<object> NotificationGroups { get; set; } = [];
}
public class InstanceDocumentEntity
{
public string UpdatedAt { get; set; }
public string Content { get; set; }
}
public class InstanceV1ConfigurationAccountsEntity
{
public int MaxFeaturedTags { get; set; }
}
public class InstanceV1ConfigurationEntity
{
public InstanceV1ConfigurationAccountsEntity Accounts { get; set; }
public object Statuses { get; set; }
public object MediaAttachments { get; set; }
public object Polls { get; set; }
}
public class InstanceV1Entity
{
public string Uri { get; set; }
public string Title { get; set; }
public string ShortDescription { get; set; }
public string Description { get; set; }
public string Email { get; set; }
public string Version { get; set; }
public InstanceV1UrlsEntity Urls { get; set; }
public InstanceV1StatsEntity Stats { get; set; }
public string Thumbnail { get; set; }
public IReadOnlyList<string> Languages { get; set; } = [];
public bool Registrations { get; set; }
public bool ApprovalRequired { get; set; }
public bool InvitesEnabled { get; set; }
public InstanceV1ConfigurationEntity Configuration { get; set; }
public object ContactAccount { get; set; }
public object Rules { get; set; }
}
public class InstanceV1StatsEntity
{
public long UserCount { get; set; }
public long StatusCount { get; set; }
public long DomainCount { get; set; }
}
public class InstanceV1UrlsEntity
{
public string StreamingApi { get; set; }
}
public class InstanceV2ApiVersionsEntity
{
public int Mastodon { get; set; }
}
public class InstanceV2ConfigurationAccountsEntity
{
public int MaxFeaturedTags { get; set; }
public int MaxPinnedStatuses { get; set; }
}
public class InstanceV2ConfigurationEntity
{
public InstanceV2ConfigurationUrlsEntity Urls { get; set; }
public InstanceV2ConfigurationAccountsEntity Accounts { get; set; }
public object Statuses { get; set; }
public object MediaAttachments { get; set; }
public object Polls { get; set; }
public InstanceV2ConfigurationTranslationEntity Translation { get; set; }
public InstanceV2ConfigurationVapidEntity Vapid { get; set; }
}
public class InstanceV2ConfigurationTranslationEntity
{
public bool Enabled { get; set; }
}
public class InstanceV2ConfigurationUrlsEntity
{
public string Streaming { get; set; }
}
public class InstanceV2ConfigurationVapidEntity
{
public string PublicKey { get; set; }
}
public class InstanceV2ContactEntity
{
public string Email { get; set; }
public object Account { get; set; }
}
public class InstanceV2Entity
{
public string Domain { get; set; }
public string Title { get; set; }
public string Version { get; set; }
public InstanceV2ApiVersionsEntity ApiVersions { get; set; }
public string SourceUrl { get; set; }
public string Description { get; set; }
public InstanceV2UsageEntity Usage { get; set; }
public InstanceV2ThumbnailEntity Thumbnail { get; set; }
public IReadOnlyList<string> Languages { get; set; } = [];
public InstanceV2ConfigurationEntity Configuration { get; set; }
public InstanceV2RegistrationsEntity Registrations { get; set; }
public InstanceV2ContactEntity Contact { get; set; }
public object Rules { get; set; }
}
public class InstanceV2RegistrationsEntity
{
public bool Enabled { get; set; }
public bool ApprovalRequired { get; set; }
public string Message { get; set; }
}
public class InstanceV2ThumbnailEntity
{
public string Url { get; set; }
}
public class InstanceV2UsageEntity
{
public InstanceV2UsageUsersEntity Users { get; set; }
}
public class InstanceV2UsageUsersEntity
{
public long ActiveMonth { get; set; }
}
public class LanguageEntity
{
public string Code { get; set; }
public string Name { get; set; }
}
public class ListEntity
{
public string Id { get; set; }
public string Title { get; set; }
public string RepliesPolicy { get; set; }
public bool Exclusive { get; set; }
}
public class MediaLimitsEntity
{
public IReadOnlyList<string> SupportedMimeTypes { get; set; } = [];
public long ImageSizeLimit { get; set; }
public long ImageMatrixLimit { get; set; }
public long VideoSizeLimit { get; set; }
public int VideoFrameRateLimit { get; set; }
public long VideoMatrixLimit { get; set; }
}
public class MediaUploadEntity
{
public string Id { get; set; }
public string Type { get; set; }
public string Url { get; set; }
public string PreviewUrl { get; set; }
public string RemoteUrl { get; set; }
public string TextUrl { get; set; }
public MediaUploadMetaEntity Meta { get; set; }
public string Description { get; set; }
public string Blurhash { get; set; }
}
public class MediaUploadMetaEntity
{
public MediaUploadMetaOriginalEntity Original { get; set; }
public MediaUploadMetaFocusEntity Focus { get; set; }
}
public class MediaUploadMetaFocusEntity
{
public float X { get; set; }
public float Y { get; set; }
}
public class MediaUploadMetaOriginalEntity
{
public int? Width { get; set; }
public int? Height { get; set; }
public string Size { get; set; }
public double Aspect { get; set; }
}
public class MergedEntity
{
public bool Merged { get; set; }
}
public class NotificationGroupEntity
{
public string GroupKey { get; set; }
public long NotificationsCount { get; set; }
public string Type { get; set; }
public string MostRecentNotificationId { get; set; }
public string PageMinId { get; set; }
public string PageMaxId { get; set; }
public string LatestPageNotificationAt { get; set; }
public List<string> SampleAccountIds { get; set; } = [];
public string StatusId { get; set; }
public string Emoji { get; set; }
public string EmojiUrl { get; set; }
public AccountWarning ModerationWarning { get; set; }
}
public class NotificationPolicyEntity
{
public string ForNotFollowing { get; set; }
public string ForNotFollowers { get; set; }
public string ForNewAccounts { get; set; }
public string ForPrivateMentions { get; set; }
public string ForLimitedAccounts { get; set; }
public object Summary { get; set; }
}
public class NotificationPolicySummaryEntity
{
public long PendingRequestsCount { get; set; }
public long PendingNotificationsCount { get; set; }
}
public class NotificationPolicyV1Entity
{
public bool FilterNotFollowing { get; set; }
public bool FilterNotFollowers { get; set; }
public bool FilterNewAccounts { get; set; }
public bool FilterPrivateMentions { get; set; }
public object Summary { get; set; }
}
public class NotificationRequestEntity
{
public string Id { get; set; }
public string CreatedAt { get; set; }
public string UpdatedAt { get; set; }
public string NotificationsCount { get; set; }
public Account Account { get; set; }
public Status LastStatus { get; set; }
}
public class PleromaReactionEntity
{
public string Name { get; set; }
public int Count { get; set; }
public bool Me { get; set; }
public string Url { get; set; }
public List<Account> Accounts { get; set; } = [];
}
public class PollLimitsEntity
{
public int MaxOptions { get; set; }
public int MaxCharactersPerOption { get; set; }
public int MinExpiration { get; set; }
public int MaxExpiration { get; set; }
}
public class ReportEntity
{
public string Id { get; set; }
public bool ActionTaken { get; set; }
public string ActionTakenAt { get; set; }
public string Category { get; set; }
public string Comment { get; set; }
public bool Forwarded { get; set; }
public string CreatedAt { get; set; }
public List<string> StatusIds { get; set; } = [];
public List<string> RuleIds { get; set; } = [];
public Account TargetAccount { get; set; }
}
public class RuleEntity
{
public string Id { get; set; }
public string Text { get; set; }
public string Hint { get; set; }
}
public class ScheduledStatusEntity
{
public string Id { get; set; }
public string ScheduledAt { get; set; }
public ScheduledStatusParamsEntity Params { get; set; }
public List<object> MediaAttachments { get; set; } = [];
}
public class ScheduledStatusParamsEntity
{
public string Text { get; set; }
public ScheduledStatusParamsPollEntity Poll { get; set; }
public List<string> MediaIds { get; set; } = [];
public bool Sensitive { get; set; }
public string SpoilerText { get; set; }
public string Visibility { get; set; }
public string InReplyToId { get; set; }
public string Language { get; set; }
public string ApplicationId { get; set; }
public string ScheduledAt { get; set; }
public string Idempotency { get; set; }
public bool WithRateLimit { get; set; }
public string QuotedStatusId { get; set; }
}
public class ScheduledStatusParamsPollEntity
{
public List<string> Options { get; set; } = [];
public int ExpiresIn { get; set; }
public bool Multiple { get; set; }
public bool HideTotals { get; set; }
}
public class SearchTagEntity
{
public string Name { get; set; }
public string Url { get; set; }
public List<object> History { get; set; } = [];
}
public class StatusLimitsEntity
{
public int MaxCharacters { get; set; }
public int MaxMediaAttachments { get; set; }
public int CharactersReservedPerUrl { get; set; }
}
public class TagEntity
{
public string Name { get; set; }
public string Url { get; set; }
public List<object> History { get; set; } = [];
public bool Following { get; set; }
public bool? Featuring { get; set; }
}
public class TagHistoryEntity
{
public string Day { get; set; }
public string Uses { get; set; }
public string Accounts { get; set; }
}
public class TermsOfServiceEntity
{
public string EffectiveDate { get; set; }
public bool Effective { get; set; }
public string Content { get; set; }
public string SucceededBy { get; set; }
}
public class TrendLinkEntity
{
public string Url { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Type { get; set; }
public string AuthorName { get; set; }
public string AuthorUrl { get; set; }
public string ProviderName { get; set; }
public string ProviderUrl { get; set; }
public string Html { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public string Image { get; set; }
public string ImageDescription { get; set; }
public string EmbedUrl { get; set; }
public string Blurhash { get; set; }
public string Language { get; set; }
public string PublishedAt { get; set; }
public List<object> Authors { get; set; } = [];
public List<object> History { get; set; } = [];
}
public class TrendTagEntity
{
public string Name { get; set; }
public string Url { get; set; }
public List<object> History { get; set; } = [];
public bool? Following { get; set; }
}
public class UnreadCountEntity
{
public int Count { get; set; }
}
public class UserInfoEntity
{
public string Iss { get; set; }
public string Sub { get; set; }
public string Name { get; set; }
public string PreferredUsername { get; set; }
public string Profile { get; set; }
public string Picture { get; set; }
}
public class WebPushSubscriptionEntity
{
public string Id { get; set; }
public string Endpoint { get; set; }
public bool Standard { get; set; }
public Dictionary<string, bool> Alerts { get; set; } = new();
public string ServerKey { get; set; }
public string Policy { get; set; }
}
}
@@ -8,6 +8,7 @@ using OpenIddict.Abstractions;
using OpenIddict.Validation.AspNetCore; using OpenIddict.Validation.AspNetCore;
using PrivaPub.Api.Mastodon.Auth; using PrivaPub.Api.Mastodon.Auth;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Federation.Actors; using PrivaPub.Federation.Actors;
using PrivaPub.Models.Federation; using PrivaPub.Models.Federation;
using PrivaPub.Models.User; using PrivaPub.Models.User;
@@ -94,7 +95,7 @@ namespace PrivaPub.Api.Mastodon.Infrastructure
new(value, MastodonJson.Options) { StatusCode = status }; new(value, MastodonJson.Options) { StatusCode = status };
protected static JsonResult Error(int status, string message) => protected static JsonResult Error(int status, string message) =>
new(new { error = message }, MastodonJson.Options) { StatusCode = status }; new(new ErrorEntity { Error = message }, MastodonJson.Options) { StatusCode = status };
protected JsonResult NotFoundError() => Error(StatusCodes.Status404NotFound, "Record not found"); protected JsonResult NotFoundError() => Error(StatusCodes.Status404NotFound, "Record not found");
@@ -1,4 +1,5 @@
using System.Text.Json; using System.Text.Json;
using PrivaPub.Api.Mastodon.Entities;
namespace PrivaPub.Api.Mastodon.Infrastructure namespace PrivaPub.Api.Mastodon.Infrastructure
{ {
@@ -9,7 +10,7 @@ namespace PrivaPub.Api.Mastodon.Infrastructure
{ {
var response = pages.HttpContext.Response; var response = pages.HttpContext.Response;
response.ContentType = "application/json; charset=utf-8"; response.ContentType = "application/json; charset=utf-8";
await response.WriteAsync(JsonSerializer.Serialize(new { error = Message(response.StatusCode) }, MastodonJson.Options)); await response.WriteAsync(JsonSerializer.Serialize(new ErrorEntity { Error = Message(response.StatusCode) }, MastodonJson.Options));
})); }));
public static string Message(int status) => status switch public static string Message(int status) => status switch
@@ -2,6 +2,8 @@ using System.Text.Encodings.Web;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using PrivaPub.Infrastructure.Json;
namespace PrivaPub.Api.Mastodon.Infrastructure namespace PrivaPub.Api.Mastodon.Infrastructure
{ {
public static class MastodonJson public static class MastodonJson
@@ -12,7 +14,8 @@ namespace PrivaPub.Api.Mastodon.Infrastructure
DictionaryKeyPolicy = default, DictionaryKeyPolicy = default,
DefaultIgnoreCondition = JsonIgnoreCondition.Never, DefaultIgnoreCondition = JsonIgnoreCondition.Never,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) } Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) },
TypeInfoResolverChain = { MastodonJsonContext.Default, UnregisteredJson.Instance }
}; };
public static string Time(DateTime value) => public static string Time(DateTime value) =>
@@ -0,0 +1,244 @@
using System.Text.Json.Serialization;
using PrivaPub.Api.Mastodon.Controllers;
using PrivaPub.Api.Mastodon.Entities;
namespace PrivaPub.Api.Mastodon.Infrastructure
{
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.SnakeCaseLower, DefaultIgnoreCondition = JsonIgnoreCondition.Never)]
[JsonSerializable(typeof(Account))]
[JsonSerializable(typeof(List<Account>))]
[JsonSerializable(typeof(CustomEmojiEntity))]
[JsonSerializable(typeof(List<CustomEmojiEntity>))]
[JsonSerializable(typeof(Field))]
[JsonSerializable(typeof(List<Field>))]
[JsonSerializable(typeof(Source))]
[JsonSerializable(typeof(List<Source>))]
[JsonSerializable(typeof(PrivaPubStatus))]
[JsonSerializable(typeof(List<PrivaPubStatus>))]
[JsonSerializable(typeof(PrivaPubSource))]
[JsonSerializable(typeof(List<PrivaPubSource>))]
[JsonSerializable(typeof(PrivaPubLink))]
[JsonSerializable(typeof(List<PrivaPubLink>))]
[JsonSerializable(typeof(PrivaPubVariant))]
[JsonSerializable(typeof(List<PrivaPubVariant>))]
[JsonSerializable(typeof(PrivaPubVideo))]
[JsonSerializable(typeof(List<PrivaPubVideo>))]
[JsonSerializable(typeof(PrivaPubCaption))]
[JsonSerializable(typeof(List<PrivaPubCaption>))]
[JsonSerializable(typeof(PrivaPubAudio))]
[JsonSerializable(typeof(List<PrivaPubAudio>))]
[JsonSerializable(typeof(PrivaPubEvent))]
[JsonSerializable(typeof(List<PrivaPubEvent>))]
[JsonSerializable(typeof(PrivaPubPlace))]
[JsonSerializable(typeof(List<PrivaPubPlace>))]
[JsonSerializable(typeof(PrivaPubFlair))]
[JsonSerializable(typeof(List<PrivaPubFlair>))]
[JsonSerializable(typeof(PrivaPubVotes))]
[JsonSerializable(typeof(List<PrivaPubVotes>))]
[JsonSerializable(typeof(QuoteEntity))]
[JsonSerializable(typeof(List<QuoteEntity>))]
[JsonSerializable(typeof(QuoteApprovalEntity))]
[JsonSerializable(typeof(List<QuoteApprovalEntity>))]
[JsonSerializable(typeof(FilterEntity))]
[JsonSerializable(typeof(List<FilterEntity>))]
[JsonSerializable(typeof(FilterKeywordEntity))]
[JsonSerializable(typeof(List<FilterKeywordEntity>))]
[JsonSerializable(typeof(FilterStatusEntity))]
[JsonSerializable(typeof(List<FilterStatusEntity>))]
[JsonSerializable(typeof(FilterResultEntity))]
[JsonSerializable(typeof(List<FilterResultEntity>))]
[JsonSerializable(typeof(FilterV1Entity))]
[JsonSerializable(typeof(List<FilterV1Entity>))]
[JsonSerializable(typeof(EmojiReactionEntity))]
[JsonSerializable(typeof(List<EmojiReactionEntity>))]
[JsonSerializable(typeof(PleromaStatus))]
[JsonSerializable(typeof(List<PleromaStatus>))]
[JsonSerializable(typeof(PollEntity))]
[JsonSerializable(typeof(List<PollEntity>))]
[JsonSerializable(typeof(PollOptionEntity))]
[JsonSerializable(typeof(List<PollOptionEntity>))]
[JsonSerializable(typeof(PreviewCard))]
[JsonSerializable(typeof(List<PreviewCard>))]
[JsonSerializable(typeof(Status))]
[JsonSerializable(typeof(List<Status>))]
[JsonSerializable(typeof(InteractionPolicyEntity))]
[JsonSerializable(typeof(List<InteractionPolicyEntity>))]
[JsonSerializable(typeof(InteractionRuleEntity))]
[JsonSerializable(typeof(List<InteractionRuleEntity>))]
[JsonSerializable(typeof(MediaAttachment))]
[JsonSerializable(typeof(List<MediaAttachment>))]
[JsonSerializable(typeof(StatusMention))]
[JsonSerializable(typeof(List<StatusMention>))]
[JsonSerializable(typeof(StatusTag))]
[JsonSerializable(typeof(List<StatusTag>))]
[JsonSerializable(typeof(Application))]
[JsonSerializable(typeof(List<Application>))]
[JsonSerializable(typeof(Relationship))]
[JsonSerializable(typeof(List<Relationship>))]
[JsonSerializable(typeof(FeaturedTagEntity))]
[JsonSerializable(typeof(List<FeaturedTagEntity>))]
[JsonSerializable(typeof(Suggestion))]
[JsonSerializable(typeof(List<Suggestion>))]
[JsonSerializable(typeof(Notification))]
[JsonSerializable(typeof(List<Notification>))]
[JsonSerializable(typeof(AccountWarning))]
[JsonSerializable(typeof(List<AccountWarning>))]
[JsonSerializable(typeof(Context))]
[JsonSerializable(typeof(List<Context>))]
[JsonSerializable(typeof(StatusEdit))]
[JsonSerializable(typeof(List<StatusEdit>))]
[JsonSerializable(typeof(StatusSource))]
[JsonSerializable(typeof(List<StatusSource>))]
[JsonSerializable(typeof(SearchResults))]
[JsonSerializable(typeof(List<SearchResults>))]
[JsonSerializable(typeof(Conversation))]
[JsonSerializable(typeof(List<Conversation>))]
[JsonSerializable(typeof(Marker))]
[JsonSerializable(typeof(List<Marker>))]
[JsonSerializable(typeof(ActivityWeekEntity))]
[JsonSerializable(typeof(List<ActivityWeekEntity>))]
[JsonSerializable(typeof(AnnualReportsEntity))]
[JsonSerializable(typeof(List<AnnualReportsEntity>))]
[JsonSerializable(typeof(AppCredentialsEntity))]
[JsonSerializable(typeof(List<AppCredentialsEntity>))]
[JsonSerializable(typeof(DomainBlockEntity))]
[JsonSerializable(typeof(List<DomainBlockEntity>))]
[JsonSerializable(typeof(DomainBlockPreviewEntity))]
[JsonSerializable(typeof(List<DomainBlockPreviewEntity>))]
[JsonSerializable(typeof(EmptyEntity))]
[JsonSerializable(typeof(List<EmptyEntity>))]
[JsonSerializable(typeof(ErrorEntity))]
[JsonSerializable(typeof(List<ErrorEntity>))]
[JsonSerializable(typeof(FamiliarFollowersEntity))]
[JsonSerializable(typeof(List<FamiliarFollowersEntity>))]
[JsonSerializable(typeof(GroupedNotificationsEntity))]
[JsonSerializable(typeof(List<GroupedNotificationsEntity>))]
[JsonSerializable(typeof(InstanceDocumentEntity))]
[JsonSerializable(typeof(List<InstanceDocumentEntity>))]
[JsonSerializable(typeof(InstanceV1ConfigurationAccountsEntity))]
[JsonSerializable(typeof(List<InstanceV1ConfigurationAccountsEntity>))]
[JsonSerializable(typeof(InstanceV1ConfigurationEntity))]
[JsonSerializable(typeof(List<InstanceV1ConfigurationEntity>))]
[JsonSerializable(typeof(InstanceV1Entity))]
[JsonSerializable(typeof(List<InstanceV1Entity>))]
[JsonSerializable(typeof(InstanceV1StatsEntity))]
[JsonSerializable(typeof(List<InstanceV1StatsEntity>))]
[JsonSerializable(typeof(InstanceV1UrlsEntity))]
[JsonSerializable(typeof(List<InstanceV1UrlsEntity>))]
[JsonSerializable(typeof(InstanceV2ApiVersionsEntity))]
[JsonSerializable(typeof(List<InstanceV2ApiVersionsEntity>))]
[JsonSerializable(typeof(InstanceV2ConfigurationAccountsEntity))]
[JsonSerializable(typeof(List<InstanceV2ConfigurationAccountsEntity>))]
[JsonSerializable(typeof(InstanceV2ConfigurationEntity))]
[JsonSerializable(typeof(List<InstanceV2ConfigurationEntity>))]
[JsonSerializable(typeof(InstanceV2ConfigurationTranslationEntity))]
[JsonSerializable(typeof(List<InstanceV2ConfigurationTranslationEntity>))]
[JsonSerializable(typeof(InstanceV2ConfigurationUrlsEntity))]
[JsonSerializable(typeof(List<InstanceV2ConfigurationUrlsEntity>))]
[JsonSerializable(typeof(InstanceV2ConfigurationVapidEntity))]
[JsonSerializable(typeof(List<InstanceV2ConfigurationVapidEntity>))]
[JsonSerializable(typeof(InstanceV2ContactEntity))]
[JsonSerializable(typeof(List<InstanceV2ContactEntity>))]
[JsonSerializable(typeof(InstanceV2Entity))]
[JsonSerializable(typeof(List<InstanceV2Entity>))]
[JsonSerializable(typeof(InstanceV2RegistrationsEntity))]
[JsonSerializable(typeof(List<InstanceV2RegistrationsEntity>))]
[JsonSerializable(typeof(InstanceV2ThumbnailEntity))]
[JsonSerializable(typeof(List<InstanceV2ThumbnailEntity>))]
[JsonSerializable(typeof(InstanceV2UsageEntity))]
[JsonSerializable(typeof(List<InstanceV2UsageEntity>))]
[JsonSerializable(typeof(InstanceV2UsageUsersEntity))]
[JsonSerializable(typeof(List<InstanceV2UsageUsersEntity>))]
[JsonSerializable(typeof(LanguageEntity))]
[JsonSerializable(typeof(List<LanguageEntity>))]
[JsonSerializable(typeof(ListEntity))]
[JsonSerializable(typeof(List<ListEntity>))]
[JsonSerializable(typeof(MediaLimitsEntity))]
[JsonSerializable(typeof(List<MediaLimitsEntity>))]
[JsonSerializable(typeof(MediaUploadEntity))]
[JsonSerializable(typeof(List<MediaUploadEntity>))]
[JsonSerializable(typeof(MediaUploadMetaEntity))]
[JsonSerializable(typeof(List<MediaUploadMetaEntity>))]
[JsonSerializable(typeof(MediaUploadMetaFocusEntity))]
[JsonSerializable(typeof(List<MediaUploadMetaFocusEntity>))]
[JsonSerializable(typeof(MediaUploadMetaOriginalEntity))]
[JsonSerializable(typeof(List<MediaUploadMetaOriginalEntity>))]
[JsonSerializable(typeof(MergedEntity))]
[JsonSerializable(typeof(List<MergedEntity>))]
[JsonSerializable(typeof(NotificationGroupEntity))]
[JsonSerializable(typeof(List<NotificationGroupEntity>))]
[JsonSerializable(typeof(NotificationPolicyEntity))]
[JsonSerializable(typeof(List<NotificationPolicyEntity>))]
[JsonSerializable(typeof(NotificationPolicySummaryEntity))]
[JsonSerializable(typeof(List<NotificationPolicySummaryEntity>))]
[JsonSerializable(typeof(NotificationPolicyV1Entity))]
[JsonSerializable(typeof(List<NotificationPolicyV1Entity>))]
[JsonSerializable(typeof(NotificationRequestEntity))]
[JsonSerializable(typeof(List<NotificationRequestEntity>))]
[JsonSerializable(typeof(PleromaReactionEntity))]
[JsonSerializable(typeof(List<PleromaReactionEntity>))]
[JsonSerializable(typeof(PollLimitsEntity))]
[JsonSerializable(typeof(List<PollLimitsEntity>))]
[JsonSerializable(typeof(ReportEntity))]
[JsonSerializable(typeof(List<ReportEntity>))]
[JsonSerializable(typeof(RuleEntity))]
[JsonSerializable(typeof(List<RuleEntity>))]
[JsonSerializable(typeof(ScheduledStatusEntity))]
[JsonSerializable(typeof(List<ScheduledStatusEntity>))]
[JsonSerializable(typeof(ScheduledStatusParamsEntity))]
[JsonSerializable(typeof(List<ScheduledStatusParamsEntity>))]
[JsonSerializable(typeof(ScheduledStatusParamsPollEntity))]
[JsonSerializable(typeof(List<ScheduledStatusParamsPollEntity>))]
[JsonSerializable(typeof(SearchTagEntity))]
[JsonSerializable(typeof(List<SearchTagEntity>))]
[JsonSerializable(typeof(StatusLimitsEntity))]
[JsonSerializable(typeof(List<StatusLimitsEntity>))]
[JsonSerializable(typeof(TagEntity))]
[JsonSerializable(typeof(List<TagEntity>))]
[JsonSerializable(typeof(TagHistoryEntity))]
[JsonSerializable(typeof(List<TagHistoryEntity>))]
[JsonSerializable(typeof(TermsOfServiceEntity))]
[JsonSerializable(typeof(List<TermsOfServiceEntity>))]
[JsonSerializable(typeof(TrendLinkEntity))]
[JsonSerializable(typeof(List<TrendLinkEntity>))]
[JsonSerializable(typeof(TrendTagEntity))]
[JsonSerializable(typeof(List<TrendTagEntity>))]
[JsonSerializable(typeof(UnreadCountEntity))]
[JsonSerializable(typeof(List<UnreadCountEntity>))]
[JsonSerializable(typeof(UserInfoEntity))]
[JsonSerializable(typeof(List<UserInfoEntity>))]
[JsonSerializable(typeof(WebPushSubscriptionEntity))]
[JsonSerializable(typeof(List<WebPushSubscriptionEntity>))]
[JsonSerializable(typeof(Account[]))]
[JsonSerializable(typeof(FeaturedTagEntity[]))]
[JsonSerializable(typeof(object[]))]
[JsonSerializable(typeof(string[]))]
[JsonSerializable(typeof(List<object>))]
[JsonSerializable(typeof(List<string>))]
[JsonSerializable(typeof(IReadOnlyList<string>))]
[JsonSerializable(typeof(Dictionary<string, object>))]
[JsonSerializable(typeof(List<Dictionary<string, object>>))]
[JsonSerializable(typeof(Dictionary<string, Marker>))]
[JsonSerializable(typeof(ProvenanceController.Provenance))]
[JsonSerializable(typeof(ProvenanceController.InstanceDescription))]
[JsonSerializable(typeof(List<ProvenanceController.InstanceDescription>))]
[JsonSerializable(typeof(List<ProvenanceController.InstanceWeek>))]
[JsonSerializable(typeof(CdnsController.CdnSummary))]
[JsonSerializable(typeof(CdnsController.CdnDetail))]
[JsonSerializable(typeof(List<CdnsController.CdnSummary>))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(bool))]
[JsonSerializable(typeof(int))]
[JsonSerializable(typeof(int?))]
[JsonSerializable(typeof(long))]
[JsonSerializable(typeof(long?))]
[JsonSerializable(typeof(double))]
[JsonSerializable(typeof(double?))]
[JsonSerializable(typeof(float))]
[JsonSerializable(typeof(DateTime))]
[JsonSerializable(typeof(DateTime?))]
public partial class MastodonJsonContext : JsonSerializerContext
{
}
}
@@ -1,4 +1,4 @@
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Infrastructure;
@@ -686,7 +686,7 @@ namespace PrivaPub.Api.Mastodon.Mappers
if (media.DurationSeconds is { } length) if (media.DurationSeconds is { } length)
meta["length"] = TimeSpan.FromSeconds(length).ToString(@"h\:mm\:ss\.ff", CultureInfo.InvariantCulture); meta["length"] = TimeSpan.FromSeconds(length).ToString(@"h\:mm\:ss\.ff", CultureInfo.InvariantCulture);
if (FocalPoint.IsSound(media.Focus)) if (FocalPoint.IsSound(media.Focus))
meta["focus"] = new { x = media.Focus[0], y = media.Focus[1] }; meta["focus"] = new MediaUploadMetaFocusEntity { X = media.Focus[0], Y = media.Focus[1] };
return meta; return meta;
} }
@@ -54,7 +54,7 @@ namespace PrivaPub.Controllers.ClientToServer
ResolvedAt = r.ResolvedAt, ResolvedAt = r.ResolvedAt,
RemoteResolvedAt = r.RemoteResolvedAt, RemoteResolvedAt = r.RemoteResolvedAt,
RemoteResolvedBy = r.RemoteResolvedBy RemoteResolvedBy = r.RemoteResolvedBy
})); }).ToList());
} }
// A report resolved, and with it what the staff does about it (R6): nothing more, the reported account silenced or // A report resolved, and with it what the staff does about it (R6): nothing more, the reported account silenced or
@@ -0,0 +1,56 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using PrivaPub.Api.Mastodon.Entities;
using PrivaPub.Api.Mastodon.Infrastructure;
using PrivaPub.ClientModels;
namespace PrivaPub.Infrastructure.Json
{
public static class PrivaPubJson
{
public static JsonSerializerOptions Web { get; } = Chained(new JsonSerializerOptions(JsonSerializerDefaults.Web));
public static JsonSerializerOptions Plain { get; } = Chained(new JsonSerializerOptions());
public static JsonSerializerOptions Chained(JsonSerializerOptions options)
{
Chain(options.TypeInfoResolverChain);
return options;
}
public static void Chain(IList<IJsonTypeInfoResolver> chain)
{
var kept = chain.Where(r => r is not DefaultJsonTypeInfoResolver and not UnregisteredJson and not ClientModelsJsonContext and not ServerJsonContext).ToList();
chain.Clear();
chain.Add(ClientModelsJsonContext.Default);
chain.Add(ServerJsonContext.Default);
foreach (var resolver in kept)
chain.Add(resolver);
chain.Add(UnregisteredJson.Instance);
}
public static void Check(IHostEnvironment environment)
{
UnregisteredJson.Strict = !environment.IsProduction();
if (environment.IsProduction())
return;
var missing = Missing(ClientModelsJsonContext.Default, typeof(WebResult).Assembly, "PrivaPub.ClientModels")
.Concat(Missing(MastodonJsonContext.Default, typeof(Account).Assembly, "PrivaPub.Api.Mastodon.Entities"))
.ToList();
if (missing.Count > 0)
throw new InvalidOperationException("Not registered in a JsonSerializerContext (HR0306): " + string.Join(", ", missing));
}
static IEnumerable<string> Missing(IJsonTypeInfoResolver context, Assembly assembly, string space) =>
assembly.GetTypes()
.Where(t => t.IsClass && t.IsPublic && !t.IsAbstract && !t.IsGenericTypeDefinition && t.Namespace is { } ns && ns.StartsWith(space, StringComparison.Ordinal)
&& !ns.EndsWith(".Resources", StringComparison.Ordinal) && !typeof(Attribute).IsAssignableFrom(t) && !typeof(JsonSerializerContext).IsAssignableFrom(t)
&& t.GetCustomAttribute<CompilerGeneratedAttribute>() == null)
.Where(t => context.GetTypeInfo(t, new JsonSerializerOptions()) == null)
.Select(t => t.FullName);
}
}
@@ -0,0 +1,22 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Mvc;
namespace PrivaPub.Infrastructure.Json
{
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull)]
[JsonSerializable(typeof(ProblemDetails))]
[JsonSerializable(typeof(ValidationProblemDetails))]
[JsonSerializable(typeof(ViewBuild))]
[JsonSerializable(typeof(Dictionary<string, object>))]
[JsonSerializable(typeof(Dictionary<string, string[]>))]
[JsonSerializable(typeof(string))]
[JsonSerializable(typeof(bool))]
[JsonSerializable(typeof(int))]
[JsonSerializable(typeof(long))]
[JsonSerializable(typeof(double))]
public partial class ServerJsonContext : JsonSerializerContext
{
}
}
@@ -0,0 +1,26 @@
using System.Collections.Concurrent;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Serilog;
namespace PrivaPub.Infrastructure.Json
{
public sealed class UnregisteredJson : IJsonTypeInfoResolver
{
public static readonly UnregisteredJson Instance = new();
static readonly DefaultJsonTypeInfoResolver Reflection = new();
static readonly ConcurrentDictionary<Type, byte> Reported = new();
public static bool Strict { get; set; }
public JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
{
if (Strict)
throw new NotSupportedException($"{type.FullName} is not registered in a JsonSerializerContext (HR0306).");
if (Reported.TryAdd(type, 0))
Log.ForContext<UnregisteredJson>().Error("{Type} is serialized without a JsonSerializerContext registration (HR0306)", type.FullName);
return Reflection.GetTypeInfo(type, options);
}
}
}
@@ -0,0 +1,9 @@
namespace PrivaPub.Infrastructure.Json
{
public class ViewBuild
{
public string Commit { get; set; }
public string BuildRef { get; set; }
public string BuiltAt { get; set; }
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
using MongoDB.Driver; using MongoDB.Driver;
using MongoDB.Entities; using MongoDB.Entities;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Models; using PrivaPub.Models;
using System.Globalization; using System.Globalization;
@@ -53,7 +54,7 @@ namespace PrivaPub.Infrastructure.Push
["aud"] = audience, ["aud"] = audience,
["exp"] = new DateTimeOffset(now + TokenLifetime).ToUnixTimeSeconds(), ["exp"] = new DateTimeOffset(now + TokenLifetime).ToUnixTimeSeconds(),
["sub"] = subject ["sub"] = subject
})); }, PrivaPubJson.Plain));
var signed = header + "." + claims; var signed = header + "." + claims;
using var key = ECDsa.Create(_parameters); using var key = ECDsa.Create(_parameters);
var signature = key.SignData(Encoding.ASCII.GetBytes(signed), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); var signature = key.SignData(Encoding.ASCII.GetBytes(signed), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation);
+2 -1
View File
@@ -13,6 +13,7 @@ using PrivaPub.Domain.Social;
using PrivaPub.Federation.Actors; using PrivaPub.Federation.Actors;
using PrivaPub.Infrastructure.Http; using PrivaPub.Infrastructure.Http;
using PrivaPub.Infrastructure.Jobs; using PrivaPub.Infrastructure.Jobs;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Models.Jobs; using PrivaPub.Models.Jobs;
using PrivaPub.Models.Social; using PrivaPub.Models.Social;
using PrivaPub.Models.User; using PrivaPub.Models.User;
@@ -114,7 +115,7 @@ namespace PrivaPub.Infrastructure.Push
["icon"] = mapped.Account?.AvatarStatic ?? mapped.Account?.Avatar, ["icon"] = mapped.Account?.AvatarStatic ?? mapped.Account?.Avatar,
["title"] = Title(notification, mapped), ["title"] = Title(notification, mapped),
["body"] = Body(mapped) ["body"] = Body(mapped)
}); }, PrivaPubJson.Plain);
} }
var key = await vapid.Key(token); var key = await vapid.Key(token);
@@ -26,6 +26,7 @@ using PrivaPub.Domain.Social;
using PrivaPub.Domain.Statuses; using PrivaPub.Domain.Statuses;
using PrivaPub.Domain.Timelines; using PrivaPub.Domain.Timelines;
using PrivaPub.Infrastructure.Http; using PrivaPub.Infrastructure.Http;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Infrastructure.Jobs; using PrivaPub.Infrastructure.Jobs;
using PrivaPub.Infrastructure.Geo; using PrivaPub.Infrastructure.Geo;
using PrivaPub.Infrastructure.Statistics; using PrivaPub.Infrastructure.Statistics;
@@ -286,7 +287,9 @@ namespace PrivaPub.Middleware
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
}).Services; PrivaPubJson.Chain(options.JsonSerializerOptions.TypeInfoResolverChain);
}).Services
.ConfigureHttpJsonOptions(options => PrivaPubJson.Chain(options.SerializerOptions.TypeInfoResolverChain));
} }
public static IServiceCollection PrivaPubCORSConfiguration(this IServiceCollection service) public static IServiceCollection PrivaPubCORSConfiguration(this IServiceCollection service)
+6 -4
View File
@@ -17,6 +17,7 @@ using PrivaPub.Infrastructure;
using PrivaPub.Infrastructure.Cli; using PrivaPub.Infrastructure.Cli;
using PrivaPub.Infrastructure.Data; using PrivaPub.Infrastructure.Data;
using PrivaPub.Infrastructure.Http; using PrivaPub.Infrastructure.Http;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Infrastructure.Statistics; using PrivaPub.Infrastructure.Statistics;
using PrivaPub.Middleware; using PrivaPub.Middleware;
using PrivaPub.Models; using PrivaPub.Models;
@@ -111,6 +112,7 @@ try
Log.ForContext<Program>().Fatal(ex, "{0}.{1}()", nameof(Program), "Build"); Log.ForContext<Program>().Fatal(ex, "{0}.{1}()", nameof(Program), "Build");
throw; throw;
} }
PrivaPubJson.Check(app.Environment);
// A restore asked for runs here, before migrations, indexes and every hosted service; a command waits for it. // A restore asked for runs here, before migrations, indexes and every hosted service; a command waits for it.
var gate = await PrivaPub.Infrastructure.Backup.MaintenanceGate.Enter(app.Services, args is ["admin", .. var asked] ? asked : default, CancellationToken.None); var gate = await PrivaPub.Infrastructure.Backup.MaintenanceGate.Enter(app.Services, args is ["admin", .. var asked] ? asked : default, CancellationToken.None);
@@ -211,11 +213,11 @@ try
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
app.MapGet(PrivaPub.ApiPaths.Build.GET_BuildJson, () => Results.Json(new app.MapGet(PrivaPub.ApiPaths.Build.GET_BuildJson, () => Results.Json(new ViewBuild
{ {
commit = BuildInfo.Commit, Commit = BuildInfo.Commit,
buildRef = BuildInfo.Ref, BuildRef = BuildInfo.Ref,
builtAt = BuildInfo.BuiltAt, BuiltAt = BuildInfo.BuiltAt,
})); }));
app.MapControllers(); app.MapControllers();
app.MapRazorPages(); app.MapRazorPages();
+2 -1
View File
@@ -3,6 +3,7 @@ using Microsoft.Extensions.Localization;
using PrivaPub.ClientModels; using PrivaPub.ClientModels;
using PrivaPub.Extensions; using PrivaPub.Extensions;
using PrivaPub.Infrastructure.Json;
using PrivaPub.Resources; using PrivaPub.Resources;
using PrivaPub.StaticServices; using PrivaPub.StaticServices;
@@ -15,7 +16,7 @@ namespace PrivaPub.Services
public class JwtEvents : JwtBearerEvents public class JwtEvents : JwtBearerEvents
{ {
static readonly string[] PolicyClaims = { Policies.IsUser, Policies.IsModerator, Policies.IsAdmin }; static readonly string[] PolicyClaims = { Policies.IsUser, Policies.IsModerator, Policies.IsAdmin };
static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web); static readonly JsonSerializerOptions Web = PrivaPubJson.Web;
ILogger<JwtEvents> _logger { get; set; } ILogger<JwtEvents> _logger { get; set; }
const string contentType = "application/json"; const string contentType = "application/json";