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
284 lines
13 KiB
C#
284 lines
13 KiB
C#
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
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;
|
|
using PrivaPub.Domain.Instance;
|
|
using PrivaPub.Domain.Privacy;
|
|
using PrivaPub.Federation.Actors;
|
|
using PrivaPub.Infrastructure;
|
|
using PrivaPub.Models;
|
|
using PrivaPub.Models.Federation;
|
|
using PrivaPub.Models.User;
|
|
|
|
using System.Globalization;
|
|
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
using PostEntity = PrivaPub.Models.Post.Post;
|
|
|
|
namespace PrivaPub.Api.Mastodon.Controllers
|
|
{
|
|
// The instance API: what the server says of itself comes from its settings (IInstanceSettings, edited on the
|
|
// administrator's page; until then exactly what it said before), its numbers from Counted, its limits from where they
|
|
// are enforced.
|
|
public class InstanceController(
|
|
ILocalActorService localActors,
|
|
IOptionsMonitor<RegistrationOptions> registrationOptions,
|
|
IInstanceSettings instanceSettings,
|
|
MastodonMapper mapper,
|
|
PrivaPub.Infrastructure.Push.IVapid vapidKeys) : MastodonController
|
|
{
|
|
// The Mastodon version this API answers as, then PrivaPub's own release (its tag, or the commit a build came from).
|
|
// 4.5.0 since R9 (2026-10-18): every client route of Mastodon 4.3, 4.4 and 4.5 is served or answers as a documented
|
|
// stub (docs/MASTODON-API.md), streaming and Web Push included. api_versions.mastodon is 4.5's own, 7.
|
|
public const string MastodonVersion = "4.5.0";
|
|
public static readonly string Version = Advertised(string.IsNullOrEmpty(BuildInfo.Ref) ? BuildInfo.Commit : BuildInfo.Ref);
|
|
|
|
static string Advertised(string release)
|
|
{
|
|
var own = release?.Trim();
|
|
if (own is { Length: > 1 } && own[0] == 'v' && char.IsDigit(own[1]))
|
|
own = own[1..];//a tag v1.27.0 is release 1.27.0
|
|
return string.IsNullOrEmpty(own) ? $"{MastodonVersion} (compatible; PrivaPub)" : $"{MastodonVersion} (compatible; PrivaPub {own})";
|
|
}
|
|
const int ActivityWeeks = 12;
|
|
static readonly TimeSpan ActivityLifetime = TimeSpan.FromHours(1);
|
|
static volatile CachedActivity _activity;
|
|
|
|
sealed record CachedActivity(DateTime At, object Weeks);
|
|
|
|
|
|
bool Open => registrationOptions.CurrentValue.IsOpen;
|
|
|
|
ServerSettings Settings => instanceSettings.Current;
|
|
|
|
string Thumbnail => Settings.ThumbnailUrl ?? $"{localActors.BaseAddress}{ServerSettings.DefaultThumbnailPath}";
|
|
|
|
static object Rules(ServerSettings settings) =>
|
|
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)
|
|
{
|
|
var id = settings.ContactAccountId;
|
|
if (string.IsNullOrEmpty(id))
|
|
return default;
|
|
var avatar = await DB.Default.Find<Avatar>().Match(a => a.ID == id && !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
|
|
if (avatar == default || (await Counted.HeldBackPersonas(token)).Contains(id))
|
|
return default;
|
|
return await mapper.Local(localActors.FromAvatar(avatar), false, token);
|
|
}
|
|
|
|
// the languages this server is set up for (AppConfiguration:SupportedLanguages), "en" when none are named
|
|
public static IReadOnlyList<string> LanguageCodes(IServiceProvider services)
|
|
{
|
|
var configured = services.GetRequiredService<Microsoft.Extensions.Options.IOptionsMonitor<Models.AppConfiguration>>().CurrentValue.SupportedLanguages;
|
|
var codes = (configured ?? new List<string>()).Where(c => !string.IsNullOrWhiteSpace(c)).Select(c => c.Split('-')[0].ToLowerInvariant()).Distinct().ToList();
|
|
return codes.Count == 0 ? new[] { "en" } : codes;
|
|
}
|
|
|
|
string Domain => new Uri(localActors.BaseAddress).Authority;
|
|
|
|
// where clients open their streams (StreamingController): this server, as ws or wss
|
|
string Streaming => new UriBuilder(localActors.BaseAddress) { Scheme = localActors.BaseAddress.StartsWith("https", StringComparison.OrdinalIgnoreCase) ? "wss" : "ws" }
|
|
.Uri.GetLeftPart(UriPartial.Authority);
|
|
|
|
// every limit is what the server enforces, read from where it is enforced
|
|
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 MediaLimitsEntity
|
|
{
|
|
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 PollLimitsEntity
|
|
{
|
|
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]
|
|
public async Task<IActionResult> V1(CancellationToken token)
|
|
{
|
|
var settings = Settings;
|
|
var users = await Counted.Users(token);
|
|
var statuses = await Counted.LocalPosts(token);
|
|
var domains = await KnownServers(token);
|
|
return Json(new InstanceV1Entity
|
|
{
|
|
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)
|
|
});
|
|
}
|
|
|
|
// the servers we have exchanged activities with, as the statistics count them. Which ones is not published
|
|
// (/instance/peers stays empty, as on a Mastodon with its peers API off): on a small server it would say who its
|
|
// personas talk to.
|
|
static async Task<long> KnownServers(CancellationToken token) =>
|
|
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 InstanceV2Entity
|
|
{
|
|
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 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 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]
|
|
public IActionResult Peers() => Json(Array.Empty<string>());
|
|
|
|
// Mastodon's weekly activity, only when the administrator publishes it (off by default): twelve weeks, this one first,
|
|
// counted as Counted counts (local posts, logins made); sign-ins are not kept, so `logins` is 0. Worked out at most
|
|
// once an hour.
|
|
[HttpGet(ApiPaths.Instance.GET_Activity), AllowAnonymous]
|
|
public async Task<IActionResult> Activity(CancellationToken token)
|
|
{
|
|
if (!Settings.PublishActivity)
|
|
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 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)
|
|
}).ToList();
|
|
_activity = new CachedActivity(DateTime.UtcNow, weeks);
|
|
return Json(weeks);
|
|
}
|
|
|
|
[HttpGet(ApiPaths.Instance.GET_InstanceRules), AllowAnonymous]
|
|
public IActionResult InstanceRules() => Json(Rules(Settings));
|
|
|
|
[HttpGet(ApiPaths.Instance.GET_ExtendedDescription), AllowAnonymous]
|
|
public IActionResult ExtendedDescription()
|
|
{
|
|
var settings = Settings;
|
|
return Json(new InstanceDocumentEntity
|
|
{
|
|
UpdatedAt = settings.DescriptionUpdatedAt is { } updated ? MastodonJson.Time(updated) : MastodonJson.Day(DateTime.UtcNow),
|
|
Content = ContentRenderer.Document(settings.Description)
|
|
});
|
|
}
|
|
|
|
[HttpGet(ApiPaths.Instance.GET_PrivacyPolicy), AllowAnonymous]
|
|
public IActionResult PrivacyPolicy()
|
|
{
|
|
var settings = Settings;
|
|
return Json(new InstanceDocumentEntity
|
|
{
|
|
UpdatedAt = MastodonJson.Time(settings.PrivacyPolicyUpdatedAt ?? ServerSettings.DefaultPrivacyPolicyUpdatedAt),
|
|
Content = ContentRenderer.Document(settings.PrivacyPolicy)
|
|
});
|
|
}
|
|
|
|
// Mastodon 4.4's terms of service: the one version the server keeps, 404 while it has none
|
|
[HttpGet(ApiPaths.Instance.GET_TermsOfService), AllowAnonymous]
|
|
public IActionResult TermsOfService() => Terms(default);
|
|
|
|
[HttpGet(ApiPaths.Instance.GET_M_TermsOfServiceOn), AllowAnonymous]
|
|
public IActionResult TermsOfServiceOn(string date) =>
|
|
DateTime.TryParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var on)
|
|
? Terms(on.Date)
|
|
: NotFoundError();
|
|
|
|
IActionResult Terms(DateTime? on)
|
|
{
|
|
var settings = Settings;
|
|
if (string.IsNullOrWhiteSpace(settings.TermsOfService))
|
|
return NotFoundError();
|
|
var effective = (settings.TermsEffectiveAt ?? settings.UpdatedAt ?? DateTime.UtcNow).Date;
|
|
if (on != default && on.Value != effective)
|
|
return NotFoundError();
|
|
return Json(new TermsOfServiceEntity
|
|
{
|
|
EffectiveDate = effective.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
|
|
Effective = effective <= DateTime.UtcNow.Date,
|
|
Content = ContentRenderer.Document(settings.TermsOfService),
|
|
SucceededBy = default(string)
|
|
});
|
|
}
|
|
|
|
// the server's blocks the administrator chose to publish (off for each by default: publishing one tells the blocked
|
|
// server, and everyone else, that it is blocked), its name partly hidden when asked, as Mastodon hides it
|
|
[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 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
|
|
}).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)
|
|
{
|
|
if (string.IsNullOrEmpty(domain))
|
|
return domain;
|
|
var visible = domain.Length / 4;
|
|
var hidden = domain.ToCharArray();
|
|
for (var i = 0; i < hidden.Length; i++)
|
|
if (i > visible && i < domain.Length - visible && hidden[i] != '.')
|
|
hidden[i] = '*';
|
|
return new string(hidden);
|
|
}
|
|
}
|
|
}
|