The API's JSON is generated at build time, and no answer is an anonymous object
Build / Build (push) Successful in 36s
Build / Build (push) Successful in 36s
Every answer of the Mastodon API and the client API now has its JSON shape generated when the server is built, instead of worked out by reflection while it runs; the bytes sent are unchanged. The small answers that were anonymous objects (the instance documents, notification policies, reports, lists, tags, trends, errors and the empty answers) are named types. A type without generated metadata fails at once in development and on the pasture, and in production is logged and still answered. Three lists that were sent as lazy sequences (moderation reports, the published domain blocks and the languages) are now built first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
1 parent
8a1e4e419b
commit
f3fdeaf038
41 files changed
+1333
-266
No files matched your search
@@ -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<IActionResult> 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<IActionResult> 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<Account>() }).ToList());
|
||||
public IActionResult FamiliarFollowers() => Json(Params.List("id").Select(id => new FamiliarFollowersEntity { Id = id, Accounts = Array.Empty<Account>() }).ToList());
|
||||
|
||||
// Endorsements (R8): Mastodon's account pins under their old names (pin, unpin) and 4.4's (endorse, unendorse). Only an
|
||||
// account the persona follows may be endorsed, as Mastodon requires; they are the persona's alone, never federated as
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
using MongoDB.Entities;
|
||||
|
||||
using 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<IActionResult> Dismiss(string id, CancellationToken token) =>
|
||||
await announcementService.Dismiss(id, MyId, token) ? Json(new { }) : NotFoundError();
|
||||
await announcementService.Dismiss(id, MyId, token) ? Json(new EmptyEntity()) : NotFoundError();
|
||||
|
||||
[HttpPut(ApiPaths.Announcements.PUT_M_React), Scope("write:favourites")]
|
||||
public Task<IActionResult> React(string id, string name, CancellationToken token) => Reaction(id, name, add: true, token);
|
||||
@@ -32,7 +33,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
async Task<IActionResult> Reaction(string id, string name, bool add, CancellationToken token)
|
||||
{
|
||||
var (status, error) = await announcementService.React(id, MyId, name, add, token);
|
||||
return error == default ? Json(new { }) : Error(status, error);
|
||||
return error == default ? Json(new EmptyEntity()) : Error(status, error);
|
||||
}
|
||||
|
||||
/// <summary>Mastodon's Announcement entities, as the viewer (a persona, or nobody) sees them.</summary>
|
||||
|
||||
@@ -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
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
|
||||
[HttpDelete(ApiPaths.FeaturedTags.DELETE_M_Unfeature), Scope("write:accounts")]
|
||||
public async Task<IActionResult> Unfeature(string id, CancellationToken token) =>
|
||||
await featuredTags.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new { });
|
||||
await featuredTags.Unfeature(Me, id, default, token) == default ? NotFoundError() : Json(new EmptyEntity());
|
||||
|
||||
// the tags the persona used lately and does not feature yet, the most used first, as Mastodon's Tag
|
||||
[HttpGet(ApiPaths.FeaturedTags.GET_Suggestions), Scope("read:accounts")]
|
||||
|
||||
@@ -177,7 +177,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
if (await Mine(id, token) is not { } filter)
|
||||
return NotFoundError();
|
||||
await DB.Default.DeleteAsync<PersonaFilter>(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<PersonaFilter>(filter.ID);
|
||||
else
|
||||
await DB.Default.SaveAsync(filter, token);
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ using Microsoft.Extensions.Options;
|
||||
|
||||
using MongoDB.Entities;
|
||||
|
||||
using 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<object> 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<IOptionsMonitor<PrivaPub.Domain.Media.MediaOptions>>().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<Models.Jobs.RemoteInstance>(i => i.Seen == "touched", token);
|
||||
|
||||
[HttpGet(ApiPaths.Instance.GET_V2), AllowAnonymous]
|
||||
public async Task<IActionResult> V2(CancellationToken token) => Json(new
|
||||
public async Task<IActionResult> V2(CancellationToken token) => Json(new InstanceV2Entity
|
||||
{
|
||||
domain = Domain,
|
||||
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<object>());
|
||||
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<IActionResult> DomainBlocks(CancellationToken token) =>
|
||||
Json((await DB.Default.Find<DomainBlock>().Match(b => b.Published).Sort(b => b.Domain, Order.Ascending).ExecuteAsync(token))
|
||||
.Select(b => new
|
||||
.Select(b => new DomainBlockEntity
|
||||
{
|
||||
domain = b.Obfuscate ? Obfuscated(b.Domain) : b.Domain,
|
||||
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)
|
||||
|
||||
@@ -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<PersonaList> Mine(string id, CancellationToken token) =>
|
||||
DB.Default.Find<PersonaList>().Match(l => l.ID == id && l.AvatarId == MyId).ExecuteFirstAsync(token);
|
||||
@@ -97,7 +98,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
return NotFoundError();
|
||||
await DB.Default.DeleteAsync<PersonaListMember>(m => m.ListId == list.ID);
|
||||
await DB.Default.DeleteAsync<PersonaList>(list.ID);
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
|
||||
[HttpGet(ApiPaths.Lists.GET_M_Accounts), Scope("read:lists")]
|
||||
@@ -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<PersonaListMember>(m => m.ListId == list.ID && ids.Contains(m.AccountId));
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
|
||||
[HttpGet(ApiPaths.Lists.GET_M_Containing), Scope("read:lists")]
|
||||
|
||||
@@ -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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<object> Summary(CancellationToken token) => new
|
||||
async Task<object> Summary(CancellationToken token) => new NotificationPolicySummaryEntity
|
||||
{
|
||||
pending_requests_count = await DB.Default.CountAsync<NotificationRequest>(r => r.AvatarId == MyId, token),
|
||||
pending_notifications_count = await DB.Default.CountAsync<Notification>(n => n.AvatarId == MyId && n.Filtered, token)
|
||||
PendingRequestsCount = await DB.Default.CountAsync<NotificationRequest>(r => r.AvatarId == MyId, token),
|
||||
PendingNotificationsCount = await DB.Default.CountAsync<Notification>(n => n.AvatarId == MyId && n.Filtered, token)
|
||||
};
|
||||
|
||||
async Task<object> V2(NotificationPolicy policy, CancellationToken token) => new
|
||||
async Task<object> V2(NotificationPolicy policy, CancellationToken token) => new NotificationPolicyEntity
|
||||
{
|
||||
for_not_following = Name(policy.ForNotFollowing),
|
||||
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<object> V1(NotificationPolicy policy, CancellationToken token) => new
|
||||
async Task<object> 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<NotificationRequest>().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<IActionResult> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<IActionResult> Delete(CancellationToken token)
|
||||
{
|
||||
await WebPush.ForgetToken(TokenId, token);
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
|
||||
async Task<PushSubscription> Mine(CancellationToken token)
|
||||
@@ -150,14 +151,14 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
}
|
||||
|
||||
// Mastodon's WebPushSubscription
|
||||
async Task<object> View(PushSubscription subscription, CancellationToken token) => new
|
||||
async Task<object> View(PushSubscription subscription, CancellationToken token) => new WebPushSubscriptionEntity
|
||||
{
|
||||
id = subscription.ID,
|
||||
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)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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<Reaction>().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")]
|
||||
|
||||
@@ -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)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<MediaAttachment>()
|
||||
: await DB.Default.Find<MediaAttachment>().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<ScheduledStatus>(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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<object>(), accounts = Array.Empty<object>(), statuses = Array.Empty<object>() });
|
||||
public IActionResult AnnualReports(string year) => Json(new AnnualReportsEntity { AnnualReports = Array.Empty<object>(), Accounts = Array.Empty<object>(), Statuses = Array.Empty<object>() });
|
||||
|
||||
[HttpPost(ApiPaths.Stubs.POST_M_ReadAnnualReport), Scope("write:accounts")]
|
||||
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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<object> 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<FollowedTag>().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<FollowedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)),
|
||||
Featuring = viewerId == default ? default(bool?)
|
||||
: featuring ?? await DB.Default.Find<FeaturedTag>().Match(t => t.AvatarId == viewerId && t.Name == tag).ExecuteAnyAsync(token)
|
||||
};
|
||||
|
||||
|
||||
@@ -191,7 +191,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
return NotFoundError();
|
||||
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<NotificationEntity>.Filter.And(Builders<NotificationEntity>.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<IActionResult> Clear(CancellationToken token)
|
||||
{
|
||||
await DB.Default.DeleteAsync<NotificationEntity>(n => n.AvatarId == MyId);
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
|
||||
[HttpPost(ApiPaths.Notifications.POST_M_Dismiss), Scope("write:notifications")]
|
||||
public async Task<IActionResult> Dismiss(string id, CancellationToken token)
|
||||
{
|
||||
await DB.Default.DeleteAsync<NotificationEntity>(n => n.ID == id && n.AvatarId == MyId);
|
||||
return Json(new { });
|
||||
return Json(new EmptyEntity());
|
||||
}
|
||||
|
||||
// counts what the list would show (Map drops notifications from gone accounts and about hidden posts), at most
|
||||
@@ -430,7 +430,7 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
{
|
||||
var unread = await DB.Default.Find<NotificationEntity>().Match(n => n.AvatarId == MyId && !n.IsRead).Match(NotFiltered)
|
||||
.Sort(n => n.ID, Order.Descending).Limit(Math.Clamp(Params.Int("limit") ?? 100, 1, 1000)).ExecuteAsync(token);
|
||||
return Json(new { count = (await Map(unread, token)).Count });
|
||||
return Json(new UnreadCountEntity { Count = (await Map(unread, token)).Count });
|
||||
}
|
||||
|
||||
Task<List<Entities.Notification>> Map(List<NotificationEntity> notifications, CancellationToken token) =>
|
||||
|
||||
@@ -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<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new
|
||||
static List<object> History(Trends.Trend trend) => trend.History.Select(h => (object)new TagHistoryEntity
|
||||
{
|
||||
day = new DateTimeOffset(h.Day, TimeSpan.Zero).ToUnixTimeSeconds().ToString(),
|
||||
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<T> Window<T>(IEnumerable<T> items, int fallback, int max) =>
|
||||
@@ -37,12 +38,12 @@ namespace PrivaPub.Api.Mastodon.Controllers
|
||||
var followed = MyId == default
|
||||
? new HashSet<string>()
|
||||
: (await DB.Default.Find<Models.Social.FollowedTag>().Match(t => t.AvatarId == MyId).ExecuteAsync(token)).Select(t => t.Name).ToHashSet();
|
||||
return Json(Window(await trendService.Tags(token), 10, 20).Select(t => new
|
||||
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());
|
||||
}
|
||||
|
||||
@@ -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<IActionResult> 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
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user