From 94af2fe9ac5656d2c8953c418d5b9eb4a72be093 Mon Sep 17 00:00:00 2001 From: pancakes Date: Wed, 27 Nov 2024 19:19:30 +1000 Subject: [PATCH] [backend/api] Add endpoints for updating and deleting user avatar --- .../Controllers/Web/ProfileController.cs | 51 ++++++++++++++++++- 1 file changed, 50 insertions(+), 1 deletion(-) diff --git a/Iceshrimp.Backend/Controllers/Web/ProfileController.cs b/Iceshrimp.Backend/Controllers/Web/ProfileController.cs index 9d80a8d1..2386bee4 100644 --- a/Iceshrimp.Backend/Controllers/Web/ProfileController.cs +++ b/Iceshrimp.Backend/Controllers/Web/ProfileController.cs @@ -16,7 +16,7 @@ namespace Iceshrimp.Backend.Controllers.Web; [EnableRateLimiting("sliding")] [Route("/api/iceshrimp/profile")] [Produces(MediaTypeNames.Application.Json)] -public class ProfileController(UserService userSvc) : ControllerBase +public class ProfileController(UserService userSvc, DriveService driveSvc) : ControllerBase { [HttpGet] [ProducesResults(HttpStatusCode.OK)] @@ -70,4 +70,53 @@ public class ProfileController(UserService userSvc) : ControllerBase var prevBannerId = user.BannerId; await userSvc.UpdateLocalUserAsync(user, prevAvatarId, prevBannerId); } + + [HttpPost("avatar")] + [ProducesResults(HttpStatusCode.OK)] + [ProducesErrors(HttpStatusCode.BadRequest)] + public async Task UpdateAvatarAsync(IFormFile file) + { + var user = HttpContext.GetUserOrFail(); + + var prevAvatarId = user.AvatarId; + var prevBannerId = user.BannerId; + + if (!file.ContentType.StartsWith("image/")) + throw GracefulException.BadRequest("Avatar must be an image"); + + var rq = new DriveFileCreationRequest + { + Filename = file.FileName, + IsSensitive = false, + MimeType = file.ContentType + }; + + var avatar = await driveSvc.StoreFileAsync(file.OpenReadStream(), user, rq); + + user.Avatar = avatar; + user.AvatarBlurhash = avatar.Blurhash; + user.AvatarUrl = avatar.AccessUrl; + + await userSvc.UpdateLocalUserAsync(user, prevAvatarId, prevBannerId); + } + + [HttpDelete("avatar")] + [ProducesResults(HttpStatusCode.OK)] + [ProducesErrors(HttpStatusCode.NotFound)] + public async Task DeleteAvatarAsync() + { + var user = HttpContext.GetUserOrFail(); + + var prevAvatarId = user.AvatarId; + var prevBannerId = user.BannerId; + + if (prevAvatarId == null) + throw GracefulException.NotFound("You do not have an avatar"); + + user.Avatar = null; + user.AvatarBlurhash = null; + user.AvatarUrl = null; + + await userSvc.UpdateLocalUserAsync(user, prevAvatarId, prevBannerId); + } } \ No newline at end of file