Files
SocialPub/PrivaPub/Controllers/ClientToServer/PrivateAvatarController.cs
T
thepraandClaude Opus 5.5 c2f439d1e9
Build / Build (push) Successful in 34s
Deploy / privapub.thepra.dev (push) Successful in 57s
Deploy / Release notes on the Releases tab (push) Successful in 3s
Every failure the server answers with names its own error code
Each refusal and failure the client API sends now starts with a code no other failure uses, such as "[ERR0030006] That
code is not valid.", so a screenshot or a report points at the exact place it came from. Nothing another program reads
changes: ActivityPub, the Mastodon API's errors, sign-in tokens and the error kinds decePubClient branches on stay as they
were. The house-rules checks move to 1.1.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
2026-11-10 08:11:24 +01:00

136 lines
6.5 KiB
C#

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
using PrivaPub.ClientModels;
using PrivaPub.Extensions;
using PrivaPub.Resources;
using PrivaPub.Services.ClientToServer.Private;
using PrivaPub.ClientModels.User;
using PrivaPub.ClientModels.User.Avatar;
namespace PrivaPub.Controllers.ClientToServer
{
[ApiController,
Route(ApiPaths.PrivateAvatar.Prefix),
Authorize(Policy = Policies.IsUser)]
public class PrivateAvatarController(
IPrivateAvatarUsersService privateAvatarUsersService,
IStringLocalizer<GenericRes> localizer,
ILogger<PrivateAvatarController> logger) : ControllerBase
{
[HttpGet, Route(ApiPaths.PrivateAvatar.GET_GetAvatars)]
public async Task<IActionResult> GetAvatars(CancellationToken token)
{
var result = await privateAvatarUsersService.GetRootAvatars(User.GetUserId(), token);
return result.IsValid ? Ok(result.Data) : StatusCode(result.StatusCode, result);
}
[HttpPost, Route(ApiPaths.PrivateAvatar.POST_InsertAvatar)]
public async Task<IActionResult> InsertAvatar(InsertAvatarForm model, CancellationToken token = default)
{
var result = new WebResult();
if (!ModelState.IsValid)
return BadRequest(result.Invalidate(20001.ToCodedError(localizer["Invalid model."])));
try
{
model.RootId = User.GetUserId();
result = await privateAvatarUsersService.InsertAvatar(model, token);
if (!result.IsValid)
return StatusCode(result.StatusCode, result);
return Ok(result.Data);
}
catch (Exception ex)
{
logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(InsertAvatar)}()");
return BadRequest(result.Invalidate(20002.ToCodedError(localizer["Something went wrong."])));
}
}
// A login deletes one of its personas, with its password again (R6): everything public it had goes, the groups it owns
// with it, as when the whole login is deleted (PersonaRemoval). A suspended persona may be deleted too.
[HttpPost, Route(ApiPaths.PrivateAvatar.POST_DeleteAvatar), Microsoft.AspNetCore.RateLimiting.EnableRateLimiting(Infrastructure.RateLimiting.Accounts)]
public async Task<IActionResult> DeleteAvatar(DeletePersonaForm form, [FromServices] Services.IRootUsersService users,
[FromServices] Services.IPersonaRemoval personas, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
{
if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(20003.ToCodedError(localizer["Invalid model."])));
var rootId = User.GetUserId();
if (!await users.PasswordMatches(rootId, form.Password, token))
return StatusCode(StatusCodes.Status403Forbidden, new WebResult().Invalidate(20004.ToCodedError(localizer[Services.RootUsersService.NoMatch]), StatusCodes.Status403Forbidden));
if (!await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == form.AvatarId).ExecuteAnyAsync(token)
|| !await personas.Remove(form.AvatarId, CancellationToken.None))
return NotFound(new WebResult().Invalidate(20005.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound));
return Ok();
}
// how the persona's clients show what others post (R8): Mastodon's reading preferences, which its API only reads
[HttpGet, Route(ApiPaths.PrivateAvatar.GET_Preferences)]
public async Task<IActionResult> Preferences([FromQuery] string avatarId, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
{
var avatar = await OwnPersona(avatarId, dbEntities, token);
return avatar == default
? NotFound(new WebResult().Invalidate(20006.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound))
: Ok(PreferencesOf(avatar));
}
[HttpPost, Route(ApiPaths.PrivateAvatar.POST_SavePreferences)]
public async Task<IActionResult> SavePreferences(PersonaPreferencesForm form, [FromServices] StaticServices.DbEntities dbEntities, CancellationToken token)
{
if (!ModelState.IsValid)
return BadRequest(new WebResult().Invalidate(20007.ToCodedError(localizer["Invalid model."])));
if (!Models.User.ExpandMediaModes.IsKnown(form.ExpandMedia))
return UnprocessableEntity(new WebResult().Invalidate(20008.ToCodedError(localizer["Media are shown as default, show_all or hide_all."]), StatusCodes.Status422UnprocessableEntity));
var avatar = await OwnPersona(form.AvatarId, dbEntities, token);
if (avatar == default)
return NotFound(new WebResult().Invalidate(20009.ToCodedError(localizer["Avatar not found."]), StatusCodes.Status404NotFound));
await MongoDB.Entities.DB.Default.Update<Models.User.Avatar>().MatchID(avatar.ID)
.Modify(a => a.Settings.ExpandMedia, form.ExpandMedia)
.Modify(a => a.Settings.ExpandSpoilers, form.ExpandSpoilers)
.ExecuteAsync(token);
avatar.Settings.ExpandMedia = form.ExpandMedia;
avatar.Settings.ExpandSpoilers = form.ExpandSpoilers;
return Ok(PreferencesOf(avatar));
}
// one of the login's own personas, not deleted (a suspended one keeps its preferences for when it is back)
async Task<Models.User.Avatar> OwnPersona(string avatarId, StaticServices.DbEntities dbEntities, CancellationToken token)
{
var rootId = User.GetUserId();
if (string.IsNullOrEmpty(avatarId) || !await dbEntities.RootToAvatars.Match(ra => ra.RootId == rootId && ra.AvatarId == avatarId).ExecuteAnyAsync(token))
return default;
return await dbEntities.Avatars.MatchID(avatarId).Match(a => !a.DeletionAt.HasValue).ExecuteFirstAsync(token);
}
static ViewPersonaPreferences PreferencesOf(Models.User.Avatar avatar) => new()
{
AvatarId = avatar.ID,
ExpandMedia = Models.User.ExpandMediaModes.IsKnown(avatar.Settings.ExpandMedia) ? avatar.Settings.ExpandMedia : Models.User.ExpandMediaModes.Default,
ExpandSpoilers = avatar.Settings.ExpandSpoilers
};
[HttpPost, Route(ApiPaths.PrivateAvatar.POST_UpdateAvatar)]
public async Task<IActionResult> UpdateAvatar(UpdateAvatarForm model, CancellationToken token = default)
{
var result = new WebResult();
if (!ModelState.IsValid)
return BadRequest(result.Invalidate(20010.ToCodedError(localizer["Invalid model."])));
try
{
model.RootId = User.GetUserId();
result = await privateAvatarUsersService.UpdateAvatar(model, token);
if (!result.IsValid)
return StatusCode(result.StatusCode, result);
return Ok(result.Data);
}
catch (Exception ex)
{
logger.LogError(ex, $"{nameof(PrivateAvatarController)}.{nameof(UpdateAvatar)}()");
return BadRequest(result.Invalidate(20011.ToCodedError(localizer["Something went wrong."])));
}
}
}
}