40 lines
2.5 KiB
C#
40 lines
2.5 KiB
C#
using Messenger.Api.Data;
|
|
using Messenger.Api.Services;
|
|
using static Messenger.Api.Services.ApiSupport;
|
|
|
|
namespace Messenger.Api.Endpoints;
|
|
|
|
public static class ReactionEndpoints
|
|
{
|
|
public static IEndpointRouteBuilder MapReactionEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
app.MapGet("/api/ui/chats/{chat_id}/reactions", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats, AppDatabase database) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
if (!Guid.TryParse(chat_id, out var chatId)) return ApiError(context, 400, "invalid_request", "Некорректный chat_id");
|
|
if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден");
|
|
var values = context.Request.Query["message_ids"].ToString().Split(',');
|
|
if (values.Length is < 1 or > 100 || values.Any(value => !Guid.TryParse(value, out _)))
|
|
return ApiError(context, 400, "invalid_request", "Укажите от 1 до 100 ID сообщений");
|
|
var ids = values.Select(Guid.Parse).Distinct().ToArray();
|
|
return Results.Ok(new { items = await database.ListReactionsAsync(chatId, ids, actor.Id) });
|
|
});
|
|
app.MapMethods("/api/ui/chats/{chat_id}/messages/{message_id}/reactions/{reaction}", ["PUT", "DELETE"], async (
|
|
string chat_id, string message_id, string reaction, HttpContext context,
|
|
SessionService sessions, ChatService chats, AppDatabase database) =>
|
|
{
|
|
var (actor, _) = await sessions.AuthenticateAsync(context);
|
|
if (actor is null) return Unauthorized(context);
|
|
if (!Guid.TryParse(chat_id, out var chatId) || !Guid.TryParse(message_id, out var messageId)
|
|
|| reaction is not ("like" or "love" or "laugh" or "mushroom"))
|
|
return ApiError(context, 400, "invalid_request", "Некорректная реакция или ID");
|
|
if (await chats.FindForMemberAsync(chatId, actor.Id) is null) return ApiError(context, 404, "not_found", "Чат не найден");
|
|
return await database.SetReactionAsync(chatId, messageId, actor.Id, reaction, context.Request.Method == "PUT")
|
|
? Results.NoContent() : ApiError(context, 404, "not_found", "Сообщение не найдено");
|
|
});
|
|
return app;
|
|
}
|
|
}
|