From f3fdeaf0380251ee7ee83ed3c0ce6024c1d99b9e Mon Sep 17 00:00:00 2001 From: thepra Date: Tue, 10 Nov 2026 07:28:02 +0100 Subject: [PATCH] The API's JSON is generated at build time, and no answer is an anonymous object Every answer of the Mastodon API and the client API now has its JSON shape generated when the server is built, instead of worked out by reflection while it runs; the bytes sent are unchanged. The small answers that were anonymous objects (the instance documents, notification policies, reports, lists, tags, trends, errors and the empty answers) are named types. A type without generated metadata fails at once in development and on the pasture, and in production is logged and still answered. Three lists that were sent as lazy sequences (moderation reports, the published domain blocks and the languages) are now built first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd --- CLAUDE.md | 22 +- .../ClientModelsJsonContext.cs | 187 +++++++ .../User/Avatar/InsertAvatarForm.cs | 1 - .../User/Avatar/UpdateAvatarForm.cs | 1 - .../User/Avatar/ViewAvatar.cs | 2 - .../User/Avatar/ViewAvatarSettings.cs | 2 - .../Controllers/AccountsController.cs | 12 +- .../Controllers/AnnouncementsController.cs | 5 +- .../Mastodon/Controllers/AppsController.cs | 14 +- .../Controllers/FeaturedTagsController.cs | 2 +- .../Mastodon/Controllers/FiltersController.cs | 8 +- .../Controllers/InstanceController.cs | 149 +++--- .../Mastodon/Controllers/ListsController.cs | 9 +- .../Mastodon/Controllers/MediaController.cs | 33 +- .../NotificationRequestsController.cs | 62 +-- .../Mastodon/Controllers/PushController.cs | 17 +- .../Controllers/ReactionsController.cs | 15 +- .../Mastodon/Controllers/ReportsController.cs | 23 +- .../ScheduledStatusesController.cs | 42 +- .../Mastodon/Controllers/SearchController.cs | 10 +- .../Controllers/SuggestionsController.cs | 2 +- .../Mastodon/Controllers/TagsController.cs | 21 +- .../Controllers/TimelinesController.cs | 46 +- .../Mastodon/Controllers/TrendsController.cs | 27 +- .../Controllers/UserinfoController.cs | 15 +- PrivaPub/Api/Mastodon/Entities/Documents.cs | 474 ++++++++++++++++++ .../Infrastructure/MastodonController.cs | 3 +- .../Mastodon/Infrastructure/MastodonErrors.cs | 3 +- .../Mastodon/Infrastructure/MastodonJson.cs | 5 +- .../Infrastructure/MastodonJsonContext.cs | 244 +++++++++ .../Api/Mastodon/Mappers/MastodonMapper.cs | 4 +- .../ClientToServer/ModeratorController.cs | 2 +- PrivaPub/Infrastructure/Json/PrivaPubJson.cs | 56 +++ .../Infrastructure/Json/ServerJsonContext.cs | 22 + .../Infrastructure/Json/UnregisteredJson.cs | 26 + PrivaPub/Infrastructure/Json/ViewBuild.cs | 9 + PrivaPub/Infrastructure/Push/Vapid.cs | 3 +- PrivaPub/Infrastructure/Push/WebPushJob.cs | 3 +- .../Middleware/SocialPubConfigurations.cs | 5 +- PrivaPub/Program.cs | 10 +- PrivaPub/Services/JwtEvents.cs | 3 +- 41 files changed, 1333 insertions(+), 266 deletions(-) create mode 100644 PrivaPub.ClientModels/ClientModelsJsonContext.cs create mode 100644 PrivaPub/Api/Mastodon/Entities/Documents.cs create mode 100644 PrivaPub/Api/Mastodon/Infrastructure/MastodonJsonContext.cs create mode 100644 PrivaPub/Infrastructure/Json/PrivaPubJson.cs create mode 100644 PrivaPub/Infrastructure/Json/ServerJsonContext.cs create mode 100644 PrivaPub/Infrastructure/Json/UnregisteredJson.cs create mode 100644 PrivaPub/Infrastructure/Json/ViewBuild.cs diff --git a/CLAUDE.md b/CLAUDE.md index 5e645b1..e0d608d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -93,6 +93,7 @@ PrivaPub/ ASP.NET Core Web API, net10.0 Infrastructure/ Http/ FederationHttp + SafeHttpHandlerFactory + IpRangeGuard: the only way out 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), WebPushJob (SendPush, through the `push` client) 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 Api/Mastodon/ 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 Controllers/ apps, instance, accounts, statuses, timelines, notifications, search, lists, filters, 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_`/…, `_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). -- **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` 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 diff --git a/PrivaPub.ClientModels/ClientModelsJsonContext.cs b/PrivaPub.ClientModels/ClientModelsJsonContext.cs new file mode 100644 index 0000000..589c2c9 --- /dev/null +++ b/PrivaPub.ClientModels/ClientModelsJsonContext.cs @@ -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))] + [JsonSerializable(typeof(ViewAdminAction))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAdminActionsPage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAdminGroup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAdminPersona))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAdminRoot))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAdminRootsPage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAnnouncement))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAnnouncementReaction))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewArchiveTicket))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewArchiveUpload))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAvatar))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewAvatarSettings))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewBackup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewBackupTicket))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewBackupUpload))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewBackups))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewContactAccount))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewCrawledHost))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewCrawler))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewDmGroup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewDomainBlock))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewFollowing))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewGroup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewGroupMember))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostCounts))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostDay))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostDelivery))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostDetail))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostInstance))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostRow))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewHostsPage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewInteractionEvent))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewLanguage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewLatency))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewLedgerCounts))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewLocalEmoji))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewMediaLimits))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewMediaTotals))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewModeratedAccount))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewModeratedAccountsPage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewNotification))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewPersonaArchive))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewPersonaPreferences))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewPost))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewRelay))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewReport))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewRestore))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewRestoreWaiting))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewServerDay))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewServerRule))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewServerSettings))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewServerSetup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewStaffPick))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewStatisticsOverview))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewStorage))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewTotpEnabled))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewTotpSetup))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ViewUserSettings))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(WebResult))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(string))] + [JsonSerializable(typeof(bool))] + [JsonSerializable(typeof(int))] + [JsonSerializable(typeof(long))] + public partial class ClientModelsJsonContext : JsonSerializerContext + { + } +} diff --git a/PrivaPub.ClientModels/User/Avatar/InsertAvatarForm.cs b/PrivaPub.ClientModels/User/Avatar/InsertAvatarForm.cs index ad413ee..7e88a31 100644 --- a/PrivaPub.ClientModels/User/Avatar/InsertAvatarForm.cs +++ b/PrivaPub.ClientModels/User/Avatar/InsertAvatarForm.cs @@ -7,7 +7,6 @@ using System.Xml.Linq; namespace PrivaPub.ClientModels.User.Avatar { - [JsonSerializable(typeof(InsertAvatarForm))] public class InsertAvatarForm { [JsonIgnore] diff --git a/PrivaPub.ClientModels/User/Avatar/UpdateAvatarForm.cs b/PrivaPub.ClientModels/User/Avatar/UpdateAvatarForm.cs index 5d583cb..a0e2778 100644 --- a/PrivaPub.ClientModels/User/Avatar/UpdateAvatarForm.cs +++ b/PrivaPub.ClientModels/User/Avatar/UpdateAvatarForm.cs @@ -5,7 +5,6 @@ using System.Text.Json.Serialization; namespace PrivaPub.ClientModels.User.Avatar { - [JsonSerializable(typeof(UpdateAvatarForm))] public class UpdateAvatarForm { [JsonIgnore] diff --git a/PrivaPub.ClientModels/User/Avatar/ViewAvatar.cs b/PrivaPub.ClientModels/User/Avatar/ViewAvatar.cs index 4f2b4b7..62ccfd8 100644 --- a/PrivaPub.ClientModels/User/Avatar/ViewAvatar.cs +++ b/PrivaPub.ClientModels/User/Avatar/ViewAvatar.cs @@ -1,8 +1,6 @@ -using System.Text.Json.Serialization; namespace PrivaPub.ClientModels.User.Avatar { - [JsonSerializable(typeof(ViewAvatar))] public class ViewAvatar { public string Id { get; set; } diff --git a/PrivaPub.ClientModels/User/Avatar/ViewAvatarSettings.cs b/PrivaPub.ClientModels/User/Avatar/ViewAvatarSettings.cs index 42e2dbf..475aee0 100644 --- a/PrivaPub.ClientModels/User/Avatar/ViewAvatarSettings.cs +++ b/PrivaPub.ClientModels/User/Avatar/ViewAvatarSettings.cs @@ -1,11 +1,9 @@ using PrivaPub.ClientModels.Resources; using System.ComponentModel.DataAnnotations; -using System.Text.Json.Serialization; namespace PrivaPub.ClientModels.User.Avatar { - [JsonSerializable(typeof(ViewAvatarSettings))] public class ViewAvatarSettings { [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ErrorsResource)), diff --git a/PrivaPub/Api/Mastodon/Controllers/AccountsController.cs b/PrivaPub/Api/Mastodon/Controllers/AccountsController.cs index 3251e05..ddbbe16 100644 --- a/PrivaPub/Api/Mastodon/Controllers/AccountsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/AccountsController.cs @@ -399,10 +399,10 @@ namespace PrivaPub.Api.Mastodon.Controllers .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); - return Json(new + return Json(new DomainBlockPreviewEntity { - following_count = 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))) + FollowingCount = followings.Count(f => Hidden.Blocks(domain, f.TargetActorURI, handles.GetValueOrDefault(f.TargetActorURI))), + 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 BlockDomain(CancellationToken token) { await relationshipService.BlockDomain(Me, Params.Get("domain"), token); - return Json(new { }); + return Json(new EmptyEntity()); } [HttpDelete(ApiPaths.Accounts.DELETE_UnblockDomain), Scope("write:blocks")] public async Task UnblockDomain(CancellationToken token) { await relationshipService.UnblockDomain(Me, Params.Get("domain"), token); - return Json(new { }); + return Json(new EmptyEntity()); } [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 // every account answers none [HttpGet(ApiPaths.Accounts.GET_FamiliarFollowers), Scope("read:follows")] - public IActionResult FamiliarFollowers() => Json(Params.List("id").Select(id => new { id, accounts = Array.Empty() }).ToList()); + public IActionResult FamiliarFollowers() => Json(Params.List("id").Select(id => new FamiliarFollowersEntity { Id = id, Accounts = Array.Empty() }).ToList()); // 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 diff --git a/PrivaPub/Api/Mastodon/Controllers/AnnouncementsController.cs b/PrivaPub/Api/Mastodon/Controllers/AnnouncementsController.cs index 7e8d152..3953f07 100644 --- a/PrivaPub/Api/Mastodon/Controllers/AnnouncementsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/AnnouncementsController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Domain.Content; using PrivaPub.Domain.Social; @@ -21,7 +22,7 @@ namespace PrivaPub.Api.Mastodon.Controllers [HttpPost(ApiPaths.Announcements.POST_M_Dismiss), Scope("write:accounts")] public async Task 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")] public Task React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token); @@ -32,7 +33,7 @@ namespace PrivaPub.Api.Mastodon.Controllers async Task Reaction(string id, string name, bool add, CancellationToken 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); } /// Mastodon's Announcement entities, as the viewer (a persona, or nobody) sees them. diff --git a/PrivaPub/Api/Mastodon/Controllers/AppsController.cs b/PrivaPub/Api/Mastodon/Controllers/AppsController.cs index 51fd764..bfdbb0a 100644 --- a/PrivaPub/Api/Mastodon/Controllers/AppsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/AppsController.cs @@ -77,14 +77,14 @@ namespace PrivaPub.Api.Mastodon.Controllers if (application == default) return Error(StatusCodes.Status401Unauthorized, "The access token is invalid"); var properties = await applications.GetPropertiesAsync(application, token); - return Json(new + return Json(new AppCredentialsEntity { - id = await applications.GetIdAsync(application, token), - name = await applications.GetDisplayNameAsync(application, token), - website = properties.TryGetValue("website", out var website) ? website.GetString() : default, - scopes = User.GetScopes().ToList(), - redirect_uris = (await applications.GetRedirectUrisAsync(application, token)).ToList(), - vapid_key = (await vapid.Key(token)).ForApi + Id = await applications.GetIdAsync(application, token), + Name = await applications.GetDisplayNameAsync(application, token), + Website = properties.TryGetValue("website", out var website) ? website.GetString() : default, + Scopes = User.GetScopes().ToList(), + RedirectUris = (await applications.GetRedirectUrisAsync(application, token)).ToList(), + VapidKey = (await vapid.Key(token)).ForApi }); } diff --git a/PrivaPub/Api/Mastodon/Controllers/FeaturedTagsController.cs b/PrivaPub/Api/Mastodon/Controllers/FeaturedTagsController.cs index 6c1123c..1cf0bbd 100644 --- a/PrivaPub/Api/Mastodon/Controllers/FeaturedTagsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/FeaturedTagsController.cs @@ -37,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers [HttpDelete(ApiPaths.FeaturedTags.DELETE_M_Unfeature), Scope("write:accounts")] public async Task 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 [HttpGet(ApiPaths.FeaturedTags.GET_Suggestions), Scope("read:accounts")] diff --git a/PrivaPub/Api/Mastodon/Controllers/FiltersController.cs b/PrivaPub/Api/Mastodon/Controllers/FiltersController.cs index 96931a1..ee85de0 100644 --- a/PrivaPub/Api/Mastodon/Controllers/FiltersController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/FiltersController.cs @@ -177,7 +177,7 @@ namespace PrivaPub.Api.Mastodon.Controllers if (await Mine(id, token) is not { } filter) return NotFoundError(); await DB.Default.DeleteAsync(filter.ID); - return Json(new { }); + return Json(new EmptyEntity()); } [HttpGet(ApiPaths.Filters.GET_M_Keywords), Scope("read:filters")] @@ -223,7 +223,7 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); filter.Keywords.RemoveAll(k => k.Id == id); await DB.Default.SaveAsync(filter, token); - return Json(new { }); + return Json(new EmptyEntity()); } [HttpGet(ApiPaths.Filters.GET_M_Statuses), Scope("read:filters")] @@ -261,7 +261,7 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); filter.Statuses.RemoveAll(s => s.Id == id); 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 @@ -351,7 +351,7 @@ namespace PrivaPub.Api.Mastodon.Controllers await DB.Default.DeleteAsync(filter.ID); else await DB.Default.SaveAsync(filter, token); - return Json(new { }); + return Json(new EmptyEntity()); } } } diff --git a/PrivaPub/Api/Mastodon/Controllers/InstanceController.cs b/PrivaPub/Api/Mastodon/Controllers/InstanceController.cs index f0772a3..c777ad9 100644 --- a/PrivaPub/Api/Mastodon/Controllers/InstanceController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/InstanceController.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Options; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Domain.Content; @@ -60,7 +61,7 @@ namespace PrivaPub.Api.Mastodon.Controllers string Thumbnail => Settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}"; 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 async Task ContactAccount(ServerSettings settings, CancellationToken token) @@ -89,31 +90,31 @@ namespace PrivaPub.Api.Mastodon.Controllers .Uri.GetLeftPart(UriPartial.Authority); // 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 { get { var media = HttpContext.RequestServices.GetRequiredService>().CurrentValue; - return new + return new MediaLimitsEntity { - supported_mime_types = PrivaPub.Domain.Media.MediaService.SupportedTypes, - image_size_limit = media.MaxImageBytes, - image_matrix_limit = media.MaxPixels, - video_size_limit = media.MaxVideoBytes, - video_frame_rate_limit = (int)media.MaxFrameRate, - video_matrix_limit = media.MaxVideoPixels + SupportedMimeTypes = PrivaPub.Domain.Media.MediaService.SupportedTypes, + ImageSizeLimit = media.MaxImageBytes, + ImageMatrixLimit = media.MaxPixels, + VideoSizeLimit = media.MaxVideoBytes, + VideoFrameRateLimit = (int)media.MaxFrameRate, + VideoMatrixLimit = media.MaxVideoPixels }; } } - static object Polls => new + static object Polls => new PollLimitsEntity { - max_options = PrivaPub.Domain.Statuses.PollService.MaxOptions, - max_characters_per_option = PrivaPub.Domain.Statuses.PollService.MaxOptionLength, - min_expiration = PrivaPub.Domain.Statuses.PollService.MinExpiration, - max_expiration = PrivaPub.Domain.Statuses.PollService.MaxExpiration + MaxOptions = PrivaPub.Domain.Statuses.PollService.MaxOptions, + MaxCharactersPerOption = PrivaPub.Domain.Statuses.PollService.MaxOptionLength, + MinExpiration = PrivaPub.Domain.Statuses.PollService.MinExpiration, + MaxExpiration = PrivaPub.Domain.Statuses.PollService.MaxExpiration }; [HttpGet(ApiPaths.Instance.GET_V1), AllowAnonymous] @@ -123,24 +124,24 @@ namespace PrivaPub.Api.Mastodon.Controllers var users = await Counted.Users(token); var statuses = await Counted.LocalPosts(token); var domains = await KnownServers(token); - return Json(new + return Json(new InstanceV1Entity { - uri = Domain, - title = settings.Title, - short_description = settings.ShortDescription ?? string.Empty, - description = settings.ShortDescription ?? string.Empty, - email = settings.ContactEmail ?? string.Empty, - version = Version, - urls = new { streaming_api = Streaming }, - stats = new { user_count = users, status_count = statuses, domain_count = domains }, - thumbnail = Thumbnail, - languages = LanguageCodes(HttpContext.RequestServices), - registrations = Open, - approval_required = false, - invites_enabled = 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 }, - contact_account = await ContactAccount(settings, token), - rules = Rules(settings) + Uri = Domain, + Title = settings.Title, + ShortDescription = settings.ShortDescription ?? string.Empty, + Description = settings.ShortDescription ?? string.Empty, + Email = settings.ContactEmail ?? string.Empty, + Version = Version, + Urls = new InstanceV1UrlsEntity { StreamingApi = Streaming }, + Stats = new InstanceV1StatsEntity { UserCount = users, StatusCount = statuses, DomainCount = domains }, + Thumbnail = Thumbnail, + Languages = LanguageCodes(HttpContext.RequestServices), + Registrations = Open, + ApprovalRequired = false, + InvitesEnabled = true,//a group invitation always creates an account + Configuration = new InstanceV1ConfigurationEntity { Accounts = new InstanceV1ConfigurationAccountsEntity { MaxFeaturedTags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured }, Statuses = Statuses, MediaAttachments = MediaAttachments, Polls = Polls }, + ContactAccount = await ContactAccount(settings, token), + Rules = Rules(settings) }); } @@ -151,30 +152,30 @@ namespace PrivaPub.Api.Mastodon.Controllers await DB.Default.CountAsync(i => i.Seen == "touched", token); [HttpGet(ApiPaths.Instance.GET_V2), AllowAnonymous] - public async Task V2(CancellationToken token) => Json(new + public async Task V2(CancellationToken token) => Json(new InstanceV2Entity { - domain = Domain, - title = Settings.Title, - version = Version, - api_versions = new { mastodon = 7 }, - source_url = "https://git.thepra.dev/thepra/SocialPub", - description = Settings.ShortDescription ?? string.Empty, - usage = new { users = new { active_month = await Counted.ActiveUsers(30, token) } }, - thumbnail = new { url = Thumbnail }, - languages = LanguageCodes(HttpContext.RequestServices), - configuration = new + Domain = Domain, + Title = Settings.Title, + Version = Version, + ApiVersions = new InstanceV2ApiVersionsEntity { Mastodon = 7 }, + SourceUrl = "https://git.thepra.dev/thepra/SocialPub", + Description = Settings.ShortDescription ?? string.Empty, + Usage = new InstanceV2UsageEntity { Users = new InstanceV2UsageUsersEntity { ActiveMonth = await Counted.ActiveUsers(30, token) } }, + Thumbnail = new InstanceV2ThumbnailEntity { Url = Thumbnail }, + Languages = LanguageCodes(HttpContext.RequestServices), + Configuration = new InstanceV2ConfigurationEntity { - urls = new { streaming = Streaming }, - accounts = new { max_featured_tags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured, max_pinned_statuses = StatusesController.MaxPins }, - statuses = Statuses, - media_attachments = MediaAttachments, - polls = Polls, - translation = new { enabled = false }, - vapid = new { public_key = (await vapidKeys.Key(token)).ForApi }//Web Push (R9): the key every push is signed with + Urls = new InstanceV2ConfigurationUrlsEntity { Streaming = Streaming }, + Accounts = new InstanceV2ConfigurationAccountsEntity { MaxFeaturedTags = PrivaPub.Domain.Social.FeaturedTags.MaxFeatured, MaxPinnedStatuses = StatusesController.MaxPins }, + Statuses = Statuses, + MediaAttachments = MediaAttachments, + Polls = Polls, + Translation = new InstanceV2ConfigurationTranslationEntity { Enabled = false }, + 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 }, - contact = new { email = Settings.ContactEmail ?? string.Empty, account = await ContactAccount(Settings, token) }, - rules = Rules(Settings) + Registrations = new InstanceV2RegistrationsEntity { Enabled = Open, ApprovalRequired = false, Message = Open ? default : RegistrationOptions.ClosedMessage }, + Contact = new InstanceV2ContactEntity { Email = Settings.ContactEmail ?? string.Empty, Account = await ContactAccount(Settings, token) }, + Rules = Rules(Settings) }); [HttpGet(ApiPaths.Instance.GET_Peers), AllowAnonymous] @@ -190,12 +191,12 @@ namespace PrivaPub.Api.Mastodon.Controllers return Json(Array.Empty()); if (_activity is { } cached && DateTime.UtcNow - cached.At < ActivityLifetime) 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), - statuses = w.Posts.ToString(CultureInfo.InvariantCulture), - logins = "0", - registrations = w.Registrations.ToString(CultureInfo.InvariantCulture) + Week = new DateTimeOffset(w.Week, TimeSpan.Zero).ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture), + Statuses = w.Posts.ToString(CultureInfo.InvariantCulture), + Logins = "0", + Registrations = w.Registrations.ToString(CultureInfo.InvariantCulture) }).ToList(); _activity = new CachedActivity(DateTime.UtcNow, weeks); return Json(weeks); @@ -208,10 +209,10 @@ namespace PrivaPub.Api.Mastodon.Controllers public IActionResult ExtendedDescription() { var settings = Settings; - return Json(new + return Json(new InstanceDocumentEntity { - updated_at = settings.DescriptionUpdatedAt is { } updated ? MastodonJson.Time(updated) : MastodonJson.Day(DateTime.UtcNow), - content = ContentRenderer.Document(settings.Description) + UpdatedAt = settings.DescriptionUpdatedAt is { } updated ? MastodonJson.Time(updated) : MastodonJson.Day(DateTime.UtcNow), + Content = ContentRenderer.Document(settings.Description) }); } @@ -219,10 +220,10 @@ namespace PrivaPub.Api.Mastodon.Controllers public IActionResult PrivacyPolicy() { var settings = Settings; - return Json(new + return Json(new InstanceDocumentEntity { - updated_at = MastodonJson.Time(settings.PrivacyPolicyUpdatedAt ?? ServerSettings.DefaultPrivacyPolicyUpdatedAt), - content = ContentRenderer.Document(settings.PrivacyPolicy) + UpdatedAt = MastodonJson.Time(settings.PrivacyPolicyUpdatedAt ?? ServerSettings.DefaultPrivacyPolicyUpdatedAt), + Content = ContentRenderer.Document(settings.PrivacyPolicy) }); } @@ -244,12 +245,12 @@ namespace PrivaPub.Api.Mastodon.Controllers var effective = (settings.TermsEffectiveAt ?? settings.UpdatedAt ?? DateTime.UtcNow).Date; if (on != default && on.Value != effective) return NotFoundError(); - return Json(new + return Json(new TermsOfServiceEntity { - effective_date = effective.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), - effective = effective <= DateTime.UtcNow.Date, - content = ContentRenderer.Document(settings.TermsOfService), - succeeded_by = default(string) + EffectiveDate = effective.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), + Effective = effective <= DateTime.UtcNow.Date, + Content = ContentRenderer.Document(settings.TermsOfService), + SucceededBy = default(string) }); } @@ -258,13 +259,13 @@ namespace PrivaPub.Api.Mastodon.Controllers [HttpGet(ApiPaths.Instance.GET_DomainBlocks), AllowAnonymous] public async Task DomainBlocks(CancellationToken token) => Json((await DB.Default.Find().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, - digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(b.Domain ?? string.Empty))), - severity = b.Severity switch { DomainBlockSeverity.Suspend => "suspend", DomainBlockSeverity.Silence => "silence", _ => "noop" }, - comment = b.PublicComment - })); + Domain = b.Obfuscate ? Obfuscated(b.Domain) : b.Domain, + Digest = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(b.Domain ?? string.Empty))), + Severity = b.Severity switch { DomainBlockSeverity.Suspend => "suspend", DomainBlockSeverity.Silence => "silence", _ => "noop" }, + 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 * public static string Obfuscated(string domain) diff --git a/PrivaPub/Api/Mastodon/Controllers/ListsController.cs b/PrivaPub/Api/Mastodon/Controllers/ListsController.cs index 390a7c4..c857fcd 100644 --- a/PrivaPub/Api/Mastodon/Controllers/ListsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/ListsController.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Domain.Privacy; @@ -20,7 +21,7 @@ namespace PrivaPub.Api.Mastodon.Controllers 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 Mine(string id, CancellationToken token) => DB.Default.Find().Match(l => l.ID == id && l.AvatarId == MyId).ExecuteFirstAsync(token); @@ -97,7 +98,7 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); await DB.Default.DeleteAsync(m => m.ListId == list.ID); await DB.Default.DeleteAsync(list.ID); - return Json(new { }); + return Json(new EmptyEntity()); } [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"); foreach (var account in ids.Where(a => !present.Contains(a))) 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")] @@ -141,7 +142,7 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); var ids = Params.List("account_ids"); await DB.Default.DeleteAsync(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")] diff --git a/PrivaPub/Api/Mastodon/Controllers/MediaController.cs b/PrivaPub/Api/Mastodon/Controllers/MediaController.cs index 8d06857..5a94608 100644 --- a/PrivaPub/Api/Mastodon/Controllers/MediaController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/MediaController.cs @@ -1,4 +1,9 @@ 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 Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; @@ -67,7 +72,7 @@ namespace PrivaPub.Api.Mastodon.Controllers if (attachment.PostId != null || attachment.ScheduledStatusId != null) 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); - 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) @@ -147,23 +152,23 @@ namespace PrivaPub.Api.Mastodon.Controllers 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, - type = attachment.Kind, - url = media.Url(attachment.FilePath), - preview_url = media.Url(attachment.PreviewPath ?? attachment.FilePath), - remote_url = default(string), - text_url = default(string), - meta = new + Id = attachment.ID, + Type = attachment.Kind, + Url = media.Url(attachment.FilePath), + PreviewUrl = media.Url(attachment.PreviewPath ?? attachment.FilePath), + RemoteUrl = default(string), + TextUrl = default(string), + Meta = new MediaUploadMetaEntity { - 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 } + Original = attachment.Width.HasValue && attachment.Height > 0 + ? new MediaUploadMetaOriginalEntity { Width = attachment.Width, Height = attachment.Height, Size = $"{attachment.Width}x{attachment.Height}", Aspect = (double)attachment.Width / attachment.Height.Value } : 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, - blurhash = attachment.Blurhash + Description = attachment.Description, + Blurhash = attachment.Blurhash }; } } diff --git a/PrivaPub/Api/Mastodon/Controllers/NotificationRequestsController.cs b/PrivaPub/Api/Mastodon/Controllers/NotificationRequestsController.cs index 4884a93..20180a5 100644 --- a/PrivaPub/Api/Mastodon/Controllers/NotificationRequestsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/NotificationRequestsController.cs @@ -3,6 +3,12 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; 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.Mappers; using PrivaPub.Domain.Social; @@ -33,30 +39,30 @@ namespace PrivaPub.Api.Mastodon.Controllers _ => null }; - async Task Summary(CancellationToken token) => new + async Task Summary(CancellationToken token) => new NotificationPolicySummaryEntity { - pending_requests_count = await DB.Default.CountAsync(r => r.AvatarId == MyId, token), - pending_notifications_count = await DB.Default.CountAsync(n => n.AvatarId == MyId && n.Filtered, token) + PendingRequestsCount = await DB.Default.CountAsync(r => r.AvatarId == MyId, token), + PendingNotificationsCount = await DB.Default.CountAsync(n => n.AvatarId == MyId && n.Filtered, token) }; - async Task V2(NotificationPolicy policy, CancellationToken token) => new + async Task V2(NotificationPolicy policy, CancellationToken token) => new NotificationPolicyEntity { - for_not_following = Name(policy.ForNotFollowing), - for_not_followers = Name(policy.ForNotFollowers), - for_new_accounts = Name(policy.ForNewAccounts), - for_private_mentions = Name(policy.ForPrivateMentions), - for_limited_accounts = Name(policy.ForLimitedAccounts), - summary = await Summary(token) + ForNotFollowing = Name(policy.ForNotFollowing), + ForNotFollowers = Name(policy.ForNotFollowers), + ForNewAccounts = Name(policy.ForNewAccounts), + ForPrivateMentions = Name(policy.ForPrivateMentions), + ForLimitedAccounts = Name(policy.ForLimitedAccounts), + Summary = await Summary(token) }; // the first version spoke of filtering only: dropped is filtered for it - async Task V1(NotificationPolicy policy, CancellationToken token) => new + async Task V1(NotificationPolicy policy, CancellationToken token) => new NotificationPolicyV1Entity { - filter_not_following = policy.ForNotFollowing != NotificationAction.Accept, - filter_not_followers = policy.ForNotFollowers != NotificationAction.Accept, - filter_new_accounts = policy.ForNewAccounts != NotificationAction.Accept, - filter_private_mentions = policy.ForPrivateMentions != NotificationAction.Accept, - summary = await Summary(token) + FilterNotFollowing = policy.ForNotFollowing != NotificationAction.Accept, + FilterNotFollowers = policy.ForNotFollowers != NotificationAction.Accept, + FilterNewAccounts = policy.ForNewAccounts != NotificationAction.Accept, + FilterPrivateMentions = policy.ForPrivateMentions != NotificationAction.Accept, + Summary = await Summary(token) }; [HttpGet(ApiPaths.NotificationRequests.GET_Policy), Scope("read:notifications")] @@ -99,14 +105,14 @@ namespace PrivaPub.Api.Mastodon.Controllers return default; var post = string.IsNullOrEmpty(request.LastPostId) ? default : await dbEntities.Posts.Match(p => p.ID == request.LastPostId && !p.DeletedAt.HasValue).ExecuteFirstAsync(token); - return new + return new NotificationRequestEntity { - id = request.ID, - created_at = MastodonJson.Time(request.CreatedAt), - updated_at = MastodonJson.Time(request.UpdatedAt), - notifications_count = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture), - account, - last_status = post == default ? default : await mapper.Status(post, MyId, token) + Id = request.ID, + CreatedAt = MastodonJson.Time(request.CreatedAt), + UpdatedAt = MastodonJson.Time(request.UpdatedAt), + NotificationsCount = request.NotificationsCount.ToString(System.Globalization.CultureInfo.InvariantCulture), + Account = account, + LastStatus = post == default ? default : await mapper.Status(post, MyId, token) }; } @@ -126,7 +132,7 @@ namespace PrivaPub.Api.Mastodon.Controllers DB.Default.Find().Match(r => r.ID == id && r.AvatarId == MyId).ExecuteFirstAsync(token); [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")] public async Task Request(string id, CancellationToken token) => @@ -138,7 +144,7 @@ namespace PrivaPub.Api.Mastodon.Controllers if (await Mine(id, token) is not { } request) return NotFoundError(); await NotificationPolicies.Accept(request, token); - return Json(new { }); + return Json(new EmptyEntity()); } [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) return NotFoundError(); await NotificationPolicies.Dismiss(request, token); - return Json(new { }); + return Json(new EmptyEntity()); } [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)) if (await Mine(id, token) is { } request) await NotificationPolicies.Accept(request, token); - return Json(new { }); + return Json(new EmptyEntity()); } [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)) if (await Mine(id, token) is { } request) await NotificationPolicies.Dismiss(request, token); - return Json(new { }); + return Json(new EmptyEntity()); } } } diff --git a/PrivaPub/Api/Mastodon/Controllers/PushController.cs b/PrivaPub/Api/Mastodon/Controllers/PushController.cs index 3617ddc..db0fef4 100644 --- a/PrivaPub/Api/Mastodon/Controllers/PushController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/PushController.cs @@ -8,6 +8,7 @@ using MongoDB.Entities; using OpenIddict.Abstractions; using OpenIddict.Validation.AspNetCore; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Domain.Social; using PrivaPub.Infrastructure.Http; @@ -111,7 +112,7 @@ namespace PrivaPub.Api.Mastodon.Controllers public async Task Delete(CancellationToken token) { await WebPush.ForgetToken(TokenId, token); - return Json(new { }); + return Json(new EmptyEntity()); } async Task Mine(CancellationToken token) @@ -150,14 +151,14 @@ namespace PrivaPub.Api.Mastodon.Controllers } // Mastodon's WebPushSubscription - async Task View(PushSubscription subscription, CancellationToken token) => new + async Task View(PushSubscription subscription, CancellationToken token) => new WebPushSubscriptionEntity { - id = subscription.ID, - endpoint = subscription.Endpoint, - standard = subscription.Standard, - alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)), - server_key = (await vapid.Key(token)).ForApi, - policy = WebPush.Name(subscription.Policy) + Id = subscription.ID, + Endpoint = subscription.Endpoint, + Standard = subscription.Standard, + Alerts = WebPush.Alerts.ToDictionary(alert => alert, alert => subscription.Alerts.Contains(alert)), + ServerKey = (await vapid.Key(token)).ForApi, + Policy = WebPush.Name(subscription.Policy) }; } } diff --git a/PrivaPub/Api/Mastodon/Controllers/ReactionsController.cs b/PrivaPub/Api/Mastodon/Controllers/ReactionsController.cs index ef84a84..b24cdfe 100644 --- a/PrivaPub/Api/Mastodon/Controllers/ReactionsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/ReactionsController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Domain.Privacy; @@ -28,14 +29,14 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); var reactions = await DB.Default.Find().Match(r => r.PostId == post.ID).ExecuteAsync(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, - count = group.Count(), - me = MyId != default && group.Any(r => r.AccountId == MyId), - url = mapper.ProxiedUrl(group.First().EmojiURL), - accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList() - }).OrderByDescending(r => r.count).ToList()); + Name = group.Key, + Count = group.Count(), + Me = MyId != default && group.Any(r => r.AccountId == MyId), + Url = mapper.ProxiedUrl(group.First().EmojiURL), + Accounts = group.Select(r => accounts.GetValueOrDefault(r.AccountId)).Where(a => a != default).ToList() + }).OrderByDescending(r => r.Count).ToList()); } [HttpPut(ApiPaths.Reactions.PUT_M_React), Scope("write:favourites")] diff --git a/PrivaPub/Api/Mastodon/Controllers/ReportsController.cs b/PrivaPub/Api/Mastodon/Controllers/ReportsController.cs index 0de70a0..4b55c3f 100644 --- a/PrivaPub/Api/Mastodon/Controllers/ReportsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/ReportsController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Mvc; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Domain.Relationships; @@ -17,18 +18,18 @@ namespace PrivaPub.Api.Mastodon.Controllers Params.List("rule_ids"), Params.Bool("forward") == true, token); if (report == default) return NotFoundError(); - return Json(new + return Json(new ReportEntity { - id = report.ID, - action_taken = false, - action_taken_at = default(string), - category = report.Category, - comment = report.Comment ?? string.Empty, - forwarded = report.Forwarded, - created_at = MastodonJson.Time(report.CreatedAt), - status_ids = report.PostIds, - rule_ids = report.RuleIds, - target_account = await mapper.Account(report.TargetAccountId, token) + Id = report.ID, + ActionTaken = false, + ActionTakenAt = default(string), + Category = report.Category, + Comment = report.Comment ?? string.Empty, + Forwarded = report.Forwarded, + CreatedAt = MastodonJson.Time(report.CreatedAt), + StatusIds = report.PostIds, + RuleIds = report.RuleIds, + TargetAccount = await mapper.Account(report.TargetAccountId, token) }); } } diff --git a/PrivaPub/Api/Mastodon/Controllers/ScheduledStatusesController.cs b/PrivaPub/Api/Mastodon/Controllers/ScheduledStatusesController.cs index 3329341..27e24b6 100644 --- a/PrivaPub/Api/Mastodon/Controllers/ScheduledStatusesController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/ScheduledStatusesController.cs @@ -2,6 +2,10 @@ using Microsoft.AspNetCore.Mvc; 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.Domain.Media; using PrivaPub.Domain.Statuses; @@ -24,27 +28,27 @@ namespace PrivaPub.Api.Mastodon.Controllers var attachments = ids.Count == 0 ? new List() : await DB.Default.Find().Match(m => ids.Contains(m.ID)).ExecuteAsync(token); - return new + return new ScheduledStatusEntity { - id = scheduled.ID, - scheduled_at = MastodonJson.Time(scheduled.ScheduledAt), - @params = new + Id = scheduled.ID, + ScheduledAt = MastodonJson.Time(scheduled.ScheduledAt), + Params = new ScheduledStatusParamsEntity { - 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 }, - media_ids = ids.Count == 0 ? default : ids, - sensitive = p.Sensitive, - spoiler_text = p.SpoilerText, - visibility = p.Visibility, - in_reply_to_id = p.InReplyToId, - language = p.Language, - application_id = default(string), - scheduled_at = default(string), - idempotency = p.Idempotency, - with_rate_limit = false, - quoted_status_id = p.QuotedStatusId + Text = p.Text, + Poll = p.Poll == default ? default : new ScheduledStatusParamsPollEntity { Options = p.Poll.Options, ExpiresIn = p.Poll.ExpiresIn, Multiple = p.Poll.Multiple, HideTotals = p.Poll.HideTotals }, + MediaIds = ids.Count == 0 ? default : ids, + Sensitive = p.Sensitive, + SpoilerText = p.SpoilerText, + Visibility = p.Visibility, + InReplyToId = p.InReplyToId, + Language = p.Language, + ApplicationId = default(string), + ScheduledAt = default(string), + Idempotency = p.Idempotency, + WithRateLimit = false, + 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() }; } @@ -91,7 +95,7 @@ namespace PrivaPub.Api.Mastodon.Controllers await DB.Default.DeleteAsync(scheduled.ID); // its media were the scheduled post's alone, never posted await mediaService.Trash(m => m.ScheduledStatusId == scheduled.ID, "scheduled post dropped", token); - return Json(new { }); + return Json(new EmptyEntity()); } } } diff --git a/PrivaPub/Api/Mastodon/Controllers/SearchController.cs b/PrivaPub/Api/Mastodon/Controllers/SearchController.cs index b02b70a..680ccda 100644 --- a/PrivaPub/Api/Mastodon/Controllers/SearchController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/SearchController.cs @@ -65,7 +65,7 @@ namespace PrivaPub.Api.Mastodon.Controllers if (type is null or "statuses" && MyId != default && !q.StartsWith('#') && !Handle().IsMatch(q)) results.Statuses = await Words(q, Math.Max(0, offset), Limit(), token); if (type is null or "hashtags" && TagsController.Normalise(q) is var tag && TagsController.IsHashtag(tag)) - results.Hashtags.Add(new { name = tag, url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", history = await TagsController.History(dbEntities, tag, token) }); + results.Hashtags.Add(new SearchTagEntity { Name = tag, Url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(tag)}", History = await TagsController.History(dbEntities, tag, token) }); return Json(results); } } @@ -138,10 +138,10 @@ namespace PrivaPub.Api.Mastodon.Controllers [HttpGet(ApiPaths.Stubs.GET_Languages), Microsoft.AspNetCore.Authorization.AllowAnonymous] public IActionResult Languages() => Json(InstanceController.LanguageCodes(HttpContext.RequestServices) - .Select(code => new { code, name = System.Globalization.CultureInfo.GetCultureInfo(code).EnglishName })); + .Select(code => new LanguageEntity { Code = code, Name = System.Globalization.CultureInfo.GetCultureInfo(code).EnglishName }).ToList()); [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 // 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 // show), and marking one read changes nothing [HttpGet(ApiPaths.Stubs.GET_AnnualReports), HttpGet(ApiPaths.Stubs.GET_M_AnnualReports), Scope("read:accounts")] - public IActionResult AnnualReports(string year) => Json(new { annual_reports = Array.Empty(), accounts = Array.Empty(), statuses = Array.Empty() }); + public IActionResult AnnualReports(string year) => Json(new AnnualReportsEntity { AnnualReports = Array.Empty(), Accounts = Array.Empty(), Statuses = Array.Empty() }); [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 // /clientapi. Mastodon answers this when its registrations are closed; its e-mail confirmation routes follow, since no diff --git a/PrivaPub/Api/Mastodon/Controllers/SuggestionsController.cs b/PrivaPub/Api/Mastodon/Controllers/SuggestionsController.cs index 55d03dc..94b84c6 100644 --- a/PrivaPub/Api/Mastodon/Controllers/SuggestionsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/SuggestionsController.cs @@ -37,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers 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 diff --git a/PrivaPub/Api/Mastodon/Controllers/TagsController.cs b/PrivaPub/Api/Mastodon/Controllers/TagsController.cs index 9159256..e0856d2 100644 --- a/PrivaPub/Api/Mastodon/Controllers/TagsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/TagsController.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Federation.Actors; 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 => { 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(), - uses = that.Count.ToString(), - accounts = that.Select(p => p.AuthorAccountId ?? p.GroupUserId).Distinct().Count().ToString() + Day = new DateTimeOffset(day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), + Uses = that.Count.ToString(), + Accounts = that.Select(p => p.AuthorAccountId ?? p.GroupUserId).Distinct().Count().ToString() }; }).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 internal static async Task TagView(DbEntities dbEntities, string baseAddress, string tag, string viewerId, bool? following, bool? featuring, - CancellationToken token) => new + CancellationToken token) => new TagEntity { - name = tag, - url = $"{baseAddress}/tags/{Uri.EscapeDataString(tag)}", - history = await History(dbEntities, tag, token), - following = following ?? (viewerId != default && await DB.Default.Find().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)), - featuring = viewerId == default ? default(bool?) + Name = tag, + Url = $"{baseAddress}/tags/{Uri.EscapeDataString(tag)}", + History = await History(dbEntities, tag, token), + Following = following ?? (viewerId != default && await DB.Default.Find().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)), + Featuring = viewerId == default ? default(bool?) : featuring ?? await DB.Default.Find().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token) }; diff --git a/PrivaPub/Api/Mastodon/Controllers/TimelinesController.cs b/PrivaPub/Api/Mastodon/Controllers/TimelinesController.cs index f7339ec..374006d 100644 --- a/PrivaPub/Api/Mastodon/Controllers/TimelinesController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/TimelinesController.cs @@ -191,7 +191,7 @@ namespace PrivaPub.Api.Mastodon.Controllers return NotFoundError(); await ConversationStates.Hide(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")] @@ -332,27 +332,27 @@ namespace PrivaPub.Api.Mastodon.Controllers var newest = mapped[group.First().ID]; var total = group.Key.StartsWith("ungrouped-", StringComparison.Ordinal) ? 1 : await DB.Default.CountAsync(Builders.Filter.And(Builders.Filter.Where(InGroup(group.Key)), NotFiltered), token); - groups.Add(new + groups.Add(new NotificationGroupEntity { - group_key = group.Key, - notifications_count = Math.Max(total, group.Count()), - type = newest.Type, - most_recent_notification_id = newest.Id, - page_min_id = group.Last().ID, - page_max_id = group.First().ID, - latest_page_notification_at = newest.CreatedAt, - sample_account_ids = group.Select(n => mapped[n.ID].Account.Id).Distinct().Take(8).ToList(), - status_id = newest.Status?.Id, - emoji = newest.Emoji, - emoji_url = newest.EmojiUrl, - moderation_warning = newest.ModerationWarning + GroupKey = group.Key, + NotificationsCount = Math.Max(total, group.Count()), + Type = newest.Type, + MostRecentNotificationId = newest.Id, + PageMinId = group.Last().ID, + PageMaxId = group.First().ID, + LatestPageNotificationAt = newest.CreatedAt, + SampleAccountIds = group.Select(n => mapped[n.ID].Account.Id).Distinct().Take(8).ToList(), + StatusId = newest.Status?.Id, + Emoji = newest.Emoji, + EmojiUrl = newest.EmojiUrl, + ModerationWarning = newest.ModerationWarning }); } - return new + return new GroupedNotificationsEntity { - 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(), - notification_groups = groups + 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(), + NotificationGroups = groups }; } @@ -371,7 +371,7 @@ namespace PrivaPub.Api.Mastodon.Controllers .Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token); var shown = (await Map(unread, token)).Select(n => n.Id).ToHashSet(); 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")] @@ -398,7 +398,7 @@ namespace PrivaPub.Api.Mastodon.Controllers if (InGroup(groupKey) is not { } filter) return NotFoundError(); await DB.Default.DeleteAsync(filter); - return Json(new { }); + return Json(new EmptyEntity()); } [HttpGet(ApiPaths.Notifications.GET_M_Get), Scope("read:notifications")] @@ -413,14 +413,14 @@ namespace PrivaPub.Api.Mastodon.Controllers public async Task Clear(CancellationToken token) { await DB.Default.DeleteAsync(n => n.AvatarId == MyId); - return Json(new { }); + return Json(new EmptyEntity()); } [HttpPost(ApiPaths.Notifications.POST_M_Dismiss), Scope("write:notifications")] public async Task Dismiss(string id, CancellationToken token) { await DB.Default.DeleteAsync(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 @@ -430,7 +430,7 @@ namespace PrivaPub.Api.Mastodon.Controllers { var unread = await DB.Default.Find().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); - return Json(new { count = (await Map(unread, token)).Count }); + return Json(new UnreadCountEntity { Count = (await Map(unread, token)).Count }); } Task> Map(List notifications, CancellationToken token) => diff --git a/PrivaPub/Api/Mastodon/Controllers/TrendsController.cs b/PrivaPub/Api/Mastodon/Controllers/TrendsController.cs index 5205363..b360de1 100644 --- a/PrivaPub/Api/Mastodon/Controllers/TrendsController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/TrendsController.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc; using MongoDB.Driver; using MongoDB.Entities; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Domain.Privacy; @@ -21,11 +22,11 @@ namespace PrivaPub.Api.Mastodon.Controllers DbEntities dbEntities, ILocalActorService localActors) : MastodonController { - static List History(Trends.Trend trend) => trend.History.Select(h => (object)new + static List History(Trends.Trend trend) => trend.History.Select(h => (object)new TagHistoryEntity { - day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), - uses = h.Uses.ToString(), - accounts = h.Accounts.ToString() + Day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(), + Uses = h.Uses.ToString(), + Accounts = h.Accounts.ToString() }).ToList(); IEnumerable Window(IEnumerable items, int fallback, int max) => @@ -37,12 +38,12 @@ namespace PrivaPub.Api.Mastodon.Controllers var followed = MyId == default ? new HashSet() : (await DB.Default.Find().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, - url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}", - history = History(t), - following = MyId == default ? default(bool?) : followed.Contains(t.Key) + Name = t.Key, + Url = $"{localActors.BaseAddress}/tags/{Uri.EscapeDataString(t.Key)}", + History = History(t), + Following = MyId == default ? default(bool?) : followed.Contains(t.Key) }).ToList()); } @@ -64,11 +65,11 @@ namespace PrivaPub.Api.Mastodon.Controllers { var link = samples[t.SamplePostId].Link; 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, - card.Html, card.Width, card.Height, card.Image, card.ImageDescription, card.EmbedUrl, card.Blurhash, card.Language, - card.PublishedAt, card.Authors, History = History(t) + Url = card.Url, Title = card.Title, Description = card.Description, Type = card.Type, AuthorName = card.AuthorName, AuthorUrl = card.AuthorUrl, ProviderName = card.ProviderName, ProviderUrl = card.ProviderUrl, + Html = card.Html, Width = card.Width, Height = card.Height, Image = card.Image, ImageDescription = card.ImageDescription, EmbedUrl = card.EmbedUrl, Blurhash = card.Blurhash, Language = card.Language, + PublishedAt = card.PublishedAt, Authors = card.Authors, History = History(t) }; }).Where(c => c != default).ToList()); } diff --git a/PrivaPub/Api/Mastodon/Controllers/UserinfoController.cs b/PrivaPub/Api/Mastodon/Controllers/UserinfoController.cs index 561e859..9a57aa5 100644 --- a/PrivaPub/Api/Mastodon/Controllers/UserinfoController.cs +++ b/PrivaPub/Api/Mastodon/Controllers/UserinfoController.cs @@ -1,5 +1,6 @@ using Microsoft.AspNetCore.Mvc; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; using PrivaPub.Api.Mastodon.Mappers; using PrivaPub.Federation.Actors; @@ -20,14 +21,14 @@ namespace PrivaPub.Api.Mastodon.Controllers public async Task Show(CancellationToken token) { var account = await mapper.Local(Me, false, token); - return Json(new + return Json(new UserInfoEntity { - iss = localActors.BaseAddress + "/", - sub = Me.Uri, - name = account.DisplayName, - preferred_username = account.Username, - profile = account.Url, - picture = account.Avatar + Iss = localActors.BaseAddress + "/", + Sub = Me.Uri, + Name = account.DisplayName, + PreferredUsername = account.Username, + Profile = account.Url, + Picture = account.Avatar }); } } diff --git a/PrivaPub/Api/Mastodon/Entities/Documents.cs b/PrivaPub/Api/Mastodon/Entities/Documents.cs new file mode 100644 index 0000000..a8f99ad --- /dev/null +++ b/PrivaPub/Api/Mastodon/Entities/Documents.cs @@ -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 Scopes { get; set; } = []; + public List 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 Accounts { get; set; } = []; + public List Statuses { get; set; } = []; + public List 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 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 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 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 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 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 StatusIds { get; set; } = []; + public List 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 MediaAttachments { get; set; } = []; + } + + public class ScheduledStatusParamsEntity + { + public string Text { get; set; } + public ScheduledStatusParamsPollEntity Poll { get; set; } + public List 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 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 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 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 Authors { get; set; } = []; + public List History { get; set; } = []; + } + + public class TrendTagEntity + { + public string Name { get; set; } + public string Url { get; set; } + public List 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 Alerts { get; set; } = new(); + public string ServerKey { get; set; } + public string Policy { get; set; } + } +} diff --git a/PrivaPub/Api/Mastodon/Infrastructure/MastodonController.cs b/PrivaPub/Api/Mastodon/Infrastructure/MastodonController.cs index 0de6804..33275c5 100644 --- a/PrivaPub/Api/Mastodon/Infrastructure/MastodonController.cs +++ b/PrivaPub/Api/Mastodon/Infrastructure/MastodonController.cs @@ -8,6 +8,7 @@ using OpenIddict.Abstractions; using OpenIddict.Validation.AspNetCore; using PrivaPub.Api.Mastodon.Auth; +using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Federation.Actors; using PrivaPub.Models.Federation; using PrivaPub.Models.User; @@ -94,7 +95,7 @@ namespace PrivaPub.Api.Mastodon.Infrastructure new(value, MastodonJson.Options) { StatusCode = status }; 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"); diff --git a/PrivaPub/Api/Mastodon/Infrastructure/MastodonErrors.cs b/PrivaPub/Api/Mastodon/Infrastructure/MastodonErrors.cs index 63b003c..1718b59 100644 --- a/PrivaPub/Api/Mastodon/Infrastructure/MastodonErrors.cs +++ b/PrivaPub/Api/Mastodon/Infrastructure/MastodonErrors.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using PrivaPub.Api.Mastodon.Entities; namespace PrivaPub.Api.Mastodon.Infrastructure { @@ -9,7 +10,7 @@ namespace PrivaPub.Api.Mastodon.Infrastructure { var response = pages.HttpContext.Response; 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 diff --git a/PrivaPub/Api/Mastodon/Infrastructure/MastodonJson.cs b/PrivaPub/Api/Mastodon/Infrastructure/MastodonJson.cs index 1e0bdd6..ff7fc05 100644 --- a/PrivaPub/Api/Mastodon/Infrastructure/MastodonJson.cs +++ b/PrivaPub/Api/Mastodon/Infrastructure/MastodonJson.cs @@ -2,6 +2,8 @@ using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Serialization; +using PrivaPub.Infrastructure.Json; + namespace PrivaPub.Api.Mastodon.Infrastructure { public static class MastodonJson @@ -12,7 +14,8 @@ namespace PrivaPub.Api.Mastodon.Infrastructure DictionaryKeyPolicy = default, DefaultIgnoreCondition = JsonIgnoreCondition.Never, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, - Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) } + Converters = { new JsonStringEnumConverter(JsonNamingPolicy.SnakeCaseLower) }, + TypeInfoResolverChain = { MastodonJsonContext.Default, UnregisteredJson.Instance } }; public static string Time(DateTime value) => diff --git a/PrivaPub/Api/Mastodon/Infrastructure/MastodonJsonContext.cs b/PrivaPub/Api/Mastodon/Infrastructure/MastodonJsonContext.cs new file mode 100644 index 0000000..8f2efef --- /dev/null +++ b/PrivaPub/Api/Mastodon/Infrastructure/MastodonJsonContext.cs @@ -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))] + [JsonSerializable(typeof(CustomEmojiEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Field))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Source))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubStatus))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubSource))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubLink))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubVariant))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubVideo))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubCaption))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubAudio))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubEvent))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubPlace))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubFlair))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PrivaPubVotes))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(QuoteEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(QuoteApprovalEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FilterEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FilterKeywordEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FilterStatusEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FilterResultEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FilterV1Entity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(EmojiReactionEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PleromaStatus))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PollEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PollOptionEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PreviewCard))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Status))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InteractionPolicyEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InteractionRuleEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaAttachment))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(StatusMention))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(StatusTag))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Application))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Relationship))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FeaturedTagEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Suggestion))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Notification))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(AccountWarning))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Context))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(StatusEdit))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(StatusSource))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(SearchResults))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Conversation))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Marker))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ActivityWeekEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(AnnualReportsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(AppCredentialsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(DomainBlockEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(DomainBlockPreviewEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(EmptyEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ErrorEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(FamiliarFollowersEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(GroupedNotificationsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceDocumentEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV1ConfigurationAccountsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV1ConfigurationEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV1Entity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV1StatsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV1UrlsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ApiVersionsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ConfigurationAccountsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ConfigurationEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ConfigurationTranslationEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ConfigurationUrlsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ConfigurationVapidEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ContactEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2Entity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2RegistrationsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2ThumbnailEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2UsageEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(InstanceV2UsageUsersEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(LanguageEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ListEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaLimitsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaUploadEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaUploadMetaEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaUploadMetaFocusEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MediaUploadMetaOriginalEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(MergedEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(NotificationGroupEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(NotificationPolicyEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(NotificationPolicySummaryEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(NotificationPolicyV1Entity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(NotificationRequestEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PleromaReactionEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(PollLimitsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ReportEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(RuleEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ScheduledStatusEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ScheduledStatusParamsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(ScheduledStatusParamsPollEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(SearchTagEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(StatusLimitsEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(TagEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(TagHistoryEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(TermsOfServiceEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(TrendLinkEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(TrendTagEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(UnreadCountEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(UserInfoEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(WebPushSubscriptionEntity))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(Account[]))] + [JsonSerializable(typeof(FeaturedTagEntity[]))] + [JsonSerializable(typeof(object[]))] + [JsonSerializable(typeof(string[]))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(IReadOnlyList))] + [JsonSerializable(typeof(Dictionary))] + [JsonSerializable(typeof(List>))] + [JsonSerializable(typeof(Dictionary))] + [JsonSerializable(typeof(ProvenanceController.Provenance))] + [JsonSerializable(typeof(ProvenanceController.InstanceDescription))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(List))] + [JsonSerializable(typeof(CdnsController.CdnSummary))] + [JsonSerializable(typeof(CdnsController.CdnDetail))] + [JsonSerializable(typeof(List))] + [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 + { + } +} diff --git a/PrivaPub/Api/Mastodon/Mappers/MastodonMapper.cs b/PrivaPub/Api/Mastodon/Mappers/MastodonMapper.cs index d9d5c67..155847c 100644 --- a/PrivaPub/Api/Mastodon/Mappers/MastodonMapper.cs +++ b/PrivaPub/Api/Mastodon/Mappers/MastodonMapper.cs @@ -1,4 +1,4 @@ -using MongoDB.Entities; +using MongoDB.Entities; using PrivaPub.Api.Mastodon.Entities; using PrivaPub.Api.Mastodon.Infrastructure; @@ -686,7 +686,7 @@ namespace PrivaPub.Api.Mastodon.Mappers if (media.DurationSeconds is { } length) meta["length"] = TimeSpan.FromSeconds(length).ToString(@"h\:mm\:ss\.ff", CultureInfo.InvariantCulture); 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; } diff --git a/PrivaPub/Controllers/ClientToServer/ModeratorController.cs b/PrivaPub/Controllers/ClientToServer/ModeratorController.cs index 443c077..da18a1b 100644 --- a/PrivaPub/Controllers/ClientToServer/ModeratorController.cs +++ b/PrivaPub/Controllers/ClientToServer/ModeratorController.cs @@ -54,7 +54,7 @@ namespace PrivaPub.Controllers.ClientToServer ResolvedAt = r.ResolvedAt, RemoteResolvedAt = r.RemoteResolvedAt, RemoteResolvedBy = r.RemoteResolvedBy - })); + }).ToList()); } // A report resolved, and with it what the staff does about it (R6): nothing more, the reported account silenced or diff --git a/PrivaPub/Infrastructure/Json/PrivaPubJson.cs b/PrivaPub/Infrastructure/Json/PrivaPubJson.cs new file mode 100644 index 0000000..d571dea --- /dev/null +++ b/PrivaPub/Infrastructure/Json/PrivaPubJson.cs @@ -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 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 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() == null) + .Where(t => context.GetTypeInfo(t, new JsonSerializerOptions()) == null) + .Select(t => t.FullName); + } +} diff --git a/PrivaPub/Infrastructure/Json/ServerJsonContext.cs b/PrivaPub/Infrastructure/Json/ServerJsonContext.cs new file mode 100644 index 0000000..b6b7b3a --- /dev/null +++ b/PrivaPub/Infrastructure/Json/ServerJsonContext.cs @@ -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))] + [JsonSerializable(typeof(Dictionary))] + [JsonSerializable(typeof(string))] + [JsonSerializable(typeof(bool))] + [JsonSerializable(typeof(int))] + [JsonSerializable(typeof(long))] + [JsonSerializable(typeof(double))] + public partial class ServerJsonContext : JsonSerializerContext + { + } +} diff --git a/PrivaPub/Infrastructure/Json/UnregisteredJson.cs b/PrivaPub/Infrastructure/Json/UnregisteredJson.cs new file mode 100644 index 0000000..f03dc98 --- /dev/null +++ b/PrivaPub/Infrastructure/Json/UnregisteredJson.cs @@ -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 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().Error("{Type} is serialized without a JsonSerializerContext registration (HR0306)", type.FullName); + return Reflection.GetTypeInfo(type, options); + } + } +} diff --git a/PrivaPub/Infrastructure/Json/ViewBuild.cs b/PrivaPub/Infrastructure/Json/ViewBuild.cs new file mode 100644 index 0000000..0ce1be6 --- /dev/null +++ b/PrivaPub/Infrastructure/Json/ViewBuild.cs @@ -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; } + } +} diff --git a/PrivaPub/Infrastructure/Push/Vapid.cs b/PrivaPub/Infrastructure/Push/Vapid.cs index 36443df..cbf9ce9 100644 --- a/PrivaPub/Infrastructure/Push/Vapid.cs +++ b/PrivaPub/Infrastructure/Push/Vapid.cs @@ -1,6 +1,7 @@ using MongoDB.Driver; using MongoDB.Entities; +using PrivaPub.Infrastructure.Json; using PrivaPub.Models; using System.Globalization; @@ -53,7 +54,7 @@ namespace PrivaPub.Infrastructure.Push ["aud"] = audience, ["exp"] = new DateTimeOffset(now + TokenLifetime).ToUnixTimeSeconds(), ["sub"] = subject - })); + }, PrivaPubJson.Plain)); var signed = header + "." + claims; using var key = ECDsa.Create(_parameters); var signature = key.SignData(Encoding.ASCII.GetBytes(signed), HashAlgorithmName.SHA256, DSASignatureFormat.IeeeP1363FixedFieldConcatenation); diff --git a/PrivaPub/Infrastructure/Push/WebPushJob.cs b/PrivaPub/Infrastructure/Push/WebPushJob.cs index 4ad36ad..8572d3b 100644 --- a/PrivaPub/Infrastructure/Push/WebPushJob.cs +++ b/PrivaPub/Infrastructure/Push/WebPushJob.cs @@ -13,6 +13,7 @@ using PrivaPub.Domain.Social; using PrivaPub.Federation.Actors; using PrivaPub.Infrastructure.Http; using PrivaPub.Infrastructure.Jobs; +using PrivaPub.Infrastructure.Json; using PrivaPub.Models.Jobs; using PrivaPub.Models.Social; using PrivaPub.Models.User; @@ -114,7 +115,7 @@ namespace PrivaPub.Infrastructure.Push ["icon"] = mapped.Account?.AvatarStatic ?? mapped.Account?.Avatar, ["title"] = Title(notification, mapped), ["body"] = Body(mapped) - }); + }, PrivaPubJson.Plain); } var key = await vapid.Key(token); diff --git a/PrivaPub/Middleware/SocialPubConfigurations.cs b/PrivaPub/Middleware/SocialPubConfigurations.cs index 9721d4e..e73b250 100644 --- a/PrivaPub/Middleware/SocialPubConfigurations.cs +++ b/PrivaPub/Middleware/SocialPubConfigurations.cs @@ -26,6 +26,7 @@ using PrivaPub.Domain.Social; using PrivaPub.Domain.Statuses; using PrivaPub.Domain.Timelines; using PrivaPub.Infrastructure.Http; +using PrivaPub.Infrastructure.Json; using PrivaPub.Infrastructure.Jobs; using PrivaPub.Infrastructure.Geo; using PrivaPub.Infrastructure.Statistics; @@ -286,7 +287,9 @@ namespace PrivaPub.Middleware options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; 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) diff --git a/PrivaPub/Program.cs b/PrivaPub/Program.cs index b2a93ff..7ea13a9 100644 --- a/PrivaPub/Program.cs +++ b/PrivaPub/Program.cs @@ -17,6 +17,7 @@ using PrivaPub.Infrastructure; using PrivaPub.Infrastructure.Cli; using PrivaPub.Infrastructure.Data; using PrivaPub.Infrastructure.Http; +using PrivaPub.Infrastructure.Json; using PrivaPub.Infrastructure.Statistics; using PrivaPub.Middleware; using PrivaPub.Models; @@ -111,6 +112,7 @@ try Log.ForContext().Fatal(ex, "{0}.{1}()", nameof(Program), "Build"); throw; } + PrivaPubJson.Check(app.Environment); // 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); @@ -211,11 +213,11 @@ try app.UseAuthentication(); 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, - buildRef = BuildInfo.Ref, - builtAt = BuildInfo.BuiltAt, + Commit = BuildInfo.Commit, + BuildRef = BuildInfo.Ref, + BuiltAt = BuildInfo.BuiltAt, })); app.MapControllers(); app.MapRazorPages(); diff --git a/PrivaPub/Services/JwtEvents.cs b/PrivaPub/Services/JwtEvents.cs index 99341b1..c9c03f6 100644 --- a/PrivaPub/Services/JwtEvents.cs +++ b/PrivaPub/Services/JwtEvents.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Localization; using PrivaPub.ClientModels; using PrivaPub.Extensions; +using PrivaPub.Infrastructure.Json; using PrivaPub.Resources; using PrivaPub.StaticServices; @@ -15,7 +16,7 @@ namespace PrivaPub.Services public class JwtEvents : JwtBearerEvents { static readonly string[] PolicyClaims = { Policies.IsUser, Policies.IsModerator, Policies.IsAdmin }; - static readonly JsonSerializerOptions Web = new(JsonSerializerDefaults.Web); + static readonly JsonSerializerOptions Web = PrivaPubJson.Web; ILogger _logger { get; set; } const string contentType = "application/json";