forked from mtusi2026/mtusi2026lab5
81 lines
4.4 KiB
C#
81 lines
4.4 KiB
C#
using Messenger.Api.Contracts;
|
|
using Messenger.Api.Services;
|
|
using System.Text.Json;
|
|
using static Messenger.Api.Services.ApiSupport;
|
|
|
|
namespace Messenger.Api.Endpoints;
|
|
|
|
public static class MessageEndpoints
|
|
{
|
|
public static IEndpointRouteBuilder MapMessageEndpoints(this IEndpointRouteBuilder app)
|
|
{
|
|
app.MapPost("/api/v1/chats/{chat_id}/messages", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
|
{
|
|
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 keys = context.Request.Headers["Idempotency-Key"];
|
|
var key = keys.ToString();
|
|
if (keys.Count != 1 || key.Length is < 1 or > 128 ||
|
|
key.Any(c => !char.IsAsciiLetterOrDigit(c) && c is not '.' and not '_' and not ':' and not '-'))
|
|
return ApiError(context, 400, "invalid_request", "Требуется корректный Idempotency-Key");
|
|
|
|
var (request, error) = await ReadJsonAsync<CreateMessageRequest>(context);
|
|
if (error is not null) return error;
|
|
if (request!.Text is null || request.Text.EnumerateRunes().Count() > 4000)
|
|
return ApiError(context, 400, "invalid_request", "Некорректный текст сообщения");
|
|
var ids = new List<Guid>();
|
|
if (request.AttachmentIds.ValueKind != JsonValueKind.Undefined)
|
|
{
|
|
if (request.AttachmentIds.ValueKind != JsonValueKind.Array || request.AttachmentIds.GetArrayLength()>10)
|
|
return ApiError(context,400,"invalid_request","Некорректный список вложений");
|
|
foreach(var item in request.AttachmentIds.EnumerateArray())
|
|
{
|
|
if(item.ValueKind!=JsonValueKind.String || !item.TryGetGuid(out var id) || ids.Contains(id))
|
|
return ApiError(context,400,"invalid_request","Некорректный ID вложения");
|
|
ids.Add(id);
|
|
}
|
|
}
|
|
if(string.IsNullOrWhiteSpace(request.Text) && ids.Count==0)
|
|
return ApiError(context,400,"invalid_request","Нужен текст или вложение");
|
|
|
|
var message = await messages.CreateAsync(chatId, actor.Id, request.Text, key, ids.ToArray());
|
|
if (message is null)
|
|
return ApiError(context, 409, "conflict", "Этот ключ уже использован для другого сообщения");
|
|
return Results.Json(message, statusCode: StatusCodes.Status201Created);
|
|
});
|
|
|
|
app.MapGet("/api/v1/chats/{chat_id}/messages", async (
|
|
string chat_id, HttpContext context, SessionService sessions, ChatService chats, MessageService messages) =>
|
|
{
|
|
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 (limit, limitError) = ParseLimit(context);
|
|
if (limitError is not null) return limitError;
|
|
var (cursor, cursorTime, cursorError) = ParseCursor(context, $"chat:{chatId}");
|
|
if (cursorError is not null) return cursorError;
|
|
|
|
var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1);
|
|
string? nextCursor = null;
|
|
if (page.Count > limit)
|
|
{
|
|
var last = page[limit - 1];
|
|
nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"chat:{chatId}", last.CreatedAt, last.Id));
|
|
page = page.Take(limit).ToList();
|
|
}
|
|
return Results.Ok(new { items = page, next_cursor = nextCursor });
|
|
});
|
|
|
|
return app;
|
|
}
|
|
}
|