using Messenger.Api.Contracts; using Messenger.Api.Services; using Messenger.Api.Data; using Messenger.Api.Infrastructure; using static Messenger.Api.Services.ApiSupport; namespace Messenger.Api.Endpoints; public static class UiEndpoints { // The required /api/v1 history stays ascending. The web client has a separate, // optional route to open a large chat at its newest page and page backwards. public static IEndpointRouteBuilder MapUiEndpoints(this IEndpointRouteBuilder app) { app.MapGet("/api/ui/cluster", async (HttpContext context, SessionService sessions, ClusterPresence presence) => { var (actor, _) = await sessions.AuthenticateAsync(context); if (actor is null) return Unauthorized(context); context.Response.Headers.CacheControl = "no-store"; return Results.Ok(await presence.ReadAsync()); }); app.MapGet("/api/ui/users/{username}",async(string username,HttpContext ctx,SessionService sessions,AppDatabase db)=> { var(actor,_)=await sessions.AuthenticateAsync(ctx);if(actor is null)return Unauthorized(ctx); if(!System.Text.RegularExpressions.Regex.IsMatch(username,"\\A[a-z0-9_]{3,32}\\z"))return ApiError(ctx,400,"invalid_request","Некорректный логин"); var user=await db.FindUserByUsernameAsync(username); return user is null?ApiError(ctx,404,"not_found","Пользователь не найден"):Results.Ok(user.ToDto()); }); app.MapGet("/api/ui/chats", async (HttpContext context, SessionService sessions, AppDatabase database) => { var (actor, _) = await sessions.AuthenticateAsync(context); if (actor is null) return Unauthorized(context); var (limit, limitError) = ParseLimit(context); if (limitError is not null) return limitError; var (cursor, cursorTime, cursorError) = ParseCursor(context, $"ui-chats:{actor.Id}"); if (cursorError is not null) return cursorError; var page = await database.ListChatPreviewsAsync(actor.Id, cursorTime, cursor?.Id, limit + 1); string? nextCursor = null; if (page.Count > limit) { var last = page[limit - 1]; nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"ui-chats:{actor.Id}", last.CreatedAt, last.Id)); page = page.Take(limit).ToList(); } return Results.Ok(new { items = page, next_cursor = nextCursor }); }); app.MapGet("/api/ui/chats/{chat_id}/members", async ( string chat_id, HttpContext context, SessionService sessions, ChatService chats, UserService users) => { 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", "Чат не найден"); return Results.Ok(new { items = await users.ListForChatAsync(chatId) }); }); app.MapGet("/api/ui/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, $"recent-chat:{chatId}"); if (cursorError is not null) return cursorError; var page = await messages.ListAsync(chatId, cursorTime, cursor?.Id, limit + 1, newestFirst: true); string? nextCursor = null; if (page.Count > limit) { var last = page[limit - 1]; nextCursor = CursorService.EncodeChatCursor(new ChatCursor($"recent-chat:{chatId}", last.CreatedAt, last.Id)); page = page.Take(limit).ToList(); } return Results.Ok(new { items = page, next_cursor = nextCursor }); }); return app; } }