diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f407ec7 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +.codex +.agents +**/bin +**/obj +**/logs +**/uploads +**/secrets +**/appsettings.Development.json +artifacts diff --git a/.github/workflows/dotnet.yml b/.github/workflows/dotnet.yml index b0d56a7..bd18166 100644 --- a/.github/workflows/dotnet.yml +++ b/.github/workflows/dotnet.yml @@ -12,6 +12,25 @@ on: jobs: build-and-test: runs-on: ubuntu-latest + strategy: + matrix: + database: [sqlite, postgres] + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: govor + POSTGRES_PASSWORD: tests-only + POSTGRES_DB: govor_tests + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + env: + TEST_POSTGRES_CONNECTION: ${{ matrix.database == 'postgres' && 'Host=localhost;Port=5432;Database=govor_tests;Username=govor;Password=tests-only' || '' }} steps: - name: Checkout code uses: actions/checkout@v4 @@ -19,15 +38,15 @@ jobs: - name: Setup .NET SDK uses: actions/setup-dotnet@v4 with: - dotnet-version: '8.0.x' + dotnet-version: '10.0.x' - name: Restore dependencies - run: dotnet restore + run: dotnet restore Govor.Server.slnx - name: Build - run: dotnet build --no-restore --configuration Release + run: dotnet build Govor.Server.slnx --no-restore --configuration Release - name: Run tests - run: dotnet test Govor.API.Tests/Govor.API.Tests.csproj + run: dotnet test Govor.Server.Tests/Govor.Server.Tests.csproj --no-build --configuration Release diff --git a/Dockerfile b/Dockerfile index ef71324..209d987 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,26 +1,18 @@ -FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build +FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src - -# Êîïèðóåì òîëüêî .sln è .csproj -COPY *.sln ./ +COPY global.json ./ COPY Govor.API/*.csproj ./Govor.API/ COPY Govor.Application/*.csproj ./Govor.Application/ -COPY Govor.Core/*.csproj ./Govor.Core/ -COPY Govor.Data/*.csproj ./Govor.Data/ +COPY Govor.Domain/*.csproj ./Govor.Domain/ COPY Govor.Contracts/*.csproj ./Govor.Contracts/ - +COPY libs/ ./libs/ RUN dotnet restore Govor.API/Govor.API.csproj - -# Êîïèðóåì âåñü êîä COPY . . -WORKDIR /src/Govor.API -RUN dotnet publish -c Release -o /app/publish +RUN dotnet publish Govor.API/Govor.API.csproj -c Release --no-restore -o /app/publish -# Runtime image -FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final +FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final WORKDIR /app COPY --from=build /app/publish . - +ENV ASPNETCORE_HTTP_PORTS=8080 EXPOSE 8080 - -ENTRYPOINT ["dotnet", "Govor.API.dll"] \ No newline at end of file +ENTRYPOINT ["dotnet", "Govor.API.dll"] diff --git a/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs b/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs index 10256d6..03df7e8 100644 --- a/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs +++ b/Govor.API/Common/Extensions/ConfigurationProgramExtensions.cs @@ -11,6 +11,7 @@ using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Validators; using Govor.Application.Medias; using Govor.Application.Messages; +using Govor.Application.Reactions; using Govor.Application.PingHandler; using Govor.Application.PrivateUserChats; using Govor.Application.Profiles; @@ -68,6 +69,9 @@ public static class ConfigurationProgramExtensions //services.AddScoped(); services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddSingleton(); services.AddScoped(); services.AddScoped(); services.AddScoped(); @@ -91,6 +95,8 @@ public static class ConfigurationProgramExtensions // Hubs Infrastructure services.AddScoped(); services.AddScoped(); + services.AddScoped(); + services.AddHostedService(); services.AddScoped(); services.AddSingleton(); @@ -98,7 +104,10 @@ public static class ConfigurationProgramExtensions // Pushs services.AddScoped(); services.AddScoped(); - services.AddSingleton(); + services.AddSingleton(sp => + sp.GetRequiredService().GetValue("Firebase:Enabled", true) + ? ActivatorUtilities.CreateInstance(sp) + : new NullPushProvider()); // Auto Mapper @@ -133,8 +142,8 @@ public static class ConfigurationProgramExtensions //options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); - options.EnableSensitiveDataLogging(); - options.EnableDetailedErrors(); + if (configuration.GetValue("Database:EnableDetailedErrors")) + options.EnableDetailedErrors(); }); } -} \ No newline at end of file +} diff --git a/Govor.API/Common/Extensions/HubResultExtensions.cs b/Govor.API/Common/Extensions/HubResultExtensions.cs new file mode 100644 index 0000000..0a68225 --- /dev/null +++ b/Govor.API/Common/Extensions/HubResultExtensions.cs @@ -0,0 +1,17 @@ +using Govor.Contracts.Responses.SignalR; +using Govor.Domain.Common; + +namespace Govor.API.Common.Extensions; + +public static class HubResultExtensions +{ + public static HubResult ToHubResult(this Error error) => error.Type switch + { + ErrorType.NotFound => HubResult.NotFound(error.Message), + ErrorType.Forbidden => HubResult.Forbidden(error.Message), + ErrorType.Unauthorized => HubResult.Unauthorized(error.Message), + ErrorType.Conflict => HubResult.Conflict(error.Message), + ErrorType.ServerError => HubResult.Error("Internal server error."), + _ => HubResult.BadRequest(error.Message) + }; +} diff --git a/Govor.API/Common/Extensions/ResultExtensions.cs b/Govor.API/Common/Extensions/ResultExtensions.cs index aa5cac4..de928bc 100644 --- a/Govor.API/Common/Extensions/ResultExtensions.cs +++ b/Govor.API/Common/Extensions/ResultExtensions.cs @@ -28,6 +28,7 @@ public static class ResultExtensions ErrorType.Conflict => StatusCodes.Status409Conflict, ErrorType.Unauthorized => StatusCodes.Status401Unauthorized, ErrorType.Forbidden => StatusCodes.Status403Forbidden, + ErrorType.ServerError => StatusCodes.Status500InternalServerError, _ => StatusCodes.Status400BadRequest }; @@ -55,6 +56,7 @@ public static class ResultExtensions ErrorType.Conflict => "Conflict", ErrorType.Unauthorized => "Unauthorized", ErrorType.Forbidden => "Forbidden", + ErrorType.ServerError => "Internal Server Error", _ => "Bad Request" }; -} \ No newline at end of file +} diff --git a/Govor.API/Common/Extensions/SessionAuthorization.cs b/Govor.API/Common/Extensions/SessionAuthorization.cs new file mode 100644 index 0000000..1b55625 --- /dev/null +++ b/Govor.API/Common/Extensions/SessionAuthorization.cs @@ -0,0 +1,21 @@ +#nullable enable +using System.Security.Claims; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; + +namespace Govor.API.Common.Extensions; + +public static class SessionAuthorization +{ + public static Task HasActiveSessionAsync(this GovorDbContext context, ClaimsPrincipal? user) + { + if (user?.Identity?.IsAuthenticated != true || user.FindFirst("tokenType")?.Value == "refresh" || + !Guid.TryParse(user.FindFirst("userId")?.Value, out var userId) || + !Guid.TryParse(user.FindFirst("sid")?.Value, out var sessionId)) + return Task.FromResult(false); + + var now = DateTime.UtcNow; + return context.UserSessions.AsNoTracking().AnyAsync(s => s.Id == sessionId && + s.UserId == userId && !s.IsRevoked && s.ExpiresAt > now); + } +} diff --git a/Govor.API/Common/Mapping/MappingProfile.cs b/Govor.API/Common/Mapping/MappingProfile.cs index 0921426..0d2b4a6 100644 --- a/Govor.API/Common/Mapping/MappingProfile.cs +++ b/Govor.API/Common/Mapping/MappingProfile.cs @@ -5,6 +5,10 @@ using Govor.Contracts.Responses; using Govor.Domain.Models; using Govor.Domain.Models.Messages; using Govor.Domain.Models.Users; +using Govor.Application.Messages.Parameters; +using Govor.Contracts.Responses.SignalR; +using Govor.Application.Reactions; +using Govor.Domain.Models.Reactions; namespace Govor.API.Common.Mapping; @@ -12,6 +16,12 @@ public class MappingProfile : Profile { public MappingProfile() { + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); + CreateMap(); CreateMap(); CreateMap(); CreateMap(); @@ -27,6 +37,5 @@ public class MappingProfile : Profile CreateMap(); - CreateMap(); } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/AdminStuff/InviteUserController.cs b/Govor.API/Controllers/AdminStuff/InviteUserController.cs index d55043f..0fbfcfa 100644 --- a/Govor.API/Controllers/AdminStuff/InviteUserController.cs +++ b/Govor.API/Controllers/AdminStuff/InviteUserController.cs @@ -2,12 +2,13 @@ using Govor.Application.Infrastructure.AdminsStuff; using Govor.Contracts.DTOs; using Govor.Contracts.Requests; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Authorization; namespace Govor.API.Controllers.AdminStuff; [Route("api/admin/[controller]")] [ApiController] -//[Authorize(Roles = "Admin")] +[Authorize(Roles = "Admin")] public class InviteUserController : Controller { private readonly IInvitationGetter _invitationGetter; @@ -144,4 +145,4 @@ public class InviteUserController : Controller return BadRequest($"An error occured: {e.Message}"); } } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/AdminStuff/ReactionPacksAdminController.cs b/Govor.API/Controllers/AdminStuff/ReactionPacksAdminController.cs new file mode 100644 index 0000000..103daa4 --- /dev/null +++ b/Govor.API/Controllers/AdminStuff/ReactionPacksAdminController.cs @@ -0,0 +1,66 @@ +using System.ComponentModel.DataAnnotations; +using AutoMapper; +using Govor.API.Common.Extensions; +using Govor.Application.Infrastructure.Extensions; +using Govor.Application.Reactions; +using Govor.Contracts.Requests; +using Govor.Contracts.Responses; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Govor.API.Controllers.AdminStuff; + +[ApiController] +[Authorize(Roles = "Admin")] +[Route("api/admin/reaction-packs")] +public class ReactionPacksAdminController(IReactionPackService packs, ICurrentUserService currentUser, IMapper mapper) : ControllerBase +{ + [HttpGet] + public async Task List([FromQuery, Range(0, int.MaxValue)] int skip = 0, + [FromQuery, Range(1, 100)] int take = 50) => + Ok(mapper.Map>(await packs.ListAsync(currentUser.GetCurrentUserId(), includeDisabled: true, skip: skip, take: take))); + + [HttpGet("{packId:guid}")] + public async Task Get(Guid packId) => (await packs.GetAsync(packId, includeDisabled: true)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpPost] + public async Task Create([FromBody] CreateReactionPackRequest request) => + (await packs.CreateAsync(currentUser.GetCurrentUserId(), request.Name, request.Description)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpPut("{packId:guid}")] + public async Task Update(Guid packId, [FromBody] UpdateReactionPackRequest request) => + (await packs.UpdateAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Description, request.IsEnabled)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpDelete("{packId:guid}")] + public async Task Disable(Guid packId) => (await packs.DisableAsync(currentUser.GetCurrentUserId(), packId)).ToActionResult(); + + [HttpPost("{packId:guid}/reactions/emoji")] + public async Task Emoji(Guid packId, [FromBody] CreateEmojiReactionRequest request) => + (await packs.AddEmojiAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Emoji)) + .Map(r => mapper.Map(r)).ToActionResult(); + + [HttpPost("{packId:guid}/reactions/media")] + [RequestSizeLimit(2_200_000)] + public async Task Media(Guid packId, [FromForm] ReactionUploadRequest request) + { + if (request.File is null || request.File.Length == 0 || request.File.Length > ReactionMediaLimits.MaxUploadBytes) + return BadRequest("Upload must contain at most 2 MiB."); + using var buffer = new MemoryStream(); + await request.File.CopyToAsync(buffer, HttpContext.RequestAborted); + return (await packs.AddMediaAsync(currentUser.GetCurrentUserId(), packId, request.Name, + buffer.ToArray(), HttpContext.RequestAborted)).Map(r => mapper.Map(r)).ToActionResult(); + } + + [HttpDelete("{packId:guid}/reactions/{reactionId:guid}")] + public async Task DisableReaction(Guid packId, Guid reactionId) => + (await packs.DisableReactionAsync(currentUser.GetCurrentUserId(), packId, reactionId)).ToActionResult(); +} + +public class ReactionUploadRequest +{ + [Required, MaxLength(100)] public string Name { get; set; } = string.Empty; + [Required] public IFormFile File { get; set; } +} diff --git a/Govor.API/Controllers/AdminStuff/UsersController.cs b/Govor.API/Controllers/AdminStuff/UsersController.cs index 4b94af6..af8194f 100644 --- a/Govor.API/Controllers/AdminStuff/UsersController.cs +++ b/Govor.API/Controllers/AdminStuff/UsersController.cs @@ -3,13 +3,14 @@ using Govor.Contracts.Responses.Admins; using Govor.Domain.Models.Users; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Govor.Contracts.Requests; namespace Govor.API.Controllers.AdminStuff; [ApiController] [Route("api/admin/[controller]")] -[Authorize]//(Roles = "Admin") +[Authorize(Roles = "Admin")] public class UsersController : Controller { private readonly ILogger _logger; @@ -48,6 +49,8 @@ public class UsersController : Controller { _logger.LogInformation($"Getting user {id} by administrator"); var read = await _users.GetUserById(id); + if (read is null) + return NotFound(); return Ok(BuildUserDtos([read]).First()); } catch (Exception e) @@ -57,13 +60,15 @@ public class UsersController : Controller } } - [HttpGet("user/{id:guid}/setpassword/{password}")] - public async Task SetNewPassword(Guid id, string password) + [HttpPost("user/{id:guid}/password")] + public async Task SetNewPassword(Guid id, [FromBody] SetPasswordRequest request) { try { - await _users.SetPasswordAsync(id, password); - return Ok(); + if (await _users.GetUserById(id) is null) + return NotFound(); + await _users.SetPasswordAsync(id, request.Password); + return NoContent(); } catch (Exception ex) { @@ -78,10 +83,9 @@ public class UsersController : Controller Description = user.Description, WasOnline = user.WasOnline, IconId = user.IconId, - PasswordHash = user.PasswordHash, InviteId = user.InviteId, CreatedOn = user.CreatedOn, IsAdmin = user.Invite?.IsAdmin ?? false, }).ToList(); -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/Authentication/SessionKeysController.cs b/Govor.API/Controllers/Authentication/SessionKeysController.cs index 4f6558e..de1953d 100644 --- a/Govor.API/Controllers/Authentication/SessionKeysController.cs +++ b/Govor.API/Controllers/Authentication/SessionKeysController.cs @@ -4,6 +4,7 @@ using Govor.Application.Users.UserSessions.Crypto; using Govor.Contracts.Requests; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; +using Govor.Contracts.DTOs; namespace Govor.API.Controllers.Authentication; @@ -27,7 +28,8 @@ public class SessionKeysController : Controller ICurrentUserSessionService currentSession, ISessionKeyAttacher sessionKeyAttacher, ISessionKeysReader sessionKeysReader, - ICurrentUserService currentUser) + ICurrentUserService currentUser, + IOneTimePreKeysRotator oneTimePreKeysRotator) { _logger = logger; _friendshipService = friendshipService; @@ -35,6 +37,7 @@ public class SessionKeysController : Controller _sessionKeyAttacher = sessionKeyAttacher; _sessionKeysReader = sessionKeysReader; _currentUser = currentUser; + _oneTimePreKeysRotator = oneTimePreKeysRotator; } [HttpPost("keys")] @@ -63,11 +66,24 @@ public class SessionKeysController : Controller var requesterId = _currentUser.GetCurrentUserId(); if (!(await _friendshipService.GetFriendsAsync(userId)).Select(u => u.Id).Contains(requesterId)) - return Forbid("You can only access keys of your friends"); + return Forbid(); var keys = await _sessionKeysReader.GetAllActiveKeysAsync(userId); - return Ok(keys); + return Ok(keys.Select(k => new PublicSessionKeysDto + { + IdentityKey = Convert.ToBase64String(k.PublicIdentityKey), + SignedPreKey = k.SignedPreKey is null ? null : new SignedPreKeyDto + { + Id = k.SignedPreKey.Id, + Key = Convert.ToBase64String(k.SignedPreKey.PublicSignedPreKey), + Signature = Convert.ToBase64String(k.SignedPreKey.SignedPreKeySignature) + }, + OneTimePreKeys = k.OneTimePreKeys.Where(p => !p.IsUsed).Select(p => new OneTimePreKeyDto + { + Id = p.Id, Key = Convert.ToBase64String(p.PublicKey) + }).ToList() + })); } [HttpPost("keys/rotate")] @@ -106,4 +122,4 @@ public class SessionKeysController : Controller return Ok("Marked as used."); } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/ChannelReactionsController.cs b/Govor.API/Controllers/ChannelReactionsController.cs new file mode 100644 index 0000000..c5ac46e --- /dev/null +++ b/Govor.API/Controllers/ChannelReactionsController.cs @@ -0,0 +1,32 @@ +using AutoMapper; +using Govor.API.Common.Extensions; +using Govor.API.Hubs.Infrastructure; +using Govor.Application.Infrastructure.Extensions; +using Govor.Application.Reactions; +using Govor.Contracts.Requests; +using Govor.Contracts.Responses.SignalR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Govor.API.Controllers; + +[ApiController] +[Authorize(Roles = "Admin,User")] +[Route("api/groups/{groupId:guid}/reactions")] +public class ChannelReactionsController(IMessageReactionService reactions, ICurrentUserService currentUser, + IMapper mapper, IChatNotificationService notifier) : ControllerBase +{ + [HttpGet] + public async Task Get(Guid groupId) => (await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpPut] + public async Task Set(Guid groupId, [FromBody] ChannelReactionPolicyRequest request) + { + var result = await reactions.SetPolicyAsync(currentUser.GetCurrentUserId(), groupId, request.Mode, request.ReactionIds); + if (result.IsFailure) return result.ToActionResult(); + var response = mapper.Map(result.Value); + await notifier.NotifyChannelReactionPolicyChangedAsync(response); + return Ok(response); + } +} diff --git a/Govor.API/Controllers/ChatLoadController.cs b/Govor.API/Controllers/ChatLoadController.cs index cc3def1..e77a348 100644 --- a/Govor.API/Controllers/ChatLoadController.cs +++ b/Govor.API/Controllers/ChatLoadController.cs @@ -41,7 +41,7 @@ public class ChatLoadController : Controller { try { - if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100) + if (query.Before < 0 || query.After < 0 || query.Before > 100 || query.After > 100 || query.After + query.Before > 100) return BadRequest("Values must be non-negative and total must not exceed 100."); var result = (await _messagesLoader.LoadMessagesInChatGroup( @@ -67,7 +67,7 @@ public class ChatLoadController : Controller { try { - if (query.Before < 0 || query.After < 0 || query.After + query.Before > 100) + if (query.Before < 0 || query.After < 0 || query.Before > 100 || query.After > 100 || query.After + query.Before > 100) return BadRequest("Values must be non-negative and total must not exceed 100."); var result = (await _messagesLoader.LoadMessagesInUserChat( @@ -86,4 +86,4 @@ public class ChatLoadController : Controller return StatusCode(500, "Unexpected Error! Please try again later."); } } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/MediaController.cs b/Govor.API/Controllers/MediaController.cs index 8607bee..f8b0872 100644 --- a/Govor.API/Controllers/MediaController.cs +++ b/Govor.API/Controllers/MediaController.cs @@ -37,6 +37,9 @@ public class MediaController : Controller if (!ModelState.IsValid) return BadRequest(ModelState); + if (request.OwnerType != MediaOwnerType.Message && request.OwnerType != MediaOwnerType.Avatar) + return BadRequest("Only message and personal avatar uploads are supported."); + if (request?.FromFile is null || request.FromFile.Length == 0) return BadRequest("No file uploaded"); @@ -85,7 +88,7 @@ public class MediaController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { diff --git a/Govor.API/Controllers/MessageReactionsController.cs b/Govor.API/Controllers/MessageReactionsController.cs new file mode 100644 index 0000000..52a0d19 --- /dev/null +++ b/Govor.API/Controllers/MessageReactionsController.cs @@ -0,0 +1,37 @@ +using AutoMapper; +using Govor.API.Common.Extensions; +using Govor.API.Hubs.Infrastructure; +using Govor.Application.Infrastructure.Extensions; +using Govor.Application.Reactions; +using Govor.Contracts.Requests; +using Govor.Contracts.Responses.SignalR; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Govor.API.Controllers; + +[ApiController] +[Authorize(Roles = "Admin,User")] +[Route("api/messages/{messageId:guid}/reactions")] +public class MessageReactionsController(IMessageReactionService reactions, ICurrentUserService currentUser, + IMapper mapper, IChatNotificationService notifier) : ControllerBase +{ + [HttpGet] + public async Task Get(Guid messageId) => (await reactions.GetAsync(currentUser.GetCurrentUserId(), messageId)) + .Map(s => mapper.Map(s)).ToActionResult(); + + [HttpPut("me")] + public Task Set(Guid messageId, [FromBody] SetReactionRequest request) => ChangeAsync(messageId, request.ReactionId); + + [HttpDelete("me")] + public Task Remove(Guid messageId) => ChangeAsync(messageId, null); + + private async Task ChangeAsync(Guid messageId, Guid? reactionId) + { + var result = await reactions.SetAsync(currentUser.GetCurrentUserId(), messageId, reactionId); + if (result.IsFailure) return result.ToActionResult(); + var response = mapper.Map(result.Value); + if (result.Value.Changed) await notifier.NotifyMessageReactionsChangedAsync(response); + return Ok(response); + } +} diff --git a/Govor.API/Controllers/MessageReadController.cs b/Govor.API/Controllers/MessageReadController.cs new file mode 100644 index 0000000..301456c --- /dev/null +++ b/Govor.API/Controllers/MessageReadController.cs @@ -0,0 +1,52 @@ +using AutoMapper; +using Govor.API.Common.Extensions; +using Govor.API.Hubs.Infrastructure; +using Govor.Application.Infrastructure.Extensions; +using Govor.Application.Messages; +using Govor.Contracts.Requests; +using Govor.Contracts.Responses.SignalR; +using Govor.Domain.Models.Messages; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Govor.API.Controllers; + +[ApiController] +[Authorize(Roles = "Admin,User")] +[Route("api/chats/{chatId:guid}")] +public class MessageReadController : ControllerBase +{ + private readonly IMessageReadingService _reader; + private readonly ICurrentUserService _currentUser; + private readonly IChatNotificationService _notifier; + private readonly IMapper _mapper; + + public MessageReadController(IMessageReadingService reader, ICurrentUserService currentUser, + IChatNotificationService notifier, IMapper mapper) + { + _reader = reader; + _currentUser = currentUser; + _notifier = notifier; + _mapper = mapper; + } + + [HttpPost("read")] + public async Task Read(Guid chatId, [FromBody] ReadChatRequest request) + { + var result = await _reader.ReadChatAsync(_currentUser.GetCurrentUserId(), chatId, + request.RecipientType, request.MessageIds, request.UpToMessageId); + if (result.IsFailure) + return result.ToActionResult(); + + var response = _mapper.Map(result.Value); + await _notifier.NotifyChatReadAsync(response); + return Ok(response); + } + + [HttpGet("unread-count")] + public async Task GetUnreadCount(Guid chatId, [FromQuery] RecipientType recipientType) + { + var result = await _reader.GetUnreadCountAsync(_currentUser.GetCurrentUserId(), chatId, recipientType); + return result.IsFailure ? result.ToActionResult() : Ok(new { unreadCount = result.Value }); + } +} diff --git a/Govor.API/Controllers/OnlinePingingController.cs b/Govor.API/Controllers/OnlinePingingController.cs index 001ce34..d0fa0c4 100644 --- a/Govor.API/Controllers/OnlinePingingController.cs +++ b/Govor.API/Controllers/OnlinePingingController.cs @@ -19,11 +19,15 @@ public class OnlinePingingController : Controller public OnlinePingingController(ILogger logger, IPingHandlerService ping, - ICurrentUserService currentUserService) + ICurrentUserService currentUserService, + IUserPresenceReader presenceReader, + IOnlineUserStore userOnlineStore) { _logger = logger; _ping = ping; _currentUserService = currentUserService; + _presenceReader = presenceReader; + _userOnlineStore = userOnlineStore; } @@ -66,4 +70,4 @@ public class OnlinePingingController : Controller return StatusCode(500, "Internal server error."); } } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/PrivateChatController.cs b/Govor.API/Controllers/PrivateChatController.cs index da3873f..6d9a2ba 100644 --- a/Govor.API/Controllers/PrivateChatController.cs +++ b/Govor.API/Controllers/PrivateChatController.cs @@ -49,7 +49,7 @@ public class PrivateChatController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (ArgumentException ex) { @@ -59,7 +59,7 @@ public class PrivateChatController : Controller catch (FriendshipException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -87,7 +87,7 @@ public class PrivateChatController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -95,4 +95,4 @@ public class PrivateChatController : Controller return StatusCode(500, "Unexpected Error! Please try again later."); } } -} \ No newline at end of file +} diff --git a/Govor.API/Controllers/ProfileController.cs b/Govor.API/Controllers/ProfileController.cs index 636805f..b23c784 100644 --- a/Govor.API/Controllers/ProfileController.cs +++ b/Govor.API/Controllers/ProfileController.cs @@ -1,4 +1,4 @@ -using AutoMapper; +using AutoMapper; using Govor.API.Common.Extensions; using Govor.API.Hubs; using Govor.Application.Infrastructure.Extensions; @@ -102,7 +102,7 @@ public class ProfileController : ControllerBase catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -124,7 +124,7 @@ public class ProfileController : ControllerBase catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { diff --git a/Govor.API/Controllers/ReactionPacksController.cs b/Govor.API/Controllers/ReactionPacksController.cs new file mode 100644 index 0000000..94b4db0 --- /dev/null +++ b/Govor.API/Controllers/ReactionPacksController.cs @@ -0,0 +1,55 @@ +using System.ComponentModel.DataAnnotations; +using AutoMapper; +using Govor.API.Common.Extensions; +using Govor.Application.Infrastructure.Extensions; +using Govor.Application.Reactions; +using Govor.Contracts.Responses; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +namespace Govor.API.Controllers; + +[ApiController] +[Authorize(Roles = "Admin,User")] +[Route("api/reaction-packs")] +public class ReactionPacksController(IReactionPackService packs, ICurrentUserService currentUser, IMapper mapper) : ControllerBase +{ + [HttpGet] + public async Task List([FromQuery, Range(0, int.MaxValue)] int skip = 0, + [FromQuery, Range(1, 100)] int take = 50) => + Ok(mapper.Map>(await packs.ListAsync(currentUser.GetCurrentUserId(), skip: skip, take: take))); + + [HttpGet("mine")] + public async Task Mine([FromQuery, Range(0, int.MaxValue)] int skip = 0, + [FromQuery, Range(1, 100)] int take = 50) => + Ok(mapper.Map>(await packs.ListAsync(currentUser.GetCurrentUserId(), installedOnly: true, skip: skip, take: take))); + + [HttpGet("{packId:guid}")] + public async Task Get(Guid packId) => (await packs.GetAsync(packId)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpGet("shared/{shareCode}")] + public async Task Shared(string shareCode) => (await packs.GetSharedAsync(shareCode)) + .Map(p => mapper.Map(p)).ToActionResult(); + + [HttpGet("/api/reactions/{reactionId:guid}")] + public async Task Reaction(Guid reactionId) => (await packs.GetReactionAsync(reactionId)) + .Map(r => mapper.Map(r)).ToActionResult(); + + [HttpPut("{packId:guid}/subscription")] + public async Task Subscribe(Guid packId) => + (await packs.SubscribeAsync(currentUser.GetCurrentUserId(), packId, true)).ToActionResult(); + + [HttpDelete("{packId:guid}/subscription")] + public async Task Unsubscribe(Guid packId) => + (await packs.SubscribeAsync(currentUser.GetCurrentUserId(), packId, false)).ToActionResult(); + + [HttpGet("limits")] + public IActionResult Limits() => Ok(new + { + maxDimension = ReactionMediaLimits.MaxDimension, maxUploadBytes = ReactionMediaLimits.MaxUploadBytes, + maxImageBytes = ReactionMediaLimits.MaxImageBytes, maxGifBytes = ReactionMediaLimits.MaxGifBytes, + maxFrames = ReactionMediaLimits.MaxFrames, maxDurationMilliseconds = ReactionMediaLimits.MaxDurationMilliseconds, + maxItemsPerPack = 100 + }); +} diff --git a/Govor.API/Controllers/SessionController.cs b/Govor.API/Controllers/SessionController.cs index a1d2b48..7e791f0 100644 --- a/Govor.API/Controllers/SessionController.cs +++ b/Govor.API/Controllers/SessionController.cs @@ -49,7 +49,7 @@ public class SessionController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -74,7 +74,7 @@ public class SessionController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -97,7 +97,7 @@ public class SessionController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -118,7 +118,7 @@ public class SessionController : Controller catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, ex.Message); - return Forbid(ex.Message); + return Forbid(); } catch (Exception ex) { @@ -126,4 +126,4 @@ public class SessionController : Controller return StatusCode(500, "Unexpected Error! Please try again later."); } } -} \ No newline at end of file +} diff --git a/Govor.API/Filters/HubExceptionFilter.cs b/Govor.API/Filters/HubExceptionFilter.cs index f11b6ef..b30a1b1 100644 --- a/Govor.API/Filters/HubExceptionFilter.cs +++ b/Govor.API/Filters/HubExceptionFilter.cs @@ -1,15 +1,19 @@ using Govor.Contracts.Responses.SignalR; using Microsoft.AspNetCore.SignalR; +using Govor.API.Common.Extensions; +using Govor.Domain; namespace Govor.API.Filters; public class HubExceptionFilter : IHubFilter { private readonly ILogger _logger; + private readonly GovorDbContext _context; - public HubExceptionFilter(ILogger logger) + public HubExceptionFilter(ILogger logger, GovorDbContext context) { _logger = logger; + _context = context; } public async ValueTask InvokeMethodAsync( @@ -18,6 +22,11 @@ public class HubExceptionFilter : IHubFilter { try { + if (!await _context.HasActiveSessionAsync(context.Context.User)) + { + context.Context.Abort(); + return CreateHubErrorResult(context, HubResultStatus.Unauthorized, "Session revoked or expired."); + } return await next(context); } catch (ArgumentException ex) @@ -66,10 +75,10 @@ public class HubExceptionFilter : IHubFilter hubResultType.GetProperty(nameof(HubResult.ErrorMessage))! .SetValue(errorResult, message); - return Task.FromResult(errorResult); + return errorResult; } } return null; } -} \ No newline at end of file +} diff --git a/Govor.API/Govor.API.csproj b/Govor.API/Govor.API.csproj index 468fa36..337c56d 100644 --- a/Govor.API/Govor.API.csproj +++ b/Govor.API/Govor.API.csproj @@ -9,7 +9,7 @@ - + @@ -34,7 +34,8 @@ - + + diff --git a/Govor.API/Hubs/ChatsHub.cs b/Govor.API/Hubs/ChatsHub.cs index 1f72d68..7bed53e 100644 --- a/Govor.API/Hubs/ChatsHub.cs +++ b/Govor.API/Hubs/ChatsHub.cs @@ -1,8 +1,12 @@ using Govor.API.Common.SignalR.Helpers; +using Govor.API.Common.Extensions; +using Govor.Contracts.Requests; using Govor.API.Hubs.Infrastructure; using Govor.Application.Exceptions.VerifyFriendship; using Govor.Application.Infrastructure.Common; using Govor.Application.Messages; +using Govor.Application.Reactions; +using AutoMapper; using Govor.Application.Messages.Parameters; using Govor.Contracts.Requests.SignalR; using Govor.Contracts.Responses.SignalR; @@ -24,6 +28,8 @@ public class ChatsHub : Hub private readonly IChatNotificationService _notifier; private readonly IConnectionManager _connectionManager; private readonly INowDateTimeProvider _nowDateTimeProvider; + private readonly IMessageReactionService _reactions; + private readonly IMapper _mapper; public ChatsHub(ILogger logger, IMessageReadingService messageReadingService, @@ -33,7 +39,9 @@ public class ChatsHub : Hub IHubUserAccessor userAccessor, IChatNotificationService notifier, INowDateTimeProvider nowDateTimeProvider, - IConnectionManager connectionManager) + IConnectionManager connectionManager, + IMessageReactionService reactions, + IMapper mapper) { _logger = logger; _nowDateTimeProvider = nowDateTimeProvider; @@ -44,6 +52,8 @@ public class ChatsHub : Hub _userAccessor = userAccessor; _notifier = notifier; _connectionManager = connectionManager; + _reactions = reactions; + _mapper = mapper; } public override async Task OnConnectedAsync() @@ -56,6 +66,12 @@ public class ChatsHub : Hub } await _connectionManager.OnConnectedAsync(Context.ConnectionId, userId); + if (!Guid.TryParse(Context.User?.FindFirst("sid")?.Value, out var sessionId)) + { + Context.Abort(); + return; + } + await Groups.AddToGroupAsync(Context.ConnectionId, ChatHubConstants.GetSessionGroup(sessionId)); _logger.LogInformation("User {UserId} connected", userId); await base.OnConnectedAsync(); } @@ -84,23 +100,25 @@ public class ChatsHub : Hub var result = await _messageSendingService.SendMessageAsync(sendParams); if (!result.IsSuccess) - throw new InvalidOperationException(result.Exception.Message ?? "Failed to send message"); + throw result.Exception ?? new InvalidOperationException("Failed to send message"); var response = MapToResponse(result.Message, request.ReplyToMessageId); await _notifier.NotifyMessageSentAsync(response); return HubResult.Ok(response); - }, request.RecipientId); + }, request?.RecipientId ?? Guid.Empty); } + // --- Read --- public async Task> Read(ReadMessageRequest request) { return await SafeExecute(async (userId) => { + ArgumentNullException.ThrowIfNull(request); var result = await _messageReadingService.ReadMessageAsync(userId, request.MessageId); if(!result.IsSuccess) - throw new InvalidOperationException(result.Error.ToString()); + return result.Error.ToHubResult(); var message = result.Value; @@ -119,13 +137,36 @@ public class ChatsHub : Hub await _notifier.NotifyMessageWasReadAsync(response); return HubResult.Ok(response); - }, request.MessageId); + }, request?.MessageId ?? Guid.Empty); } // --- REMOVE --- + public async Task> ReadChat(Guid chatId, ReadChatRequest request) + { + return await SafeExecute(async userId => + { + if (request is null) + return HubResult.BadRequest("Request is required."); + var result = await _messageReadingService.ReadChatAsync(userId, chatId, + request.RecipientType, request.MessageIds, request.UpToMessageId); + if (result.IsFailure) + return result.Error.ToHubResult(); + var read = result.Value; + var response = new ChatReadResponse + { + ChatId = read.ChatId, RecipientType = read.RecipientType, ReaderId = read.ReaderId, + ReadAt = read.ReadAt, UpToMessageId = read.UpToMessageId, UpToSentAt = read.UpToSentAt, + MessageIds = read.MessageIds, ReadCount = read.ReadCount, UnreadCount = read.UnreadCount + }; + await _notifier.NotifyChatReadAsync(response); + return HubResult.Ok(response); + }, chatId); + } + public async Task> Remove(RemoveMessageRequest request) { return await SafeExecute(async (userId) => { + ArgumentNullException.ThrowIfNull(request); var deletemessage = new DeleteMessage( userId, request.MessageId, @@ -140,7 +181,7 @@ public class ChatsHub : Hub var result = await _messageRemovingService.DeleteMessageAsync(deletemessage); if (!result.IsSuccess) - throw new InvalidOperationException(result.Error.ToString()); + return result.Error.ToHubResult(); var notification = new MessageRemovedResponse { @@ -154,7 +195,26 @@ public class ChatsHub : Hub await _notifier.NotifyMessageRemovedAsync(notification); return HubResult.Ok(notification); - }, request.MessageId); + }, request?.MessageId ?? Guid.Empty); + } + + public Task> React(Guid messageId, SetReactionRequest request) => + SafeExecute(async userId => + { + ArgumentNullException.ThrowIfNull(request); + return await ChangeReactionAsync(userId, messageId, request.ReactionId); + }, messageId); + + public Task> RemoveReaction(Guid messageId) => + SafeExecute(userId => ChangeReactionAsync(userId, messageId, null), messageId); + + private async Task> ChangeReactionAsync(Guid userId, Guid messageId, Guid? reactionId) + { + var result = await _reactions.SetAsync(userId, messageId, reactionId); + if (result.IsFailure) return result.Error.ToHubResult(); + var response = _mapper.Map(result.Value); + if (result.Value.Changed) await _notifier.NotifyMessageReactionsChangedAsync(response); + return HubResult.Ok(response); } // --- EDIT --- @@ -162,6 +222,7 @@ public class ChatsHub : Hub { return await SafeExecute(async (userId) => { + ArgumentNullException.ThrowIfNull(request); var editParams = new EditMessage( userId, request.MessageId, @@ -171,7 +232,7 @@ public class ChatsHub : Hub var result = await _messageEditingService.EditMessageAsync(editParams); if (!result.IsSuccess || result.OriginalMessage == null) - throw new InvalidOperationException("Edit message error"); + throw result.Exception ?? new InvalidOperationException("Edit message error"); var response = new MessageEditResponse { @@ -186,20 +247,21 @@ public class ChatsHub : Hub await _notifier.NotifyMessageEditedAsync(response); return HubResult.Ok(response); - }, request.MessageId); + }, request?.MessageId ?? Guid.Empty); } private async Task> SafeExecute(Func>> action, Guid targetIdForLog) { - var userId = _userAccessor.GetUserId(Context); + var userId = Guid.Empty; try { + userId = _userAccessor.GetUserId(Context); return await action(userId); } catch (UnauthorizedAccessException ex) { _logger.LogWarning(ex, "Unauthorized: {UserId} -> {TargetId}", userId, targetIdForLog); - return HubResult.Unauthorized("You are not authorized."); + return HubResult.Forbidden("You do not have permission to perform this action."); } catch (FriendshipException) { @@ -213,6 +275,10 @@ public class ChatsHub : Hub { return HubResult.NotFound("Resource not found."); } + catch (InvalidOperationException ex) + { + return HubResult.BadRequest(ex.Message); + } catch (Exception ex) { _logger.LogError(ex, "Error executing hub method for {UserId}", userId); @@ -222,12 +288,13 @@ public class ChatsHub : Hub private void ValidateMessageRequest(MessageRequest request) { + ArgumentNullException.ThrowIfNull(request); if (string.IsNullOrWhiteSpace(request.EncryptedContent) && (request.MediaAttachments == null || !request.MediaAttachments.Any())) { throw new ArgumentException("Message must contain content or media."); } - if (request.EncryptedContent.Length > 50_000) + if ((request.EncryptedContent?.Length ?? 0) > 50_000) { throw new ArgumentException("Message is too long."); } @@ -262,4 +329,4 @@ public class ChatsHub : Hub ReplyToMessageId = replyToId }; } -} \ No newline at end of file +} diff --git a/Govor.API/Hubs/FriendsHub.cs b/Govor.API/Hubs/FriendsHub.cs index cdd240d..34066bb 100644 --- a/Govor.API/Hubs/FriendsHub.cs +++ b/Govor.API/Hubs/FriendsHub.cs @@ -5,9 +5,11 @@ using Govor.Application.Friends; using Govor.Contracts.DTOs; using Govor.Contracts.Responses.SignalR; using Microsoft.AspNetCore.SignalR; +using Microsoft.AspNetCore.Authorization; namespace Govor.API.Hubs; +[Authorize(Roles = "Admin,User")] public class FriendsHub : Hub { private readonly ILogger _logger; @@ -194,4 +196,4 @@ public class FriendsHub : Hub return HubResult.Error("Unexpected error! Please try later!"); } } -} \ No newline at end of file +} diff --git a/Govor.API/Hubs/Infrastructure/ChatHubConstants.cs b/Govor.API/Hubs/Infrastructure/ChatHubConstants.cs index 945531f..31d8efe 100644 --- a/Govor.API/Hubs/Infrastructure/ChatHubConstants.cs +++ b/Govor.API/Hubs/Infrastructure/ChatHubConstants.cs @@ -7,8 +7,12 @@ public static class ChatHubConstants public const string MessageRemoved = "MessageRemoved"; public const string MessageEdited = "MessageEdited"; public static string MessageRead = "MessageReaded"; + public const string ChatRead = "ChatRead"; + public const string MessageReactionsChanged = "MessageReactionsChanged"; + public const string ChannelReactionPolicyChanged = "ChannelReactionPolicyChanged"; public static string GetUserGroup(Guid userId) => userId.ToString(); + public static string GetSessionGroup(Guid sessionId) => $"session_{sessionId}"; public static string GetChatGroup(Guid groupId) => $"group_{groupId}"; public static string GetPrivateChat(Guid groupId) => $"private_{groupId}"; -} \ No newline at end of file +} diff --git a/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs b/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs index fd5c04f..05e4c98 100644 --- a/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs +++ b/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs @@ -2,130 +2,161 @@ using Govor.Application.PrivateUserChats; using Govor.Application.Profiles; using Govor.Application.PushNotifications; using Govor.Contracts.Responses.SignalR; +using Govor.Domain; +using Govor.Domain.Common; using Govor.Domain.Models.Messages; using Microsoft.AspNetCore.SignalR; +using Microsoft.EntityFrameworkCore; namespace Govor.API.Hubs.Infrastructure; -public class ChatNotificationService : IChatNotificationService +public class ChatNotificationService : IChatNotificationService { private readonly IHubContext _hubContext; private readonly IPushNotificationService _notificationService; - private readonly IUserPrivateChatsGetterService _userPrivateChatsGetterService; - private readonly IProfileService _profileService; + private readonly IUserPrivateChatsGetterService _chats; + private readonly IProfileService _profiles; + private readonly GovorDbContext _context; + private readonly ILogger _logger; - public ChatNotificationService( - IHubContext hubContext, - IPushNotificationService notificationService, - IUserPrivateChatsGetterService userPrivateChatsGetterService, - IProfileService profileService) + public ChatNotificationService(IHubContext hubContext, + IPushNotificationService notificationService, IUserPrivateChatsGetterService chats, + IProfileService profiles, GovorDbContext context, ILogger logger) { _hubContext = hubContext; _notificationService = notificationService; - _userPrivateChatsGetterService = userPrivateChatsGetterService; - _profileService = profileService; + _chats = chats; + _profiles = profiles; + _context = context; + _logger = logger; } public async Task NotifyMessageSentAsync(UserMessageResponse message) { - if (message.RecipientType == RecipientType.User) + await TryNotifyAsync(() => NotifyParticipantsAsync(message.RecipientId, + message.RecipientType, ChatHubConstants.ReceiveMessage, message)); + await TryNotifyAsync(() => NotifyUsersAsync(new[] { message.SenderId }, ChatHubConstants.MessageSent, message)); + + } + + public async Task DeliverPushAsync(UserMessageResponse message) + { + try { - await _hubContext.Clients.Group(ChatHubConstants.GetPrivateChat(message.RecipientId)) - .SendAsync(ChatHubConstants.ReceiveMessage, message); - - await NotifyMessageReceivedInPrivateChatAsync(message); + List recipients; + if (message.RecipientType == RecipientType.User) + { + var result = await _chats.GetPrivateChatAsync(message.RecipientId); + if (result.IsFailure) + return result.Error.Type == ErrorType.NotFound; + recipients = new[] { result.Value.UserAId, result.Value.UserBId } + .Where(id => id != message.SenderId).Distinct().ToList(); + } + else + recipients = await _context.GroupMemberships.AsNoTracking() + .Where(m => m.GroupId == message.RecipientId && m.UserId != message.SenderId && !m.IsBanned) + .Select(m => m.UserId).Distinct().ToListAsync(); + + if (recipients.Count == 0) + return true; + var readers = await _context.MessageViews.AsNoTracking() + .Where(v => v.MessageId == message.MessageId).Select(v => v.UserId).ToListAsync(); + recipients = recipients.Except(readers).ToList(); + if (recipients.Count == 0) + return true; + var profile = await _profiles.GetUserProfileAsync(message.SenderId); + var title = profile.IsSuccess ? profile.Value.Username : "Govor"; + var content = message.EncryptedContent ?? string.Empty; + var body = content.Length == 0 ? "Attachment" : content[..Math.Min(40, content.Length)]; + var data = new Dictionary + { + ["chatId"] = message.RecipientId.ToString(), + ["messageId"] = message.MessageId.ToString(), + ["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false" + }; + var push = await _notificationService.SendToUsersAsync(recipients, title, body, + "chat_messages", $"chat_{message.RecipientId}", data); + if (push.IsFailure) + _logger.LogWarning("Push failed for message {MessageId}: {Error}", + message.MessageId, push.Error); + return push.IsSuccess; } - else + catch (Exception ex) { - await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(message.RecipientId)) - .SendAsync(ChatHubConstants.ReceiveMessage, message); + _logger.LogError(ex, "Failed to deliver push for message {MessageId}", message.MessageId); + return false; } - - // await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(message.SenderId)) - // .SendAsync(ChatHubConstants.MessageSent, message); } public async Task NotifyMessageWasReadAsync(MessageReadResponse response) { - await NotifyParticipantsAsync( - response.ReaderId, - response.RecipientId, - response.RecipientType, - ChatHubConstants.MessageRead, - response); + // Keep the existing wire name for old clients; new clients can use MessageRead. + await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId, + response.RecipientType, ChatHubConstants.MessageRead, response)); + await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId, + response.RecipientType, "MessageRead", response)); } - private async Task NotifyMessageReceivedInPrivateChatAsync(UserMessageResponse message) - { - - var result = await _userPrivateChatsGetterService.GetPrivateChatAsync(message.RecipientId); - - if(result.IsFailure) - return; - var privateChat = result.Value; - - var text = message.EncryptedContent.Substring(0, Math.Min(40, message.EncryptedContent.Length)); - var userId = message.SenderId == privateChat.UserAId ? privateChat.UserBId : privateChat.UserAId; - - var resultProf = await _profileService.GetUserProfileAsync(message.SenderId); - - if(resultProf.IsFailure) - return; - var profile = resultProf.Value; - - var title = profile.Username; - Dictionary data = new Dictionary(); - - data["chatId"] = message.RecipientId.ToString(); - data["isGroup"] = message.RecipientType == RecipientType.Group ? "true" : "false"; - - await _notificationService.SendToUserAsync( - userId, - title, - text, - "chat_messages", - $"private_chat_{message.RecipientId}", - data); - } - - public async Task NotifyMessageRemovedAsync(MessageRemovedResponse response) - { - await NotifyParticipantsAsync( - response.SenderId, - response.RecipientId, - response.RecipientType, - ChatHubConstants.MessageRemoved, - response); - } + public Task NotifyChatReadAsync(ChatReadResponse response) => + TryNotifyAsync(() => NotifyParticipantsAsync(response.ChatId, + response.RecipientType, ChatHubConstants.ChatRead, response)); - public async Task NotifyMessageEditedAsync(MessageEditResponse response) - { - await NotifyParticipantsAsync( - response.EditorId, - response.RecipientId, - response.RecipientType, - ChatHubConstants.MessageEdited, - response); - } - - private async Task NotifyParticipantsAsync(Guid initiatorId, Guid targetId, RecipientType type, string method, object payload) + public Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response) => + TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId, + response.RecipientType, ChatHubConstants.MessageReactionsChanged, response)); + + public Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response) => + TryNotifyAsync(() => NotifyParticipantsAsync(response.GroupId, + RecipientType.Group, ChatHubConstants.ChannelReactionPolicyChanged, response)); + + public Task NotifyMessageRemovedAsync(MessageRemovedResponse response) => + TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId, + response.RecipientType, ChatHubConstants.MessageRemoved, response)); + + public Task NotifyMessageEditedAsync(MessageEditResponse response) => + TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId, + response.RecipientType, ChatHubConstants.MessageEdited, response)); + + private async Task NotifyParticipantsAsync(Guid chatId, RecipientType type, string method, object payload) { + // Resolve current participants instead of treating a chat ID as a user ID. + // Deliver only to active sessions, including all of a participant's devices. + List participants; if (type == RecipientType.User) { - await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(initiatorId)) - .SendAsync(method, payload); - - if (initiatorId != targetId) - { - await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(targetId)) - .SendAsync(method, payload); - } + var result = await _chats.GetPrivateChatAsync(chatId); + if (result.IsFailure) + return; + participants = new[] { result.Value.UserAId, result.Value.UserBId }.Distinct().ToList(); } else - { - // to groups - await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(targetId)) + participants = await _context.GroupMemberships.AsNoTracking() + .Where(m => m.GroupId == chatId && !m.IsBanned).Select(m => m.UserId).Distinct().ToListAsync(); + + if (participants.Count > 0) + await NotifyUsersAsync(participants, method, payload); + } + + private async Task NotifyUsersAsync(IEnumerable users, string method, object payload) + { + var now = DateTime.UtcNow; + var sessions = await _context.UserSessions.AsNoTracking() + .Where(s => users.Contains(s.UserId) && !s.IsRevoked && s.ExpiresAt > now) + .Select(s => s.Id).ToListAsync(); + if (sessions.Count > 0) + await _hubContext.Clients.Groups(sessions.Select(ChatHubConstants.GetSessionGroup).ToList()) .SendAsync(method, payload); + } + + private async Task TryNotifyAsync(Func notify) + { + try + { + await notify(); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to deliver chat notification; clients can resync from history."); } } -} \ No newline at end of file +} diff --git a/Govor.API/Hubs/Infrastructure/ChatPushDispatcher.cs b/Govor.API/Hubs/Infrastructure/ChatPushDispatcher.cs new file mode 100644 index 0000000..ea98f4f --- /dev/null +++ b/Govor.API/Hubs/Infrastructure/ChatPushDispatcher.cs @@ -0,0 +1,51 @@ +using Govor.Application.Infrastructure.Common; +using Govor.Contracts.Responses.SignalR; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; + +namespace Govor.API.Hubs.Infrastructure; + +public class ChatPushDispatcher(GovorDbContext context, IChatNotificationService notifier, + INowDateTimeProvider dateTimeProvider) +{ + public async Task DispatchAsync(CancellationToken cancellationToken = default) + { + var now = dateTimeProvider.Now; + var pending = await context.ChatPushNotifications.AsNoTracking() + .Where(n => n.NextAttemptAt <= now).OrderBy(n => n.NextAttemptAt) + .Take(20).Select(n => n.MessageId).ToListAsync(cancellationToken); + + foreach (var id in pending) + { + cancellationToken.ThrowIfCancellationRequested(); + // Conditional update claims a two-minute lease, including across server instances. + // An interrupted worker leaves a retryable row rather than losing the notification. + var claimed = await context.ChatPushNotifications + .Where(n => n.MessageId == id && n.NextAttemptAt <= now) + .ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, now.AddMinutes(2)) + .SetProperty(n => n.Attempts, n => n.Attempts + 1), cancellationToken); + if (claimed == 0) + continue; + + var message = await context.Messages.AsNoTracking() + .Where(m => m.Id == id).Select(m => new UserMessageResponse + { + MessageId = m.Id, SenderId = m.SenderId, RecipientId = m.RecipientId, + RecipientType = m.RecipientType, EncryptedContent = m.EncryptedContent, + SentAt = m.SentAt, ReplyToMessageId = m.ReplyToMessageId + }).FirstOrDefaultAsync(cancellationToken); + var delivered = message is null || await notifier.DeliverPushAsync(message); + if (delivered) + await context.ChatPushNotifications.Where(n => n.MessageId == id) + .ExecuteDeleteAsync(cancellationToken); + else + { + var attempts = await context.ChatPushNotifications.Where(n => n.MessageId == id) + .Select(n => n.Attempts).FirstOrDefaultAsync(cancellationToken); + var retryAt = dateTimeProvider.Now.AddSeconds(Math.Min(300, Math.Pow(2, Math.Min(attempts, 9)))); + await context.ChatPushNotifications.Where(n => n.MessageId == id) + .ExecuteUpdateAsync(s => s.SetProperty(n => n.NextAttemptAt, retryAt), cancellationToken); + } + } + } +} diff --git a/Govor.API/Hubs/Infrastructure/ChatPushWorker.cs b/Govor.API/Hubs/Infrastructure/ChatPushWorker.cs new file mode 100644 index 0000000..5e0e878 --- /dev/null +++ b/Govor.API/Hubs/Infrastructure/ChatPushWorker.cs @@ -0,0 +1,33 @@ +namespace Govor.API.Hubs.Infrastructure; + +public class ChatPushWorker(IServiceScopeFactory scopeFactory, ILogger logger) : BackgroundService +{ + protected override async Task ExecuteAsync(CancellationToken stoppingToken) + { + while (!stoppingToken.IsCancellationRequested) + { + try + { + using var scope = scopeFactory.CreateScope(); + await scope.ServiceProvider.GetRequiredService().DispatchAsync(stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + catch (Exception ex) + { + logger.LogError(ex, "Chat push dispatch failed; pending notifications will be retried."); + } + + try + { + await Task.Delay(TimeSpan.FromSeconds(2), stoppingToken); + } + catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) + { + break; + } + } + } +} diff --git a/Govor.API/Hubs/Infrastructure/IChatNotificationService.cs b/Govor.API/Hubs/Infrastructure/IChatNotificationService.cs index 49b8d78..6bafacf 100644 --- a/Govor.API/Hubs/Infrastructure/IChatNotificationService.cs +++ b/Govor.API/Hubs/Infrastructure/IChatNotificationService.cs @@ -5,7 +5,11 @@ namespace Govor.API.Hubs.Infrastructure; public interface IChatNotificationService { Task NotifyMessageSentAsync(UserMessageResponse message); + Task DeliverPushAsync(UserMessageResponse message); Task NotifyMessageWasReadAsync(MessageReadResponse response); + Task NotifyChatReadAsync(ChatReadResponse response); + Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response); + Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response); Task NotifyMessageRemovedAsync(MessageRemovedResponse response); Task NotifyMessageEditedAsync(MessageEditResponse response); -} \ No newline at end of file +} diff --git a/Govor.API/Hubs/ProfileHub.cs b/Govor.API/Hubs/ProfileHub.cs index fdf531b..fac111c 100644 --- a/Govor.API/Hubs/ProfileHub.cs +++ b/Govor.API/Hubs/ProfileHub.cs @@ -1,5 +1,6 @@ using Govor.API.Common.SignalR.Helpers; using Govor.Application.Friends; +using Govor.API.Common.Extensions; using Govor.Application.Medias; using Govor.Application.Profiles; using Govor.Application.Synching; @@ -101,9 +102,11 @@ public sealed class ProfileHub : Hub try { - await _profileService.SetDescription( + var result = await _profileService.SetDescription( description, userId); + if (result.IsFailure) + return result.Error.ToHubResult(); var payload = new DescriptionUpdatePayload { @@ -146,9 +149,11 @@ public sealed class ProfileHub : Hub return HubResult.BadRequest( "Invalid icon id."); - await _profileService.SetNewIcon( + var result = await _profileService.SetNewIcon( userId, iconId); + if (result.IsFailure) + return result.Error.ToHubResult(); var payload = new AvatarUpdatePayload { @@ -265,4 +270,4 @@ public sealed class ProfileHub : Hub { return $"{UserGroupPrefix}{userId}"; } -} \ No newline at end of file +} diff --git a/Govor.API/Program.cs b/Govor.API/Program.cs index d28cc98..3c2032e 100644 --- a/Govor.API/Program.cs +++ b/Govor.API/Program.cs @@ -1,4 +1,4 @@ -using System.Text; +using System.Text; using FirebaseAdmin; using Google.Apis.Auth.OAuth2; using Govor.API.Common.Extensions; @@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi; +using Govor.Domain; var builder = WebApplication.CreateBuilder(args); @@ -18,23 +19,23 @@ builder.AddLogger();// Serilog builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true); -#if DEBUG -builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); -//builder.Configuration.AddJsonFile("appsettings.Development.json", optional: false, reloadOnChange: true); -#else -builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); -#endif -FirebaseApp.Create(new AppOptions() +if (configuration.GetValue("Firebase:Enabled", true)) { - Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json") -}); + FirebaseApp.Create(new AppOptions() + { + Credential = GoogleCredential.FromFile("secrets/firebase-adminsdk.json") + }); +} builder.Services.AddCors(options => { options.AddPolicy("AllowFrontend", policy => { - policy.SetIsOriginAllowed(_ => true) + var origins = configuration.GetSection("Cors:AllowedOrigins").Get() ?? []; + if (origins.Length > 0) + policy.WithOrigins(origins); + policy .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); @@ -60,6 +61,12 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) }; options.Events = new JwtBearerEvents { + OnTokenValidated = async context => + { + var db = context.HttpContext.RequestServices.GetRequiredService(); + if (!await db.HasActiveSessionAsync(context.Principal)) + context.Fail("The access session is invalid or revoked."); + }, OnMessageReceived = context => { var accessToken = context.Request.Query["access_token"]; @@ -110,25 +117,24 @@ services.AddSwaggerGen(options => //builder.Services.AddOpenApi(); -var app = builder.Build(); - -// Configure the HTTP request pipeline. -if (!app.Environment.IsDevelopment()) +if (!builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["urls"]) && + string.IsNullOrWhiteSpace(configuration["HTTP_PORTS"])) { - //app.MapOpenApi(); builder.WebHost.UseUrls("http://0.0.0.0:8080"); - //builder.WebHost.UseUrls("http://10.8.0.5:5000"); - //builder.WebHost.UseUrls("http://192.168.1.107:8080"); } -app.UseSwagger(); -app.UseSwaggerUI(); +var app = builder.Build(); -app.UseCors("AllowFrontend"); +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} //app.UseHttpsRedirection(); app.UseRouting(); +app.UseCors("AllowFrontend"); app.UseAuthentication(); app.UseAuthorization(); @@ -136,16 +142,18 @@ app.UseAuthorization(); app.MapControllers(); app.MapGet("/server/ping", - () => new OkResult()); + () => Results.Ok()); -app.MapHub("/hubs/chats"); -app.MapHub("/hubs/friends"); -app.MapHub("/hubs/profiles"); -app.MapHub("/hubs/presence"); +app.MapHub("/hubs/chats", options => options.CloseOnAuthenticationExpiration = true); +app.MapHub("/hubs/friends", options => options.CloseOnAuthenticationExpiration = true); +app.MapHub("/hubs/profiles", options => options.CloseOnAuthenticationExpiration = true); +app.MapHub("/hubs/presence", options => options.CloseOnAuthenticationExpiration = true); app.MapSwagger() .RequireAuthorization(); app.Map("/", () => "Not for browsers"); -app.Run(); \ No newline at end of file +app.Run(); + +public partial class Program { } diff --git a/Govor.Application/Authentication/JWT/JwtService.cs b/Govor.Application/Authentication/JWT/JwtService.cs index 8938b32..240addb 100644 --- a/Govor.Application/Authentication/JWT/JwtService.cs +++ b/Govor.Application/Authentication/JWT/JwtService.cs @@ -26,6 +26,7 @@ public class JwtService : IJwtService { new Claim("userId", user.Id.ToString()), new Claim("sid", sessionId.ToString()), + new Claim("tokenType", "access"), new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user)) //new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String) }; @@ -50,7 +51,8 @@ public class JwtService : IJwtService var claims = new[] { new Claim("userId", user.Id.ToString()), - new Claim("tokenType", "refresh") + new Claim("tokenType", "refresh"), + new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var token = new JwtSecurityToken( @@ -82,4 +84,4 @@ public class JwtService : IJwtService return principal; } -} \ No newline at end of file +} diff --git a/Govor.Application/Govor.Application.csproj b/Govor.Application/Govor.Application.csproj index 78d9a3a..7f18399 100644 --- a/Govor.Application/Govor.Application.csproj +++ b/Govor.Application/Govor.Application.csproj @@ -11,6 +11,7 @@ + diff --git a/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs b/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs index 0f4d982..b3c222f 100644 --- a/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs +++ b/Govor.Application/Infrastructure/AdminsStuff/UsersService.cs @@ -34,6 +34,13 @@ public class UsersService : IUsersAdministration user.PasswordHash = _passwordHasher.Hash(password); + var sessions = await _context.UserSessions.Where(s => s.UserId == userId && !s.IsRevoked).ToListAsync(); + foreach (var session in sessions) + session.IsRevoked = true; + var pushTokens = await _context.UserPushTokens.Where(t => t.UserId == userId).ToListAsync(); + foreach (var token in pushTokens) + token.IsActive = false; + await _context.SaveChangesAsync(); } @@ -43,4 +50,4 @@ public class UsersService : IUsersAdministration return result; } -} \ No newline at end of file +} diff --git a/Govor.Application/Medias/AccesserToDownloadMediaService.cs b/Govor.Application/Medias/AccesserToDownloadMediaService.cs index 6fee042..7f9f962 100644 --- a/Govor.Application/Medias/AccesserToDownloadMediaService.cs +++ b/Govor.Application/Medias/AccesserToDownloadMediaService.cs @@ -1,6 +1,7 @@ using Govor.Domain.Models; using Govor.Domain; using Microsoft.EntityFrameworkCore; +using Govor.Domain.Models.Messages; namespace Govor.Application.Medias; @@ -28,20 +29,23 @@ public class AccesserToDownloadMediaService : IAccesserToDownloadMedia { MediaOwnerType.Avatar => true, // media.OwnerId == userId MediaOwnerType.GroupAvatar => await _dbContext.GroupMemberships - .AnyAsync(gm => gm.GroupId == media.OwnerId && gm.UserId == userId), + .AnyAsync(gm => gm.GroupId == media.OwnerId && gm.UserId == userId && !gm.IsBanned), MediaOwnerType.Message => await _dbContext.MediaAttachments .AnyAsync(ma => ma.MediaFileId == mediaId && ( - ma.Message.SenderId == userId || - ma.Message.RecipientId == userId || - _dbContext.GroupMemberships.Any(gm => - gm.GroupId == ma.Message.RecipientId && gm.UserId == userId) + (ma.Message.RecipientType == RecipientType.User && + _dbContext.PrivateChats.Any(c => c.Id == ma.Message.RecipientId && + (c.UserAId == userId || c.UserBId == userId))) || + (ma.Message.RecipientType == RecipientType.Group && + _dbContext.GroupMemberships.Any(gm => + gm.GroupId == ma.Message.RecipientId && gm.UserId == userId && !gm.IsBanned)) )), MediaOwnerType.System => true, + MediaOwnerType.Reaction => await _dbContext.ReactionItems.AnyAsync(r => r.MediaFileId == mediaId), _ => false }; } -} \ No newline at end of file +} diff --git a/Govor.Application/Medias/MediaService.cs b/Govor.Application/Medias/MediaService.cs index bc75350..202addb 100644 --- a/Govor.Application/Medias/MediaService.cs +++ b/Govor.Application/Medias/MediaService.cs @@ -100,7 +100,7 @@ public class MediaService : IMediaService } // Загрузить бинарные данные из хранилища - Stream dataStream = await _storageService.LoadAsync(mediaFile.Url); + await using Stream dataStream = await _storageService.LoadAsync(mediaFile.Url); // Считать поток в byte[] using var memoryStream = new MemoryStream(); @@ -174,4 +174,4 @@ public class MediaService : IMediaService return new Unit(); } -} \ No newline at end of file +} diff --git a/Govor.Application/Messages/ChatAccess.cs b/Govor.Application/Messages/ChatAccess.cs new file mode 100644 index 0000000..11050b1 --- /dev/null +++ b/Govor.Application/Messages/ChatAccess.cs @@ -0,0 +1,24 @@ +using Govor.Domain; +using Govor.Domain.Models.Messages; +using Microsoft.EntityFrameworkCore; + +namespace Govor.Application.Messages; + +public static class ChatAccess +{ + public static Task HasChatAccessAsync(this GovorDbContext context, + Guid userId, Guid chatId, RecipientType type) + { + if (userId == Guid.Empty || chatId == Guid.Empty) + return Task.FromResult(false); + + return type switch + { + RecipientType.User => context.PrivateChats.AnyAsync(c => c.Id == chatId && + (c.UserAId == userId || c.UserBId == userId)), + RecipientType.Group => context.GroupMemberships.AnyAsync(m => + m.GroupId == chatId && m.UserId == userId && !m.IsBanned), + _ => Task.FromResult(false) + }; + } +} diff --git a/Govor.Application/Messages/IMessageReadingService.cs b/Govor.Application/Messages/IMessageReadingService.cs index 71a8ffd..df2e63d 100644 --- a/Govor.Application/Messages/IMessageReadingService.cs +++ b/Govor.Application/Messages/IMessageReadingService.cs @@ -1,10 +1,14 @@ using Govor.Domain.Common; using Govor.Domain.Models.Messages; using SmartRes; +using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult; namespace Govor.Application.Messages; public interface IMessageReadingService { Task> ReadMessageAsync(Guid readerId, Guid messageId); -} \ No newline at end of file + Task> ReadChatAsync(Guid readerId, Guid chatId, + RecipientType type, IReadOnlyCollection? messageIds = null, Guid? upToMessageId = null); + Task> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type); +} diff --git a/Govor.Application/Messages/MessageEditingService.cs b/Govor.Application/Messages/MessageEditingService.cs index 4dd6a98..eab2526 100644 --- a/Govor.Application/Messages/MessageEditingService.cs +++ b/Govor.Application/Messages/MessageEditingService.cs @@ -37,7 +37,8 @@ public class MessageEditingService : IMessageEditingService null); } - if (message.SenderId != editParams.EditorId) + if (message.SenderId != editParams.EditorId || !await _dbContext.HasChatAccessAsync( + editParams.EditorId, message.RecipientId, message.RecipientType)) { _logger.LogWarning( "User {EditorId} unauthorized to edit message {MessageId}", @@ -52,7 +53,7 @@ public class MessageEditingService : IMessageEditingService } // Проверяем время, прошедшее с момента отправки - var now = DateTime.UtcNow; + var now = editParams.EditedAt; var editDeadline = message.SentAt.AddMinutes( _options.MaxEditTimeMinutes); @@ -83,6 +84,10 @@ public class MessageEditingService : IMessageEditingService MediaAttachments = message.MediaAttachments?.ToList() ?? [] }; + if (editParams.NewContent is null || editParams.NewContent.Length > 50_000 || + (string.IsNullOrWhiteSpace(editParams.NewContent) && message.MediaAttachments.Count == 0)) + return new EditMessageResult(false, new ArgumentException("Invalid message content."), null); + message.EncryptedContent = editParams.NewContent; message.IsEdited = true; message.EditedAt = editParams.EditedAt; @@ -98,4 +103,4 @@ public class MessageEditingService : IMessageEditingService null, originalMessageSnapshot); } -} \ No newline at end of file +} diff --git a/Govor.Application/Messages/MessageReadingService.cs b/Govor.Application/Messages/MessageReadingService.cs index cd9d1c5..ad61832 100644 --- a/Govor.Application/Messages/MessageReadingService.cs +++ b/Govor.Application/Messages/MessageReadingService.cs @@ -1,4 +1,5 @@ using Govor.Application.Infrastructure.Common; +using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult; using Govor.Domain; using Govor.Domain.Common; using Govor.Domain.Models.Messages; @@ -14,10 +15,7 @@ public class MessageReadingService : IMessageReadingService private readonly ILogger _logger; private readonly INowDateTimeProvider _dateTimeProvider; - - public MessageReadingService( - GovorDbContext dbContext, - ILogger logger, + public MessageReadingService(GovorDbContext dbContext, ILogger logger, INowDateTimeProvider dateTimeProvider) { _dbContext = dbContext; @@ -27,46 +25,127 @@ public class MessageReadingService : IMessageReadingService public async Task> ReadMessageAsync(Guid readerId, Guid messageId) { - var message = await _dbContext.Messages - .Include(msg => msg.MessageViews) - .FirstOrDefaultAsync(msg => msg.Id == messageId); - - if(message is null) - return Result.Failure(Error.NotFound( - "Message not found", - "Message with id: " + messageId + " was not found.") - ); + var message = await _dbContext.Messages.AsNoTracking() + .FirstOrDefaultAsync(m => m.Id == messageId); + if (message is null) + return Result.Failure(Error.NotFound("Message.NotFound", "Message not found.")); - if (CanReadMessage(readerId, message)) - { - var view = new MessageView() - { - Id = Guid.NewGuid(), - MessageId = messageId, - UserId = readerId, - ViewedAt = _dateTimeProvider.Now, - }; - - _dbContext.MessageViews.Add(view); - - await _dbContext.SaveChangesAsync(); - - _logger.LogInformation("Message with id: {Id} was read by user {user} at {time}", view.Id, view.UserId, view.ViewedAt); - } - - return message; + var result = await ReadChatAsync(readerId, message.RecipientId, + message.RecipientType, new[] { messageId }); + if (result.IsFailure) + return Result.Failure(result.Error); + + // Fresh query also returns the existing receipt on repeated calls. + var readMessage = await _dbContext.Messages.AsNoTracking().Include(m => m.MessageViews) + .FirstOrDefaultAsync(m => m.Id == messageId); + return readMessage is null + ? Result.Failure(Error.NotFound("Message.NotFound", "Message was removed.")) + : Result.Success(readMessage); } - private bool CanReadMessage(Guid readerId, Message message) + public async Task> ReadChatAsync(Guid readerId, Guid chatId, + RecipientType type, IReadOnlyCollection? messageIds = null, Guid? upToMessageId = null) { - if (message.RecipientType == RecipientType.User) + if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type)) + return Result.Failure(Denied()); + + if (messageIds is not null && (messageIds.Count == 0 || messageIds.Count > 100 || + messageIds.Contains(Guid.Empty) || upToMessageId.HasValue)) + return Result.Failure(Error.Validation("Message.Read.InvalidSelection", + "Provide 1 to 100 message IDs or an inclusive message boundary, not both.")); + + var chat = _dbContext.Messages.AsNoTracking() + .Where(m => m.RecipientId == chatId && m.RecipientType == type); + Guid[]? ids = messageIds?.Distinct().ToArray(); + Message? boundary = null; + if (ids is not null) { - return _dbContext.PrivateChats.Any(pr => pr.UserAId == readerId || pr.UserBId == readerId) && - message.MessageViews.All(mv => mv.UserId != readerId); + // Validate the whole selection before writing any receipt. + if (await chat.CountAsync(m => ids.Contains(m.Id)) != ids.Length) + return Result.Failure(Error.NotFound("Message.Read.InvalidSelection", + "One or more messages do not belong to this chat.")); + if (await chat.AnyAsync(m => ids.Contains(m.Id) && m.SenderId == readerId)) + return Result.Failure(Error.Validation("Message.Read.OwnMessage", + "Only incoming messages can be marked as read.")); } else { - return false; + boundary = upToMessageId.HasValue + ? await chat.FirstOrDefaultAsync(m => m.Id == upToMessageId.Value) + : await chat.OrderByDescending(m => m.SentAt).ThenByDescending(m => m.Id) + .FirstOrDefaultAsync(); + if (upToMessageId.HasValue && boundary is null) + return Result.Failure(Error.NotFound("Message.Read.BoundaryNotFound", + "The boundary message does not belong to this chat.")); } + + var readAt = _dateTimeProvider.Now; + var readCount = 0; + var selected = chat.Where(m => m.SenderId != readerId); + if (ids is not null) + selected = selected.Where(m => ids.Contains(m.Id)); + else if (boundary is not null) + { + var sentAt = boundary.SentAt; + var id = boundary.Id; + selected = selected.Where(m => m.SentAt < sentAt || + (m.SentAt == sentAt && m.Id.CompareTo(id) <= 0)); + } + else + selected = selected.Where(m => false); + + // Small bounded batches; PostgreSQL/SQLite ON CONFLICT handles concurrent devices + // against the existing unique (MessageId, UserId) index without losing receipts. + while (true) + { + var pending = await selected.Where(m => !_dbContext.MessageViews + .Any(v => v.MessageId == m.Id && v.UserId == readerId)) + .Select(m => m.Id).Take(200).ToListAsync(); + if (pending.Count == 0) + break; + + var values = new List(); + var parameters = new List(); + using var command = _dbContext.Database.GetDbConnection().CreateCommand(); + foreach (var id in pending) + { + var names = new List(); + foreach (var value in new object[] { Guid.NewGuid(), id, readerId, readAt }) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = "p" + parameters.Count; + parameter.Value = value; + parameters.Add(parameter); + names.Add("@" + parameter.ParameterName); + } + values.Add("SELECT " + string.Join(", ", names) + + " WHERE EXISTS (SELECT 1 FROM \"Messages\" WHERE \"Id\" = " + names[1] + ")"); + } + var sql = "INSERT INTO \"MessageViews\" (\"Id\", \"MessageId\", \"UserId\", \"ViewedAt\") " + + string.Join(" UNION ALL ", values) + " ON CONFLICT (\"MessageId\", \"UserId\") DO NOTHING"; + readCount += await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters); + } + + var unreadCount = await CountUnreadAsync(readerId, chat); + _logger.LogInformation("User {ReaderId} marked {Count} messages read in chat {ChatId}", + readerId, readCount, chatId); + return new ChatReadResult(chatId, type, readerId, readAt, + boundary?.Id, boundary?.SentAt, ids, readCount, unreadCount); } -} \ No newline at end of file + + public async Task> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type) + { + if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type)) + return Result.Failure(Denied()); + + return await CountUnreadAsync(readerId, _dbContext.Messages.AsNoTracking() + .Where(m => m.RecipientId == chatId && m.RecipientType == type)); + } + + private Task CountUnreadAsync(Guid readerId, IQueryable chat) => + chat.CountAsync(m => m.SenderId != readerId && + !_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId)); + + private static Error Denied() => Error.Forbidden("Chat.AccessDenied", + "You are not a member of this chat."); +} diff --git a/Govor.Application/Messages/MessageRemovingService.cs b/Govor.Application/Messages/MessageRemovingService.cs index c0d9a78..7ea7dd7 100644 --- a/Govor.Application/Messages/MessageRemovingService.cs +++ b/Govor.Application/Messages/MessageRemovingService.cs @@ -1,4 +1,4 @@ -using Govor.Application.Messages.Parameters; +using DeleteMessage = Govor.Application.Messages.Parameters.DeleteMessage; using Govor.Domain; using Govor.Domain.Common; using Govor.Domain.Models.Messages; @@ -13,75 +13,38 @@ public class MessageRemovingService : IMessageRemovingService private readonly GovorDbContext _govorDbContext; private readonly ILogger _logger; - public MessageRemovingService - (GovorDbContext govorDbContext, - ILogger logger) + public MessageRemovingService(GovorDbContext govorDbContext, ILogger logger) { _govorDbContext = govorDbContext; _logger = logger; } - public async Task> DeleteMessageAsync(DeleteMessage deleteParams) + public async Task> DeleteMessageAsync(DeleteMessage deleteParams) { - var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId); - - if (message == null) - return Result.Failure( - Error.NotFound( - "MessageRemoving", - "Message with given id doesn't exist") - ); + var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId); + if (message is null) + return Result.Failure(Error.NotFound("Message.NotFound", "Message not found.")); - var result = message.RecipientType switch - { - RecipientType.Group => await ValidateGroupRecipientAsync(message, deleteParams), - RecipientType.User => await ValidateUserRecipientAsync(message, deleteParams), - - _ => Result.Failure(Error.Failure( - "MessageRemoving.ArgumentOutOfRangeException", - $"Argument out of range: {nameof(message.RecipientType)}" - ) - ) - }; - - return result; - } + if (!await _govorDbContext.HasChatAccessAsync(deleteParams.DeleterId, + message.RecipientId, message.RecipientType)) + return Result.Failure(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat.")); - private async Task> ValidateGroupRecipientAsync(Message message, DeleteMessage deleteParams) - { - if (deleteParams.DeleterId == message.RecipientId) - { - return await ForceRemoveAsync(message); - } - else - { - // TODO made admin rules - return Result.Failure(Error.Failure("MessageRemoving.HaveNoPermission", - $"You do not have permission to delete message {message.Id}" - )); - } - } + // Do not silently turn a local hide into deletion for everyone. + if (!deleteParams.ForceRemove) + return Result.Failure(Error.Validation("Message.HideNotSupported", + "HideForMe is not supported. Use ForceRemove to delete a message for everyone.")); - private async Task> ValidateUserRecipientAsync(Message message, DeleteMessage deleteParams) - { - if (deleteParams.DeleterId == message.SenderId) - { - return await ForceRemoveAsync(message); - } - else - { - // TODO made hide rules - return Result.Failure(Error.Failure("MessageRemoving.HaveNoPermission", - $"You do not have permission to delete message {message.Id}" - )); - } - } + var canDelete = message.SenderId == deleteParams.DeleterId || + (message.RecipientType == RecipientType.Group && + await _govorDbContext.GroupAdmins.AnyAsync(a => + a.GroupId == message.RecipientId && a.UserId == deleteParams.DeleterId)); + if (!canDelete) + return Result.Failure(Error.Forbidden("Message.Remove.AccessDenied", + "Only the author or a group administrator can delete this message.")); - private async Task> ForceRemoveAsync(Message message) - { _govorDbContext.Messages.Remove(message); await _govorDbContext.SaveChangesAsync(); - + _logger.LogInformation("Message {MessageId} removed by {UserId}", message.Id, deleteParams.DeleterId); return message; } -} \ No newline at end of file +} diff --git a/Govor.Application/Messages/MessageSendingService.cs b/Govor.Application/Messages/MessageSendingService.cs index b6c318b..c94a833 100644 --- a/Govor.Application/Messages/MessageSendingService.cs +++ b/Govor.Application/Messages/MessageSendingService.cs @@ -2,6 +2,7 @@ using Govor.Application.Messages.Parameters; using Microsoft.EntityFrameworkCore; using Govor.Domain; using Govor.Domain.Models.Messages; +using Govor.Domain.Models; using Microsoft.Extensions.Logging; namespace Govor.Application.Messages; @@ -19,9 +20,14 @@ public class MessageSendingService : IMessageSendingService public async Task SendMessageAsync(SendMessage sendParams) { + var media = sendParams.Media?.ToArray() ?? []; + if ((string.IsNullOrWhiteSpace(sendParams.EncryptContent) && media.Length == 0) || + (sendParams.EncryptContent?.Length ?? 0) > 50_000 || media.Length > 100) + return new SendMessageResult(false, new ArgumentException("Invalid message content or attachment count."), default); + var validationResult = sendParams.RecipientType switch { - RecipientType.User => await ValidateUserRecipientAsync(sendParams.RecipientId), + RecipientType.User => await ValidateUserRecipientAsync(sendParams.FromUserId, sendParams.RecipientId), RecipientType.Group => await ValidateGroupRecipientAsync(sendParams.FromUserId, sendParams.RecipientId), _ => (Success: false, Error: "Invalid recipient type.") }; @@ -29,9 +35,20 @@ public class MessageSendingService : IMessageSendingService if (!validationResult.Success) { _logger.LogWarning("Message send failed: {Error}", validationResult.Error); - return new SendMessageResult(false, new InvalidOperationException(validationResult.Error), default); + return new SendMessageResult(false, new UnauthorizedAccessException(validationResult.Error), default); } + var mediaIds = media.Select(m => m.MediaId).Distinct().ToArray(); + var files = await _dbContext.MediaFiles.Where(m => mediaIds.Contains(m.Id) && + m.UploaderId == sendParams.FromUserId && m.OwnerType == MediaOwnerType.Message).ToListAsync(); + if (files.Count != mediaIds.Length) + return new SendMessageResult(false, new UnauthorizedAccessException("Invalid media ownership."), default); + + if (sendParams.ReplyToMessageId.HasValue && !await _dbContext.Messages.AnyAsync(m => + m.Id == sendParams.ReplyToMessageId && m.RecipientId == sendParams.RecipientId && + m.RecipientType == sendParams.RecipientType)) + return new SendMessageResult(false, new ArgumentException("Reply must belong to the same chat."), default); + var messageId = Guid.NewGuid(); var message = new Message { @@ -39,38 +56,51 @@ public class MessageSendingService : IMessageSendingService SenderId = sendParams.FromUserId, RecipientId = sendParams.RecipientId, RecipientType = sendParams.RecipientType, - EncryptedContent = sendParams.EncryptContent, + EncryptedContent = sendParams.EncryptContent ?? string.Empty, SentAt = sendParams.SendAt, IsEdited = false, ReplyToMessageId = sendParams.ReplyToMessageId, - MediaAttachments = sendParams.Media?.Select(m => new MediaAttachments + MediaAttachments = files.Select(file => new MediaAttachments { Id = Guid.NewGuid(), MessageId = messageId, - MediaFileId = m.MediaId - }).ToList() ?? [] + MediaFileId = file.Id, + MediaFile = file + }).ToList() }; await _dbContext.Messages.AddAsync(message); + // Save message and pending push atomically so a restart/provider outage cannot lose the push. + _dbContext.ChatPushNotifications.Add(new ChatPushNotification + { MessageId = messageId, NextAttemptAt = DateTime.UtcNow }); await _dbContext.SaveChangesAsync(); _logger.LogInformation("Message {MessageId} sent successfully.", messageId); return new SendMessageResult(true, null, message); } - private async Task<(bool Success, string Error)> ValidateUserRecipientAsync(Guid chatId) + private async Task<(bool Success, string Error)> ValidateUserRecipientAsync(Guid userId, Guid chatId) { - var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == chatId); - return chatExists ? (true, null) : (false, $"Private chat {chatId} not found."); + var chat = await _dbContext.PrivateChats.AsNoTracking().FirstOrDefaultAsync(c => c.Id == chatId && + (c.UserAId == userId || c.UserBId == userId)); + if (chat is null) + return (false, "You are not a member of this chat."); + var blocked = await _dbContext.Friendships.AnyAsync(f => f.Status == FriendshipStatus.Blocked && + ((f.RequesterId == chat.UserAId && f.AddresseeId == chat.UserBId) || + (f.RequesterId == chat.UserBId && f.AddresseeId == chat.UserAId))); + return blocked ? (false, "This conversation is blocked.") : (true, null); } private async Task<(bool Success, string Error)> ValidateGroupRecipientAsync(Guid userId, Guid groupId) { - var groupExists = await _dbContext.ChatGroups.AnyAsync(g => g.Id == groupId); - if (!groupExists) return (false, $"Group {groupId} not found."); + var group = await _dbContext.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == groupId); + if (group is null) return (false, "Group not found."); - var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId); + var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId && !gm.IsBanned); if (!isMember) return (false, "Sender is not a member of the group."); + if (group.IsChannel && !await _dbContext.GroupAdmins.AnyAsync(a => + a.GroupId == groupId && a.UserId == userId)) + return (false, "Only channel administrators can send messages."); return (true, null); } diff --git a/Govor.Application/Messages/MessagesLoader.cs b/Govor.Application/Messages/MessagesLoader.cs index bf1a37a..3e88905 100644 --- a/Govor.Application/Messages/MessagesLoader.cs +++ b/Govor.Application/Messages/MessagesLoader.cs @@ -26,12 +26,13 @@ public class MessagesLoader : IMessagesLoader if (privateChatId == Guid.Empty) return Result.Failure>(Error.Failure(nameof(ArgumentException),"PrivateChatId id cannot be empty.")); - var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId); - if (!chatExists) - return new List(0); + if (!await _dbContext.HasChatAccessAsync(currentUser, privateChatId, RecipientType.User)) + return Result.Failure>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat.")); var query = _dbContext.Messages .AsNoTracking() + .Include(m => m.MessageViews) + .Include(m => m.Reactions) .Include(m => m.MediaAttachments) .ThenInclude(m => m.MediaFile) .Where(m => m.RecipientType == RecipientType.User && m.RecipientId == privateChatId); @@ -50,13 +51,15 @@ public class MessagesLoader : IMessagesLoader return Result.Failure>(Error.Failure(nameof(ArgumentException),"Chat id cannot be empty.")); var isMember = await _dbContext.GroupMemberships - .AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId); + .AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId && !gm.IsBanned); - if (!isMember) - return new List(0); + if (!isMember) + return Result.Failure>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat.")); var query = _dbContext.Messages .AsNoTracking() + .Include(m => m.MessageViews) + .Include(m => m.Reactions) .Include(m => m.MediaAttachments) .ThenInclude(m => m.MediaFile) .AsSplitQuery() @@ -75,8 +78,10 @@ public class MessagesLoader : IMessagesLoader { return await baseQuery .OrderByDescending(m => m.SentAt) + .ThenByDescending(m => m.Id) .Take(before) .OrderBy(m => m.SentAt) + .ThenBy(m => m.Id) .ToListAsync(); } @@ -85,14 +90,18 @@ public class MessagesLoader : IMessagesLoader return []; var beforeMessages = await baseQuery - .Where(m => m.SentAt < startMessage.SentAt) + .Where(m => m.SentAt < startMessage.SentAt || + (m.SentAt == startMessage.SentAt && m.Id.CompareTo(startMessage.Id) < 0)) .OrderByDescending(m => m.SentAt) + .ThenByDescending(m => m.Id) .Take(before) .ToListAsync(); var afterMessages = await baseQuery - .Where(m => m.SentAt > startMessage.SentAt) + .Where(m => m.SentAt > startMessage.SentAt || + (m.SentAt == startMessage.SentAt && m.Id.CompareTo(startMessage.Id) > 0)) .OrderBy(m => m.SentAt) + .ThenBy(m => m.Id) .Take(after) .ToListAsync(); diff --git a/Govor.Application/Messages/Parameters/ChatReadResult.cs b/Govor.Application/Messages/Parameters/ChatReadResult.cs new file mode 100644 index 0000000..ab77f67 --- /dev/null +++ b/Govor.Application/Messages/Parameters/ChatReadResult.cs @@ -0,0 +1,7 @@ +using Govor.Domain.Models.Messages; + +namespace Govor.Application.Messages.Parameters; + +public record ChatReadResult(Guid ChatId, RecipientType RecipientType, Guid ReaderId, + DateTime ReadAt, Guid? UpToMessageId, DateTime? UpToSentAt, + IReadOnlyList? MessageIds, int ReadCount, int UnreadCount); diff --git a/Govor.Application/PrivateUserChats/UserPrivateChatsGetter.cs b/Govor.Application/PrivateUserChats/UserPrivateChatsGetter.cs index e38690a..c94dfb5 100644 --- a/Govor.Application/PrivateUserChats/UserPrivateChatsGetter.cs +++ b/Govor.Application/PrivateUserChats/UserPrivateChatsGetter.cs @@ -30,8 +30,8 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService if (res == null) return Result.Failure( - Error.Failure( - nameof(InvalidOperationException), + Error.NotFound( + "PrivateChat.NotFound", "PrivateChat not found.") ); @@ -46,4 +46,4 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService (p.UserBId == userIdA && p.UserAId == userIdB) ); } -} \ No newline at end of file +} diff --git a/Govor.Application/Profiles/ProfileService.cs b/Govor.Application/Profiles/ProfileService.cs index da575af..9f76648 100644 --- a/Govor.Application/Profiles/ProfileService.cs +++ b/Govor.Application/Profiles/ProfileService.cs @@ -1,5 +1,6 @@ using Govor.Domain; using Govor.Domain.Common; +using Govor.Domain.Models; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using SmartRes; @@ -61,6 +62,10 @@ public class ProfileService : IProfileService { _logger.LogInformation("Updating icon for user {UserId}", userId); + if (!await _context.MediaFiles.AnyAsync(f => f.Id == iconId && f.UploaderId == userId && + f.OwnerType == MediaOwnerType.Avatar)) + return Result.Failure(Error.Forbidden("Profile.IconAccess", "Only your uploaded avatar can be used.")); + var updatedRows = await _context.Users .Where(u => u.Id == userId) diff --git a/Govor.Application/PushNotifications/Providers/FirebasePushProvider.cs b/Govor.Application/PushNotifications/Providers/FirebasePushProvider.cs index 7f3be8d..02737a1 100644 --- a/Govor.Application/PushNotifications/Providers/FirebasePushProvider.cs +++ b/Govor.Application/PushNotifications/Providers/FirebasePushProvider.cs @@ -40,6 +40,21 @@ public class FirebasePushProvider : IPushNotificationProvider { if (tokens.Count == 0) return new SendPushResult(0, 0, []); + + if (tokens.Count > 500) + { + var success = 0; + var failure = 0; + var invalid = new List(); + foreach (var batch in tokens.Distinct().Chunk(500)) + { + var result = await SendMulticastAsync(batch, message); + success += result.SuccessCount; + failure += result.FailureCount; + invalid.AddRange(result.FailedTokens); + } + return new SendPushResult(success, failure, invalid); + } var multicastMsg = new MulticastMessage { @@ -89,7 +104,7 @@ public class FirebasePushProvider : IPushNotificationProvider catch (Exception ex) { _logger.LogError(ex, "FCM multicast failed"); - return new SendPushResult(0, tokens.Count, tokens.ToList()); + throw; // A provider outage does not invalidate device tokens. } } @@ -124,8 +139,6 @@ public class FirebasePushProvider : IPushNotificationProvider private static bool IsInvalidTokenError(FirebaseMessagingException ex) { - return ex.MessagingErrorCode is MessagingErrorCode.Unregistered - or MessagingErrorCode.InvalidArgument - or MessagingErrorCode.SenderIdMismatch; + return ex.MessagingErrorCode is MessagingErrorCode.Unregistered; } -} \ No newline at end of file +} diff --git a/Govor.Application/PushNotifications/Providers/NullPushProvider.cs b/Govor.Application/PushNotifications/Providers/NullPushProvider.cs index 41ee252..3e782f4 100644 --- a/Govor.Application/PushNotifications/Providers/NullPushProvider.cs +++ b/Govor.Application/PushNotifications/Providers/NullPushProvider.cs @@ -9,11 +9,11 @@ public class NullPushProvider : IPushNotificationProvider public Task SendToTokenAsync(string token, PushMessage message) { - throw new NotImplementedException(); + return Task.FromResult(new SendPushResult(0, 0, [])); } public Task SendMulticastAsync(IReadOnlyList tokens, PushMessage message) { - throw new NotImplementedException(); + return Task.FromResult(new SendPushResult(0, 0, [])); } -} \ No newline at end of file +} diff --git a/Govor.Application/PushNotifications/PushNotificationService.cs b/Govor.Application/PushNotifications/PushNotificationService.cs index 0f6121c..cf8b1ed 100644 --- a/Govor.Application/PushNotifications/PushNotificationService.cs +++ b/Govor.Application/PushNotifications/PushNotificationService.cs @@ -75,6 +75,8 @@ public class PushNotificationService : IPushNotificationService _logger.LogWarning("Removed {Count} invalid FCM tokens for session {SessionId}", result.FailureCount, sessionId); } + if (result.FailureCount > result.FailedTokens.Count()) + return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily.")); return Result.Success(); } catch (Exception ex) @@ -97,6 +99,8 @@ public class PushNotificationService : IPushNotificationService _logger.LogWarning("Removed {Count} invalid FCM tokens for target: {Target}", result.FailureCount, targetInfo); } + if (result.FailureCount > result.FailedTokens.Count()) + return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily.")); return Result.Success(); } catch (Exception ex) @@ -117,4 +121,4 @@ public class PushNotificationService : IPushNotificationService ChannelId = channelId }; } -} \ No newline at end of file +} diff --git a/Govor.Application/PushNotifications/PushTokenService.cs b/Govor.Application/PushNotifications/PushTokenService.cs index b03216f..40c59e8 100644 --- a/Govor.Application/PushNotifications/PushTokenService.cs +++ b/Govor.Application/PushNotifications/PushTokenService.cs @@ -63,8 +63,10 @@ public class PushTokenService : IPushTokenService { var tokens = await _context.UserPushTokens .AsNoTracking() - .Where(t => t.UserId == userId && t.IsActive) + .Where(t => t.UserId == userId && t.IsActive && _context.UserSessions.Any(s => + s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now)) .Select(t => t.Token) + .Distinct() .ToListAsync(); return tokens; @@ -82,8 +84,10 @@ public class PushTokenService : IPushTokenService { var tokens = await _context.UserPushTokens .AsNoTracking() - .Where(t => userIds.Contains(t.UserId) && t.IsActive) + .Where(t => userIds.Contains(t.UserId) && t.IsActive && _context.UserSessions.Any(s => + s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now)) .Select(t => t.Token) + .Distinct() .ToListAsync(); return tokens; @@ -101,7 +105,8 @@ public class PushTokenService : IPushTokenService { var token = await _context.UserPushTokens .AsNoTracking() - .Where(t => t.UserSessionId == sessionId && t.IsActive) + .Where(t => t.UserSessionId == sessionId && t.IsActive && _context.UserSessions.Any(s => + s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now)) .Select(t => t.Token) .FirstOrDefaultAsync(); @@ -138,13 +143,22 @@ public class PushTokenService : IPushTokenService public async Task> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform) { - if (string.IsNullOrWhiteSpace(token)) + if (string.IsNullOrWhiteSpace(token) || token.Length > 512 || string.IsNullOrWhiteSpace(platform) || platform.Length > 50) { return Result.Failure(Error.Failure("PushToken.Empty", "Push token cannot be empty.")); } - var existingToken = await _context.UserPushTokens - .FirstOrDefaultAsync(t => t.Platform == platform && t.UserId == userId && t.UserSessionId == sessionId); + if (!await _context.UserSessions.AnyAsync(s => s.Id == sessionId && s.UserId == userId && + !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now)) + return Result.Failure(Error.Forbidden("PushToken.Session", "An active own session is required.")); + + // Token and session both have unique indexes. Reassign the device row when an + // account changes, instead of inserting a duplicate or retaining the old owner. + var sessionToken = await _context.UserPushTokens.FirstOrDefaultAsync(t => t.UserSessionId == sessionId); + var deviceToken = await _context.UserPushTokens.FirstOrDefaultAsync(t => t.Token == token); + if (sessionToken is not null && deviceToken is not null && sessionToken.Id != deviceToken.Id) + _context.UserPushTokens.Remove(sessionToken); + var existingToken = deviceToken ?? sessionToken; if (existingToken is null) { @@ -167,6 +181,8 @@ public class PushTokenService : IPushTokenService existingToken.Platform = platform; existingToken.Token = token; existingToken.UpdatedAt = _nowDateTimeProvider.Now; + existingToken.IsActive = true; + _context.Entry(existingToken).Property(t => t.IsActive).IsModified = true; } await _context.SaveChangesAsync(); diff --git a/Govor.Application/Reactions/IMessageReactionService.cs b/Govor.Application/Reactions/IMessageReactionService.cs new file mode 100644 index 0000000..635af85 --- /dev/null +++ b/Govor.Application/Reactions/IMessageReactionService.cs @@ -0,0 +1,19 @@ +using Govor.Domain.Common; +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Reactions; +using SmartRes; + +namespace Govor.Application.Reactions; + +public record ReactionCount(Guid? ReactionId, string ReactionCode, int Count); +public record MessageReactionState(Guid MessageId, Guid RecipientId, RecipientType RecipientType, + long Version, Guid ActorId, MessageReaction? ActorReaction, IReadOnlyList Counts, bool Changed = false); +public record ChannelReactionPolicy(Guid GroupId, ChannelReactionMode Mode, long Version, IReadOnlyList ReactionIds); + +public interface IMessageReactionService +{ + Task> GetAsync(Guid userId, Guid messageId); + Task> SetAsync(Guid userId, Guid messageId, Guid? reactionId); + Task> GetPolicyAsync(Guid userId, Guid groupId); + Task> SetPolicyAsync(Guid userId, Guid groupId, ChannelReactionMode mode, IReadOnlyCollection reactionIds); +} diff --git a/Govor.Application/Reactions/IReactionPackService.cs b/Govor.Application/Reactions/IReactionPackService.cs new file mode 100644 index 0000000..97d7825 --- /dev/null +++ b/Govor.Application/Reactions/IReactionPackService.cs @@ -0,0 +1,20 @@ +using Govor.Domain.Common; +using Govor.Domain.Models.Reactions; +using SmartRes; + +namespace Govor.Application.Reactions; + +public interface IReactionPackService +{ + Task> ListAsync(Guid userId, bool installedOnly = false, bool includeDisabled = false, int skip = 0, int take = 50); + Task> GetAsync(Guid packId, bool includeDisabled = false); + Task> GetSharedAsync(string shareCode); + Task> GetReactionAsync(Guid reactionId); + Task> SubscribeAsync(Guid userId, Guid packId, bool subscribe); + Task> CreateAsync(Guid actorId, string name, string description); + Task> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled); + Task> DisableAsync(Guid actorId, Guid packId); + Task> AddEmojiAsync(Guid actorId, Guid packId, string name, string emoji); + Task> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data, CancellationToken cancellationToken = default); + Task> DisableReactionAsync(Guid actorId, Guid packId, Guid reactionId); +} diff --git a/Govor.Application/Reactions/MessageReactionService.cs b/Govor.Application/Reactions/MessageReactionService.cs new file mode 100644 index 0000000..7b7e3f3 --- /dev/null +++ b/Govor.Application/Reactions/MessageReactionService.cs @@ -0,0 +1,157 @@ +using Govor.Application.Infrastructure.Common; +using Govor.Application.Messages; +using Govor.Domain; +using Govor.Domain.Common; +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Reactions; +using Microsoft.EntityFrameworkCore; +using SmartRes; + +namespace Govor.Application.Reactions; + +public class MessageReactionService(GovorDbContext context, INowDateTimeProvider clock) : IMessageReactionService +{ + public async Task> GetAsync(Guid userId, Guid messageId) + { + var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId); + if (message is null) return Result.Failure(Missing()); + if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType)) + return Result.Failure(Denied()); + // A repeatable snapshot keeps version, counts and actor reaction consistent. + return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable); + if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType)) + return Result.Failure(Denied()); + var state = await StateAsync(messageId, userId); + await transaction.CommitAsync(); + return state is null ? Result.Failure(Missing()) : Result.Success(state); + }); + } + + public async Task> SetAsync(Guid userId, Guid messageId, Guid? reactionId) + { + if (reactionId == Guid.Empty) + return Result.Failure(Error.Validation("Reaction.InvalidId", "A reaction ID is required.")); + var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId); + if (message is null) return Result.Failure(Missing()); + if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType)) + return Result.Failure(Denied()); + return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var transaction = await context.Database.BeginTransactionAsync(); + if (message.RecipientType == RecipientType.Group) + // Same lock order as channel policy changes; serialize reaction decisions with policy writes. + await context.ChatGroups.Where(g => g.Id == message.RecipientId) + .ExecuteUpdateAsync(s => s.SetProperty(g => g.ReactionMode, g => g.ReactionMode)); + if (await context.Messages.Where(m => m.Id == messageId) + .ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion)) == 0) + return Result.Failure(Missing()); + if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType)) + return Result.Failure(Denied()); + + ReactionItem? item = null; + if (reactionId.HasValue) + { + item = await context.ReactionItems.AsNoTracking() + .FirstOrDefaultAsync(r => r.Id == reactionId && r.IsEnabled && r.Pack.IsEnabled); + if (item is null) return Result.Failure(Error.NotFound("Reaction.NotAvailable", "Reaction is not available.")); + var channel = message.RecipientType == RecipientType.Group + ? await context.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == message.RecipientId && g.IsChannel) + : null; + if (channel is not null && (channel.ReactionMode == ChannelReactionMode.None || + (channel.ReactionMode == ChannelReactionMode.Selected && !await context.ChannelAllowedReactions + .AnyAsync(r => r.GroupId == channel.Id && r.ReactionId == item.Id)))) + return Result.Failure(Error.Forbidden("Reaction.ChannelRestricted", "This reaction is not allowed in the channel.")); + } + + var current = await context.MessageReactions.AsNoTracking().FirstOrDefaultAsync(r => r.MessageId == messageId && r.UserId == userId); + var changed = reactionId.HasValue ? current?.ReactionId != reactionId : current is not null; + if (changed) + { + if (item is null) + await context.MessageReactions.Where(r => r.MessageId == messageId && r.UserId == userId).ExecuteDeleteAsync(); + else + { + var id = Guid.NewGuid(); + var now = clock.Now; + await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"MessageReactions\" (\"Id\", \"MessageId\", \"UserId\", \"ReactionId\", \"ReactionCode\", \"ReactedAt\") VALUES ({id}, {messageId}, {userId}, {item.Id}, {item.Code}, {now}) ON CONFLICT (\"MessageId\", \"UserId\") DO UPDATE SET \"ReactionId\" = excluded.\"ReactionId\", \"ReactionCode\" = excluded.\"ReactionCode\", \"ReactedAt\" = excluded.\"ReactedAt\""); + } + await context.Messages.Where(m => m.Id == messageId) + .ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion + 1)); + } + var state = (await StateAsync(messageId, userId))! with { Changed = changed }; + await transaction.CommitAsync(); + return Result.Success(state); + }); + } + + private async Task StateAsync(Guid messageId, Guid actorId) + { + var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId); + if (message is null) return null; + var counts = await context.MessageReactions.AsNoTracking().Where(r => r.MessageId == messageId) + .GroupBy(r => new { r.ReactionId, r.ReactionCode }) + .OrderByDescending(g => g.Count()).ThenBy(g => g.Key.ReactionCode) + .Select(g => new ReactionCount(g.Key.ReactionId, g.Key.ReactionCode, g.Count())) + .ToListAsync(); + var actor = await context.MessageReactions.AsNoTracking().FirstOrDefaultAsync(r => r.MessageId == messageId && r.UserId == actorId); + return new MessageReactionState(messageId, message.RecipientId, message.RecipientType, + message.ReactionsVersion, actorId, actor, counts); + } + + public async Task> GetPolicyAsync(Guid userId, Guid groupId) + { + if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group)) + return Result.Failure(Denied()); + return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable); + var policy = await PolicyAsync(groupId); + await transaction.CommitAsync(); + return Result.Success(policy); + }); + } + + public async Task> SetPolicyAsync(Guid userId, Guid groupId, + ChannelReactionMode mode, IReadOnlyCollection reactionIds) + { + if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) || + !await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId)) + return Result.Failure(Denied()); + if (!Enum.IsDefined(mode) || reactionIds is null || reactionIds.Count > 100 || reactionIds.Contains(Guid.Empty) || + (mode != ChannelReactionMode.Selected && reactionIds.Count > 0)) + return Result.Failure(Error.Validation("Reaction.Policy.Invalid", "Provide a valid mode and at most 100 reaction IDs for Selected mode.")); + var ids = reactionIds.Distinct().ToArray(); + return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + await using var transaction = await context.Database.BeginTransactionAsync(); + var updated = await context.ChatGroups.Where(g => g.Id == groupId && g.IsChannel) + .ExecuteUpdateAsync(s => s.SetProperty(g => g.ReactionMode, mode) + .SetProperty(g => g.ReactionPolicyVersion, g => g.ReactionPolicyVersion + 1)); + if (updated == 0) return Result.Failure(Error.Validation("Reaction.Policy.NotChannel", "Only channels support reaction restrictions.")); + if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) || + !await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId)) + return Result.Failure(Denied()); + if (await context.ReactionItems.CountAsync(r => ids.Contains(r.Id) && r.IsEnabled && r.Pack.IsEnabled) != ids.Length) + return Result.Failure(Error.Validation("Reaction.Policy.InvalidSelection", "All reactions must be active and available.")); + await context.ChannelAllowedReactions.Where(r => r.GroupId == groupId).ExecuteDeleteAsync(); + foreach (var id in ids) + await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"ChannelAllowedReactions\" (\"GroupId\", \"ReactionId\") VALUES ({groupId}, {id})"); + var policy = await PolicyAsync(groupId); + await transaction.CommitAsync(); + return Result.Success(policy); + }); + } + + private async Task PolicyAsync(Guid groupId) + { + var group = await context.ChatGroups.AsNoTracking().FirstAsync(g => g.Id == groupId); + var ids = await context.ChannelAllowedReactions.Where(r => r.GroupId == groupId) + .OrderBy(r => r.ReactionId).Select(r => r.ReactionId).ToListAsync(); + return new ChannelReactionPolicy(groupId, group.ReactionMode, group.ReactionPolicyVersion, ids); + } + + private static Error Missing() => Error.NotFound("Message.NotFound", "Message not found."); + private static Error Denied() => Error.Forbidden("Reaction.AccessDenied", "You do not have access to this chat or operation."); +} diff --git a/Govor.Application/Reactions/ReactionMediaProcessor.cs b/Govor.Application/Reactions/ReactionMediaProcessor.cs new file mode 100644 index 0000000..e6f8edc --- /dev/null +++ b/Govor.Application/Reactions/ReactionMediaProcessor.cs @@ -0,0 +1,101 @@ +using Govor.Domain.Common; +using Govor.Domain.Models.Reactions; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats; +using SixLabors.ImageSharp.Formats.Gif; +using SixLabors.ImageSharp.Memory; +using SixLabors.ImageSharp.PixelFormats; +using SixLabors.ImageSharp.Processing; +using SmartRes; + +namespace Govor.Application.Reactions; + +public static class ReactionMediaLimits +{ + public const int MaxDimension = 128; + public const int MaxUploadBytes = 2 * 1024 * 1024; + public const int MaxImageBytes = 256 * 1024; + public const int MaxGifBytes = 512 * 1024; + public const int MaxFrames = 60; + public const int MaxDurationMilliseconds = 5000; +} + +public record ProcessedReactionMedia(byte[] Data, ReactionKind Kind, string MimeType, + string Extension, int Width, int Height, int DurationMilliseconds); + +public interface IReactionMediaProcessor +{ + Task> ProcessAsync(byte[] data, CancellationToken cancellationToken = default); +} + +public class ReactionMediaProcessor : IReactionMediaProcessor +{ + public async Task> ProcessAsync(byte[] data, CancellationToken cancellationToken = default) + { + if (data.Length == 0 || data.Length > ReactionMediaLimits.MaxUploadBytes) + return Invalid("Upload must contain at most 2 MiB."); + + try + { + var configuration = Configuration.Default.Clone(); + configuration.MaxDegreeOfParallelism = 2; + configuration.MemoryAllocator = MemoryAllocator.Create(new MemoryAllocatorOptions + { MaximumPoolSizeMegabytes = 16, AllocationLimitMegabytes = 64 }); + var options = new DecoderOptions + { + Configuration = configuration, SkipMetadata = true, + MaxFrames = ReactionMediaLimits.MaxFrames + 1, + TargetSize = new Size(ReactionMediaLimits.MaxDimension, ReactionMediaLimits.MaxDimension) + }; + using var input = new MemoryStream(data, writable: false); + var format = await Image.DetectFormatAsync(input, cancellationToken); + var isGif = format.Name == "GIF"; + if (!isGif && format.Name is not ("PNG" or "JPEG" or "WEBP")) + return Invalid("Only PNG, JPEG, WebP and GIF are supported."); + input.Position = 0; + var info = await Image.IdentifyAsync(options, input, cancellationToken); + if (info.Width > 2048 || info.Height > 2048 || info.FrameMetadataCollection.Count > ReactionMediaLimits.MaxFrames) + return Invalid("Source dimensions must not exceed 2048 px and GIF must not exceed 60 frames."); + input.Position = 0; + using var image = await Image.LoadAsync(options, input, cancellationToken); + if (image.Frames.Count > ReactionMediaLimits.MaxFrames || (!isGif && image.Frames.Count > 1)) + return Invalid("Only GIF animations with at most 60 frames are supported."); + + var duration = 0; + if (isGif) + { + foreach (var frame in image.Frames) + { + var metadata = frame.Metadata.GetGifMetadata(); + metadata.FrameDelay = Math.Max(2, metadata.FrameDelay); + duration += metadata.FrameDelay * 10; + } + if (duration > ReactionMediaLimits.MaxDurationMilliseconds) + return Invalid("GIF duration must not exceed 5 seconds per loop."); + } + + // Re-encode pixels, never store the original upload or trust its MIME/extension. + foreach (var dimension in new[] { 128, 96, 64, 48 }) + { + image.Mutate(x => x.Resize(new ResizeOptions + { Size = new Size(dimension, dimension), Mode = ResizeMode.Max })); + using var output = new MemoryStream(); + if (isGif) + await image.SaveAsGifAsync(output, new GifEncoder { SkipMetadata = true }, cancellationToken); + else + await image.SaveAsPngAsync(output, cancellationToken); + if (output.Length <= (isGif ? ReactionMediaLimits.MaxGifBytes : ReactionMediaLimits.MaxImageBytes)) + return new ProcessedReactionMedia(output.ToArray(), isGif ? ReactionKind.Gif : ReactionKind.Image, + isGif ? "image/gif" : "image/png", isGif ? ".gif" : ".png", image.Width, image.Height, duration); + } + return Invalid("The processed file exceeds the reaction size limit."); + } + catch (Exception ex) when (ex is UnknownImageFormatException or InvalidImageContentException or InvalidMemoryOperationException or ArgumentException) + { + return Invalid("Invalid or excessively complex image."); + } + } + + private static Result Invalid(string message) => + Result.Failure(Error.Validation("Reaction.Media.Invalid", message)); +} diff --git a/Govor.Application/Reactions/ReactionPackService.cs b/Govor.Application/Reactions/ReactionPackService.cs new file mode 100644 index 0000000..f786e7c --- /dev/null +++ b/Govor.Application/Reactions/ReactionPackService.cs @@ -0,0 +1,201 @@ +using System.Globalization; +using Govor.Application.Infrastructure.Common; +using Govor.Application.Storage; +using Govor.Domain; +using Govor.Domain.Common; +using Govor.Domain.Models; +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Reactions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; +using SmartRes; + +namespace Govor.Application.Reactions; + +public class ReactionPackService(GovorDbContext context, INowDateTimeProvider clock, + IReactionMediaProcessor processor, IStorageService storage, ILogger logger) : IReactionPackService +{ + public async Task> ListAsync(Guid userId, bool installedOnly = false, + bool includeDisabled = false, int skip = 0, int take = 50) + { + var query = context.ReactionPacks.AsNoTracking(); + if (!includeDisabled) query = query.Where(p => p.IsEnabled); + if (installedOnly) query = query.Where(p => p.IsDefault || context.UserReactionPacks + .Any(s => s.UserId == userId && s.PackId == p.Id)); + return await query.OrderByDescending(p => p.IsDefault).ThenBy(p => p.CreatedAt).ThenBy(p => p.Id) + .Skip(Math.Max(0, skip)).Take(Math.Clamp(take, 1, 100)) + .Include(p => p.Reactions.Where(r => includeDisabled || r.IsEnabled)).AsSplitQuery().ToListAsync(); + } + + public async Task> GetAsync(Guid packId, bool includeDisabled = false) + { + var pack = await context.ReactionPacks.AsNoTracking() + .Include(p => p.Reactions.Where(r => includeDisabled || r.IsEnabled)) + .FirstOrDefaultAsync(p => p.Id == packId && (includeDisabled || p.IsEnabled)); + return pack is null ? Result.Failure(Missing()) : Result.Success(pack); + } + + public async Task> GetSharedAsync(string shareCode) + { + var id = await context.ReactionPacks.Where(p => p.ShareCode == shareCode && p.IsEnabled) + .Select(p => (Guid?)p.Id).FirstOrDefaultAsync(); + return id.HasValue ? await GetAsync(id.Value) : Result.Failure(Missing()); + } + + // Definitions remain readable after disabling so historical reactions still render. + public async Task> GetReactionAsync(Guid reactionId) + { + var item = await context.ReactionItems.AsNoTracking().FirstOrDefaultAsync(r => r.Id == reactionId); + return item is null ? Result.Failure(Missing()) : Result.Success(item); + } + + public async Task> SubscribeAsync(Guid userId, Guid packId, bool subscribe) + { + var pack = await context.ReactionPacks.AsNoTracking().FirstOrDefaultAsync(p => p.Id == packId && (!subscribe || p.IsEnabled)); + if (pack is null) return Result.Failure(Missing()); + if (pack.IsDefault) + return subscribe ? Result.Success() : Result.Failure(Invalid("The default pack is always available.")); + if (subscribe) + await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"UserReactionPacks\" (\"UserId\", \"PackId\") VALUES ({userId}, {packId}) ON CONFLICT (\"UserId\", \"PackId\") DO NOTHING"); + else + await context.UserReactionPacks.Where(p => p.UserId == userId && p.PackId == packId).ExecuteDeleteAsync(); + return Result.Success(); + } + + public async Task> CreateAsync(Guid actorId, string name, string description) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + if (!ValidText(name, description)) return Result.Failure(Invalid("Invalid name or description.")); + var pack = new ReactionPack + { + Id = Guid.NewGuid(), Name = name.Trim(), Description = description.Trim(), + ShareCode = Guid.NewGuid().ToString("N"), CreatedByUserId = actorId, CreatedAt = clock.Now + }; + context.ReactionPacks.Add(pack); + await context.SaveChangesAsync(); + return pack; + } + + public async Task> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + if (!ValidText(name, description)) return Result.Failure(Invalid("Invalid name or description.")); + var pack = await context.ReactionPacks.FirstOrDefaultAsync(p => p.Id == packId); + if (pack is null) return Result.Failure(Missing()); + if (pack.IsDefault) return Result.Failure(Invalid("The default pack cannot be modified.")); + pack.Name = name.Trim(); pack.Description = description.Trim(); pack.IsEnabled = enabled; + await context.SaveChangesAsync(); + return pack; + } + + public async Task> DisableAsync(Guid actorId, Guid packId) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + var pack = await context.ReactionPacks.FirstOrDefaultAsync(p => p.Id == packId); + if (pack is null) return Result.Failure(Missing()); + if (pack.IsDefault) return Result.Failure(Invalid("The default pack cannot be disabled.")); + pack.IsEnabled = false; + await context.SaveChangesAsync(); + return Result.Success(); + } + + public async Task> AddEmojiAsync(Guid actorId, Guid packId, string name, string emoji) + { + if (string.IsNullOrWhiteSpace(emoji) || emoji.Length > 64 || StringInfo.ParseCombiningCharacters(emoji).Length != 1 || + !emoji.EnumerateRunes().Any(r => System.Text.Rune.GetUnicodeCategory(r) == UnicodeCategory.OtherSymbol)) + return Result.Failure(Invalid("Provide a single emoji grapheme.")); + return await AddAsync(actorId, packId, name, emoji, null); + } + + public async Task> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data, + CancellationToken cancellationToken = default) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + if (!await context.ReactionPacks.AnyAsync(p => p.Id == packId && !p.IsDefault && p.IsEnabled)) + return Result.Failure(Invalid("An active custom pack is required.")); + var processed = await processor.ProcessAsync(data, cancellationToken); + if (processed.IsFailure) return Result.Failure(processed.Error); + return await AddAsync(actorId, packId, name, null, processed.Value); + } + + private async Task> AddAsync(Guid actorId, Guid packId, string name, + string? emoji, ProcessedReactionMedia? media) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + if (!ValidText(name, "")) return Result.Failure(Invalid("Invalid reaction name.")); + var operationId = Guid.NewGuid(); + return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () => + { + var completed = await context.ReactionItems.AsNoTracking().FirstOrDefaultAsync(r => r.Id == operationId); + if (completed is not null) return Result.Success(completed); + await using var transaction = await context.Database.BeginTransactionAsync(); + // Lock the pack to serialize the item limit and concurrent disabling. + var locked = await context.ReactionPacks.Where(p => p.Id == packId && !p.IsDefault && p.IsEnabled) + .ExecuteUpdateAsync(s => s.SetProperty(p => p.Name, p => p.Name)); + if (locked == 0) return Result.Failure(Invalid("An active custom pack is required.")); + if (await context.ReactionItems.CountAsync(r => r.PackId == packId) >= 100) + return Result.Failure(Invalid("A pack can contain at most 100 reactions, including disabled entries.")); + + var item = new ReactionItem + { + Id = operationId, PackId = packId, Name = name.Trim(), Emoji = emoji, + Kind = media?.Kind ?? ReactionKind.Emoji, CreatedAt = clock.Now + }; + item.Code = $":reaction_{item.Id:N}:"; + string? path = null; + try + { + if (media is not null) + { + path = await storage.SaveAsync(media.Data, item.Id.ToString("N") + media.Extension); + var file = new MediaFile + { + Id = Guid.NewGuid(), UploaderId = actorId, Url = path, MineType = media.MimeType, + DateCreated = clock.Now, OwnerType = MediaOwnerType.Reaction, OwnerId = item.Id, + MediaType = MediaType.Image + }; + context.MediaFiles.Add(file); + item.MediaFileId = file.Id; item.Width = media.Width; item.Height = media.Height; + item.SizeBytes = media.Data.Length; item.DurationMilliseconds = media.DurationMilliseconds; + } + context.ReactionItems.Add(item); + await context.SaveChangesAsync(); + } + catch + { + if (path is not null) + { + try { await storage.RemoveAsync(path); } + catch (Exception ex) { logger.LogError(ex, "Cannot remove failed reaction upload {ReactionId}", item.Id); } + } + // Clear failed tracked additions before an execution-strategy retry. + context.ChangeTracker.Clear(); + throw; + } + // Do not delete the file on an ambiguous Commit outcome. The stable operation ID + // above detects an already committed item when the execution strategy retries. + try { await transaction.CommitAsync(); } + catch { context.ChangeTracker.Clear(); throw; } + return Result.Success(item); + }); + } + + public async Task> DisableReactionAsync(Guid actorId, Guid packId, Guid reactionId) + { + if (!await IsAdminAsync(actorId)) return Result.Failure(Denied()); + var item = await context.ReactionItems.Include(r => r.Pack) + .FirstOrDefaultAsync(r => r.Id == reactionId && r.PackId == packId); + if (item is null) return Result.Failure(Missing()); + if (item.Pack.IsDefault) return Result.Failure(Invalid("Default reactions cannot be disabled.")); + item.IsEnabled = false; + await context.SaveChangesAsync(); + return Result.Success(); + } + + private Task IsAdminAsync(Guid actorId) => context.Users.AnyAsync(u => u.Id == actorId && u.Invite != null && u.Invite.IsAdmin); + private static bool ValidText(string name, string description) => !string.IsNullOrWhiteSpace(name) && + name.Trim().Length <= 100 && description is not null && description.Length <= 500; + private static Error Invalid(string message) => Error.Validation("ReactionPack.Invalid", message); + private static Error Missing() => Error.NotFound("ReactionPack.NotFound", "Reaction pack or item not found."); + private static Error Denied() => Error.Forbidden("ReactionPack.AdminRequired", "Administrator permission is required."); +} diff --git a/Govor.Application/Users/UserSessions/Crypto/SessionKeysReader.cs b/Govor.Application/Users/UserSessions/Crypto/SessionKeysReader.cs index f8c474f..bf7b7d1 100644 --- a/Govor.Application/Users/UserSessions/Crypto/SessionKeysReader.cs +++ b/Govor.Application/Users/UserSessions/Crypto/SessionKeysReader.cs @@ -30,7 +30,7 @@ public class SessionKeysReader : ISessionKeysReader return await _context.UserCryptoSessions .AsNoTracking() .Include(c => c.OneTimePreKeys) - .Include(c => c.UserSession) + .Include(c => c.SignedPreKey) .Where(c => c.UserSession.UserId == userId && !c.UserSession.IsRevoked && c.UserSession.ExpiresAt > now) @@ -44,7 +44,7 @@ public class SessionKeysReader : ISessionKeysReader return await _context.OneTimePreKeys .AsNoTracking() .Include(f => f.UserCryptoSession) - .CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId); + .CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId && !f.IsUsed); } public async Task GetKeysBySessionIdAsync(Guid sessionId) @@ -57,4 +57,4 @@ public class SessionKeysReader : ISessionKeysReader .Include(c => c.UserSession) .FirstOrDefaultAsync(c => c.UserSessionId == sessionId); } -} \ No newline at end of file +} diff --git a/Govor.Application/Users/UserSessions/UserSessionOpener.cs b/Govor.Application/Users/UserSessions/UserSessionOpener.cs index 8646cf8..ff6a58b 100644 --- a/Govor.Application/Users/UserSessions/UserSessionOpener.cs +++ b/Govor.Application/Users/UserSessions/UserSessionOpener.cs @@ -45,21 +45,10 @@ public class UserSessionOpener : IUserSessionOpener return Result.Failure(result.Error); } - var sessions = result.Value; - var existingSession = sessions.FirstOrDefault(s => s.DeviceInfo == deviceInfo); - try { - RefreshResult refreshResult; - - if (existingSession is not null) - { - refreshResult = await UpdateExistingSessionAsync(user, deviceInfo, existingSession); - } - else - { - refreshResult = await CreateNewSessionAsync(user, deviceInfo); - } + // DeviceInfo is a display label, not a device identity. Never reuse another sid. + var refreshResult = await CreateNewSessionAsync(user, deviceInfo ?? string.Empty); await _context.SaveChangesAsync(); @@ -120,4 +109,4 @@ public class UserSessionOpener : IUserSessionOpener var refreshToken = await _jwtService.GenerateRefreshTokenAsync(user); return (accessToken, refreshToken); } -} \ No newline at end of file +} diff --git a/Govor.Application/Users/UserSessions/UserSessionRefresher.cs b/Govor.Application/Users/UserSessions/UserSessionRefresher.cs index 441c281..a72b854 100644 --- a/Govor.Application/Users/UserSessions/UserSessionRefresher.cs +++ b/Govor.Application/Users/UserSessions/UserSessionRefresher.cs @@ -61,11 +61,15 @@ public class UserSessionRefresher : IUserSessionRefresher var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(session.User); var newRefreshTokenHash = _jwtTokenHasher.HashToken(newRefreshToken); - session.RefreshTokenHash = newRefreshTokenHash; - session.CreatedAt = DateTime.UtcNow; - session.ExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays); - - await _context.SaveChangesAsync(); + var now = DateTime.UtcNow; + var updated = await _context.UserSessions.Where(s => s.Id == session.Id && + s.RefreshTokenHash == hashedToken && !s.IsRevoked && s.ExpiresAt > now) + .ExecuteUpdateAsync(setters => setters + .SetProperty(s => s.RefreshTokenHash, newRefreshTokenHash) + .SetProperty(s => s.ExpiresAt, now.AddDays(_options.RefreshTokenLifetimeDays))); + if (updated == 0) + return Result.Failure(Error.Unauthorized("Auth.InvalidToken", + "Refresh token was already used or the session was revoked.")); _logger.LogInformation("Successfully refreshed session {SessionId} for user {UserId}", session.Id, session.UserId); diff --git a/Govor.Contracts/Requests/ReactionRequests.cs b/Govor.Contracts/Requests/ReactionRequests.cs new file mode 100644 index 0000000..e7d16a6 --- /dev/null +++ b/Govor.Contracts/Requests/ReactionRequests.cs @@ -0,0 +1,32 @@ +using System.ComponentModel.DataAnnotations; +using Govor.Domain.Models.Reactions; + +namespace Govor.Contracts.Requests; + +public class SetReactionRequest +{ + public Guid ReactionId { get; set; } +} + +public class CreateReactionPackRequest +{ + [Required, MaxLength(100)] public string Name { get; set; } = string.Empty; + [MaxLength(500)] public string Description { get; set; } = string.Empty; +} + +public class UpdateReactionPackRequest : CreateReactionPackRequest +{ + public bool IsEnabled { get; set; } = true; +} + +public class CreateEmojiReactionRequest +{ + [Required, MaxLength(100)] public string Name { get; set; } = string.Empty; + [Required, MaxLength(64)] public string Emoji { get; set; } = string.Empty; +} + +public class ChannelReactionPolicyRequest +{ + [EnumDataType(typeof(ChannelReactionMode))] public ChannelReactionMode Mode { get; set; } + [MaxLength(100)] public List ReactionIds { get; set; } = []; +} diff --git a/Govor.Contracts/Requests/ReadChatRequest.cs b/Govor.Contracts/Requests/ReadChatRequest.cs new file mode 100644 index 0000000..b4d0c87 --- /dev/null +++ b/Govor.Contracts/Requests/ReadChatRequest.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations; +using Govor.Domain.Models.Messages; + +namespace Govor.Contracts.Requests; + +public class ReadChatRequest +{ + [EnumDataType(typeof(RecipientType))] + public RecipientType RecipientType { get; set; } + + // Visible messages, or an inclusive boundary. Neither means the current chat snapshot. + [MaxLength(100)] + public List? MessageIds { get; set; } + public Guid? UpToMessageId { get; set; } +} diff --git a/Govor.Contracts/Requests/SetPasswordRequest.cs b/Govor.Contracts/Requests/SetPasswordRequest.cs new file mode 100644 index 0000000..27cabd0 --- /dev/null +++ b/Govor.Contracts/Requests/SetPasswordRequest.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; + +namespace Govor.Contracts.Requests; + +public class SetPasswordRequest +{ + [Required, MinLength(8), MaxLength(256)] + public string Password { get; set; } = string.Empty; +} diff --git a/Govor.Contracts/Responses/Admins/UserResponse.cs b/Govor.Contracts/Responses/Admins/UserResponse.cs index 2cfc5e2..d127c90 100644 --- a/Govor.Contracts/Responses/Admins/UserResponse.cs +++ b/Govor.Contracts/Responses/Admins/UserResponse.cs @@ -5,10 +5,9 @@ public class UserResponse public Guid Id { get; set; } public string Username { get; set; } public string Description { get; set; } - public string PasswordHash { get; set; } public DateTime WasOnline { get; set; } public DateOnly CreatedOn { get; set; } public Guid IconId {get; set;} public Guid InviteId {get; set;} public bool IsAdmin {get; set;} -} \ No newline at end of file +} diff --git a/Govor.Contracts/Responses/MessageReactionResponse.cs b/Govor.Contracts/Responses/MessageReactionResponse.cs index d512e7d..85a7b0c 100644 --- a/Govor.Contracts/Responses/MessageReactionResponse.cs +++ b/Govor.Contracts/Responses/MessageReactionResponse.cs @@ -5,6 +5,7 @@ public class MessageReactionResponse public Guid Id { get; set; } public Guid MessageId { get; set; } public Guid UserId { get; set; } + public Guid? ReactionId { get; set; } public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:" public DateTime ReactedAt { get; set; } = DateTime.UtcNow; -} \ No newline at end of file +} diff --git a/Govor.Contracts/Responses/MessageResponse.cs b/Govor.Contracts/Responses/MessageResponse.cs index 6d013f0..84cdafc 100644 --- a/Govor.Contracts/Responses/MessageResponse.cs +++ b/Govor.Contracts/Responses/MessageResponse.cs @@ -13,8 +13,9 @@ public class MessageResponse public bool IsEdited { get; set; } = false; public DateTime? EditedAt { get; set; } public Guid? ReplyToMessageId { get; set; } + public long ReactionsVersion { get; set; } public List MediaAttachments { get; set; } = new(); public List Reactions { get; set; } = new(); public List MessageViews { get; set; } = new(); -} \ No newline at end of file +} diff --git a/Govor.Contracts/Responses/ReactionPackResponse.cs b/Govor.Contracts/Responses/ReactionPackResponse.cs new file mode 100644 index 0000000..b9da64e --- /dev/null +++ b/Govor.Contracts/Responses/ReactionPackResponse.cs @@ -0,0 +1,35 @@ +using Govor.Domain.Models.Reactions; + +namespace Govor.Contracts.Responses; + +public class ReactionPackResponse +{ + public Guid Id { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string ShareCode { get; set; } = string.Empty; + public string SharePath => $"/api/reaction-packs/shared/{ShareCode}"; + public bool IsDefault { get; set; } + public bool IsEnabled { get; set; } + public Guid? CreatedByUserId { get; set; } + public DateTime CreatedAt { get; set; } + public List Reactions { get; set; } = []; +} + +public class ReactionItemResponse +{ + public Guid Id { get; set; } + public Guid PackId { get; set; } + public string Code { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public ReactionKind Kind { get; set; } + public string? Emoji { get; set; } + public Guid? MediaFileId { get; set; } + public string? MediaUrl => MediaFileId.HasValue ? $"/api/media/download/{MediaFileId}" : null; + public int Width { get; set; } + public int Height { get; set; } + public int SizeBytes { get; set; } + public int DurationMilliseconds { get; set; } + public bool IsEnabled { get; set; } + public DateTime CreatedAt { get; set; } +} diff --git a/Govor.Contracts/Responses/SignalR/ChatReadResponse.cs b/Govor.Contracts/Responses/SignalR/ChatReadResponse.cs new file mode 100644 index 0000000..f781745 --- /dev/null +++ b/Govor.Contracts/Responses/SignalR/ChatReadResponse.cs @@ -0,0 +1,16 @@ +using Govor.Domain.Models.Messages; + +namespace Govor.Contracts.Responses.SignalR; + +public class ChatReadResponse +{ + public Guid ChatId { get; set; } + public RecipientType RecipientType { get; set; } + public Guid ReaderId { get; set; } + public DateTime ReadAt { get; set; } + public Guid? UpToMessageId { get; set; } + public DateTime? UpToSentAt { get; set; } + public IReadOnlyList? MessageIds { get; set; } + public int ReadCount { get; set; } + public int UnreadCount { get; set; } +} diff --git a/Govor.Contracts/Responses/SignalR/HubResult.cs b/Govor.Contracts/Responses/SignalR/HubResult.cs index 0875275..87f7d99 100644 --- a/Govor.Contracts/Responses/SignalR/HubResult.cs +++ b/Govor.Contracts/Responses/SignalR/HubResult.cs @@ -49,6 +49,12 @@ public class HubResult ErrorMessage = message, }; + public static HubResult Forbidden(string message) => new() + { + Status = HubResultStatus.Forbidden, + ErrorMessage = message + }; + public static HubResult UnprocessableEntity(string message) => new() { Status = HubResultStatus.UnprocessableEntity, @@ -69,8 +75,9 @@ public enum HubResultStatus : int NoContent = 204, BadRequest = 400, Unauthorized = 401, + Forbidden = 403, NotFound = 404, Conflict = 409, UnprocessableEntity = 422, ServerError = 500, -} \ No newline at end of file +} diff --git a/Govor.Contracts/Responses/SignalR/MessageReactionsChangedResponse.cs b/Govor.Contracts/Responses/SignalR/MessageReactionsChangedResponse.cs new file mode 100644 index 0000000..e6f273d --- /dev/null +++ b/Govor.Contracts/Responses/SignalR/MessageReactionsChangedResponse.cs @@ -0,0 +1,30 @@ +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Reactions; + +namespace Govor.Contracts.Responses.SignalR; + +public class ReactionCountResponse +{ + public Guid? ReactionId { get; set; } + public string ReactionCode { get; set; } = string.Empty; + public int Count { get; set; } +} + +public class MessageReactionsChangedResponse +{ + public Guid MessageId { get; set; } + public Guid RecipientId { get; set; } + public RecipientType RecipientType { get; set; } + public long Version { get; set; } + public Guid ActorId { get; set; } + public MessageReactionResponse? ActorReaction { get; set; } + public List Counts { get; set; } = []; +} + +public class ChannelReactionPolicyResponse +{ + public Guid GroupId { get; set; } + public ChannelReactionMode Mode { get; set; } + public long Version { get; set; } + public List ReactionIds { get; set; } = []; +} diff --git a/Govor.Domain/Configurations/ChatPushNotificationConfiguration.cs b/Govor.Domain/Configurations/ChatPushNotificationConfiguration.cs new file mode 100644 index 0000000..ea01902 --- /dev/null +++ b/Govor.Domain/Configurations/ChatPushNotificationConfiguration.cs @@ -0,0 +1,16 @@ +using Govor.Domain.Models.Messages; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Govor.Domain.Configurations; + +public class ChatPushNotificationConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(n => n.MessageId); + builder.HasIndex(n => n.NextAttemptAt); + builder.HasOne().WithMany().HasForeignKey(n => n.MessageId) + .OnDelete(DeleteBehavior.Cascade); + } +} diff --git a/Govor.Domain/Configurations/MessageReactionConfiguration.cs b/Govor.Domain/Configurations/MessageReactionConfiguration.cs index d606070..ca07315 100644 --- a/Govor.Domain/Configurations/MessageReactionConfiguration.cs +++ b/Govor.Domain/Configurations/MessageReactionConfiguration.cs @@ -9,6 +9,8 @@ public class MessageReactionConfiguration : IEntityTypeConfiguration builder) { builder.HasKey(r => r.Id); + builder.HasOne().WithMany() + .HasForeignKey(r => r.ReactionId).OnDelete(DeleteBehavior.Restrict); builder.HasIndex(r => new { r.MessageId, r.UserId }).IsUnique(); // Одна реакция от одного юзера @@ -21,4 +23,4 @@ public class MessageReactionConfiguration : IEntityTypeConfiguration r.UserId) .OnDelete(DeleteBehavior.Cascade); } -} \ No newline at end of file +} diff --git a/Govor.Domain/Configurations/ReactionPackConfiguration.cs b/Govor.Domain/Configurations/ReactionPackConfiguration.cs new file mode 100644 index 0000000..9ebea96 --- /dev/null +++ b/Govor.Domain/Configurations/ReactionPackConfiguration.cs @@ -0,0 +1,57 @@ +using Govor.Domain.Models; +using Govor.Domain.Models.Reactions; +using Govor.Domain.Models.Users; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Govor.Domain.Configurations; + +public class ReactionPackConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(p => p.Id); + builder.Property(p => p.Name).IsRequired().HasMaxLength(100); + builder.Property(p => p.Description).HasMaxLength(500); + builder.Property(p => p.ShareCode).IsRequired().HasMaxLength(32); + builder.HasIndex(p => p.ShareCode).IsUnique(); + builder.HasIndex(p => p.IsDefault).IsUnique().HasFilter("\"IsDefault\" = TRUE"); + builder.HasOne().WithMany().HasForeignKey(p => p.CreatedByUserId).OnDelete(DeleteBehavior.SetNull); + builder.HasMany(p => p.Reactions).WithOne(r => r.Pack).HasForeignKey(r => r.PackId).OnDelete(DeleteBehavior.Restrict); + builder.HasData(DefaultReactionPack.Create()); + } +} + +public class ReactionItemConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(r => r.Id); + builder.Property(r => r.Name).IsRequired().HasMaxLength(100); + builder.Property(r => r.Code).IsRequired().HasMaxLength(64); + builder.Property(r => r.Emoji).HasMaxLength(64); + builder.HasIndex(r => r.Code).IsUnique(); + builder.HasOne().WithMany().HasForeignKey(r => r.MediaFileId).OnDelete(DeleteBehavior.Restrict); + builder.HasData(DefaultReactionPack.Items()); + } +} + +public class UserReactionPackConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(p => new { p.UserId, p.PackId }); + builder.HasOne().WithMany().HasForeignKey(p => p.UserId).OnDelete(DeleteBehavior.Cascade); + builder.HasOne().WithMany().HasForeignKey(p => p.PackId).OnDelete(DeleteBehavior.Cascade); + } +} + +public class ChannelAllowedReactionConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.HasKey(r => new { r.GroupId, r.ReactionId }); + builder.HasOne().WithMany().HasForeignKey(r => r.GroupId).OnDelete(DeleteBehavior.Cascade); + builder.HasOne().WithMany().HasForeignKey(r => r.ReactionId).OnDelete(DeleteBehavior.Restrict); + } +} diff --git a/Govor.Domain/GovorDbContext.cs b/Govor.Domain/GovorDbContext.cs index ecc436a..23571b4 100644 --- a/Govor.Domain/GovorDbContext.cs +++ b/Govor.Domain/GovorDbContext.cs @@ -3,6 +3,7 @@ using Govor.Domain.Models.Messages; using Govor.Domain.Models.Users; using Govor.Domain.Models.Users.Crypto; using Govor.Domain.Configurations; +using Govor.Domain.Models.Reactions; using Microsoft.EntityFrameworkCore; namespace Govor.Domain; @@ -22,6 +23,11 @@ public class GovorDbContext(DbContextOptions options) : DbContex public virtual DbSet Invitations { get; set; } public virtual DbSet Messages { get; set; } + public virtual DbSet ReactionPacks { get; set; } + public virtual DbSet ReactionItems { get; set; } + public virtual DbSet UserReactionPacks { get; set; } + public virtual DbSet ChannelAllowedReactions { get; set; } + public virtual DbSet ChatPushNotifications { get; set; } public virtual DbSet MessageViews { get; set; } public virtual DbSet MessageReactions { get; set; } public virtual DbSet MediaAttachments { get; set; } @@ -40,7 +46,12 @@ public class GovorDbContext(DbContextOptions options) : DbContex modelBuilder.ApplyConfiguration(new InvitationConfiguration()); modelBuilder.ApplyConfiguration(new AdminConfiguration()); modelBuilder.ApplyConfiguration(new MessagesConfiguration()); + modelBuilder.ApplyConfiguration(new ChatPushNotificationConfiguration()); modelBuilder.ApplyConfiguration(new MessageReactionConfiguration()); + modelBuilder.ApplyConfiguration(new ReactionPackConfiguration()); + modelBuilder.ApplyConfiguration(new ReactionItemConfiguration()); + modelBuilder.ApplyConfiguration(new UserReactionPackConfiguration()); + modelBuilder.ApplyConfiguration(new ChannelAllowedReactionConfiguration()); modelBuilder.ApplyConfiguration(new MediaAttachmentsConfiguration()); modelBuilder.ApplyConfiguration(new MessageViewConfiguration()); modelBuilder.ApplyConfiguration(new MediaFileConfiguration()); @@ -56,4 +67,4 @@ public class GovorDbContext(DbContextOptions options) : DbContex modelBuilder.ApplyConfiguration(new UserPushTokenConfiguration()); base.OnModelCreating(modelBuilder); } -} \ No newline at end of file +} diff --git a/Govor.Domain/Migrations/20261003070406_ReliableChatPush.Designer.cs b/Govor.Domain/Migrations/20261003070406_ReliableChatPush.Designer.cs new file mode 100644 index 0000000..e9a7227 --- /dev/null +++ b/Govor.Domain/Migrations/20261003070406_ReliableChatPush.Designer.cs @@ -0,0 +1,878 @@ +// +using System; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + [DbContext(typeof(GovorDbContext))] + [Migration("20261003070406_ReliableChatPush")] + partial class ReliableChatPush + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageId") + .HasColumnType("uuid"); + + b.Property("IsChannel") + .HasColumnType("boolean"); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.HasKey("Id"); + + b.ToTable("ChatGroups"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddresseeId") + .HasColumnType("uuid"); + + b.Property("RequesterId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AddresseeId"); + + b.HasIndex("RequesterId"); + + b.ToTable("Friendships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.ToTable("GroupAdmins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationCode") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("UserMakerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.HasIndex("UserMakerId"); + + b.ToTable("GroupInvitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationId") + .HasColumnType("uuid"); + + b.Property("IsBanned") + .HasColumnType("boolean"); + + b.Property("MemberSince") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("GroupId"); + + b.HasIndex("InvitationId"); + + b.ToTable("GroupMemberships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("Participants") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Invitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("MediaType") + .IsRequired() + .HasColumnType("text"); + + b.Property("MineType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OwnerId") + .HasColumnType("uuid"); + + b.Property("OwnerType") + .HasColumnType("integer"); + + b.Property("UploaderId") + .HasColumnType("uuid"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MessageId"); + + b.HasIndex("NextAttemptAt"); + + b.ToTable("ChatPushNotifications"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("MediaFileId"); + + b.HasIndex("MessageId"); + + b.ToTable("MediaAttachments"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedContent") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsEdited") + .HasColumnType("boolean"); + + b.Property("PrivateChatId") + .HasColumnType("uuid"); + + b.Property("RecipientId") + .HasColumnType("uuid"); + + b.Property("RecipientType") + .HasColumnType("integer"); + + b.Property("ReplyToMessageId") + .HasColumnType("uuid"); + + b.Property("SenderId") + .HasColumnType("uuid"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("PrivateChatId"); + + b.HasIndex("RecipientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("ReactedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReactionCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("ViewedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageViews"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("UserAId") + .HasColumnType("uuid"); + + b.Property("UserBId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.ToTable("PrivateChats"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("UserId"); + + b.ToTable("Admins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("IsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("PublicKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UploadedAt"); + + b.HasIndex("UserCryptoSessionId", "IsUsed"); + + b.ToTable("OneTimePreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicSignedPreKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("SignedPreKeySignature") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserCryptoSessionId") + .IsUnique(); + + b.ToTable("SignedPreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicIdentityKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.ToTable("UserCryptoSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedOn") + .HasColumnType("date"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IconId") + .HasColumnType("uuid"); + + b.Property("InviteId") + .HasColumnType("uuid"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("WasOnline") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatedOn"); + + b.HasIndex("InviteId"); + + b.HasIndex("Username") + .IsUnique(); + + b.HasIndex("WasOnline"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserPushToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.HasIndex("UserId", "IsActive"); + + b.ToTable("UserPushTokens"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceInfo") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("RefreshTokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RefreshTokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("UserSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "Addressee") + .WithMany("ReceivedFriendRequests") + .HasForeignKey("AddresseeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "Requester") + .WithMany("SentFriendRequests") + .HasForeignKey("RequesterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Addressee"); + + b.Navigation("Requester"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Admins") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("InviteCodes") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "UserMaker") + .WithMany() + .HasForeignKey("UserMakerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserMaker"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Members") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.ChatGroup", "ChatGroup") + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.GroupInvitation", null) + .WithMany() + .HasForeignKey("InvitationId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ChatGroup"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany() + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("MediaAttachments") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MediaFile"); + + b.Navigation("Message"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Messages") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.PrivateChat", null) + .WithMany("Messages") + .HasForeignKey("PrivateChatId"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("Reactions") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Message"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany("MessageViews") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Admin", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithMany("OneTimePreKeys") + .HasForeignKey("UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithOne("SignedPreKey") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.SignedPreKey", "UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.HasOne("Govor.Domain.Models.Users.UserSession", "UserSession") + .WithOne("CryptoSession") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.HasOne("Govor.Domain.Models.Invitation", "Invite") + .WithMany("Users") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invite"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Navigation("Admins"); + + b.Navigation("InviteCodes"); + + b.Navigation("Members"); + + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Navigation("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Navigation("MediaAttachments"); + + b.Navigation("MessageViews"); + + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Navigation("OneTimePreKeys"); + + b.Navigation("SignedPreKey") + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Navigation("ReceivedFriendRequests"); + + b.Navigation("SentFriendRequests"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Navigation("CryptoSession") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Govor.Domain/Migrations/20261003070406_ReliableChatPush.cs b/Govor.Domain/Migrations/20261003070406_ReliableChatPush.cs new file mode 100644 index 0000000..5a3375a --- /dev/null +++ b/Govor.Domain/Migrations/20261003070406_ReliableChatPush.cs @@ -0,0 +1,46 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + /// + public partial class ReliableChatPush : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "ChatPushNotifications", + columns: table => new + { + MessageId = table.Column(type: "uuid", nullable: false), + NextAttemptAt = table.Column(type: "timestamp with time zone", nullable: false), + Attempts = table.Column(type: "integer", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ChatPushNotifications", x => x.MessageId); + table.ForeignKey( + name: "FK_ChatPushNotifications_Messages_MessageId", + column: x => x.MessageId, + principalTable: "Messages", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_ChatPushNotifications_NextAttemptAt", + table: "ChatPushNotifications", + column: "NextAttemptAt"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "ChatPushNotifications"); + } + } +} diff --git a/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.Designer.cs b/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.Designer.cs new file mode 100644 index 0000000..7f03f17 --- /dev/null +++ b/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.Designer.cs @@ -0,0 +1,1286 @@ +// +using System; +using Govor.Domain; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Govor.Domain.Migrations +{ + [DbContext(typeof(GovorDbContext))] + [Migration("20261003101700_ReactionPacksAndChannelPolicies")] + partial class ReactionPacksAndChannelPolicies + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.10") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("ImageId") + .HasColumnType("uuid"); + + b.Property("IsChannel") + .HasColumnType("boolean"); + + b.Property("IsPrivate") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ReactionMode") + .HasColumnType("integer"); + + b.Property("ReactionPolicyVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("ChatGroups"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("AddresseeId") + .HasColumnType("uuid"); + + b.Property("RequesterId") + .HasColumnType("uuid"); + + b.Property("Status") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("AddresseeId"); + + b.HasIndex("RequesterId"); + + b.ToTable("Friendships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.ToTable("GroupAdmins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationCode") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("UserMakerId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("GroupId"); + + b.HasIndex("UserMakerId"); + + b.ToTable("GroupInvitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("InvitationId") + .HasColumnType("uuid"); + + b.Property("IsBanned") + .HasColumnType("boolean"); + + b.Property("MemberSince") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("GroupId"); + + b.HasIndex("InvitationId"); + + b.ToTable("GroupMemberships"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasColumnType("text"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text"); + + b.Property("EndDate") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("IsAdmin") + .HasColumnType("boolean"); + + b.Property("MaxParticipants") + .HasColumnType("integer"); + + b.Property("Participants") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.ToTable("Invitations"); + }); + + modelBuilder.Entity("Govor.Domain.Models.MediaFile", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("DateCreated") + .HasColumnType("timestamp with time zone"); + + b.Property("MediaType") + .IsRequired() + .HasColumnType("text"); + + b.Property("MineType") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("OwnerId") + .HasColumnType("uuid"); + + b.Property("OwnerType") + .HasColumnType("integer"); + + b.Property("UploaderId") + .HasColumnType("uuid"); + + b.Property("Url") + .IsRequired() + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("MediaFiles"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MessageId"); + + b.HasIndex("NextAttemptAt"); + + b.ToTable("ChatPushNotifications"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("MediaFileId"); + + b.HasIndex("MessageId"); + + b.ToTable("MediaAttachments"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("ChatGroupId") + .HasColumnType("uuid"); + + b.Property("EditedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("EncryptedContent") + .IsRequired() + .HasColumnType("text"); + + b.Property("IsEdited") + .HasColumnType("boolean"); + + b.Property("PrivateChatId") + .HasColumnType("uuid"); + + b.Property("ReactionsVersion") + .HasColumnType("bigint"); + + b.Property("RecipientId") + .HasColumnType("uuid"); + + b.Property("RecipientType") + .HasColumnType("integer"); + + b.Property("ReplyToMessageId") + .HasColumnType("uuid"); + + b.Property("SenderId") + .HasColumnType("uuid"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("ChatGroupId"); + + b.HasIndex("PrivateChatId"); + + b.HasIndex("RecipientId"); + + b.ToTable("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("ReactedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("ReactionCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("ReactionId"); + + b.HasIndex("UserId"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("ViewedAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("MessageId", "UserId") + .IsUnique(); + + b.ToTable("MessageViews"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("UserAId") + .HasColumnType("uuid"); + + b.Property("UserBId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.ToTable("PrivateChats"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "ReactionId"); + + b.HasIndex("ReactionId"); + + b.ToTable("ChannelAllowedReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationMilliseconds") + .HasColumnType("integer"); + + b.Property("Emoji") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.Property("SizeBytes") + .HasColumnType("integer"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.HasIndex("MediaFileId"); + + b.HasIndex("PackId"); + + b.ToTable("ReactionItems"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000001"), + Code = "👍", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👍", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👍", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000002"), + Code = "👎", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👎", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👎", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000003"), + Code = "❤️", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "❤️", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "❤️", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000004"), + Code = "🔥", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🔥", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🔥", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000005"), + Code = "🥰", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🥰", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🥰", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000006"), + Code = "👏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000007"), + Code = "😁", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😁", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😁", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000008"), + Code = "🤔", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤔", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤔", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000009"), + Code = "😢", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😢", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😢", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000010"), + Code = "🎉", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🎉", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🎉", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000011"), + Code = "🤯", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤯", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤯", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000012"), + Code = "🙏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🙏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🙏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ShareCode") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("IsDefault") + .IsUnique() + .HasFilter("\"IsDefault\" = TRUE"); + + b.HasIndex("ShareCode") + .IsUnique(); + + b.ToTable("ReactionPacks"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0000-000000000001"), + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Default public emoji reactions", + IsDefault = true, + IsEnabled = true, + Name = "Emoji", + ShareCode = "default" + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PackId"); + + b.HasIndex("PackId"); + + b.ToTable("UserReactionPacks"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("UserId"); + + b.ToTable("Admins"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("IsUsed") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false); + + b.Property("PublicKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UploadedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UploadedAt"); + + b.HasIndex("UserCryptoSessionId", "IsUsed"); + + b.ToTable("OneTimePreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicSignedPreKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("SignedPreKeySignature") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserCryptoSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserCryptoSessionId") + .IsUnique(); + + b.ToTable("SignedPreKeys"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("PublicIdentityKey") + .IsRequired() + .HasColumnType("bytea"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.ToTable("UserCryptoSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedOn") + .HasColumnType("date"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IconId") + .HasColumnType("uuid"); + + b.Property("InviteId") + .HasColumnType("uuid"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("WasOnline") + .HasColumnType("timestamp with time zone"); + + b.HasKey("Id"); + + b.HasIndex("CreatedOn"); + + b.HasIndex("InviteId"); + + b.HasIndex("Username") + .IsUnique(); + + b.HasIndex("WasOnline"); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserPushToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsActive") + .HasColumnType("boolean"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("Platform") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Provider") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("character varying(512)"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("UserSessionId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("Token") + .IsUnique(); + + b.HasIndex("UserSessionId") + .IsUnique(); + + b.HasIndex("UserId", "IsActive"); + + b.ToTable("UserPushTokens"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DeviceInfo") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone"); + + b.Property("IsRevoked") + .HasColumnType("boolean"); + + b.Property("RefreshTokenHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("UserId") + .HasColumnType("uuid"); + + b.HasKey("Id"); + + b.HasIndex("RefreshTokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.ToTable("UserSessions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Friendship", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "Addressee") + .WithMany("ReceivedFriendRequests") + .HasForeignKey("AddresseeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "Requester") + .WithMany("SentFriendRequests") + .HasForeignKey("RequesterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Addressee"); + + b.Navigation("Requester"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Admins") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("InviteCodes") + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", "UserMaker") + .WithMany() + .HasForeignKey("UserMakerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("UserMaker"); + }); + + modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Members") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.ChatGroup", "ChatGroup") + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.GroupInvitation", null) + .WithMany() + .HasForeignKey("InvitationId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("ChatGroup"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany() + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("MediaAttachments") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("MediaFile"); + + b.Navigation("Message"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany("Messages") + .HasForeignKey("ChatGroupId"); + + b.HasOne("Govor.Domain.Models.PrivateChat", null) + .WithMany("Messages") + .HasForeignKey("PrivateChatId"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageReaction", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", "Message") + .WithMany("Reactions") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Message"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.MessageView", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany("MessageViews") + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", null) + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", "Pack") + .WithMany("Reactions") + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Pack"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", null) + .WithMany() + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithOne() + .HasForeignKey("Govor.Domain.Models.Users.Admin", "UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithMany("OneTimePreKeys") + .HasForeignKey("UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.SignedPreKey", b => + { + b.HasOne("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserCryptoSession") + .WithOne("SignedPreKey") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.SignedPreKey", "UserCryptoSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserCryptoSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.HasOne("Govor.Domain.Models.Users.UserSession", "UserSession") + .WithOne("CryptoSession") + .HasForeignKey("Govor.Domain.Models.Users.Crypto.UserCryptoSession", "UserSessionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("UserSession"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.HasOne("Govor.Domain.Models.Invitation", "Invite") + .WithMany("Users") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Invite"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.HasOne("Govor.Domain.Models.Users.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b => + { + b.Navigation("Admins"); + + b.Navigation("InviteCodes"); + + b.Navigation("Members"); + + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Invitation", b => + { + b.Navigation("Users"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Messages.Message", b => + { + b.Navigation("MediaAttachments"); + + b.Navigation("MessageViews"); + + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.PrivateChat", b => + { + b.Navigation("Messages"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Navigation("Reactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => + { + b.Navigation("OneTimePreKeys"); + + b.Navigation("SignedPreKey") + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.User", b => + { + b.Navigation("ReceivedFriendRequests"); + + b.Navigation("SentFriendRequests"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Users.UserSession", b => + { + b.Navigation("CryptoSession") + .IsRequired(); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.cs b/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.cs new file mode 100644 index 0000000..047c843 --- /dev/null +++ b/Govor.Domain/Migrations/20261003101700_ReactionPacksAndChannelPolicies.cs @@ -0,0 +1,280 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +#pragma warning disable CA1814 // Prefer jagged arrays over multidimensional + +namespace Govor.Domain.Migrations +{ + /// + public partial class ReactionPacksAndChannelPolicies : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "ReactionsVersion", + table: "Messages", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.AddColumn( + name: "ReactionId", + table: "MessageReactions", + type: "uuid", + nullable: true); + + migrationBuilder.AddColumn( + name: "ReactionMode", + table: "ChatGroups", + type: "integer", + nullable: false, + defaultValue: 0); + + migrationBuilder.AddColumn( + name: "ReactionPolicyVersion", + table: "ChatGroups", + type: "bigint", + nullable: false, + defaultValue: 0L); + + migrationBuilder.CreateTable( + name: "ReactionPacks", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + Name = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + Description = table.Column(type: "character varying(500)", maxLength: 500, nullable: false), + ShareCode = table.Column(type: "character varying(32)", maxLength: 32, nullable: false), + IsDefault = table.Column(type: "boolean", nullable: false), + IsEnabled = table.Column(type: "boolean", nullable: false), + CreatedByUserId = table.Column(type: "uuid", nullable: true), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReactionPacks", x => x.Id); + table.ForeignKey( + name: "FK_ReactionPacks_Users_CreatedByUserId", + column: x => x.CreatedByUserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.SetNull); + }); + + migrationBuilder.CreateTable( + name: "ReactionItems", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + PackId = table.Column(type: "uuid", nullable: false), + Code = table.Column(type: "character varying(64)", maxLength: 64, nullable: false), + Name = table.Column(type: "character varying(100)", maxLength: 100, nullable: false), + Kind = table.Column(type: "integer", nullable: false), + Emoji = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + MediaFileId = table.Column(type: "uuid", nullable: true), + Width = table.Column(type: "integer", nullable: false), + Height = table.Column(type: "integer", nullable: false), + SizeBytes = table.Column(type: "integer", nullable: false), + DurationMilliseconds = table.Column(type: "integer", nullable: false), + IsEnabled = table.Column(type: "boolean", nullable: false), + CreatedAt = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ReactionItems", x => x.Id); + table.ForeignKey( + name: "FK_ReactionItems_MediaFiles_MediaFileId", + column: x => x.MediaFileId, + principalTable: "MediaFiles", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_ReactionItems_ReactionPacks_PackId", + column: x => x.PackId, + principalTable: "ReactionPacks", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "UserReactionPacks", + columns: table => new + { + UserId = table.Column(type: "uuid", nullable: false), + PackId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_UserReactionPacks", x => new { x.UserId, x.PackId }); + table.ForeignKey( + name: "FK_UserReactionPacks_ReactionPacks_PackId", + column: x => x.PackId, + principalTable: "ReactionPacks", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserReactionPacks_Users_UserId", + column: x => x.UserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateTable( + name: "ChannelAllowedReactions", + columns: table => new + { + GroupId = table.Column(type: "uuid", nullable: false), + ReactionId = table.Column(type: "uuid", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_ChannelAllowedReactions", x => new { x.GroupId, x.ReactionId }); + table.ForeignKey( + name: "FK_ChannelAllowedReactions_ChatGroups_GroupId", + column: x => x.GroupId, + principalTable: "ChatGroups", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_ChannelAllowedReactions_ReactionItems_ReactionId", + column: x => x.ReactionId, + principalTable: "ReactionItems", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.InsertData( + table: "ReactionPacks", + columns: new[] { "Id", "CreatedAt", "CreatedByUserId", "Description", "IsDefault", "IsEnabled", "Name", "ShareCode" }, + values: new object[] { new Guid("b3000000-0000-0000-0000-000000000001"), new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), null, "Default public emoji reactions", true, true, "Emoji", "default" }); + + migrationBuilder.InsertData( + table: "ReactionItems", + columns: new[] { "Id", "Code", "CreatedAt", "DurationMilliseconds", "Emoji", "Height", "IsEnabled", "Kind", "MediaFileId", "Name", "PackId", "SizeBytes", "Width" }, + values: new object[,] + { + { new Guid("b3000000-0000-0000-0001-000000000001"), "👍", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "👍", 0, true, 0, null, "👍", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000002"), "👎", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "👎", 0, true, 0, null, "👎", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000003"), "❤️", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "❤️", 0, true, 0, null, "❤️", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000004"), "🔥", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🔥", 0, true, 0, null, "🔥", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000005"), "🥰", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🥰", 0, true, 0, null, "🥰", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000006"), "👏", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "👏", 0, true, 0, null, "👏", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000007"), "😁", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "😁", 0, true, 0, null, "😁", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000008"), "🤔", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🤔", 0, true, 0, null, "🤔", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000009"), "😢", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "😢", 0, true, 0, null, "😢", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000010"), "🎉", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🎉", 0, true, 0, null, "🎉", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000011"), "🤯", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🤯", 0, true, 0, null, "🤯", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 }, + { new Guid("b3000000-0000-0000-0001-000000000012"), "🙏", new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), 0, "🙏", 0, true, 0, null, "🙏", new Guid("b3000000-0000-0000-0000-000000000001"), 0, 0 } + }); + + migrationBuilder.CreateIndex( + name: "IX_MessageReactions_ReactionId", + table: "MessageReactions", + column: "ReactionId"); + + migrationBuilder.CreateIndex( + name: "IX_ChannelAllowedReactions_ReactionId", + table: "ChannelAllowedReactions", + column: "ReactionId"); + + migrationBuilder.CreateIndex( + name: "IX_ReactionItems_Code", + table: "ReactionItems", + column: "Code", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_ReactionItems_MediaFileId", + table: "ReactionItems", + column: "MediaFileId"); + + migrationBuilder.CreateIndex( + name: "IX_ReactionItems_PackId", + table: "ReactionItems", + column: "PackId"); + + migrationBuilder.CreateIndex( + name: "IX_ReactionPacks_CreatedByUserId", + table: "ReactionPacks", + column: "CreatedByUserId"); + + migrationBuilder.CreateIndex( + name: "IX_ReactionPacks_IsDefault", + table: "ReactionPacks", + column: "IsDefault", + unique: true, + filter: "\"IsDefault\" = TRUE"); + + migrationBuilder.CreateIndex( + name: "IX_ReactionPacks_ShareCode", + table: "ReactionPacks", + column: "ShareCode", + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_UserReactionPacks_PackId", + table: "UserReactionPacks", + column: "PackId"); + + migrationBuilder.AddForeignKey( + name: "FK_MessageReactions_ReactionItems_ReactionId", + table: "MessageReactions", + column: "ReactionId", + principalTable: "ReactionItems", + principalColumn: "Id", + onDelete: ReferentialAction.Restrict); + // Link known legacy emoji receipts to the seeded catalogue; preserve unknown codes. + migrationBuilder.Sql(""" + UPDATE "MessageReactions" AS mr + SET "ReactionId" = (SELECT ri."Id" FROM "ReactionItems" AS ri + WHERE ri."Code" = mr."ReactionCode" AND ri."PackId" = 'b3000000-0000-0000-0000-000000000001') + WHERE mr."ReactionId" IS NULL AND EXISTS (SELECT 1 FROM "ReactionItems" AS ri + WHERE ri."Code" = mr."ReactionCode" AND ri."PackId" = 'b3000000-0000-0000-0000-000000000001'); + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropForeignKey( + name: "FK_MessageReactions_ReactionItems_ReactionId", + table: "MessageReactions"); + + migrationBuilder.DropTable( + name: "ChannelAllowedReactions"); + + migrationBuilder.DropTable( + name: "UserReactionPacks"); + + migrationBuilder.DropTable( + name: "ReactionItems"); + + migrationBuilder.DropTable( + name: "ReactionPacks"); + + migrationBuilder.DropIndex( + name: "IX_MessageReactions_ReactionId", + table: "MessageReactions"); + + migrationBuilder.DropColumn( + name: "ReactionsVersion", + table: "Messages"); + + migrationBuilder.DropColumn( + name: "ReactionId", + table: "MessageReactions"); + + migrationBuilder.DropColumn( + name: "ReactionMode", + table: "ChatGroups"); + + migrationBuilder.DropColumn( + name: "ReactionPolicyVersion", + table: "ChatGroups"); + } + } +} diff --git a/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs b/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs index 5e8d8c5..4d8a41d 100644 --- a/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs +++ b/Govor.Domain/Migrations/GovorDbContextModelSnapshot.cs @@ -47,6 +47,12 @@ namespace Govor.Domain.Migrations .HasMaxLength(100) .HasColumnType("character varying(100)"); + b.Property("ReactionMode") + .HasColumnType("integer"); + + b.Property("ReactionPolicyVersion") + .HasColumnType("bigint"); + b.HasKey("Id"); b.ToTable("ChatGroups"); @@ -243,6 +249,24 @@ namespace Govor.Domain.Migrations b.ToTable("MediaFiles"); }); + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.Property("MessageId") + .HasColumnType("uuid"); + + b.Property("Attempts") + .HasColumnType("integer"); + + b.Property("NextAttemptAt") + .HasColumnType("timestamp with time zone"); + + b.HasKey("MessageId"); + + b.HasIndex("NextAttemptAt"); + + b.ToTable("ChatPushNotifications"); + }); + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => { b.Property("Id") @@ -286,6 +310,9 @@ namespace Govor.Domain.Migrations b.Property("PrivateChatId") .HasColumnType("uuid"); + b.Property("ReactionsVersion") + .HasColumnType("bigint"); + b.Property("RecipientId") .HasColumnType("uuid"); @@ -329,11 +356,16 @@ namespace Govor.Domain.Migrations .HasMaxLength(64) .HasColumnType("character varying(64)"); + b.Property("ReactionId") + .HasColumnType("uuid"); + b.Property("UserId") .HasColumnType("uuid"); b.HasKey("Id"); + b.HasIndex("ReactionId"); + b.HasIndex("UserId"); b.HasIndex("MessageId", "UserId") @@ -382,6 +414,336 @@ namespace Govor.Domain.Migrations b.ToTable("PrivateChats"); }); + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.Property("GroupId") + .HasColumnType("uuid"); + + b.Property("ReactionId") + .HasColumnType("uuid"); + + b.HasKey("GroupId", "ReactionId"); + + b.HasIndex("ReactionId"); + + b.ToTable("ChannelAllowedReactions"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("Code") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("DurationMilliseconds") + .HasColumnType("integer"); + + b.Property("Emoji") + .HasMaxLength(64) + .HasColumnType("character varying(64)"); + + b.Property("Height") + .HasColumnType("integer"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Kind") + .HasColumnType("integer"); + + b.Property("MediaFileId") + .HasColumnType("uuid"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.Property("SizeBytes") + .HasColumnType("integer"); + + b.Property("Width") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("Code") + .IsUnique(); + + b.HasIndex("MediaFileId"); + + b.HasIndex("PackId"); + + b.ToTable("ReactionItems"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000001"), + Code = "👍", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👍", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👍", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000002"), + Code = "👎", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👎", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👎", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000003"), + Code = "❤️", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "❤️", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "❤️", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000004"), + Code = "🔥", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🔥", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🔥", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000005"), + Code = "🥰", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🥰", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🥰", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000006"), + Code = "👏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "👏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "👏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000007"), + Code = "😁", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😁", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😁", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000008"), + Code = "🤔", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤔", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤔", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000009"), + Code = "😢", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "😢", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "😢", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000010"), + Code = "🎉", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🎉", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🎉", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000011"), + Code = "🤯", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🤯", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🤯", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }, + new + { + Id = new Guid("b3000000-0000-0000-0001-000000000012"), + Code = "🙏", + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + DurationMilliseconds = 0, + Emoji = "🙏", + Height = 0, + IsEnabled = true, + Kind = 0, + Name = "🙏", + PackId = new Guid("b3000000-0000-0000-0000-000000000001"), + SizeBytes = 0, + Width = 0 + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(500) + .HasColumnType("character varying(500)"); + + b.Property("IsDefault") + .HasColumnType("boolean"); + + b.Property("IsEnabled") + .HasColumnType("boolean"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("ShareCode") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.HasIndex("IsDefault") + .IsUnique() + .HasFilter("\"IsDefault\" = TRUE"); + + b.HasIndex("ShareCode") + .IsUnique(); + + b.ToTable("ReactionPacks"); + + b.HasData( + new + { + Id = new Guid("b3000000-0000-0000-0000-000000000001"), + CreatedAt = new DateTime(2026, 10, 3, 0, 0, 0, 0, DateTimeKind.Utc), + Description = "Default public emoji reactions", + IsDefault = true, + IsEnabled = true, + Name = "Emoji", + ShareCode = "default" + }); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.Property("UserId") + .HasColumnType("uuid"); + + b.Property("PackId") + .HasColumnType("uuid"); + + b.HasKey("UserId", "PackId"); + + b.HasIndex("PackId"); + + b.ToTable("UserReactionPacks"); + }); + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => { b.Property("UserId") @@ -668,6 +1030,15 @@ namespace Govor.Domain.Migrations b.Navigation("ChatGroup"); }); + modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b => + { + b.HasOne("Govor.Domain.Models.Messages.Message", null) + .WithMany() + .HasForeignKey("MessageId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => { b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") @@ -706,6 +1077,11 @@ namespace Govor.Domain.Migrations .OnDelete(DeleteBehavior.Cascade) .IsRequired(); + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict); + b.HasOne("Govor.Domain.Models.Users.User", "User") .WithMany() .HasForeignKey("UserId") @@ -726,6 +1102,60 @@ namespace Govor.Domain.Migrations .IsRequired(); }); + modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b => + { + b.HasOne("Govor.Domain.Models.ChatGroup", null) + .WithMany() + .HasForeignKey("GroupId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null) + .WithMany() + .HasForeignKey("ReactionId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b => + { + b.HasOne("Govor.Domain.Models.MediaFile", null) + .WithMany() + .HasForeignKey("MediaFileId") + .OnDelete(DeleteBehavior.Restrict); + + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", "Pack") + .WithMany("Reactions") + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Pack"); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.SetNull); + }); + + modelBuilder.Entity("Govor.Domain.Models.Reactions.UserReactionPack", b => + { + b.HasOne("Govor.Domain.Models.Reactions.ReactionPack", null) + .WithMany() + .HasForeignKey("PackId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Govor.Domain.Models.Users.User", null) + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => { b.HasOne("Govor.Domain.Models.Users.User", "User") @@ -822,6 +1252,11 @@ namespace Govor.Domain.Migrations b.Navigation("Messages"); }); + modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b => + { + b.Navigation("Reactions"); + }); + modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => { b.Navigation("OneTimePreKeys"); diff --git a/Govor.Domain/Models/ChatGroup.cs b/Govor.Domain/Models/ChatGroup.cs index d6d8f30..8098ce4 100644 --- a/Govor.Domain/Models/ChatGroup.cs +++ b/Govor.Domain/Models/ChatGroup.cs @@ -9,6 +9,8 @@ public class ChatGroup public string Description { get; set; } public Guid ImageId { get; set; } public bool IsChannel { get; set; } + public Govor.Domain.Models.Reactions.ChannelReactionMode ReactionMode { get; set; } + public long ReactionPolicyVersion { get; set; } public bool IsPrivate { get; set; } public List Admins { get; set; } = new(); public List Members { get; set; } = new(); @@ -26,4 +28,4 @@ public class ChatGroup IsChannel == chatGroup.IsChannel && IsPrivate == chatGroup.IsPrivate; } -} \ No newline at end of file +} diff --git a/Govor.Domain/Models/MediaFile.cs b/Govor.Domain/Models/MediaFile.cs index c3ef8be..f20009f 100644 --- a/Govor.Domain/Models/MediaFile.cs +++ b/Govor.Domain/Models/MediaFile.cs @@ -20,5 +20,6 @@ public enum MediaOwnerType Message = 0, Avatar = 1, GroupAvatar = 2, - System = 3 // (Emoge, icons � e.t.c) -} \ No newline at end of file + System = 3, // (Emoge, icons and other system assets) + Reaction = 4 +} diff --git a/Govor.Domain/Models/Messages/ChatPushNotification.cs b/Govor.Domain/Models/Messages/ChatPushNotification.cs new file mode 100644 index 0000000..a56b544 --- /dev/null +++ b/Govor.Domain/Models/Messages/ChatPushNotification.cs @@ -0,0 +1,8 @@ +namespace Govor.Domain.Models.Messages; + +public class ChatPushNotification +{ + public Guid MessageId { get; set; } + public DateTime NextAttemptAt { get; set; } + public int Attempts { get; set; } +} diff --git a/Govor.Domain/Models/Messages/Message.cs b/Govor.Domain/Models/Messages/Message.cs index c8e423b..09120cf 100644 --- a/Govor.Domain/Models/Messages/Message.cs +++ b/Govor.Domain/Models/Messages/Message.cs @@ -15,6 +15,7 @@ public class Message public List MessageViews { get; set; } = new List(); public Guid? ReplyToMessageId { get; set; } + public long ReactionsVersion { get; set; } public override bool Equals(object? obj) { @@ -36,4 +37,4 @@ public enum RecipientType { User, Group -} \ No newline at end of file +} diff --git a/Govor.Domain/Models/Messages/MessageReaction.cs b/Govor.Domain/Models/Messages/MessageReaction.cs index 0f0ea71..7bdf4d3 100644 --- a/Govor.Domain/Models/Messages/MessageReaction.cs +++ b/Govor.Domain/Models/Messages/MessageReaction.cs @@ -13,5 +13,6 @@ public class MessageReaction public User User { get; set; } public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:" + public Guid? ReactionId { get; set; } public DateTime ReactedAt { get; set; } = DateTime.UtcNow; -} \ No newline at end of file +} diff --git a/Govor.Domain/Models/Reactions/DefaultReactionPack.cs b/Govor.Domain/Models/Reactions/DefaultReactionPack.cs new file mode 100644 index 0000000..0ad2b29 --- /dev/null +++ b/Govor.Domain/Models/Reactions/DefaultReactionPack.cs @@ -0,0 +1,19 @@ +namespace Govor.Domain.Models.Reactions; + +public static class DefaultReactionPack +{ + public static readonly Guid Id = Guid.Parse("b3000000-0000-0000-0000-000000000001"); + private static readonly DateTime CreatedAt = new(2026, 10, 3, 0, 0, 0, DateTimeKind.Utc); + public static ReactionPack Create() => new() + { + Id = Id, Name = "Emoji", Description = "Default public emoji reactions", + ShareCode = "default", IsDefault = true, IsEnabled = true, CreatedAt = CreatedAt + }; + public static ReactionItem[] Items() => new[] { "👍", "👎", "❤️", "🔥", "🥰", "👏", "😁", "🤔", "😢", "🎉", "🤯", "🙏" } + .Select((emoji, index) => new ReactionItem + { + Id = Guid.Parse($"b3000000-0000-0000-0001-{index + 1:000000000000}"), + PackId = Id, Code = emoji, Name = emoji, Emoji = emoji, + Kind = ReactionKind.Emoji, IsEnabled = true, CreatedAt = CreatedAt + }).ToArray(); +} diff --git a/Govor.Domain/Models/Reactions/ReactionItem.cs b/Govor.Domain/Models/Reactions/ReactionItem.cs new file mode 100644 index 0000000..76cd968 --- /dev/null +++ b/Govor.Domain/Models/Reactions/ReactionItem.cs @@ -0,0 +1,34 @@ +namespace Govor.Domain.Models.Reactions; + +public enum ReactionKind { Emoji, Image, Gif } +public enum ChannelReactionMode { All, None, Selected } + +public class ReactionItem +{ + public Guid Id { get; set; } + public Guid PackId { get; set; } + public ReactionPack Pack { get; set; } = null!; + public string Code { get; set; } = string.Empty; + public string Name { get; set; } = string.Empty; + public ReactionKind Kind { get; set; } + public string? Emoji { get; set; } + public Guid? MediaFileId { get; set; } + public int Width { get; set; } + public int Height { get; set; } + public int SizeBytes { get; set; } + public int DurationMilliseconds { get; set; } + public bool IsEnabled { get; set; } = true; + public DateTime CreatedAt { get; set; } +} + +public class UserReactionPack +{ + public Guid UserId { get; set; } + public Guid PackId { get; set; } +} + +public class ChannelAllowedReaction +{ + public Guid GroupId { get; set; } + public Guid ReactionId { get; set; } +} diff --git a/Govor.Domain/Models/Reactions/ReactionPack.cs b/Govor.Domain/Models/Reactions/ReactionPack.cs new file mode 100644 index 0000000..e4f7883 --- /dev/null +++ b/Govor.Domain/Models/Reactions/ReactionPack.cs @@ -0,0 +1,14 @@ +namespace Govor.Domain.Models.Reactions; + +public class ReactionPack +{ + public Guid Id { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string ShareCode { get; set; } = string.Empty; + public bool IsDefault { get; set; } + public bool IsEnabled { get; set; } = true; + public Guid? CreatedByUserId { get; set; } + public DateTime CreatedAt { get; set; } + public List Reactions { get; set; } = []; +} diff --git a/Govor.Server.Tests/Govor.Server.Tests.csproj b/Govor.Server.Tests/Govor.Server.Tests.csproj new file mode 100644 index 0000000..b5e6abe --- /dev/null +++ b/Govor.Server.Tests/Govor.Server.Tests.csproj @@ -0,0 +1,21 @@ + + + net10.0 + enable + enable + false + true + + + + + + + + + + + + ../libs/SmartRes.dll + + diff --git a/Govor.Server.Tests/HubSessionTests.cs b/Govor.Server.Tests/HubSessionTests.cs new file mode 100644 index 0000000..31ee5a7 --- /dev/null +++ b/Govor.Server.Tests/HubSessionTests.cs @@ -0,0 +1,37 @@ +using Govor.API.Filters; +using Govor.Contracts.Responses.SignalR; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +public class HubSessionTests +{ + [Test] + public async Task InvalidSessionReturnsAHubResultAndAbortsWithoutRunningMethod() + { + using var db = new TestDatabase(); + var caller = new Mock(); + var hub = new StubHub(); + var invocation = new HubInvocationContext(caller.Object, Mock.Of(), hub, + typeof(StubHub).GetMethod(nameof(StubHub.Echo))!, Array.Empty()); + var filter = new HubExceptionFilter(NullLogger.Instance, db.Context); + var invoked = false; + var response = await filter.InvokeMethodAsync(invocation, _ => + { + invoked = true; + return ValueTask.FromResult(HubResult.Ok("unexpected")); + }); + Assert.That(invoked, Is.False); + Assert.That(response, Is.TypeOf>()); + Assert.That(((HubResult)response!).Status, Is.EqualTo(HubResultStatus.Unauthorized)); + caller.Verify(c => c.Abort(), Times.Once); + } + + private sealed class StubHub : Hub + { + public Task> Echo() => Task.FromResult(HubResult.Ok("ok")); + } +} diff --git a/Govor.Server.Tests/MessageAccessTests.cs b/Govor.Server.Tests/MessageAccessTests.cs new file mode 100644 index 0000000..87f9a7c --- /dev/null +++ b/Govor.Server.Tests/MessageAccessTests.cs @@ -0,0 +1,218 @@ +using Govor.Application.Infrastructure.Common; +using Govor.Application.Medias; +using Govor.Application.Messages; +using Govor.Application.Messages.Parameters; +using Govor.Domain.Common; +using Govor.Domain.Models; +using Govor.Domain.Models.Messages; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +public class MessageAccessTests +{ + private TestDatabase _db = null!; + private MessageReadingService _reader = null!; + private readonly DateTime _now = new(2026, 10, 3, 0, 0, 0, DateTimeKind.Utc); + + [SetUp] + public void SetUp() + { + _db = new TestDatabase(); + var clock = new Mock(); + clock.SetupGet(c => c.Now).Returns(_now); + _reader = new MessageReadingService(_db.Context, NullLogger.Instance, clock.Object); + } + + [TearDown] + public void TearDown() => _db.Dispose(); + + [Test] + public async Task OutsiderCannotLoadSendReadOrDownloadPrivateMessages() + { + // The outsider has a different chat; that must not grant access to Alice–Bob. + _db.Context.PrivateChats.Add(new PrivateChat + { Id = Guid.NewGuid(), UserAId = _db.Outsider, UserBId = _db.Alice }); + var message = _db.AddMessage(); + var loader = new MessagesLoader(_db.Context); + var loaded = await loader.LoadMessagesInUserChat(_db.ChatId, _db.Outsider, null); + var read = await _reader.ReadMessageAsync(_db.Outsider, message.Id); + var sender = new MessageSendingService(_db.Context, NullLogger.Instance); + var sent = await sender.SendMessageAsync(new SendMessage("intrusion", null, _db.ChatId, + RecipientType.User, _db.Outsider, _now, [])); + Assert.Multiple(() => + { + Assert.That(loaded.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(read.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(sent.IsSuccess, Is.False); + }); + Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero); + Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task RepeatedSingleReadReturnsTheSameReceipt() + { + var message = _db.AddMessage(); + var first = await _reader.ReadMessageAsync(_db.Bob, message.Id); + var second = await _reader.ReadMessageAsync(_db.Bob, message.Id); + Assert.That(first.IsSuccess && second.IsSuccess, Is.True); + Assert.That(second.Value.MessageViews.Single().Id, Is.EqualTo(first.Value.MessageViews.Single().Id)); + Assert.That(second.Value.MessageViews.Single().ViewedAt, Is.EqualTo(_now)); + Assert.That(await _db.Context.MessageViews.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task VisibleMessageSelectionDoesNotReadOffscreenOrOwnMessages() + { + var visible = _db.AddMessage(); + _db.AddMessage(); + _db.AddMessage(_db.Bob); + var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, [visible.Id]); + Assert.That(result.IsSuccess, Is.True); + Assert.That(result.Value.ReadCount, Is.EqualTo(1)); + Assert.That(result.Value.UnreadCount, Is.EqualTo(1)); + Assert.That(await _db.Context.MessageViews.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task InvalidMixedChatSelectionDoesNotPartiallyWrite() + { + var valid = _db.AddMessage(); + var other = _db.AddMessage(chat: Guid.NewGuid()); + var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, [valid.Id, other.Id]); + Assert.That(result.IsFailure, Is.True); + Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero); + } + + [Test] + public async Task ReadThroughBoundaryHandlesEqualTimestampsAndLeavesNewerUnread() + { + var earlier = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000001")); + var boundary = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000002")); + _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000003")); + _db.AddMessage(sentAt: _now.AddSeconds(1)); + var result = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User, upToMessageId: boundary.Id); + Assert.That(result.IsSuccess, Is.True); + Assert.That(result.Value.ReadCount, Is.EqualTo(2)); + Assert.That(result.Value.UnreadCount, Is.EqualTo(2)); + Assert.That(await _db.Context.MessageViews.AnyAsync(v => v.MessageId == earlier.Id), Is.True); + } + + [Test] + public async Task MarkAllReadsMoreThanOneBatchAndSurvivesRepeatedCall() + { + for (var i = 0; i < 205; i++) + _db.AddMessage(sentAt: _now.AddSeconds(i)); + _db.AddMessage(_db.Bob, sentAt: _now.AddSeconds(300)); + var first = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User); + var second = await _reader.ReadChatAsync(_db.Bob, _db.ChatId, RecipientType.User); + Assert.That(first.Value.ReadCount, Is.EqualTo(205)); + Assert.That(second.Value.ReadCount, Is.Zero); + Assert.That(second.Value.UnreadCount, Is.Zero); + } + + [Test] + public async Task GroupReadRequiresMembershipAndExcludesOwnMessages() + { + var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" }; + _db.Context.ChatGroups.Add(group); + _db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob }); + _db.Context.SaveChanges(); + _db.AddMessage(chat: group.Id, type: RecipientType.Group); + _db.AddMessage(_db.Bob, group.Id, RecipientType.Group); + var denied = await _reader.ReadChatAsync(_db.Outsider, group.Id, RecipientType.Group); + var read = await _reader.ReadChatAsync(_db.Bob, group.Id, RecipientType.Group); + Assert.That(denied.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(read.Value.ReadCount, Is.EqualTo(1)); + Assert.That(read.Value.UnreadCount, Is.Zero); + } + + [Test] + public async Task PrivateAttachmentIsAvailableToBothParticipantsOnly() + { + var message = _db.AddMessage(); + var file = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Alice, + Url = "test", MineType = "image/png", OwnerType = MediaOwnerType.Message }; + _db.Context.MediaFiles.Add(file); + _db.Context.MediaAttachments.Add(new MediaAttachments + { Id = Guid.NewGuid(), MessageId = message.Id, MediaFileId = file.Id }); + _db.Context.SaveChanges(); + var access = new AccesserToDownloadMediaService(_db.Context); + Assert.That(await access.HasAccessAsync(file.Id, _db.Alice), Is.True); + Assert.That(await access.HasAccessAsync(file.Id, _db.Bob), Is.True); + Assert.That(await access.HasAccessAsync(file.Id, _db.Outsider), Is.False); + } + + [Test] + public async Task HideForMeNeverDeletesForEveryone() + { + var message = _db.AddMessage(); + var remover = new MessageRemovingService(_db.Context, NullLogger.Instance); + var result = await remover.DeleteMessageAsync(new DeleteMessage(_db.Alice, message.Id, false)); + Assert.That(result.IsFailure, Is.True); + Assert.That(await _db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.True); + } + + [Test] + public async Task SameTimestampHistoryDoesNotSkipMessagesAroundCursor() + { + var earlier = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000001")); + var cursor = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000002")); + var later = _db.AddMessage(sentAt: _now, id: Guid.Parse("00000000-0000-0000-0000-000000000003")); + var result = await new MessagesLoader(_db.Context).LoadMessagesInUserChat(_db.ChatId, _db.Bob, cursor.Id); + Assert.That(result.Value.Select(m => m.Id), Is.EqualTo(new[] { earlier.Id, cursor.Id, later.Id })); + } + + [Test] + public async Task RecipientCannotEditOrDeleteAnotherAuthorsMessage() + { + var message = _db.AddMessage(sentAt: _now); + var editor = new MessageEditingService(_db.Context, NullLogger.Instance, + Microsoft.Extensions.Options.Options.Create(new MessageEditingOptions())); + var edited = await editor.EditMessageAsync(new EditMessage(_db.Bob, message.Id, "changed", _now)); + var remover = new MessageRemovingService(_db.Context, NullLogger.Instance); + var removed = await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true)); + Assert.That(edited.Exception, Is.TypeOf()); + Assert.That(removed.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That((await _db.Context.Messages.AsNoTracking().SingleAsync()).EncryptedContent, Is.EqualTo("hello")); + } + + [Test] + public async Task BannedGroupMemberCannotLoadSendOrReadMessages() + { + var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" }; + _db.Context.ChatGroups.Add(group); + _db.Context.GroupMemberships.Add(new GroupMembership + { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob, IsBanned = true }); + _db.Context.SaveChanges(); + var loaded = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(group.Id, _db.Bob, null); + var read = await _reader.ReadChatAsync(_db.Bob, group.Id, RecipientType.Group); + var sent = await new MessageSendingService(_db.Context, NullLogger.Instance) + .SendMessageAsync(new SendMessage("hello", null, group.Id, RecipientType.Group, _db.Bob, _now, [])); + Assert.That(loaded.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(read.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(sent.Exception, Is.TypeOf()); + } + + [Test] + public async Task ForeignUploadAndReplyFromAnotherChatCannotBeAttached() + { + var file = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Bob, + Url = "test", MineType = "image/png", OwnerType = MediaOwnerType.Message }; + _db.Context.MediaFiles.Add(file); + _db.Context.SaveChanges(); + var sender = new MessageSendingService(_db.Context, NullLogger.Instance); + var attachment = await sender.SendMessageAsync(new SendMessage("hello", null, _db.ChatId, + RecipientType.User, _db.Alice, _now, new[] { new SendMedia(file.Id, "") })); + var other = _db.AddMessage(chat: Guid.NewGuid()); + var reply = await sender.SendMessageAsync(new SendMessage("hello", other.Id, _db.ChatId, + RecipientType.User, _db.Alice, _now, [])); + Assert.That(attachment.Exception, Is.TypeOf()); + Assert.That(reply.Exception, Is.TypeOf()); + Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero); + } +} diff --git a/Govor.Server.Tests/NotificationTests.cs b/Govor.Server.Tests/NotificationTests.cs new file mode 100644 index 0000000..2d95748 --- /dev/null +++ b/Govor.Server.Tests/NotificationTests.cs @@ -0,0 +1,162 @@ +using Govor.API.Hubs; +using Govor.API.Hubs.Infrastructure; +using Govor.Application.PrivateUserChats; +using Govor.Application.Profiles; +using Govor.Application.PushNotifications; +using Govor.Contracts.Responses.SignalR; +using Govor.Domain.Common; +using Govor.Domain.Models; +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Users; +using Microsoft.AspNetCore.SignalR; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using SmartRes; + +namespace Govor.Server.Tests; + +[TestFixture] +public class NotificationTests +{ + private TestDatabase _db = null!; + private Mock _push = null!; + private Mock _proxy = null!; + private ChatNotificationService _notifier = null!; + private readonly List<(string Method, string[] Groups)> _events = []; + private string[] _targetGroups = []; + private Guid _aliceSession; + private Guid _bobSession; + + [SetUp] + public void SetUp() + { + _db = new TestDatabase(); + _events.Clear(); + _aliceSession = AddSession(_db.Alice); + _bobSession = AddSession(_db.Bob); + AddSession(_db.Bob, revoked: true); + AddSession(_db.Outsider); + _proxy = new Mock(); + _proxy.Setup(p => p.SendCoreAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .Callback((method, _, _) => _events.Add((method, _targetGroups))) + .Returns(Task.CompletedTask); + var clients = new Mock(); + clients.Setup(c => c.Groups(It.IsAny>())) + .Callback>(groups => _targetGroups = groups.ToArray()) + .Returns(_proxy.Object); + var hub = new Mock>(); + hub.SetupGet(h => h.Clients).Returns(clients.Object); + var chats = new Mock(); + chats.Setup(c => c.GetPrivateChatAsync(_db.ChatId)) + .ReturnsAsync(Result.Success(_db.Context.PrivateChats.Single())); + var profiles = new Mock(); + profiles.Setup(p => p.GetUserProfileAsync(_db.Alice)) + .ReturnsAsync(Result.Success(new UserProfile { Id = _db.Alice, Username = "Alice" })); + _push = new Mock(); + _push.Setup(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny?>())) + .ReturnsAsync(Govor.Domain.Common.Result.Success()); + _notifier = new ChatNotificationService(hub.Object, _push.Object, chats.Object, profiles.Object, + _db.Context, NullLogger.Instance); + } + + [TearDown] + public void TearDown() => _db.Dispose(); + + [Test] + public async Task PrivateMessageReachesBothActiveSessionsAndPushGoesOnlyToRecipient() + { + var message = Message(); + await _notifier.NotifyMessageSentAsync(message); + await _notifier.DeliverPushAsync(message); + Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups, + Is.EquivalentTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); + Assert.That(_events.Single(e => e.Method == ChatHubConstants.MessageSent).Groups, + Is.EqualTo(new[] { ChatHubConstants.GetSessionGroup(_aliceSession) })); + _push.Verify(p => p.SendToUsersAsync(It.Is>(ids => ids.SequenceEqual(new[] { _db.Bob })), + "Alice", "hello", "chat_messages", $"chat_{_db.ChatId}", + It.Is?>(data => data != null && data["messageId"] == message.MessageId.ToString())), Times.Once); + } + + [Test] + public async Task GroupMessageExcludesBannedMembersFromSignalRAndPush() + { + var group = new ChatGroup { Id = Guid.NewGuid(), Name = "group", Description = "" }; + _db.Context.ChatGroups.Add(group); + foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider }) + _db.Context.GroupMemberships.Add(new GroupMembership + { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider }); + _db.Context.SaveChanges(); + var message = Message(); + message.RecipientId = group.Id; + message.RecipientType = RecipientType.Group; + await _notifier.NotifyMessageSentAsync(message); + await _notifier.DeliverPushAsync(message); + Assert.That(_events.Single(e => e.Method == ChatHubConstants.ReceiveMessage).Groups.Length, Is.EqualTo(2)); + _push.Verify(p => p.SendToUsersAsync(It.Is>(ids => ids.SequenceEqual(new[] { _db.Bob })), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny?>()), Times.Once); + } + + [Test] + public async Task SignalRFailureStillAttemptsPushAndProviderFailureDoesNotFailSavedSend() + { + _proxy.Setup(p => p.SendCoreAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ThrowsAsync(new InvalidOperationException("offline")); + _push.Setup(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny?>())) + .ThrowsAsync(new InvalidOperationException("provider unavailable")); + await _notifier.NotifyMessageSentAsync(Message()); + Assert.That(await _notifier.DeliverPushAsync(Message()), Is.False); + _push.Verify(p => p.SendToUsersAsync(It.IsAny>(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny?>()), Times.Once); + } + + [Test] + public async Task ReadNotificationReachesReaderAndAuthorDevices() + { + await _notifier.NotifyChatReadAsync(new ChatReadResponse { ChatId = _db.ChatId, ReaderId = _db.Bob, RecipientType = RecipientType.User }); + Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChatRead)); + Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] + { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); + } + + [Test] + public async Task ReactionChangesReachBothParticipantsActiveDevices() + { + await _notifier.NotifyMessageReactionsChangedAsync(new MessageReactionsChangedResponse + { MessageId = Guid.NewGuid(), RecipientId = _db.ChatId, RecipientType = RecipientType.User, ActorId = _db.Bob }); + Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.MessageReactionsChanged)); + Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] + { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); + } + + [Test] + public async Task ChannelPolicyChangesExcludeBannedMembers() + { + var group = new ChatGroup { Id = Guid.NewGuid(), Name = "channel", Description = "", IsChannel = true }; + _db.Context.ChatGroups.Add(group); + foreach (var user in new[] { _db.Alice, _db.Bob, _db.Outsider }) + _db.Context.GroupMemberships.Add(new GroupMembership + { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user, IsBanned = user == _db.Outsider }); + await _db.Context.SaveChangesAsync(); + await _notifier.NotifyChannelReactionPolicyChangedAsync(new ChannelReactionPolicyResponse { GroupId = group.Id }); + Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.ChannelReactionPolicyChanged)); + Assert.That(_events.Single().Groups, Is.EquivalentTo(new[] + { ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) })); + } + + private Guid AddSession(Guid userId, bool revoked = false) + { + var session = new UserSession { UserId = userId, RefreshTokenHash = Guid.NewGuid().ToString(), IsRevoked = revoked, ExpiresAt = DateTime.UtcNow.AddDays(1) }; + _db.Context.UserSessions.Add(session); + _db.Context.SaveChanges(); + return session.Id; + } + + private UserMessageResponse Message() => new() + { + MessageId = Guid.NewGuid(), SenderId = _db.Alice, RecipientId = _db.ChatId, + RecipientType = RecipientType.User, EncryptedContent = "hello" + }; +} diff --git a/Govor.Server.Tests/PushReliabilityTests.cs b/Govor.Server.Tests/PushReliabilityTests.cs new file mode 100644 index 0000000..baf4a00 --- /dev/null +++ b/Govor.Server.Tests/PushReliabilityTests.cs @@ -0,0 +1,122 @@ +using Govor.API.Hubs.Infrastructure; +using Govor.Application.Infrastructure.Common; +using Govor.Application.Messages; +using Govor.Application.Messages.Parameters; +using Govor.Application.Profiles; +using Govor.Application.PushNotifications; +using Govor.Contracts.Responses.SignalR; +using Govor.Domain.Common; +using Govor.Domain.Models; +using Govor.Domain.Models.Users; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +public class PushReliabilityTests +{ + private TestDatabase _db = null!; + private Mock _clock = null!; + private PushTokenService _tokens = null!; + private DateTime _now; + + [SetUp] + public void SetUp() + { + _db = new TestDatabase(); + _now = DateTime.UtcNow.AddMinutes(1); + _clock = new Mock(); + _clock.SetupGet(c => c.Now).Returns(() => _now); + _tokens = new PushTokenService(_db.Context, _clock.Object, NullLogger.Instance); + } + + [TearDown] + public void TearDown() => _db.Dispose(); + + [Test] + public async Task SavedMessageHasDurablePushAndFailureRetriesAfterBackoff() + { + var sender = new MessageSendingService(_db.Context, NullLogger.Instance); + var sent = await sender.SendMessageAsync(new SendMessage("hello", null, _db.ChatId, + Govor.Domain.Models.Messages.RecipientType.User, _db.Alice, _now, [])); + Assert.That(sent.IsSuccess, Is.True); + Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.EqualTo(1)); + var notifier = new Mock(); + notifier.SetupSequence(n => n.DeliverPushAsync(It.IsAny())).ReturnsAsync(false).ReturnsAsync(true); + var dispatcher = new ChatPushDispatcher(_db.Context, notifier.Object, _clock.Object); + await dispatcher.DispatchAsync(); + var pending = await _db.Context.ChatPushNotifications.AsNoTracking().SingleAsync(); + Assert.That(pending.Attempts, Is.EqualTo(1)); + Assert.That(pending.NextAttemptAt, Is.GreaterThan(_now)); + await dispatcher.DispatchAsync(); + notifier.Verify(n => n.DeliverPushAsync(It.IsAny()), Times.Once); + _now = pending.NextAttemptAt.AddSeconds(1); + // A new scope simulates worker restart, while the queued row remains durable. + using var restarted = _db.CreateContext(); + await new ChatPushDispatcher(restarted, notifier.Object, _clock.Object).DispatchAsync(); + notifier.Verify(n => n.DeliverPushAsync(It.IsAny()), Times.Exactly(2)); + Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero); + } + + [Test] + public async Task ReassignedDeviceTokenCannotNotifyThePreviousAccount() + { + var aliceSession = AddSession(_db.Alice); + var bobSession = AddSession(_db.Bob); + await _tokens.AddOrUpdateTokenAsync(_db.Alice, aliceSession, "device-token", "android"); + await _tokens.AddOrUpdateTokenAsync(_db.Bob, bobSession, "other-token", "android"); + var result = await _tokens.AddOrUpdateTokenAsync(_db.Bob, bobSession, "device-token", "ios"); + Assert.That(result.IsSuccess, Is.True); + Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Alice)).Value, Is.Empty); + Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.EqualTo(new[] { "device-token" })); + Assert.That(await _db.Context.UserPushTokens.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task InactiveTokenCanBeReactivatedButForeignSessionCannotRegisterIt() + { + var session = AddSession(_db.Bob); + await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android"); + await _tokens.DeactivateTokenBySessionAsync(session); + _db.Context.ChangeTracker.Clear(); + Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.Empty); + await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android"); + Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Has.Count.EqualTo(1)); + var foreign = await _tokens.AddOrUpdateTokenAsync(_db.Alice, session, "stolen", "android"); + Assert.That(foreign.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + } + + [Test] + public async Task ExpiredOrRevokedSessionTokensAreExcludedWithoutWaitingForCleanup() + { + var session = AddSession(_db.Bob); + await _tokens.AddOrUpdateTokenAsync(_db.Bob, session, "token", "android"); + await _db.Context.UserSessions.Where(s => s.Id == session) + .ExecuteUpdateAsync(s => s.SetProperty(row => row.IsRevoked, true)); + Assert.That((await _tokens.GetStringsActiveTokensAsync(_db.Bob)).Value, Is.Empty); + Assert.That((await _tokens.GetUsersStringsActiveTokensAsync(new[] { _db.Bob })).Value, Is.Empty); + Assert.That((await _tokens.GetActiveTokenBySessionAsync(session)).Value, Is.Null); + } + + [Test] + public async Task ForeignAttachmentCannotBePublishedAsAnAvatar() + { + var media = new MediaFile { Id = Guid.NewGuid(), UploaderId = _db.Alice, + OwnerType = MediaOwnerType.Message, Url = "test", MineType = "image/png" }; + _db.Context.MediaFiles.Add(media); + _db.Context.SaveChanges(); + var profiles = new ProfileService(_db.Context, NullLogger.Instance); + var forbidden = await profiles.SetNewIcon(_db.Bob, media.Id); + Assert.That(forbidden.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + } + + private Guid AddSession(Guid user) + { + var session = new UserSession { UserId = user, ExpiresAt = _now.AddDays(1), RefreshTokenHash = Guid.NewGuid().ToString() }; + _db.Context.UserSessions.Add(session); + _db.Context.SaveChanges(); + return session.Id; + } +} diff --git a/Govor.Server.Tests/ReactionMediaTests.cs b/Govor.Server.Tests/ReactionMediaTests.cs new file mode 100644 index 0000000..921cbca --- /dev/null +++ b/Govor.Server.Tests/ReactionMediaTests.cs @@ -0,0 +1,81 @@ +using Govor.Application.Reactions; +using Govor.Domain.Models.Reactions; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.Formats.Gif; +using SixLabors.ImageSharp.Metadata.Profiles.Exif; +using SixLabors.ImageSharp.PixelFormats; + +namespace Govor.Server.Tests; + +[TestFixture] +public class ReactionMediaTests +{ + private readonly ReactionMediaProcessor _processor = new(); + + [Test] + public async Task StaticImageIsResizedReencodedAndMetadataIsRemoved() + { + using var source = new Image(512, 256, Color.Red.ToPixel()); + source.Metadata.ExifProfile = new ExifProfile(); + source.Metadata.ExifProfile.SetValue(ExifTag.Artist, "private metadata"); + using var input = new MemoryStream(); + await source.SaveAsJpegAsync(input); + var result = await _processor.ProcessAsync(input.ToArray()); + Assert.That(result.IsSuccess, Is.True); + Assert.That(result.Value.Kind, Is.EqualTo(ReactionKind.Image)); + Assert.That(result.Value.MimeType, Is.EqualTo("image/png")); + Assert.That(result.Value.Width, Is.LessThanOrEqualTo(128)); + Assert.That(result.Value.Height, Is.LessThanOrEqualTo(128)); + Assert.That(result.Value.Data.Length, Is.LessThanOrEqualTo(256 * 1024)); + using var decoded = Image.Load(result.Value.Data); + Assert.That(decoded.Metadata.ExifProfile, Is.Null); + } + + [Test] + public async Task GifKeepsFramesAndTimingWithinLimits() + { + var input = await GifAsync(2, 25, 256); + var result = await _processor.ProcessAsync(input); + Assert.That(result.IsSuccess, Is.True); + Assert.That(result.Value.Kind, Is.EqualTo(ReactionKind.Gif)); + Assert.That(result.Value.DurationMilliseconds, Is.EqualTo(500)); + Assert.That(result.Value.Data.Length, Is.LessThanOrEqualTo(512 * 1024)); + using var decoded = Image.Load(result.Value.Data); + Assert.That(decoded.Frames.Count, Is.EqualTo(2)); + Assert.That(decoded.Width, Is.LessThanOrEqualTo(128)); + Assert.That(decoded.Frames.Select(f => f.Metadata.GetGifMetadata().FrameDelay), Is.EqualTo(new[] { 25, 25 })); + } + + [Test] + public async Task LongAndExcessiveFrameAnimationsAreRejected() + { + Assert.That((await _processor.ProcessAsync(await GifAsync(2, 300))).IsFailure, Is.True); + Assert.That((await _processor.ProcessAsync(await GifAsync(61, 2))).IsFailure, Is.True); + } + + [Test] + public async Task UnsupportedMalformedAndOversizedInputsAreRejected() + { + Assert.That((await _processor.ProcessAsync(""u8.ToArray())).IsFailure, Is.True); + Assert.That((await _processor.ProcessAsync(new byte[ReactionMediaLimits.MaxUploadBytes + 1])).IsFailure, Is.True); + using var source = new Image(4096, 1); + using var input = new MemoryStream(); + await source.SaveAsPngAsync(input); + Assert.That((await _processor.ProcessAsync(input.ToArray())).IsFailure, Is.True); + } + + public static async Task GifAsync(int frames, int delay, int dimension = 16) + { + using var image = new Image(dimension, dimension, Color.Red.ToPixel()); + image.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = delay; + for (var i = 1; i < frames; i++) + { + using var next = new Image(dimension, dimension, (i % 2 == 0 ? Color.Red : Color.Blue).ToPixel()); + next.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = delay; + image.Frames.AddFrame(next.Frames.RootFrame); + } + using var input = new MemoryStream(); + await image.SaveAsGifAsync(input); + return input.ToArray(); + } +} diff --git a/Govor.Server.Tests/ReactionTests.cs b/Govor.Server.Tests/ReactionTests.cs new file mode 100644 index 0000000..c3ab8fe --- /dev/null +++ b/Govor.Server.Tests/ReactionTests.cs @@ -0,0 +1,194 @@ +using Govor.Application.Infrastructure.Common; +using Govor.Application.Reactions; +using Govor.Application.Storage; +using Govor.Domain; +using Govor.Domain.Common; +using Govor.Domain.Models; +using Govor.Domain.Models.Reactions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +public class ReactionTests +{ + private TestDatabase _db = null!; + private MessageReactionService _reactions = null!; + private ReactionPackService _packs = null!; + private TestReactionStorage _storage = null!; + private readonly DateTime _now = new(2026, 10, 3, 10, 0, 0, DateTimeKind.Utc); + private Guid First => DefaultReactionPack.Items()[0].Id; + private Guid Second => DefaultReactionPack.Items()[1].Id; + + [SetUp] + public void SetUp() + { + _db = new TestDatabase(); + var clock = new Mock(); + clock.SetupGet(c => c.Now).Returns(_now); + _storage = new TestReactionStorage(); + _reactions = new MessageReactionService(_db.Context, clock.Object); + _packs = new ReactionPackService(_db.Context, clock.Object, new ReactionMediaProcessor(), _storage, + NullLogger.Instance); + MakeAdmin(_db.Context, _db.Alice); + } + + [TearDown] + public void TearDown() => _db.Dispose(); + + [Test] + public async Task DefaultPackIsAutomaticallyAvailableAndImmutable() + { + var mine = await _packs.ListAsync(_db.Bob, installedOnly: true); + Assert.That(mine.Single().IsDefault, Is.True); + Assert.That(mine.Single().Reactions.Count, Is.EqualTo(12)); + Assert.That((await _packs.DisableAsync(_db.Alice, DefaultReactionPack.Id)).Error.Type, Is.EqualTo(ErrorType.Validation)); + Assert.That((await _packs.AddEmojiAsync(_db.Alice, DefaultReactionPack.Id, "new", "😎")).IsFailure, Is.True); + Assert.That((await _packs.SubscribeAsync(_db.Bob, DefaultReactionPack.Id, false)).IsFailure, Is.True); + } + + [Test] + public async Task PutIsIdempotentAndReplacementKeepsOneOwnReaction() + { + var message = _db.AddMessage(); + var first = await _reactions.SetAsync(_db.Bob, message.Id, First); + var repeated = await _reactions.SetAsync(_db.Bob, message.Id, First); + Assert.That(first.Value.Version, Is.EqualTo(1)); + Assert.That(repeated.Value.Changed, Is.False); + Assert.That(repeated.Value.Version, Is.EqualTo(1)); + Assert.That(repeated.Value.ActorReaction!.ReactedAt, Is.EqualTo(_now)); + var replaced = await _reactions.SetAsync(_db.Bob, message.Id, Second); + Assert.That(replaced.Value.Version, Is.EqualTo(2)); + Assert.That(replaced.Value.Counts.Single().ReactionId, Is.EqualTo(Second)); + Assert.That(await _db.Context.MessageReactions.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task AggregateCountsAndRemovingOwnReactionDoNotRemoveOtherUsers() + { + var message = _db.AddMessage(); + await _reactions.SetAsync(_db.Alice, message.Id, First); + await _reactions.SetAsync(_db.Bob, message.Id, First); + var state = await _reactions.GetAsync(_db.Alice, message.Id); + Assert.That(state.Value.Counts.Single().Count, Is.EqualTo(2)); + var removed = await _reactions.SetAsync(_db.Bob, message.Id, null); + Assert.That(removed.Value.ActorReaction, Is.Null); + Assert.That(removed.Value.Counts.Single().Count, Is.EqualTo(1)); + Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, null)).Value.Changed, Is.False); + Assert.That((await _db.Context.MessageReactions.SingleAsync()).UserId, Is.EqualTo(_db.Alice)); + } + + [Test] + public async Task OutsiderCannotReadSetOrDeleteReactions() + { + var message = _db.AddMessage(); + await _reactions.SetAsync(_db.Alice, message.Id, First); + foreach (var result in new[] + { + await _reactions.GetAsync(_db.Outsider, message.Id), + await _reactions.SetAsync(_db.Outsider, message.Id, Second), + await _reactions.SetAsync(_db.Outsider, message.Id, null) + }) Assert.That(result.Error.Type, Is.EqualTo(ErrorType.Forbidden)); + Assert.That(await _db.Context.MessageReactions.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task ChannelAdministratorSelectsAllowedReactionsAndPolicyFailureRollsBack() + { + var groupId = Channel(); + var message = _db.AddMessage(chat: groupId, type: Govor.Domain.Models.Messages.RecipientType.Group); + var selected = await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.Selected, new[] { First }); + Assert.That(selected.Value.Version, Is.EqualTo(1)); + Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, First)).IsSuccess, Is.True); + Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, Second)).Error.Type, Is.EqualTo(ErrorType.Forbidden)); + var invalid = await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.Selected, new[] { Second, Guid.NewGuid() }); + Assert.That(invalid.IsFailure, Is.True); + var unchanged = await _reactions.GetPolicyAsync(_db.Bob, groupId); + Assert.That(unchanged.Value.Version, Is.EqualTo(1)); + Assert.That(unchanged.Value.ReactionIds, Is.EqualTo(new[] { First })); + await _reactions.SetPolicyAsync(_db.Alice, groupId, ChannelReactionMode.None, Array.Empty()); + Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, First)).Error.Type, Is.EqualTo(ErrorType.Forbidden)); + // Restricting new reactions does not erase history; users can still remove their own. + Assert.That((await _reactions.SetAsync(_db.Bob, message.Id, null)).IsSuccess, Is.True); + } + + [Test] + public async Task OrdinaryAndBannedMembersCannotChangeChannelPolicy() + { + var group = Channel(); + Assert.That((await _reactions.SetPolicyAsync(_db.Bob, group, ChannelReactionMode.None, Array.Empty())).Error.Type, + Is.EqualTo(ErrorType.Forbidden)); + await _db.Context.GroupMemberships.Where(m => m.GroupId == group && m.UserId == _db.Alice) + .ExecuteUpdateAsync(s => s.SetProperty(m => m.IsBanned, true)); + Assert.That((await _reactions.SetPolicyAsync(_db.Alice, group, ChannelReactionMode.All, Array.Empty())).Error.Type, + Is.EqualTo(ErrorType.Forbidden)); + var message = _db.AddMessage(chat: group, type: Govor.Domain.Models.Messages.RecipientType.Group); + Assert.That((await _reactions.SetAsync(_db.Alice, message.Id, First)).Error.Type, Is.EqualTo(ErrorType.Forbidden)); + } + + [Test] + public async Task UsersCanShareInstallAndUninstallAnAdminCreatedPack() + { + Assert.That((await _packs.CreateAsync(_db.Bob, "forbidden", "")).Error.Type, Is.EqualTo(ErrorType.Forbidden)); + var pack = (await _packs.CreateAsync(_db.Alice, "Custom", "description")).Value; + var item = (await _packs.AddEmojiAsync(_db.Alice, pack.Id, "cool", "😎")).Value; + Assert.That((await _packs.GetSharedAsync(pack.ShareCode)).Value.Reactions.Single().Id, Is.EqualTo(item.Id)); + await _packs.SubscribeAsync(_db.Bob, pack.Id, true); + await _packs.SubscribeAsync(_db.Bob, pack.Id, true); + Assert.That(await _db.Context.UserReactionPacks.CountAsync(), Is.EqualTo(1)); + Assert.That((await _packs.ListAsync(_db.Bob, installedOnly: true)).Count, Is.EqualTo(2)); + await _packs.SubscribeAsync(_db.Bob, pack.Id, false); + Assert.That((await _packs.ListAsync(_db.Bob, installedOnly: true)).Count, Is.EqualTo(1)); + // Installation affects the picker, not who may use a publicly shared reaction. + Assert.That((await _reactions.SetAsync(_db.Bob, _db.AddMessage().Id, item.Id)).IsSuccess, Is.True); + } + + [Test] + public async Task DisabledPackBlocksNewReactionsButPreservesHistoryAndDefinition() + { + var pack = (await _packs.CreateAsync(_db.Alice, "Custom", "")).Value; + var item = (await _packs.AddEmojiAsync(_db.Alice, pack.Id, "cool", "😎")).Value; + var message = _db.AddMessage(); + await _reactions.SetAsync(_db.Bob, message.Id, item.Id); + await _packs.DisableAsync(_db.Alice, pack.Id); + Assert.That((await _reactions.SetAsync(_db.Alice, message.Id, item.Id)).Error.Type, Is.EqualTo(ErrorType.NotFound)); + Assert.That((await _reactions.GetAsync(_db.Bob, message.Id)).Value.Counts.Single().ReactionId, Is.EqualTo(item.Id)); + Assert.That((await _packs.GetReactionAsync(item.Id)).IsSuccess, Is.True); + Assert.That((await _packs.GetSharedAsync(pack.ShareCode)).IsFailure, Is.True); + } + + public static void MakeAdmin(GovorDbContext context, Guid userId) + { + var invite = new Invitation { Id = Guid.NewGuid(), Code = Guid.NewGuid().ToString("N"), IsAdmin = true, + Description = "admin test", EndDate = DateTime.UtcNow.AddDays(1), MaxParticipants = 10 }; + context.Invitations.Add(invite); + context.Users.Single(u => u.Id == userId).InviteId = invite.Id; + context.SaveChanges(); + } + + private Guid Channel() + { + var group = new ChatGroup { Id = Guid.NewGuid(), Name = "channel", Description = "", IsChannel = true }; + _db.Context.ChatGroups.Add(group); + foreach (var user in new[] { _db.Alice, _db.Bob }) + _db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = user }); + _db.Context.GroupAdmins.Add(new GroupAdmins { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Alice }); + _db.Context.SaveChanges(); + return group.Id; + } +} + +public class TestReactionStorage : IStorageService +{ + public Dictionary Files { get; } = new(); + public Task SaveAsync(byte[] data, string fileName) + { + var path = Guid.NewGuid().ToString("N") + fileName; + Files.Add(path, data.ToArray()); + return Task.FromResult(path); + } + public Task LoadAsync(string url) => Task.FromResult(new MemoryStream(Files[url], writable: false)); + public Task RemoveAsync(string url) { Files.Remove(url); return Task.CompletedTask; } +} diff --git a/Govor.Server.Tests/ReadApiTests.cs b/Govor.Server.Tests/ReadApiTests.cs new file mode 100644 index 0000000..cafafd2 --- /dev/null +++ b/Govor.Server.Tests/ReadApiTests.cs @@ -0,0 +1,236 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Net.Http.Headers; +using System.Net.Http.Json; +using System.Security.Claims; +using System.Text; +using Govor.API.Hubs.Infrastructure; +using Govor.API.Hubs; +using Govor.Application.Storage; +using Govor.Contracts.Requests; +using Govor.Contracts.Responses; +using Govor.Domain.Models.Reactions; +using Microsoft.AspNetCore.SignalR; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; +using Govor.Contracts.Responses.SignalR; +using Govor.Domain; +using Govor.Domain.Models.Users; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Microsoft.IdentityModel.Tokens; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +[NonParallelizable] +public class ReadApiTests +{ + private const string Secret = "Govor-server-tests-only-signing-key-at-least-64-characters-long-123456"; + private TestDatabase _db = null!; + private TestFactory _factory = null!; + private HttpClient _client = null!; + private Mock _notifier = null!; + private Guid _session; + + [SetUp] + public void SetUp() + { + _db = new TestDatabase(); + var session = new UserSession { UserId = _db.Bob, ExpiresAt = DateTime.UtcNow.AddDays(1) }; + _db.Context.UserSessions.Add(session); + _db.Context.SaveChanges(); + _session = session.Id; + _notifier = new Mock(); + _notifier.Setup(n => n.NotifyChatReadAsync(It.IsAny())).Returns(Task.CompletedTask); + _notifier.Setup(n => n.NotifyMessageReactionsChangedAsync(It.IsAny())).Returns(Task.CompletedTask); + _notifier.Setup(n => n.NotifyChannelReactionPolicyChangedAsync(It.IsAny())).Returns(Task.CompletedTask); + _factory = new TestFactory(_db, _notifier.Object); + _client = _factory.CreateClient(); + } + + [TearDown] + public void TearDown() + { + _client.Dispose(); + _factory.Dispose(); + _db.Dispose(); + } + + [Test] + public async Task ReadEndpointPersistsReceiptsNotifiesAndReturnsUnreadCount() + { + var message = _db.AddMessage(); + Authorize(); + var response = await _client.PostAsJsonAsync($"/api/chats/{_db.ChatId}/read", + new { recipientType = 0, messageIds = new[] { message.Id } }); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var body = await response.Content.ReadFromJsonAsync(); + Assert.That(body!.ReadCount, Is.EqualTo(1)); + Assert.That(body.UnreadCount, Is.Zero); + _notifier.Verify(n => n.NotifyChatReadAsync(It.Is(r => r.ReaderId == _db.Bob && r.ChatId == _db.ChatId)), Times.Once); + var count = await _client.GetAsync($"/api/chats/{_db.ChatId}/unread-count?recipientType=0"); + Assert.That(count.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(await count.Content.ReadAsStringAsync(), Does.Contain("\"unreadCount\":0")); + } + + [Test] + public async Task AnonymousAndRefreshTokenCannotUseReadApi() + { + var path = $"/api/chats/{_db.ChatId}/unread-count?recipientType=0"; + Assert.That((await _client.GetAsync(path)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + Authorize(tokenType: "refresh"); + Assert.That((await _client.GetAsync(path)).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + [Test] + public async Task SessionRevocationInvalidatesAnAlreadyIssuedAccessToken() + { + Authorize(); + await _db.Context.UserSessions.Where(s => s.Id == _session) + .ExecuteUpdateAsync(setters => setters.SetProperty(s => s.IsRevoked, true)); + var response = await _client.GetAsync($"/api/chats/{_db.ChatId}/unread-count?recipientType=0"); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + } + + [Test] + public async Task ForeignChatIsForbiddenAndInvalidSelectionIsBadRequest() + { + var message = _db.AddMessage(); + Authorize(); + var foreign = await _client.PostAsJsonAsync($"/api/chats/{Guid.NewGuid()}/read", new { recipientType = 0 }); + Assert.That(foreign.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden)); + var invalid = await _client.PostAsJsonAsync($"/api/chats/{_db.ChatId}/read", + new { recipientType = 0, messageIds = new[] { message.Id }, upToMessageId = message.Id }); + Assert.That(invalid.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + Assert.That(await _db.Context.MessageViews.CountAsync(), Is.Zero); + } + + [Test] + public async Task OrdinaryUserCannotReadAdminUserList() + { + Authorize(); + var response = await _client.GetAsync("/api/admin/Users/all"); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Forbidden)); + } + + [Test] + public async Task ReactionHttpApiReturnsVersionedCountsAndNotifiesOnlyOnChange() + { + var message = _db.AddMessage(); + Authorize(); + var packs = await _client.GetFromJsonAsync>("/api/reaction-packs/mine"); + var reaction = packs!.Single(p => p.IsDefault).Reactions.First().Id; + var path = $"/api/messages/{message.Id}/reactions"; + var response = await _client.PutAsJsonAsync(path + "/me", new { reactionId = reaction }); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var state = await response.Content.ReadFromJsonAsync(); + Assert.That(state!.Version, Is.EqualTo(1)); + Assert.That(state.ActorReaction!.ReactionId, Is.EqualTo(reaction)); + Assert.That(state.Counts.Single().Count, Is.EqualTo(1)); + Assert.That((await _client.PutAsJsonAsync(path + "/me", new { reactionId = reaction })).StatusCode, Is.EqualTo(HttpStatusCode.OK)); + _notifier.Verify(n => n.NotifyMessageReactionsChangedAsync(It.IsAny()), Times.Once); + Assert.That((await _client.PutAsJsonAsync(path + "/me", new { reactionId = Guid.Empty })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + var removed = await _client.DeleteAsync(path + "/me"); + Assert.That(removed.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var empty = await _client.GetFromJsonAsync(path); + Assert.That(empty!.Version, Is.EqualTo(2)); + Assert.That(empty.Counts, Is.Empty); + } + + [Test] + public async Task AdminPackUploadUsesRealContentAndCanBeSharedAndDownloaded() + { + Authorize(); + Assert.That((await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom" })).StatusCode, + Is.EqualTo(HttpStatusCode.Forbidden)); + Authorize(role: "Admin"); + Assert.That((await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom" })).StatusCode, + Is.EqualTo(HttpStatusCode.Forbidden)); + ReactionTests.MakeAdmin(_db.Context, _db.Bob); + var created = await _client.PostAsJsonAsync("/api/admin/reaction-packs", new { name = "Custom", description = "Shared" }); + Assert.That(created.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var pack = (await created.Content.ReadFromJsonAsync())!; + using var image = new Image(256, 256); + using var bytes = new MemoryStream(); + await image.SaveAsPngAsync(bytes); + using var multipart = new MultipartFormDataContent(); + multipart.Add(new StringContent("Picture"), "name"); + var upload = new ByteArrayContent(bytes.ToArray()); + upload.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); + multipart.Add(upload, "file", "incorrect.txt"); + var response = await _client.PostAsync($"/api/admin/reaction-packs/{pack.Id}/reactions/media", multipart); + Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + var item = (await response.Content.ReadFromJsonAsync())!; + Assert.That(item.Kind, Is.EqualTo(ReactionKind.Image)); + Assert.That(item.Width, Is.EqualTo(128)); + Authorize(); + var shared = await _client.GetFromJsonAsync(pack.SharePath); + Assert.That(shared!.Reactions.Single().Id, Is.EqualTo(item.Id)); + Assert.That((await _client.PutAsync($"/api/reaction-packs/{pack.Id}/subscription", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent)); + var downloaded = await _client.GetAsync(item.MediaUrl); + Assert.That(downloaded.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(downloaded.Content.Headers.ContentType!.MediaType, Is.EqualTo("image/png")); + using var decoded = Image.Load(await downloaded.Content.ReadAsByteArrayAsync()); + Assert.That(decoded.Width, Is.EqualTo(128)); + } + + [Test] + public async Task SignalRReactionMethodsUseTheSameStateAndAccessChecks() + { + var message = _db.AddMessage(); + using var scope = _factory.Services.CreateScope(); + var hub = ActivatorUtilities.CreateInstance(scope.ServiceProvider); + var caller = new Mock(); + caller.SetupGet(c => c.User).Returns(new ClaimsPrincipal(new ClaimsIdentity(new[] + { new Claim("userId", _db.Bob.ToString()), new Claim("sid", _session.ToString()) }, "test"))); + hub.Context = caller.Object; + var reaction = DefaultReactionPack.Items().First().Id; + var result = await hub.React(message.Id, new SetReactionRequest { ReactionId = reaction }); + Assert.That(result.Status, Is.EqualTo(HubResultStatus.Success)); + Assert.That(result.Result!.Counts.Single().Count, Is.EqualTo(1)); + Assert.That((await hub.RemoveReaction(message.Id)).Status, Is.EqualTo(HubResultStatus.Success)); + Assert.That((await hub.React(Guid.NewGuid(), new SetReactionRequest { ReactionId = reaction })).Status, Is.EqualTo(HubResultStatus.NotFound)); + } + + private void Authorize(string tokenType = "access", string role = "User") + { + var token = new JwtSecurityToken(claims: new[] + { + new Claim("userId", _db.Bob.ToString()), new Claim("sid", _session.ToString()), + new Claim("tokenType", tokenType), new Claim(ClaimTypes.Role, role) + }, expires: DateTime.UtcNow.AddMinutes(10), + signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Secret)), SecurityAlgorithms.HmacSha256)); + _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", new JwtSecurityTokenHandler().WriteToken(token)); + } + + private sealed class TestFactory(TestDatabase db, IChatNotificationService notifier) : WebApplicationFactory + { + protected override void ConfigureWebHost(IWebHostBuilder builder) + { + builder.UseEnvironment("Development"); + builder.UseSetting("Firebase:Enabled", "false"); + builder.UseSetting("JwtAccessOption:SecretKey", Secret); + builder.ConfigureServices(services => + { + services.AddDataProtection().UseEphemeralDataProtectionProvider(); + var worker = services.Single(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ChatPushWorker)); + services.Remove(worker); + services.RemoveAll>(); + services.RemoveAll>(); + services.AddDbContext(db.ConfigureOptions); + services.RemoveAll(); + services.AddSingleton(notifier); + services.RemoveAll(); + services.AddSingleton(new TestReactionStorage()); + }); + } + } +} diff --git a/Govor.Server.Tests/ReadConcurrencyTests.cs b/Govor.Server.Tests/ReadConcurrencyTests.cs new file mode 100644 index 0000000..03c307e --- /dev/null +++ b/Govor.Server.Tests/ReadConcurrencyTests.cs @@ -0,0 +1,84 @@ +using System.Data.Common; +using Govor.Application.Infrastructure.Common; +using Govor.Application.Messages; +using Govor.Domain; +using Govor.Domain.Models.Messages; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; + +namespace Govor.Server.Tests; + +[TestFixture] +public class ReadConcurrencyTests +{ + [Test] + public async Task AnotherDeviceCanInsertTheReceiptBetweenSelectionAndWrite() + { + using var db = new TestDatabase(); + var message = db.AddMessage(); + var clock = new Mock(); + clock.SetupGet(c => c.Now).Returns(DateTime.UtcNow); + using var other = db.CreateContext(); + var competingReader = new MessageReadingService(other, NullLogger.Instance, clock.Object); + var interceptor = new BeforeReceiptInsert(async () => + { + var result = await competingReader.ReadMessageAsync(db.Bob, message.Id); + Assert.That(result.IsSuccess, Is.True); + }); + using var first = db.CreateContext(interceptor); + var reader = new MessageReadingService(first, NullLogger.Instance, clock.Object); + var read = await reader.ReadChatAsync(db.Bob, db.ChatId, RecipientType.User, new[] { message.Id }); + Assert.That(read.IsSuccess, Is.True); + Assert.That(read.Value.ReadCount, Is.Zero); + Assert.That(await db.Context.MessageViews.CountAsync(), Is.EqualTo(1)); + } + + [Test] + public async Task MessageRemovedBetweenSelectionAndWriteDoesNotCreateOrphanReceipt() + { + using var db = new TestDatabase(); + var message = db.AddMessage(); + var clock = new Mock(); + clock.SetupGet(c => c.Now).Returns(DateTime.UtcNow); + using var other = db.CreateContext(); + var interceptor = new BeforeReceiptInsert(async () => + await other.Messages.Where(m => m.Id == message.Id).ExecuteDeleteAsync()); + using var first = db.CreateContext(interceptor); + var reader = new MessageReadingService(first, NullLogger.Instance, clock.Object); + var read = await reader.ReadChatAsync(db.Bob, db.ChatId, RecipientType.User, new[] { message.Id }); + Assert.That(read.IsSuccess, Is.True); + Assert.That(read.Value.ReadCount, Is.Zero); + Assert.That(await db.Context.MessageViews.CountAsync(), Is.Zero); + } + + [Test] + public void ReadBoundaryQueryTranslatesForPostgreSql() + { + using var db = new GovorDbContext(new DbContextOptionsBuilder() + .UseNpgsql("Host=localhost;Database=translation_tests;Username=tests").Options); + var boundary = Guid.NewGuid(); + var sentAt = DateTime.UtcNow; + var sql = db.Messages.Where(m => m.SentAt < sentAt || + (m.SentAt == sentAt && m.Id.CompareTo(boundary) <= 0)) + .OrderBy(m => m.SentAt).ThenBy(m => m.Id).ToQueryString(); + Assert.That(sql, Does.Contain("ORDER BY")); + } + + // Deterministically interleave a competing device/deletion after SELECT, before INSERT. + private sealed class BeforeReceiptInsert(Func callback) : DbCommandInterceptor + { + private bool _invoked; + public override async ValueTask> NonQueryExecutingAsync(DbCommand command, + CommandEventData eventData, InterceptionResult result, CancellationToken cancellationToken = default) + { + if (!_invoked && command.CommandText.StartsWith("INSERT INTO \"MessageViews\"", StringComparison.Ordinal)) + { + _invoked = true; + await callback(); + } + return result; + } + } +} diff --git a/Govor.Server.Tests/TestDatabase.cs b/Govor.Server.Tests/TestDatabase.cs new file mode 100644 index 0000000..99bc30d --- /dev/null +++ b/Govor.Server.Tests/TestDatabase.cs @@ -0,0 +1,106 @@ +using Govor.Domain; +using Govor.Domain.Models; +using Govor.Domain.Models.Messages; +using Govor.Domain.Models.Users; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using System.Data.Common; +using Npgsql; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Govor.Server.Tests; + +public sealed class TestDatabase : IDisposable +{ + public DbConnection Connection { get; } + private readonly string? _schema; + public GovorDbContext Context { get; } + public Guid Alice { get; } = Guid.NewGuid(); + public Guid Bob { get; } = Guid.NewGuid(); + public Guid Outsider { get; } = Guid.NewGuid(); + public Guid ChatId { get; } = Guid.NewGuid(); + + public TestDatabase() + { + var postgres = Environment.GetEnvironmentVariable("TEST_POSTGRES_CONNECTION"); + if (string.IsNullOrWhiteSpace(postgres)) + Connection = new SqliteConnection("Data Source=:memory:"); + else + { + var settings = new NpgsqlConnectionStringBuilder(postgres); + if (settings.Database?.EndsWith("_tests", StringComparison.Ordinal) != true) + throw new InvalidOperationException("PostgreSQL tests require a dedicated database ending in _tests."); + _schema = "test_" + Guid.NewGuid().ToString("N"); + settings.SearchPath = _schema; + Connection = new NpgsqlConnection(settings.ConnectionString); + } + Connection.Open(); + if (_schema is not null) + { + using var command = Connection.CreateCommand(); + command.CommandText = $"CREATE SCHEMA {_schema}"; + command.ExecuteNonQuery(); + } + Context = CreateContext(); + if (_schema is null) + Context.Database.EnsureCreated(); + else + Context.Database.Migrate(); + var invite = new Invitation + { + Id = Guid.NewGuid(), Code = "test", Description = "test", + EndDate = DateTime.UtcNow.AddDays(1), MaxParticipants = 100 + }; + Context.Invitations.Add(invite); + foreach (var id in new[] { Alice, Bob, Outsider }) + Context.Users.Add(new User + { + Id = id, Username = id.ToString(), PasswordHash = "test", Description = "", + InviteId = invite.Id, WasOnline = DateTime.UtcNow + }); + Context.PrivateChats.Add(new PrivateChat { Id = ChatId, UserAId = Alice, UserBId = Bob }); + Context.SaveChanges(); + } + + public void ConfigureOptions(DbContextOptionsBuilder options) + { + if (_schema is null) + options.UseSqlite(Connection); + else + options.UseNpgsql(Connection); + } + + public GovorDbContext CreateContext(params IInterceptor[] interceptors) + { + var options = new DbContextOptionsBuilder(); + ConfigureOptions(options); + options.AddInterceptors(interceptors); + return new GovorDbContext(options.Options); + } + + public Message AddMessage(Guid? sender = null, Guid? chat = null, + RecipientType type = RecipientType.User, DateTime? sentAt = null, Guid? id = null) + { + var message = new Message + { + Id = id ?? Guid.NewGuid(), SenderId = sender ?? Alice, + RecipientId = chat ?? ChatId, RecipientType = type, + SentAt = sentAt ?? DateTime.UtcNow, EncryptedContent = "hello" + }; + Context.Messages.Add(message); + Context.SaveChanges(); + return message; + } + + public void Dispose() + { + Context.Dispose(); + if (_schema is not null) + { + using var command = Connection.CreateCommand(); + command.CommandText = $"DROP SCHEMA {_schema} CASCADE"; + command.ExecuteNonQuery(); + } + Connection.Dispose(); + } +} diff --git a/Govor.Server.slnx b/Govor.Server.slnx new file mode 100644 index 0000000..c6a0796 --- /dev/null +++ b/Govor.Server.slnx @@ -0,0 +1,7 @@ + + + + + + + diff --git a/docs/README.md b/docs/README.md index 482e6b1..a3131dd 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,48 +1,40 @@ +# Govor.API — обзор + +Govor — мессенджер на ASP.NET Core и .NET MAUI. Эта документация описывает сервер Govor.API и его контракт с клиентом. Стек сервера: .NET 10, EF Core, PostgreSQL, JWT, SignalR, Firebase и локальное хранилище файлов. + +## Что реализовано + +Изменения рабочей копии сервера описаны в [исправлениях](server-fixes.md), включая [API прочтения](endpoints/message-read.md). Страницы со ссылками на commit `4603be9` описывают исходную версию до этих исправлений. + +| Область | Состояние по коду | +| --- | --- | +| Регистрация и вход | Регистрация по приглашению, BCrypt, открытие сессии и пара токенов | +| Сессии | Список, отзыв одной или всех сессий, обновление токенов | +| Друзья | Поиск, списки, отправка/принятие/отклонение заявок через SignalR | +| Личные чаты | Создание между друзьями, история, отправка и редактирование | +| Прочтение и удаление | HTTP/SignalR, видимые сообщения/граница/весь чат, квитанции и счётчики; удаление с проверкой прав | +| Реакции | [HTTP/SignalR, базовые эмодзи, общие паки картинок/GIF, административный API и выбор разрешённых реакций канала](endpoints/reactions.md) | +| Профиль | Описание, аватар, загрузка профиля и события изменений | +| Присутствие | События подключения/отключения; исправлены зависимости HTTP status | +| Медиа и push | Доступ к вложениям, привязка FCM к сессии, очередь и повторные попытки | +| Группы | Модели и часть сервисов сообщений; полноценный сценарий управления не завершён | +| Шифрование | Есть хранение публичных ключей, но готового E2EE нет | + +## Как читать + +Начните с «Запуск и конфигурация» и «Аутентификация». Для чатов используйте HTTP для истории и SignalR для команд и событий. Раздел «Диагностика» описывает ограничения, которые нельзя считать рабочими гарантиями API. + +Имена `userId`, `friendId`, `chatId` обозначают разные сущности. В сообщениях личного чата `recipientId` — ID записи PrivateChat, а не ID собеседника. + +## Границы готовности + +Текущая версия не готова к открытому развёртыванию: обнаружены критичные ошибки авторизации и доступа к личным чатам. Контракты ниже полезны для разработки, но не являются подтверждением безопасности. + +Эффект стекла относится к MAUI-интерфейсу. API передаёт данные и события; производительность размытия, контрастность и анимации нужно проверять отдельно на устройствах. + +Регистрация сейчас требует код приглашения. Обещание отключить приглашения после релиза является продуктовым планом, а не поведением текущего кода. + --- -icon: face-confounded -coverY: 0 ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# The invitation code RU - -### Что это такое - -**Код приглашения** — это временный механизм доступа, действующий на этапах **альфа-** и **бета-тестирования** мессенджера **Говор**.\ -Он используется для **ограничения количества аккаунтов** и **контроля числа пользователей**, получающих ранний доступ к продукту. - -Пока Говор находится в стадии активной разработки и внутреннего тестирования, регистрация новых пользователей возможна **только при наличии действующего кода приглашения**. - -### Как получить код приглашения - -Коды приглашения **создаются администрацией проекта** и **выдаются вручную** по мере готовности новых тестовых слотов. - -Чтобы запросить код приглашения: - -1. Свяжитесь с командой разработчиков. -2. Кратко опишите, зачем вы хотите протестировать Говор. -3. Дождитесь ответа с вашим уникальным кодом. - -📩 **Контакт для запроса:**\ -`BurntRoostersOfficial@protonmail.com` - -### Как выглядит код - -Код приглашения представляет собой **уникальный случайно сгенерированный идентификатор** (объект `Guid`).\ -Пример: - -``` -c7a5f1b3-8c64-47e2-9e3e-b7df6a2b021f -``` - -### Ограничения - -Каждый код приглашения имеет: - -* 🔹 **Ограниченное количество регистраций.**\ - После достижения лимита использование кода становится невозможным. -* ⏳ **Ограниченный срок действия.**\ - По истечении времени жизни код автоматически теряет актуальность. - -### После официального релиза - -После выхода **первой стабильной версии Говора** система кодов приглашений будет **отключена**, и регистрация станет **открытой для всех пользователей**. +Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs). diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index 1403c18..4702310 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -1,29 +1,29 @@ -# Table of contents +# Оглавление -* [The invitation code RU](README.md) - -## Endpoints - -* [Authentication](endpoints/authentication/README.md) - * [AuthController](endpoints/authentication/authcontroller.md) - * [RefreshController](endpoints/authentication/refreshcontroller.md) -* [SessionController](endpoints/sessioncontroller.md) -* [FriendshipController](endpoints/friendshipcontroller.md) -* [FriendsRequestQueryController](endpoints/friendsrequestquerycontroller.md) -* [MediaController](endpoints/mediacontroller.md) -* [ChatLoadController](endpoints/chatloadcontroller.md) -* [OnlinePingingController(не работает)](endpoints/onlinepingingcontroller-ne-rabotaet.md) - -## SignalR - -* [PresenceHub](signalr/presencehub.md) -* [ChatHub](signalr/chathub.md) - -*** - -* [FriendsHub](friendshub/README.md) - * [FriendsHub Client (Java)](friendshub/friendshub-client-java.md) - -## Code Docs - -* [HubResult\](code-docs/hubresult-less-than-t-greater-than.md) +* [Govor.API — обзор](README.md) +* [Исправления серверной части](server-fixes.md) +* [Запуск и конфигурация](getting-started.md) +* [Архитектура и границы](architecture.md) +* [Аутентификация](endpoints/authentication/README.md) +* [Регистрация и вход](endpoints/authentication/authcontroller.md) +* [Обновление токенов](endpoints/authentication/refreshcontroller.md) +* [Сессии](endpoints/sessioncontroller.md) +* [Друзья и поиск](endpoints/friendshipcontroller.md) +* [Списки заявок в друзья](endpoints/friendsrequestquerycontroller.md) +* [Личные чаты](endpoints/private-chats.md) +* [История сообщений](endpoints/chatloadcontroller.md) +* [Прочтение сообщений и счётчики](endpoints/message-read.md) +* [Реакции, паки и настройки каналов](endpoints/reactions.md) +* [Медиа](endpoints/mediacontroller.md) +* [Профиль и аватар](endpoints/profile.md) +* [Push-уведомления](endpoints/push.md) +* [HTTP-присутствие — ограничения](endpoints/onlinepingingcontroller-ne-rabotaet.md) +* [Ключи сессий — экспериментальный API](endpoints/session-keys.md) +* [Администрирование и незавершённые группы](endpoints/admin-and-groups.md) +* [ChatsHub — сообщения](signalr/chathub.md) +* [PresenceHub — online и offline](signalr/presencehub.md) +* [FriendsHub — заявки](friendshub/README.md) +* [Клиент SignalR на C# для MAUI](friendshub/friendshub-client-java.md) +* [ProfileHub — изменения профиля](signalr/profilehub.md) +* [Ответы, ошибки и сериализация](code-docs/hubresult-less-than-t-greater-than.md) +* [Диагностика и порядок исправлений](diagnostics.md) diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..637b7a3 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,41 @@ +# Архитектура и границы + +## Поток запроса + +MAUI → HTTP Controller / SignalR Hub → Application service → GovorDbContext → PostgreSQL. Медиа-сервис сохраняет бинарные данные через LocalStorageService; ChatNotificationService отправляет SignalR-события и push через Firebase. + +| Проект | Ответственность сейчас | +| --- | --- | +| Govor.API | Маршруты, хабы, авторизация, DI, преобразование ошибок и DTO | +| Govor.Application | Сценарии пользователей, друзей, сообщений, медиа и push | +| Govor.Contracts | HTTP/SignalR запросы, ответы и DTO | +| Govor.Domain | Сущности, DbContext, EF-конфигурации и миграции | + +Это многослойное приложение, но Domain уже зависит от EF Core и содержит инфраструктуру БД. Не следует описывать его как полностью независимую доменную модель. + +## Хранение и идентификаторы + +PrivateChat связывает UserAId и UserBId. Message хранит SenderId и полиморфный RecipientId: ID PrivateChat для RecipientType.User или ID ChatGroup для RecipientType.Group. Ошибки возникают там, где этот ID сравнивают с ID пользователя. + +Роль access token получается из приглашения пользователя (`Invite.IsAdmin`), хотя есть отдельная сущность Admin. Нужен один источник истины для ролей. + +## Состояние соединений + +ConnectionStore и OnlineUserStore — singleton в памяти одного процесса. Подключения автоматически вступают в группы пользователя, его чатов и групп. Перезапуск очищает это состояние; несколько инстансов без общего решения для SignalR и presence не имеют согласованного состояния. + +## Рекомендуемые решения + +1. Ввести общую проверку участия в конкретном чате и применять её к истории, Send, Read, медиа и событиям. +2. Разделить команды и чтение: создание чата и смена пароля не должны выполняться GET-запросами. +3. Возвращать только DTO, особенно для криптосессий и медиа. +4. Описать ошибки единым контрактом, сохранив совместимость с MAUI. +5. Для доставки отделить сохранение сообщения от внешних уведомлений: outbox и повторная доставка с дедупликацией. +6. Принять отдельное решение о E2EE: протокол, проверка ключей, несколько устройств, восстановление и миграция существующих сообщений. + +Это предложения, они не внедрены в рамках переписывания документации. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.Domain/GovorDbContext.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Domain/GovorDbContext.cs). + diff --git a/docs/code-docs/hubresult-less-than-t-greater-than.md b/docs/code-docs/hubresult-less-than-t-greater-than.md index 8e1bf6d..0b4b260 100644 --- a/docs/code-docs/hubresult-less-than-t-greater-than.md +++ b/docs/code-docs/hubresult-less-than-t-greater-than.md @@ -1,164 +1,47 @@ +# Ответы, ошибки и сериализация + +## HTTP + +ResultExtensions преобразует Result: успешный T → 200 со значением; Unit → 204 без тела. + +| ErrorType | HTTP | +| --- | --- | +| Validation | 400 | +| NotFound | 404 | +| Conflict | 409 | +| Unauthorized | 401 | +| Forbidden | 403 | +| Остальные, включая ServerError | 400 (текущий дефект mapping) | + +Сервисная ошибка: + +```json +{"status":404,"title":"Not Found","detail":"<описание>","errorCode":"<код>"} +``` + +errors добавляется при наличии. Автоматическая MVC-валидация, middleware авторизации и ручные BadRequest/StatusCode могут возвращать другую форму. Единого тела ошибки для всех маршрутов сейчас нет. + +В контроллерах встречается Forbid(ex.Message): строка трактуется как authentication scheme, а не тело ответа; результат может быть 500 вместо 403. + +## SignalR HubResult + +```json +{"status":200,"result":null,"errorMessage":null} +``` + +status — число внутри ответа команды, не HTTP-статус соединения. Значения: 200 Success, 201 Created, 204 NoContent, 400 BadRequest, 401 Unauthorized, 404 NotFound, 409 Conflict, 422 UnprocessableEntity, 500 ServerError. + +Static factories: Ok(result), Created(result), NoContent(), BadRequest(message, details), NotFound(message, details), Unauthorized(message), Conflict(message), UnprocessableEntity(message), Error(message). + +Каждый хаб сам преобразует бизнес-ошибки; наличие enum не гарантирует точный status для каждого Failure. HubExceptionFilter возвращает Task.FromResult(errorResult) вместо объекта результата из InvokeMethodAsync; исключения вне локальных catch требуют исправления и проверки сериализации. + +## JSON-контракт + +Стандартные ASP.NET настройки используют camelCase; enum передаются числами, Guid — строками, byte[] — base64, даты — ISO 8601. StringEnumConverter явно не настроен. + +HTTP MessageResponse.id и SignalR UserMessageResponse.messageId отличаются. HTTP и SignalR вложения также имеют разные структуры. Клиент должен иметь явное преобразование; не подменяйте один DTO другим. + --- -description: >- - Description: A generic class used to encapsulate the result of SignalR hub - operations, providing a standardized way to return status, data, and error - messages. It supports various HTTP-like status cod ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. -# HubResult\ - -**Namespace**: `Govor.Contracts.Responses.SignalR` - -### Properties - -* **Status**: (`HubResultStatus`) Indicates the status of the hub operation, corresponding to HTTP-like status codes (e.g., Success, BadRequest). -* **Result**: (`T?`) The data returned by the hub operation, if applicable. Can be null for error cases or when no data is returned. -* **ErrorMessage**: (`string?`) A message describing the error, if the operation failed. Null for successful operations. - -### Static Methods - -#### Ok - -**Description**: Creates a successful result with an optional data payload.\ -**Parameters**: - -* `result`: (`T?`, optional) The data to include in the response (default: `null`).\ - **Returns**: A `HubResult` with `Status` set to `Success` (200) and the provided `result`.\ - **Example**: - -```csharp -HubResult result = HubResult.Ok("Operation completed"); -``` - -#### Created - -**Description**: Creates a result indicating a resource was created, with an optional data payload.\ -**Parameters**: - -* `result`: (`T?`, optional) The data to include in the response (default: `null`).\ - **Returns**: A `HubResult` with `Status` set to `Created` (201) and the provided `result`.\ - **Example**: - -```csharp -HubResult result = HubResult.Created("Resource created"); -``` - -#### NoContent - -**Description**: Creates a result indicating the operation was successful but no data is returned.\ -**Parameters**: None\ -**Returns**: A `HubResult` with `Status` set to `NoContent` (204) and `Result` set to `null`.\ -**Example**: - -```csharp -HubResult result = HubResult.NoContent(); -``` - -#### BadRequest - -**Description**: Creates a result indicating a client error due to invalid input.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue. -* `details`: (`T?`, optional) Additional details about the error (default: `null`).\ - **Returns**: A `HubResult` with `Status` set to `BadRequest` (400), the provided `message`, and optional `details`.\ - **Example**: - -```csharp -HubResult result = HubResult.BadRequest("Invalid input provided"); -``` - -#### NotFound - -**Description**: Creates a result indicating a requested resource was not found.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue. -* `details`: (`T?`, optional) Additional details about the error (default: `null`).\ - **Returns**: A `HubResult` with `Status` set to `NotFound` (404), the provided `message`, and optional `details`.\ - **Example**: - -```csharp -HubResult result = HubResult.NotFound("User not found"); -``` - -#### Unauthorized - -**Description**: Creates a result indicating the client is not authorized to perform the operation.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue.\ - **Returns**: A `HubResult` with `Status` set to `Unauthorized` (401) and the provided `message`.\ - **Example**: - -```csharp -HubResult result = HubResult.Unauthorized("Authentication required"); -``` - -#### Conflict - -**Description**: Creates a result indicating a conflict, such as a duplicate resource.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue.\ - **Returns**: A `HubResult` with `Status` set to `Conflict` (409) and the provided `message`.\ - **Example**: - -```csharp -HubResult result = HubResult.Conflict("Resource already exists"); -``` - -#### UnprocessableEntity - -**Description**: Creates a result indicating the request could not be processed due to semantic errors.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue.\ - **Returns**: A `HubResult` with `Status` set to `UnprocessableEntity` (422) and the provided `message`.\ - **Example**: - -```csharp -HubResult result = HubResult.UnprocessableEntity("Invalid data format"); -``` - -#### Error - -**Description**: Creates a result indicating an internal server error.\ -**Parameters**: - -* `message`: (`string`) The error message describing the issue.\ - **Returns**: A `HubResult` with `Status` set to `ServerError` (500) and the provided `message`.\ - **Example**: - -```csharp -HubResult result = HubResult.Error("Unexpected server error"); -``` - -### Enum: HubResultStatus - -**Description**: Enumerates the possible status codes for a `HubResult` response, aligning with HTTP status codes for consistency in SignalR hub operations. - -**Values**: - -* **Success** (200): The operation was successful. -* **Created** (201): A resource was successfully created. -* **NoContent** (204): The operation was successful, but no content is returned. -* **BadRequest** (400): The request was invalid or malformed. -* **Unauthorized** (401): The client is not authorized to perform the operation. -* **NotFound** (404): The requested resource was not found. -* **Conflict** (409): The request conflicts with an existing resource. -* **UnprocessableEntity** (422): The request could not be processed due to semantic errors. -* **ServerError** (500): An unexpected server error occurred. - -### Example Usage - -```csharp -// Successful operation with data -var successResult = HubResult.Ok(new UserDto { Id = Guid.NewGuid(), Username = "example" }); - -// Error due to invalid input -var errorResult = HubResult.BadRequest("Invalid username provided"); - -// Not found scenario -var notFoundResult = HubResult.NotFound("User not found in database"); -``` +Источник: [Govor.API/Common/Extensions/ResultExtensions.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Common/Extensions/ResultExtensions.cs). diff --git a/docs/diagnostics.md b/docs/diagnostics.md new file mode 100644 index 0000000..958996c --- /dev/null +++ b/docs/diagnostics.md @@ -0,0 +1,77 @@ +# Диагностика и порядок исправлений + +## Основание и пределы проверки + +Проверен master Govor-team/Govor, commit 4603be9f714135e0af72d505d17f3d1709834bea (GitHub и локальный checkout совпали). Изучены контроллеры, хабы, сервисы, DTO, EF-модели, DI, запуск и часть MAUI-интеграции. Старый опубликованный GitBook оставался на ревизии 18.12.2025 и расходился с кодом. + +Сборка API на SDK 10.0.400 успешна: первая сборка 90 предупреждений, 0 ошибок. Restore Govor.API.Tests неуспешен: NU1201, net8.0 → net10.0. Тесты не выполнены; утверждать, что они проходят, нельзя. Производственный сервер, БД, Firebase, Docker и UI на устройствах не проверялись. + +Ниже «подтверждено» означает выявлено по конкретному коду или диагностике сборки, а не воспроизведено атакой на живой сервис. + +## P0 — закрыть до публичного доступа + +| Проблема | Доказательство | Последствие | Исправление | +| --- | --- | --- | --- | +| Административные приглашения доступны анонимно | InviteUserController: Authorize закомментирован; isAdmin принимается из запроса | Получение административной роли через собственное приглашение | Admin policy и серверная проверка права выдавать роль | +| Смена чужого пароля и выдача passwordHash обычному пользователю | UsersController: только Authorize; GET setpassword; BuildUserDtos включает PasswordHash | Захват аккаунтов, раскрытие хешей, пароль в URL | Admin policy, убрать hash из DTO, POST-команда, аудит и отзыв сессий | +| Чужая история и отправка в чужой личный чат | MessagesLoader игнорирует currentUser; Send проверяет только существование PrivateChat | Чтение и запись по чужому chatId | Общая проверка участия в конкретном чате | +| Неправильная авторизация Read | CanReadMessage проверяет любой PrivateChat пользователя | Отметки чужих сообщений прочитанными | Привязать проверку к message.RecipientId | +| Криптосессия выдаётся как EF-сущность с UserSession | SessionKeysReader Include(UserSession), контроллер Ok(keys) | Риск раскрытия внутренних полей и циклов JSON | PublicSessionKeysDto, проекция только публичных полей | + +## P1 — восстановить корректность + +| Проблема | Где | Действие | +| --- | --- | --- | +| rotate/used всегда обращаются к null | SessionKeysController._oneTimePreKeysRotator | Передать зависимость конструктору | +| online/status всегда падает | OnlinePingingController, две зависимости не присвоены | Исправить DI и проверку поведения | +| Вступление в группу неработоспособно | InviteController._currentUser и незарегистрированный IGroupService | Завершить сервис и инъекцию | +| HideForMe физически удаляет сообщение автора | MessageRemovingService игнорирует ForceRemove | Реализовать отдельную запись скрытия | +| Удаление группового сообщения сравнивает userId с groupId | MessageRemovingService | Проверять автора/администратора и участие | +| Собеседнику не приходят Edit/Remove/Read | NotifyParticipantsAsync адресует ID чата как группу пользователя | Определять обоих участников чата | +| Личные вложения недоступны получателю | AccesserToDownloadMediaService сравнивает RecipientId с userId | Проверять участников PrivateChat | +| Нет владения вложениями и аватаром | Send; ProfileHub.SetAvatar; OwnerType от клиента | Серверная политика ownership, лимиты и whitelist | +| EncryptedKey теряется | MediaService и MessageSendingService не сохраняют ключ | Выбрать и реализовать контракт хранения/доставки | +| Отзыв сессии не отзывает access/соединение | Program.cs; UserSessionRevoker | Проверять sid и закрывать соединения по политике | +| Refresh может повторяться/конфликтовать | JwtService без jti/sid; hash unique; неатомарная ротация | Случайный refresh, атомарная ротация и replay-политика | +| Ошибки превращаются в ложные статусы | ResultExtensions, Forbid(text), хабы, фильтр | Единый mapping, 500 для server errors, корректный объект из фильтра | +| Тестовая инфраструктура отстала | API.Tests net8, API net10; устаревшие проекты | Выровнять TFM/EF и восстановить CI | +| Контейнер не соответствует проекту | Dockerfile .NET 8, ссылки Core/Data | Обновить слои сборки и зависимости | + +## P2 — надёжность и сопровождение + +- Конкурентные регистрации могут превысить лимит приглашения; IsActive не проверяется. Нужна атомарная квота. +- Повторный Read конфликтует при гонке по unique(MessageId, UserId); требуется идемпотентная запись. +- Нет clientMessageId/outbox: после сохранения уведомление может упасть, а повторная отправка создаст дубль. +- Пагинация только по SentAt пропускает одинаковые timestamps; нужен стабильный курсор. +- Состояние соединений локально процессу; для нескольких инстансов требуется общее решение. +- CORS принимает любой origin с credentials; sensitive EF logging включён без ограничения окружения. +- Firebase обязателен даже для локального старта; внешние зависимости должны включаться явно. +- global.json содержит некорректную sdk/version; solution зависит от внешнего SmartRes, а API — от DLL в libs. +- Дубликат маппинга UserProfileDto, nullable выключен в API, а предупреждения CS0649 уже указывают реальные дефекты. +- Приглашение определяет роль одновременно с отдельной таблицей Admin; выбрать один источник. +- PrivacyUserSettings и Blocked-модель не означают, что приватность и блокировка покрывают все сценарии. + +NuGet сообщил NU1903 для AutoMapper 16.0.0. [GHSA-rvv3-g6hj-g44x](https://github.com/advisories/GHSA-rvv3-g6hj-g44x) описывает DoS от рекурсивного mapping; исправленная версия ветки 16 — 16.1.1. Это подтверждение уязвимости зависимости; доступность конкретного exploit-пути в Govor отдельно не доказана. + +## MAUI и стеклянный интерфейс + +MessagesListController присваивает EncryptedContent = text; mapping читает его прямо в Text, а репозиторий редактирует как NewEncryptedContent = newText. Следовательно, в проверенном пути сообщения передаются обычным текстом. Хранение ключей на сервере не делает этот путь E2EE. + +ChatHub клиента отбрасывает сообщения с пустым текстом, даже если есть вложение. Клиент подписан на MessageSent, которое сервер не отправляет. Перезапуск из Closed может конфликтовать с logout; refresh на любом HTTP-сбое очищает токены. MessagesListController.SendAsync возвращает Success(true), не проверяя результат SendMessageAsync; экран может считать неуспешную отправку успешной. Эти проблемы важнее полировки оформления. + +В ChatPage.xaml есть слои с Opacity и Shadow. Визуально подтвердить эффект, FPS и поведение blur без запуска приложения нельзя. Рекомендуется отдельно измерить скролл длинного чата, работу клавиатуры, контраст текста на светлом/тёмном фоне и отключение тяжёлых эффектов. Полный UI-аудит не проводился. + +## Последовательность работ + +1. Закрыть P0, добавить проверки «пользователь C не может читать/писать/читать ключи чата A–B; User не управляет Admin». +2. Выровнять .NET и тесты; проверить реальные PostgreSQL-запросы и DI через старт приложения. +3. Исправить P1: события двух участников, HideForMe, медиа, ключи, logout. +4. Закрепить API контрактами и интеграционными тестами HTTP/SignalR, включая повторные и параллельные операции. +5. Решить E2EE и доставку; после этого расширять группы и оптимизировать визуальные эффекты. + +Критерий готовности: воспроизводимый запуск, зелёные проверки доступа, согласованный MAUI-контракт и отсутствие известных неработающих методов. Архитектурная переработка должна опираться на эти проверки, а не начинаться с переписывания всего приложения. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. + +Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs). diff --git a/docs/endpoints/admin-and-groups.md b/docs/endpoints/admin-and-groups.md new file mode 100644 index 0000000..791865e --- /dev/null +++ b/docs/endpoints/admin-and-groups.md @@ -0,0 +1,35 @@ +# Администрирование и незавершённые группы + +## Административные маршруты + +Следующая таблица показывает фактические атрибуты, а не требуемую безопасную политику. + +| Метод | Маршрут | Защита сейчас | +| --- | --- | --- | +| POST | /api/admin/InviteUser/Invitation | Без Authorize | +| GET | /api/admin/InviteUser | Без Authorize | +| GET | /api/admin/InviteUser/GetAllActiveInvitations | Без Authorize | +| GET | /api/admin/InviteUser/{id} | Без Authorize | +| GET | /api/admin/Users/all | Любой аутентифицированный пользователь | +| GET | /api/admin/Users/{id} | Любой аутентифицированный пользователь | +| GET | /api/admin/Users/user/{id}/setpassword/{password} | Любой аутентифицированный пользователь | + +CreateInvitationRequest: endDate, maxParticipants, isAdmin, description. Генератор возвращает строковый код в JSON (200). Списки приглашений возвращают id, description, isAdmin, maxParticipants, code, createdAt, endAt, isActive, participantCount. + +Users/all фактически ограничен 50 записями без стабильной пагинации. Ответ UserResponse включает passwordHash, что недопустимо для клиентского контракта. Смена пароля выполняется GET и кладёт пароль в URL. + +Эти маршруты нужно закрыть ролью Admin до публичного использования. Создание административного приглашения вместе с регистрацией позволяет получить роль Admin. Не подключайте их к пользовательскому интерфейсу. + +## Группы + +GET /invite/{code} задуман как вход в группу и требует Authorize. IGroupService не зарегистрирован в AddServices, а _currentUser не присваивается. Маршрут не является рабочим сценарием вступления. + +GroupsHub пуст и не подключён MapHub. Административный FriendshipsController содержит только закомментированные действия, поэтому рабочих endpoints у него нет. + +Наличие моделей ChatGroup/GroupMembership/GroupInvitation и проверки участия в групповом Send не подтверждает готовый продуктовый сценарий групп и каналов. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Controllers/AdminStuff/UsersController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/AdminStuff/UsersController.cs). + diff --git a/docs/endpoints/authentication/README.md b/docs/endpoints/authentication/README.md index c891b49..82bf45e 100644 --- a/docs/endpoints/authentication/README.md +++ b/docs/endpoints/authentication/README.md @@ -1,45 +1,26 @@ +# Аутентификация + +## Последовательность + +1. `POST /api/auth/register` либо `POST /api/auth/login` возвращает `{ refreshToken, accessToken }`. +2. HTTP-запросы передают `Authorization: Bearer `. +3. Для SignalR задайте AccessTokenProvider, который возвращает актуальный access token. Program.cs также принимает query `access_token` на путях /hubs. +4. `POST /api/auth/token/refresh` возвращает новую пару; клиент сохраняет новый refresh token. +5. Отзыв сессий выполняется методами /api/Session/close. + +Access token содержит `userId`, `sid` и роль User/Admin. Подпись HS256 проверяется, срок проверяется, issuer и audience не проверяются. Токены возвращаются JSON; сервер не устанавливает HttpOnly-cookie. + +## Ограничения реализации + +Отзыв сессии блокирует refresh, но Program.cs не проверяет IsRevoked при каждом использовании access token. Уже открытые SignalR-соединения явно не разрываются. Немедленный logout на всех устройствах не гарантирован. + +Refresh JWT содержит userId и tokenType, но не случайный jti или sid. При выпуске одному пользователю в одну секунду возможны одинаковые токены, конфликтующие с уникальным RefreshTokenHash. Ротация не защищена атомарным compare-and-swap от параллельных запросов. + +Не используйте refresh token как access token. В bearer-валидации нет явного требования tokenType=access; методы с одним Authorize требуют исправления разделения типов токенов. + +На MAUI рекомендовано хранить refresh token в SecureStorage и выполнять обновление последовательно. Это рекомендация клиенту, а не свойство сервера. + --- -description: How to work with jwt tokens -icon: user ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# Authentication - -### Components - -* **AuthController**: Handles registration and login. - * **Route**: `/api/auth` -* **RefreshController**: Manages token refresh. - * **Route**: `/api/auth/token` - -### Authentication Process - -* **Registration**: - * **Endpoint**: `POST /api/auth/register` - * **Input**: `RegistrationRequest` (name, password, inviteLink, deviceInfo) - * **Output**: Access token - * **Action**: Validates invite, registers user, opens session. -* **Login**: - * **Endpoint**: `POST /api/auth/login` - * **Input**: `LoginRequest` (name, password, deviceInfo) - * **Output**: Access token - * **Action**: Authenticates user, opens session. -* **Token Refresh**: - * **Endpoint**: `POST /api/auth/token/refresh` - * **Input**: `RefreshTokenRequest` (refreshToken) - * **Output**: `RefreshTokenResponse` (accessToken, refreshToken) - * **Action**: Refreshes expired access token. - -### Token Usage - -* **Access Token**: - * **Request**: Obtain during registration or login. - * **Refresh**: Request via `/api/auth/token/refresh` when expired (e.g., 02:12 PM CEST, July 21, 2025). -* **Refresh Token**: - * **Request**: Received during registration or login. - * **Refresh**: Use to obtain new access token when current one expires. - -### Security - -* **Protocol**: Requires HTTPS. -* **Storage**: Store refresh token in HTTP-only cookie with `Secure` and `SameSite=Strict`. +Источник: [Govor.Application/Authentication/JWT/JwtService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Authentication/JWT/JwtService.cs). diff --git a/docs/endpoints/authentication/authcontroller.md b/docs/endpoints/authentication/authcontroller.md index 3cd6d03..262a024 100644 --- a/docs/endpoints/authentication/authcontroller.md +++ b/docs/endpoints/authentication/authcontroller.md @@ -1,141 +1,45 @@ +# Регистрация и вход + +Оба метода доступны анонимно, Content-Type: application/json. + +## POST /api/auth/register + +```json +{ + "name": "Артём", + "password": "example-password", + "inviteLink": "<код приглашения>", + "deviceInfo": "Android test device" +} +``` + +Имя: 4–44 символа, только кириллица и цифры, первый символ — буква. Модерация запрещает зарезервированные имена, совпадения/подстроки из конфигурации и пять одинаковых символов подряд. Пароль: минимум 8 символов. DeviceInfo необязателен в запросе, но в БД ограничен 256 символами. + +Код создаётся как Guid.ToString("N"): 32 символа без дефисов. Поиск кода — по строковому равенству. InviteLink — код, а не URL. + +Проверяется существование приглашения, срок и число участников. Проверка IsActive отсутствует, лимит участников не защищён от конкурентной регистрации. + +Успех 200: + +```json +{"refreshToken":"","accessToken":""} +``` + +Конфликт имени — 409; ошибки валидации — 400; отсутствующее приглашение — 404. Тело сервисных ошибок — ProblemDetails с errorCode. Регистрация и открытие сессии — отдельные сохранения: ошибка открытия сессии не откатывает созданного пользователя. + +## POST /api/auth/login + +```json +{"name":"Артём","password":"example-password","deviceInfo":"Android test device"} +``` + +Успех 200 с той же парой токенов. Пользователь не найден — 404 (UserNotRegisteredException); неверный пароль — 400 (InvalidOperationException). Это текущее поведение, а не рекомендуемая политика ошибок входа: разные ответы раскрывают существование аккаунта. + +## Ограничения + +Rate limiting и блокировка перебора в Program.cs не настроены. Для публичного запуска нужны единая ошибка входа, ограничение частоты и защита административных приглашений. + --- -description: >- - Controller for handling user authentication operations, including registration - and login, with session management and invite-based registration. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# AuthController - -### Controller Description - -* **Route**: `api/auth` -* **Authorize**: Allows anonymous access (`[AllowAnonymous]`). - -### Endpoints - -#### Register - -* **Description**: Registers a new user using a valid invite link and opens a user session, returning an authentication token. -* **Route**: `[POST] api/auth/register` -* **HTTP Method**: `POST` -* **Request**: - * **Content-Type**: `application/json` - * **Request Body**: `RegistrationRequest` object with the following structure: - - ```json - { - "name": "string", - "password": "string", - "inviteLink": "string", - "deviceInfo": "string" - } - ``` -* **Responses**: - * **200 OK**: Returns the authentication token upon successful registration and session creation. - - ```json - { - "refreshToken": "string", - "accessToken": "string" - } - ``` - * **400 Bad Request**: - * If model validation fails. - * If the user already exists: `"Registration failed: user already exists."` - * If the invite link is invalid: `"Invite link invalid."` - * If the username is invalid: `"Invalid username: "` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "An unexpected error occurred. Please try again later." - ``` - -#### Login - -* **Description**: Authenticates an existing user and opens a session, returning an authentication token. -* **Route**: `[POST] api/auth/login` -* **HTTP Method**: `POST` -* **Request**: - * **Content-Type**: `application/json` - * **Request Body**: `LoginRequest` object with the following structure: - - ```json - { - "name": "string", - "password": "string", - "deviceInfo": "string" - } - ``` -* **Responses**: - * **200 OK**: Returns the authentication token upon successful login and session creation. - - ```json - { - "refreshToken": "string", - "accessToken": "string" - } - ``` - * **400 Bad Request**: - * If model validation fails. - * If the user does not exist: `"Login failed: user does not exist."` - * If the username or password is incorrect: `"Login failed: username or password is incorrect."` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "An unexpected error occurred. Please try again later." - ``` - -### Data Models - -#### RegistrationRequest - -* **Description**: Model for registration request data. -* **Structure**: - - ```json - { - "name": "string", - "password": "string", - "inviteLink": "string", - "deviceInfo": "string" - } - ``` - -#### LoginRequest - -* **Description**: Model for login request data. -* **Structure**: - - ```json - { - "name": "string", - "password": "string", - "deviceInfo": "string" - } - ``` - -#### RefreshResult - -* **Description**: Model for refresh token response data. -* **Structure**: - - ```json - { - "refreshToken": "string", - "accessToken": "string" - } - ``` - -### Error Handling - -* **Invalid User ID**: Not applicable (handled by session service). -* **Invalid Operations**: Registration fails if the user already exists, invite link is invalid, or username is invalid, returning `400 Bad Request`. -* **Unauthorized Access**: Not applicable (endpoint is `[AllowAnonymous]`). -* **Unexpected Errors**: General exceptions are caught, logged, and returned as `500 Internal Server Error`. - -### Logging - -* Logs successful registration and login events with username and user ID. -* Logs session opening events with username and user ID. -* Logs warnings for specific exceptions (e.g., user already exists, invalid invite link, login failures). -* Logs errors for unexpected exceptions during registration and login. +Источник: [Govor.API/Controllers/Authentication/AuthController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Authentication/AuthController.cs). diff --git a/docs/endpoints/authentication/refreshcontroller.md b/docs/endpoints/authentication/refreshcontroller.md index 403b6b5..9aae6b3 100644 --- a/docs/endpoints/authentication/refreshcontroller.md +++ b/docs/endpoints/authentication/refreshcontroller.md @@ -1,90 +1,36 @@ +# Обновление токенов + +## POST /api/auth/token/refresh + +Доступ анонимный. JSON: + +```json +{"refreshToken":"<последний сохранённый refresh token>"} +``` + +Сервис хеширует переданную строку и ищет UserSession по RefreshTokenHash. Проверяет IsRevoked и ExpiresAt, выпускает новую пару, заменяет хеш и продлевает ExpiresAt. CreatedAt также перезаписывается, поэтому после refresh это не исходная дата открытия сессии. + +Успех 200: + +```json +{"refreshToken":"","accessToken":""} +``` + +| Случай | Текущий ответ | +| --- | --- | +| Пустая строка | 400, errorCode Auth.EmptyToken | +| Хеш не найден | 400, errorCode Auth.InvalidToken | +| Истекшая/отозванная сессия | 400, errorCode Auth.InvalidToken | + +Не документируйте неверный refresh как гарантированный 401: текущий Error.Failure преобразуется в 400. + +## Клиент + +Сохраните оба новых токена и сериализуйте refresh-запросы. Ошибка сети не должна автоматически удалять авторизацию пользователя. При подтверждённо недействительном refresh требуется повторный вход. + +Ротация сейчас не имеет защиты от конкурентного использования и истории повторного применения. Детали — в разделе «Аутентификация». + --- -description: >- - Controller for managing token refresh operations, allowing users to refresh - their access tokens using a valid refresh token. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# RefreshController - -### Controller Description - -* **Route**: `api/auth/token` -* **Authorize**: Allows anonymous access (`[AllowAnonymous]`). - -### Endpoints - -#### Refresh - -* **Description**: Refreshes an access token using a provided refresh token and returns a new access token and refresh token pair. -* **Route**: `[POST] api/auth/token/refresh` -* **HTTP Method**: `POST` -* **Request**: - * **Content-Type**: `application/json` - * **Request Body**: `RefreshTokenRequest` object with the following structure: - - ```json - { - "refreshToken": "string" - } - ``` -* **Responses**: - * **200 OK**: Returns a new access token and refresh token upon successful refresh. - - ```json - { - "accessToken": "string", - "refreshToken": "string" - } - ``` - * **400 Bad Request**: If model validation fails or the refresh token is empty. - - ```json - "Refresh token cant be empty." - ``` - * **401 Unauthorized**: If the refresh token is invalid or authorization fails. - - ```json - "Invalid refresh token" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "An unexpected error occurred." - ``` - -### Data Models - -#### RefreshTokenRequest - -* **Description**: Model for refresh token request data. -* **Structure**: - - ```json - { - "refreshToken": "string" - } - ``` - -#### RefreshTokenResponse - -* **Description**: Model for refresh token response data. -* **Structure**: - - ```json - { - "accessToken": "string", - "refreshToken": "string" - } - ``` - -### Error Handling - -* **Invalid User ID**: Not applicable (handled by session service). -* **Invalid Operations**: Returns `400 Bad Request` if the refresh token is empty or invalid. -* **Unauthorized Access**: Returns `401 Unauthorized` if the refresh token fails authorization. -* **Unexpected Errors**: General exceptions are caught, logged, and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for invalid or failed refresh token attempts. -* Logs errors for unexpected exceptions during token refresh. +Источник: [Govor.Application/Users/UserSessions/UserSessionRefresher.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Users/UserSessions/UserSessionRefresher.cs). diff --git a/docs/endpoints/chatloadcontroller.md b/docs/endpoints/chatloadcontroller.md index 5917f14..71ff254 100644 --- a/docs/endpoints/chatloadcontroller.md +++ b/docs/endpoints/chatloadcontroller.md @@ -1,259 +1,44 @@ +# История сообщений + +Требуется роль User/Admin. + +| Метод | Маршрут | Идентификатор | +| --- | --- | --- | +| GET | /api/user/{userId}/messages | В userId передаётся **ID PrivateChat** | +| GET | /api/groups/{groupId}/messages | ID ChatGroup | + +Query: StartMessageId (Guid?, необязателен), Before=20, After=2. Before и After неотрицательные, сумма ≤100. + +Без StartMessageId возвращаются последние Before сообщений, упорядоченные по SentAt по возрастанию; After не используется. С якорем возвращаются Before старых, якорное сообщение и After новых: максимум 101 запись. Неизвестный якорь — []. + +Успех 200, MessageResponse[]: + +```json +[{ + "id":"11111111-1111-1111-1111-111111111111", + "senderId":"22222222-2222-2222-2222-222222222222", + "recipientId":"33333333-3333-3333-3333-333333333333", + "recipientType":0, + "encryptedContent":"<строка>", + "sentAt":"2026-10-03T00:00:00Z", + "isEdited":false, + "editedAt":null, + "replyToMessageId":null, + "mediaAttachments":[], + "reactions":[], + "messageViews":[] +}] +``` + +У HTTP-ответа поле id; у SignalR UserMessageResponse — messageId. Вложения HTTP имеют id, messageId, mediaFileId. + +## Известные проблемы + +Личный загрузчик принимает currentUser, но не проверяет участие в указанном чате. Это критичная ошибка доступа. Для группы участие проверяется; неучастнику возвращается []. + +Пагинация сравнивает только SentAt: сообщения с одинаковой датой могут выпадать вокруг якоря. Reactions и MessageViews не включаются явным Include, поэтому эти массивы не являются надёжным источником состояния. Нужны проверки доступа и стабильный курсор (SentAt, Id). + --- -description: Controller for loading chat messages for users and groups with pagination. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# ChatLoadController - -### Controller Description - -* **Route**: `api/chats` -* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`). - -### Endpoints - -#### GetGroupMessages - -* **Description**: Retrieves messages from a specified group chat with pagination. -* **Route**: `[GET] api/chats/group-messages` -* **HTTP Method**: `GET` -* **Request**: - * **Path Parameter**: `chatId` (Guid, required): ID of the group chat. - * **Query Parameter**: `query` (`MessageQuery`, required) with: - * `startMessageId` (Guid?, optional): ID of the starting message. - * `before` (int, default=20): Number of messages before the start. - * `after` (int, default=2): Number of messages after the start. -* **Responses**: - * **200 OK**: Returns a list of group chat messages. - - ```json - [ - { - "id": "Guid", - "senderId": "Guid", - "recipientId": "Guid", - "recipientType": "string", - "encryptedContent": "string", - "sentAt": "DateTime", - "isEdited": "boolean", - "editedAt": "DateTime?", - "replyToMessageId": "Guid?", - "mediaAttachments": [ - { - "id": "Guid", - "messageId": "Guid", - "mediaFileId": "Guid" - } - ], - "reactions": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "reactionCode": "string", - "reactedAt": "DateTime" - } - ], - "messageViews": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "viewedAt": "DateTime" - } - ] - } - ] - ``` - * **400 Bad Request**: - * If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."` - * If an argument or resource is invalid: `"string"` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -#### GetUserMessages - -* **Description**: Retrieves messages from a specified user chat with pagination. -* **Route**: `[GET] api/chats/user-messages` -* **HTTP Method**: `GET` -* **Request**: - * **Path Parameter**: `userId` (Guid, required): ID of the target user. - * **Query Parameter**: `query` (`MessageQuery`, required) with: - * `startMessageId` (Guid?, optional): ID of the starting message. - * `before` (int, default=20): Number of messages before the start. - * `after` (int, default=2): Number of messages after the start. -* **Responses**: - * **200 OK**: Returns a list of user chat messages. - - ```json - [ - { - "id": "Guid", - "senderId": "Guid", - "recipientId": "Guid", - "recipientType": "string", - "encryptedContent": "string", - "sentAt": "DateTime", - "isEdited": "boolean", - "editedAt": "DateTime?", - "replyToMessageId": "Guid?", - "mediaAttachments": [ - { - "id": "Guid", - "messageId": "Guid", - "mediaFileId": "Guid" - } - ], - "reactions": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "reactionCode": "string", - "reactedAt": "DateTime" - } - ], - "messageViews": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "viewedAt": "DateTime" - } - ] - } - ] - ``` - * **400 Bad Request**: - * If `before` or `after` is negative or total exceeds 100: `"Values must be non-negative and total must not exceed 100."` - * If an operation or resource is invalid: `"string"` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -### Data Models - -#### MessageQuery - -* **Description**: Model for pagination query parameters. -* **Structure**: - - ```json - { - "startMessageId": "Guid?", - "before": "int", - "after": "int" - } - ``` - -#### MessageResponse - -* **Description**: Data transfer object for chat message details. -* **Structure**: - - ```json - { - "id": "Guid", - "senderId": "Guid", - "recipientId": "Guid", - "recipientType": "string", - "encryptedContent": "string", - "sentAt": "DateTime", - "isEdited": "boolean", - "editedAt": "DateTime?", - "replyToMessageId": "Guid?", - "mediaAttachments": [ - { - "id": "Guid", - "messageId": "Guid", - "mediaFileId": "Guid" - } - ], - "reactions": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "reactionCode": "string", - "reactedAt": "DateTime" - } - ], - "messageViews": [ - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "viewedAt": "DateTime" - } - ] - } - ``` - -#### MediaAttachmentResponse - -* **Description**: Data transfer object for media attachments in messages. -* **Structure**: - - ```json - { - "id": "Guid", - "messageId": "Guid", - "mediaFileId": "Guid" - } - ``` - -#### MessageReactionResponse - -* **Description**: Data transfer object for message reactions. -* **Structure**: - - ```json - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "reactionCode": "string", - "reactedAt": "DateTime" - } - ``` - -#### MessageViewResponse - -* **Description**: Data transfer object for message view tracking. -* **Structure**: - - ```json - { - "id": "Guid", - "messageId": "Guid", - "userId": "Guid", - "viewedAt": "DateTime" - } - ``` - -### Error Handling - -* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid. -* **Invalid Operations**: Returns `400 Bad Request` for negative values, total exceeding 100, or `InvalidOperationException`. -* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`. -* **Resource Not Found**: Returns `400 Bad Request` for `NotFoundException`. -* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for `UnauthorizedAccessException`, `NotFoundException`, `ArgumentException`, and `InvalidOperationException`. -* Logs errors for unexpected exceptions. +Источник: [Govor.Application/Messages/MessagesLoader.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Application/Messages/MessagesLoader.cs). diff --git a/docs/endpoints/friendshipcontroller.md b/docs/endpoints/friendshipcontroller.md index 4ba6894..c0bc196 100644 --- a/docs/endpoints/friendshipcontroller.md +++ b/docs/endpoints/friendshipcontroller.md @@ -1,114 +1,30 @@ +# Друзья и поиск + +Bearer token обязателен; отдельная роль в атрибуте не задана. + +| Метод | Маршрут | Результат | +| --- | --- | --- | +| GET | /api/friends | UserDto[] друзей | +| GET | /api/friends/search?query=Арт | UserDto[] результатов поиска | + +```json +[{ + "id":"11111111-1111-1111-1111-111111111111", + "username":"Артём", + "description":"", + "wasOnline":"2026-10-03T00:00:00Z", + "iconId":"00000000-0000-0000-0000-000000000000", + "isOnline":false +}] +``` + +Пустой/пробельный query возвращает 400 строкой "Query cannot be empty". Успех — 200; серверные ошибки — 500 с объектом error. Не смешивайте UserDto и UserProfileDto: у второго нет wasOnline. + +Изменение заявок выполняется через FriendsHub. HTTP-контроллер не содержит команды отправки, принятия и отклонения. + +Статус isOnline зависит от состояния процесса и подключения к presence. Он не является гарантией доставки сообщений или фоновой доступности устройства. + --- -description: >- - Description: Controller for managing friendship-related operations, including - searching for users and retrieving the list of friends for the current user. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# FriendshipController - -### Controller Description - -* **Route**: `api/friends` -* **Authorize**: Requires authenticated user (`[Authorize]`). - -### Endpoints - -#### Search - -* **Description**: Searches for users based on a query string. -* **Route**: `[GET] api/friends/search?query=` -* **HTTP Method**: `GET` -* **Request**: - * **Query Parameter**: `query` (string, required) -* **Responses**: - * **200 OK**: Returns a list of matching users. - - ```json - [ - { - "id": "Guid", - "username": "string", - "description": "string", - "wasOnline": "DateTime", - "iconId": "Guid" - } - ] - ``` - * **400 Bad Request**: If the query is empty. - - ```json - "Query cannot be empty" - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - { - "error": "Internal error during user search." - } - ``` - -#### GetFriends - -* **Description**: Retrieves the list of friends for the authenticated user. -* **Route**: `[GET] api/friends` -* **HTTP Method**: `GET` -* **Request**: None -* **Responses**: - * **200 OK**: Returns a list of the user's friends or an empty list if none. - - ```json - [ - { - "id": "Guid", - "username": "string", - "description": "string", - "wasOnline": "DateTime", - "iconId": "Guid" - } - ] - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - { - "error": "Internal server error." - } - ``` - -### Data Models - -#### UserDto - -* **Description**: Data transfer object for user information. -* **Structure**: - - ```json - { - "id": "Guid", - "username": "string", - "description": "string", - "wasOnline": "DateTime", - "iconId": "Guid" - } - ``` - -### Error Handling - -* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid. -* **Invalid Operations**: Returns `400 Bad Request` for empty query. -* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for `SearchUsersException`. -* Logs errors for unexpected exceptions and `InvalidOperationException`. +Источник: [Govor.API/Controllers/Friends/FriendshipController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Friends/FriendshipController.cs). diff --git a/docs/endpoints/friendsrequestquerycontroller.md b/docs/endpoints/friendsrequestquerycontroller.md index 0af2473..0806283 100644 --- a/docs/endpoints/friendsrequestquerycontroller.md +++ b/docs/endpoints/friendsrequestquerycontroller.md @@ -1,109 +1,26 @@ +# Списки заявок в друзья + +Оба маршрута требуют Bearer token и возвращают 200 с FriendshipDto[]. + +| Метод | Маршрут | Назначение | +| --- | --- | --- | +| GET | /api/friends/requests | Входящие заявки | +| GET | /api/friends/responses | Исходящие записи, кроме Accepted (включая Pending, Rejected, Blocked) | + +```json +[{ + "id":"11111111-1111-1111-1111-111111111111", + "requesterId":"22222222-2222-2222-2222-222222222222", + "addresseeId":"33333333-3333-3333-3333-333333333333", + "status":0 +}] +``` + +FriendshipStatus сериализуется числом: Pending=0, Accepted=1, Rejected=2, Blocked=3. id — идентификатор заявки/дружбы; именно он передаётся в AcceptRequest и RejectRequest. + +При отсутствии записей — пустой массив. Ошибки контроллера — 500 с {"error":"Internal server error."}. Для восстановления после reconnect перечитайте списки: события не являются журналом гарантированной доставки. + --- -description: >- - Description: Controller for querying friend request-related data, including - incoming friend requests and responses to sent friend requests. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# FriendsRequestQueryController - -### Controller Description - -* **Route**: `api/friends` -* **Authorize**: Requires authenticated user (`[Authorize]`). - -### Endpoints - -#### GetIncomingRequests - -* **Description**: Retrieves a list of incoming friend requests for the authenticated user. -* **Route**: `[GET] api/friends/requests` -* **HTTP Method**: `GET` -* **Request**: None -* **Responses**: - * **200 OK**: Returns a list of incoming friend requests or an empty list if none. - - ```json - [ - { - "id": "Guid", - "senderId": "Guid", - "receiverId": "Guid", - "status": "string", - "createdAt": "DateTime" - } - ] - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - { - "error": "Internal server error." - } - ``` - -#### GetResponses - -* **Description**: Retrieves a list of responses to the authenticated user's sent friend requests. -* **Route**: `[GET] api/friends/responses` -* **HTTP Method**: `GET` -* **Request**: None -* **Responses**: - * **200 OK**: Returns a list of friend request responses or an empty list if none. - - ```json - [ - { - "id": "Guid", - "senderId": "Guid", - "receiverId": "Guid", - "status": "string", - "createdAt": "DateTime" - } - ] - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - { - "error": "Internal server error." - } - ``` - -### Data Models - -#### FriendshipDto - -* **Description**: Data transfer object for friend request information. -* **Structure**: - - ```json - { - "id": "Guid", - "senderId": "Guid", - "receiverId": "Guid", - "status": "string", - "createdAt": "DateTime" - } - ``` - -### Error Handling - -* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid. -* **Invalid Operations**: Returns `200 OK` with an empty list for `InvalidOperationException`. -* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for `InvalidOperationException`. -* Logs information for successful response retrieval. -* Logs errors for unexpected exceptions. +Источник: [Govor.API/Controllers/Friends/FriendsRequestQueryController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Friends/FriendsRequestQueryController.cs). diff --git a/docs/endpoints/mediacontroller.md b/docs/endpoints/mediacontroller.md index a9b47f5..109f088 100644 --- a/docs/endpoints/mediacontroller.md +++ b/docs/endpoints/mediacontroller.md @@ -1,107 +1,42 @@ +# Медиа + +Требуется роль User/Admin. + +## POST /api/media/upload + +Content-Type: multipart/form-data. Поля: + +| Поле | Тип | Назначение | +| --- | --- | --- | +| FromFile | файл | Непустое содержимое | +| Type | число | Image=0, Video=1, Audio=2, File=3, Voice=4 | +| MimeType | строка ≤255 | MIME типа файла | +| EncryptedKey | строка | Обязательное поле запроса; сохранение ключа не реализовано | +| OwnerType | число | Message=0, Avatar=1, GroupAvatar=2, System=3 | + +Ограничение запроса — 20 000 000 байт, включая multipart; проверка файла также ≤20 000 000. Не следует обещать загрузку файла ровно этого размера: overhead тоже входит в лимит. + +Успех 200: + +```json +{"mediaId":"11111111-1111-1111-1111-111111111111","url":"2026/10/<имя файла>"} +``` + +url — относительный путь хранилища, не публичный URL. Для скачивания используйте endpoint. + +## GET /api/media/download/{id} + +Проверяет HasAccessAsync, затем возвращает бинарный файл с MIME и Content-Disposition. Если доступа нет или запись не найдена — 403, потому что проверка доступа выполняется первой. Сервисные ошибки — через ResultExtensions. + +## Ограничения + +Для личного сообщения accesser сравнивает Message.RecipientId с userId, хотя там ID чата: получатель может получить 403. При Send принадлежность вложения загрузившему пользователю не проверяется. OwnerType задаёт клиент, включая публично доступный System, — нужна серверная политика владения. + +EncryptedKey не хранится ни в MediaFile, ни в MediaAttachments. Нельзя обещать восстановление ключа из истории. + +Файлы целиком буферизуются в памяти, MIME принимается от клиента. Запись файла и БД не атомарна: возможны файлы без записи. Очистка неиспользуемых загрузок и stream-based выдача требуют реализации. + --- -description: Controller for uploading and downloading media files. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# MediaController - -### Controller Description - -* **Route**: `api/media` -* **Authorize**: Requires authenticated user with roles "User" or "Admin" (`[Authorize(Roles = "User,Admin")]`). - -### Endpoints - -#### Upload - -* **Description**: Uploads a media file with associated metadata. -* **Route**: `[POST] api/media/upload` -* **HTTP Method**: `POST` -* **Request**: - * **Content-Type**: `multipart/form-data` - * **Request Body**: `MediaUploadRequest` object with the following structure: - - ```json - { - "fromFile": "IFormFile", - "type": "MediaType", - "mimeType": "string", - "encryptedKey": "string" - } - ``` - * **Constraints**: File size limit of 20 MB. -* **Responses**: - * **200 OK**: Returns the upload result. - - ```json - "string" // Media ID or similar result - ``` - * **400 Bad Request**: - * If model validation fails. - * If no file is uploaded: `"No file uploaded"` - * If file exceeds 20 MB: `"File is too large"` - * If MIME type is missing: `"Missing MIME type"` - * If operation is invalid: `"string"` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Internal server error" - ``` - -#### Download - -* **Description**: Downloads a media file by its ID. -* **Route**: `[GET] api/media/download/{id}` -* **HTTP Method**: `GET` -* **Request**: - * **Path Parameter**: `id` (Guid, required): ID of the media file. -* **Responses**: - * **200 OK**: Returns the media file as a stream. - * **Content-Type**: Matches `MimeType` of the media. - * **Content-Disposition**: Includes `filename` from `FileName`. - * **403 Forbidden**: If user lacks access. - * No body. - * **404 Not Found**: If media is not found. - - ```json - "Media not found" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Internal server error" - ``` - -### Data Models - -#### MediaUploadRequest - -* **Description**: Model for media upload request data. -* **Structure**: - - ```json - { - "fromFile": "IFormFile", - "type": "MediaType", - "mimeType": "string", - "encryptedKey": "string" - } - ``` - -### Error Handling - -* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid. -* **Invalid Operations**: Returns `400 Bad Request` for `InvalidOperationException`. -* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`. -* **Resource Not Found**: Returns `404 Not Found` for `KeyNotFoundException`. -* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for `UnauthorizedAccessException`, `InvalidOperationException`, and `KeyNotFoundException`. -* Logs information for successful file uploads. -* Logs errors for unexpected exceptions during upload and download. +Источник: [Govor.API/Controllers/MediaController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/MediaController.cs). diff --git a/docs/endpoints/message-read.md b/docs/endpoints/message-read.md new file mode 100644 index 0000000..6c19e09 --- /dev/null +++ b/docs/endpoints/message-read.md @@ -0,0 +1,67 @@ +# Прочтение сообщений + +Контракт реализован в рабочей копии сервера от 03.10.2026. Требуются access token, роль User/Admin и участие именно в запрошенном чате. `chatId` — ID PrivateChat либо ChatGroup, а не ID собеседника. `recipientType`: 0 — личный чат, 1 — группа. + +## POST /api/chats/{chatId}/read + +Три взаимоисключающих режима: + +| Действие клиента | Тело запроса | Семантика | +| --- | --- | --- | +| Скролл, входящие сообщения видны на экране | `{"recipientType":0,"messageIds":["",""]}` | Прочитать только эти сообщения | +| Пользователь просмотрел историю до определённого сообщения | `{"recipientType":0,"upToMessageId":""}` | Прочитать входящие до границы включительно | +| Команда «Пометить как прочитано» | `{"recipientType":0}` | Зафиксировать последнюю границу и прочитать входящие до неё | + +Граница упорядочена по `(sentAt, messageId)`: ID разрешает совпадающие timestamps. Сообщения после этой границы остаются непрочитанными. Свои сообщения не получают MessageView. В режиме messageIds передавайте только входящие: от 1 до 100 ID, без Guid.Empty. Список и upToMessageId нельзя объединять. Весь список проверяется до записи; ID из другого чата возвращает 404 без частичного прочтения. Отсутствие участия возвращает 403; неверная комбинация и собственные сообщения в списке — 400. + +200 OK, JSON: + +```json +{ + "chatId":"", + "recipientType":0, + "readerId":"", + "readAt":"2026-10-03T07:00:00Z", + "upToMessageId":null, + "upToSentAt":null, + "messageIds":[""], + "readCount":1, + "unreadCount":3 +} +``` + +Для режима границы messageIds=null, upToMessageId/upToSentAt заполнены. У пустого чата граница null. readCount — число новых записей данного вызова; повторный запрос возвращает 0 и не меняет время существующих MessageView. readAt — время операции; исходное время каждого прочтения доступно в истории, через messageViews. unreadCount относится к readerId в этом чате и включает все оставшиеся входящие сообщения на момент подсчёта. + +Уникальный индекс `(MessageId, UserId)` и `ON CONFLICT DO NOTHING` защищают параллельные отметки с нескольких устройств. Получение истории само по себе ничего не помечает. + +## GET /api/chats/{chatId}/unread-count?recipientType=0 + +200 OK: `{"unreadCount":3}`. Считает входящие без MessageView текущего пользователя. Те же требования авторизации и участия. Клиент использует endpoint после подключения/переподключения и для восстановления локального счётчика. + +## SignalR + +`ReadChat(Guid chatId, ReadChatRequest request)` на `/hubs/chats` выполняет ту же операцию, возвращает `HubResult`. После успешного HTTP или SignalR вызова сервер отправляет событие `ChatRead` с ChatReadResponse всем активным сессиям текущих участников, включая устройства читателя. Ошибки HubResult используют 400/401/403/404/500; это поле status, а не HTTP-статус WebSocket. + +Старый `Read(ReadMessageRequest)` сохраняется. Он читает одно входящее сообщение и возвращает прежнюю квитанцию при повторении. Для совместимости отправляются `MessageReaded` и `MessageRead`; подпишитесь на одно из этих имён. Для массового прочтения используйте ChatRead. + +## Использование в MAUI + +Собирайте ID реально видимых входящих сообщений, отправляйте пачками до 100, объединяя частые события скролла. Отправляйте запрос только при активном окне чата. Обновляйте локальное состояние после успешного ответа; при потере сети повторяйте тот же список. Не отмечайте всю загруженную страницу как просмотренную, если она была вне экрана. + +```csharp +var request = new ReadChatRequest +{ + RecipientType = RecipientType.User, + MessageIds = visibleIncomingIds.Distinct().Take(100).ToList() +}; +if (request.MessageIds.Count > 0) +{ + var result = await connection.InvokeAsync>( + "ReadChat", chatId, request); + // При успешном status примените result.Result и его UnreadCount. +} +``` + +Кнопка «Пометить как прочитано» передаёт `new ReadChatRequest { RecipientType = type }`. Событие ChatRead обновляет галочки у автора и состояние на остальных устройствах читателя. Оно не требует от других участников подтверждать прочтение. При отключённом SignalR восстановите messageViews через историю и счётчик через unread-count. На устройстве читателя отмените уведомление с tag `chat_`, когда чат полностью прочитан. + +ReceiveMessage и MessageSent могут описывать одно исходящее сообщение. Дедуплицируйте их по messageId; счётчик увеличивается только для новых входящих. diff --git a/docs/endpoints/onlinepingingcontroller-ne-rabotaet.md b/docs/endpoints/onlinepingingcontroller-ne-rabotaet.md index adb67f5..314c1b3 100644 --- a/docs/endpoints/onlinepingingcontroller-ne-rabotaet.md +++ b/docs/endpoints/onlinepingingcontroller-ne-rabotaet.md @@ -1,50 +1,19 @@ +# HTTP-присутствие — ограничения + +Требуется роль User/Admin. + +| Метод | Маршрут | Текущее поведение | +| --- | --- | --- | +| PATCH | /api/online/ping | Вызывает PingHandlerService, успех 200 без тела | +| GET | /api/online/status/{userId} | Неработоспособен: 500 | + +В конструкторе не присваиваются _userOnlineStore и _presenceReader. GetStatus обращается к null; catch возвращает 500 "Internal server error.". + +Задуманное тело status — { isOnline, lastSeen }, но сейчас его нельзя считать рабочим контрактом. + +Для событий online/offline подключайтесь к /hubs/presence. Ping и наличие SignalR-подключения — разные механизмы; требуется единая политика lastSeen/TTL. Не считайте HTTP ping подтверждением активного presence-соединения. + --- -description: >- - Description: Controller for handling user online status updates by processing - ping requests. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# OnlinePingingController(не работает) - -**Route**: `api/online`\ -**Authorize**: Requires "User" or "Admin" role - -### End Point {PATCH} - -`[PATCH] api/online/ping` - -#### Description - -Updates the online status of the current user by sending a ping request. - -**Request** - -* **Content-Type**: `application/json` -* **Request Body**: None - -**Responses** - -* **200 OK**: Ping processed successfully. - - ```json - {} - ``` -* **400 Bad Request**: If the user cannot be found in the database. - - ```json - "User can't be found in our database." - ``` -* **403 Forbidden**: If the user is not authorized to perform the action. - - ```json - { - "error": "Not authorized to perform this action." - } - ``` -* **500 Internal Server Error**: Indicates an unexpected error. - - ```json - { - "error": "Failed to send friend request." - } - ``` +Источник: [Govor.API/Controllers/OnlinePingingController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/OnlinePingingController.cs). diff --git a/docs/endpoints/private-chats.md b/docs/endpoints/private-chats.md new file mode 100644 index 0000000..e2a1fae --- /dev/null +++ b/docs/endpoints/private-chats.md @@ -0,0 +1,29 @@ +# Личные чаты + +Требуется роль User/Admin. + +| Метод | Маршрут | Успех | +| --- | --- | --- | +| GET | /api/user/{friendId}/private-chat | 200, Guid чата в JSON | +| GET | /api/user/private-chats | 200, PrivateChatDto[] | + +Первый метод проверяет дружбу, возвращает существующий чат либо создаёт новый. Это побочный эффект GET; рекомендуемый будущий контракт — POST, но маршрут пока не изменён. + +```json +[{ + "chatId":"11111111-1111-1111-1111-111111111111", + "friendId":"22222222-2222-2222-2222-222222222222" +}] +``` + +При принятии заявки FriendRequestCommandService также создаёт личный чат и добавляет текущие соединения участников в SignalR-группу. + +Используйте chatId в Send.recipientId и в /api/user/{userId}/messages. Несмотря на имя параметра userId, загрузчик ожидает ID PrivateChat. + +Ошибки дружбы передаются через Forbid(ex.Message), что ошибочно трактует сообщение как имя схемы аутентификации и может дать 500. Параллельное создание и повторное присоединение после частичного сбоя требуют отдельной проверки. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Controllers/PrivateChatController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/PrivateChatController.cs). + diff --git a/docs/endpoints/profile.md b/docs/endpoints/profile.md new file mode 100644 index 0000000..cdf785e --- /dev/null +++ b/docs/endpoints/profile.md @@ -0,0 +1,29 @@ +# Профиль и аватар + +Требуется роль User/Admin. + +| Метод | Маршрут | Успех | +| --- | --- | --- | +| GET | /api/profile/download/me | 200, UserProfileDto текущего пользователя | +| GET | /api/profile/download/{id} | 200, UserProfileDto указанного пользователя | +| POST | /api/profile/avatar | 200, MediaUploadResult | + +UserProfileDto: id, username, description (nullable), iconId (nullable), isOnline. Отсутствующий пользователь — 404 ProblemDetails. + +Загрузка аватара: multipart/form-data с FromFile, Type, MimeType. В отличие от MediaController, отдельный лимит 20 MB не задан; действуют ограничения хоста. Контроллер сохраняет медиа с OwnerType.Avatar и устанавливает IconId. + +Описание изменяется через ProfileHub.SetDescription. ProfileHub.SetAvatar принимает существующий iconId и рассылает AvatarUpdated. + +## Ограничения + +REST UploadAvatar не рассылает AvatarUpdated. Клиентам может потребоваться отдельное обновление данных. В ProfileHub.SetAvatar проверяется существование файла, но не его загрузчик/тип/владелец. + +Хаб игнорирует Result от SetDescription и SetNewIcon, поэтому успех true не всегда подтверждает изменение. MappingProfile дважды регистрирует UserProfile → UserProfileDto; это нужно устранить и проверить isOnline. + +Чтение чужого профиля не применяет PrivacyUserSettings. Наличие моделей приватности не означает действующую политику доступа. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Controllers/ProfileController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/ProfileController.cs). + diff --git a/docs/endpoints/push.md b/docs/endpoints/push.md new file mode 100644 index 0000000..78bd2ed --- /dev/null +++ b/docs/endpoints/push.md @@ -0,0 +1,29 @@ +# Push-уведомления + +## POST /api/pushes/token/register + +Требуется роль User/Admin. JSON: + +```json +{"token":"","platform":"Android"} +``` + +Сервис связывает токен с userId и sid текущего access token, добавляет или обновляет запись. Успех Unit — 204. Пустой token/platform отклоняется 400; тело BadRequest(ModelState) не всегда содержит полезное объяснение. + +При отзыве сессии связанные токены деактивируются. В DI зарегистрирован FirebasePushProvider; credentials читаются при старте приложения. + +## Отправка + +Личные сообщения вызывают отправку push собеседнику. title — имя отправителя; body — первые 40 символов EncryptedContent. Data содержит chatId и isGroup ("false"). Это текущая реализация: сервер не расшифровывает содержимое. + +Для E2EE тело push должно быть нейтральным. Для текущего MAUI, отправляющего обычный текст, этот body раскрывает превью сообщения внешнему push-провайдеру. + +## Доставка + +Сохранение сообщения, SignalR и Firebase не образуют единую транзакцию. Ошибка после SaveChanges может дать ошибку Send, хотя сообщение уже записано. Автоматическое повторение без идентификатора клиентской операции может создать дубль. Нужны outbox, дедупликация и обработка недействительных FCM-токенов. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Hubs/Infrastructure/ChatNotificationService.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/Infrastructure/ChatNotificationService.cs). + diff --git a/docs/endpoints/reactions.md b/docs/endpoints/reactions.md new file mode 100644 index 0000000..70c99d0 --- /dev/null +++ b/docs/endpoints/reactions.md @@ -0,0 +1,133 @@ +# Реакции, паки и настройки каналов + +Контракт рабочей версии сервера от 03.10.2026. Все маршруты требуют Bearer **access** token и активную сессию. JSON использует camelCase, перечисления передаются числами. HTTP и SignalR вызывают один сервис с одинаковыми проверками доступа. + +## Реакции сообщения + +На одном сообщении пользователь может иметь одну реакцию: новая заменяет предыдущую. Изменять чужую реакцию нельзя; userId берётся из токена. Доступ имеют участники личного чата и незаблокированные участники группы/канала. + +| Метод | Маршрут | Тело / результат | +| --- | --- | --- | +| GET | `/api/messages/{messageId}/reactions` | Снимок реакций | +| PUT | `/api/messages/{messageId}/reactions/me` | `{ "reactionId": "" }`; снимок | +| DELETE | `/api/messages/{messageId}/reactions/me` | Без тела; снимок | + +Успех — HTTP 200. Повтор PUT той же реакции и DELETE отсутствующей реакции идемпотентны: не повышают version и не отправляют событие. PUT требует активную реакцию активного пака. Ошибки: 400 — некорректный ID; 401 — нет активной access-сессии; 403 — нет доступа или запрещено настройками канала; 404 — сообщение/реакция недоступны. + +Снимок и событие `MessageReactionsChanged` имеют одинаковый формат: + +```json +{ + "messageId": "11111111-1111-1111-1111-111111111111", + "recipientId": "22222222-2222-2222-2222-222222222222", + "recipientType": 0, + "version": 3, + "actorId": "33333333-3333-3333-3333-333333333333", + "actorReaction": null, + "counts": [ + { "reactionId": "b3000000-0000-0000-0001-000000000001", "reactionCode": "👍", "count": 2 } + ] +} +``` + +В GET actorId — текущий пользователь. В событии — пользователь, который изменил реакцию. actorReaction — его текущая MessageReactionResponse либо null после удаления. Не принимайте чужую actorReaction за свою. В counts передаётся полный снимок счётчиков, а не приращения. recipientType: 0 — личный чат (recipientId = PrivateChat.Id), 1 — группа/канал. + +История сообщений содержит reactionsVersion и reactions с reactionId, reactionCode, userId и reactedAt. Старая неизвестная reactionCode может иметь reactionId=null; отображайте её как сохранённый код. Миграция связывает известные старые эмодзи с базовым паком. + +## SignalR и синхронизация клиента + +Подключение: `/hubs/chats`, обычный access token. Методы возвращают существующий `HubResult` с status, result, errorMessage: + +```csharp +var result = await connection.InvokeAsync>( + "React", messageId, new SetReactionRequest { ReactionId = reactionId }); +var removed = await connection.InvokeAsync>( + "RemoveReaction", messageId); + +connection.On("MessageReactionsChanged", state => +{ + // На UI-потоке: принять более новую версию и заменить counts целиком. + // actorReaction обновляет собственный выбор только при actorId == currentUserId. +}); +connection.On("ChannelReactionPolicyChanged", policy => +{ + // Обновить разрешённые реакции канала по более новой version. +}); +``` + +Событие после сохранения получают активные сессии обоих участников личного чата или незаблокированных участников группы, включая устройства автора изменения. Для этих событий push не отправляется. События SignalR не имеют долговременной очереди: после reconnect загрузите HTTP-снимки видимых сообщений и политику канала. Подпишитесь на события до загрузки истории и сравнивайте version отдельно для каждого сообщения, чтобы запоздавший ответ не затёр новое состояние. Ответ команды и событие могут дублировать одну версию. + +## Каталог, установка и обмен + +Базовый пак Emoji доступен каждому автоматически, не требует установки и не отключается. Его ID — `b3000000-0000-0000-0000-000000000001`; содержит 👍 👎 ❤️ 🔥 🥰 👏 😁 🤔 😢 🎉 🤯 🙏. Пользовательские паки публичны среди авторизованных пользователей. Установка добавляет пак в личный выбор; применять публичную реакцию можно и без установки. + +| Метод | Маршрут | Назначение | +| --- | --- | --- | +| GET | `/api/reaction-packs?skip=0&take=50` | Активный каталог | +| GET | `/api/reaction-packs/mine?skip=0&take=50` | Базовый и установленные паки | +| GET | `/api/reaction-packs/{packId}` | Активный пак с активными реакциями | +| GET | `/api/reaction-packs/shared/{shareCode}` | Открыть пак по коду обмена | +| PUT | `/api/reaction-packs/{packId}/subscription` | Установить; HTTP 204 | +| DELETE | `/api/reaction-packs/{packId}/subscription` | Удалить из выбора; HTTP 204 | +| GET | `/api/reactions/{reactionId}` | Определение реакции, включая отключённую | +| GET | `/api/reaction-packs/limits` | Лимиты файлов и пака | + +skip >= 0, take от 1 до 100. Возвращается список паков. Каждый пак: id, name, description, shareCode, sharePath, isDefault, isEnabled, createdByUserId, createdAt, reactions. sharePath — относительный API-маршрут; клиент может передавать shareCode в своей deep link. Отдельного механизма отправки приглашения/сообщения сервер не добавляет. + +Элемент reactions: id, packId, code, name, kind, emoji, mediaFileId, mediaUrl, width, height, sizeBytes, durationMilliseconds, isEnabled, createdAt. kind: Emoji=0, Image=1, Gif=2. Для файлов используйте mediaUrl (`/api/media/download/{id}`) с Bearer token. Файлы реакций доступны всем авторизованным пользователям, включая исторические файлы отключённых реакций. ID файла не даёт доступ к обычным закрытым вложениям чата. + +При отображении незнакомого reactionId получите `/api/reactions/{reactionId}` и кешируйте определение/изображение. Идентичность и файл реакции неизменяемы; для замены изображения администратор создаёт новый элемент. + +## Администрирование паков + +Требуется роль Admin; операции изменения дополнительно проверяют административное приглашение пользователя в БД, согласно существующей модели прав проекта. Будущий бот может использовать эти маршруты с access-сессией административного пользователя. Выдача отдельной bot-учётной записи/токена пока не реализована. + +| Метод | Маршрут | Тело | +| --- | --- | --- | +| GET | `/api/admin/reaction-packs?skip=0&take=50` | Каталог, включая отключённые паки и элементы | +| GET | `/api/admin/reaction-packs/{packId}` | Пак, включая отключённые элементы | +| POST | `/api/admin/reaction-packs` | `{ "name": "Cats", "description": "..." }` | +| PUT | `/api/admin/reaction-packs/{packId}` | `{ "name": "Cats", "description": "...", "isEnabled": true }` | +| DELETE | `/api/admin/reaction-packs/{packId}` | Мягкое отключение пака; 204 | +| POST | `/api/admin/reaction-packs/{packId}/reactions/emoji` | `{ "name": "Cool", "emoji": "😎" }` | +| POST | `/api/admin/reaction-packs/{packId}/reactions/media` | multipart/form-data: name и file | +| DELETE | `/api/admin/reaction-packs/{packId}/reactions/{reactionId}` | Мягкое отключение элемента; 204 | + +Создание/обновление возвращает HTTP 200 с DTO. name — 1–100 символов, description — до 500. До 100 элементов в паке, включая отключённые. Базовый пак и его элементы неизменяемы. Отключение исключает пак/элемент из выбора и запрещает новые реакции, но сохраняет ранее поставленные реакции и файлы; пользователь может снять свою старую реакцию. Отдельного события изменения каталога нет: обновляйте каталог при открытии выбора и после отказа установки реакции. + +## Файлы + +Формат определяется по содержимому: PNG, JPEG, WebP для статичных картинок; GIF для анимации. SVG и анимации других форматов отклоняются. Имя файла и заявленный MIME не определяют результат. Сервер декодирует, удаляет необязательные метаданные, уменьшает и заново кодирует файл. Картинки сохраняются как PNG, анимации как GIF. + +| Ограничение | Значение | +| --- | --- | +| Исходный файл | До 2 МиБ, стороны до 2048 пикселей | +| Результат | Обе стороны не больше 128 пикселей | +| Картинка | До 256 КиБ | +| GIF | До 512 КиБ, до 60 кадров, до 5 секунд за цикл | + +Для достижения лимита размера сервер может уменьшить стороны до 96, 64 или 48 пикселей. Задержка кадра GIF нормализуется минимум до 20 мс; лимит длительности проверяется после нормализации. Слишком сложный/повреждённый файл возвращает 400; тело запроса выше транспортного лимита может вернуть 413. + +Обработка использует SixLabors.ImageSharp 3.1.12 с Six Labors Split License; пакет не требует лицензионного ключа для сборки. Условия использования доступны в [пакете NuGet](https://www.nuget.org/packages/SixLabors.ImageSharp/3.1.12). Переход на ImageSharp 4 требует отдельно настроить build-time license key. + +## Настройки канала + +Группы с IsChannel=true поддерживают ограничения. Новые и существующие каналы после миграции используют All. Управлять политикой может незаблокированный участник, записанный в GroupAdmins этого канала; глобальная роль Admin сама по себе не даёт этих прав. + +| Метод | Маршрут | Результат | +| --- | --- | --- | +| GET | `/api/groups/{groupId}/reactions` | Политика для участников | +| PUT | `/api/groups/{groupId}/reactions` | `{ "mode": 2, "reactionIds": [""] }`; обновлённая политика | + +mode: All=0 — все активные реакции; None=1 — новые реакции запрещены; Selected=2 — только выбранные ID (до 100). Для All/None reactionIds должен быть пустым. Пустой Selected запрещает все новые реакции. Выбираются только активные элементы активных паков. Результат: groupId, mode, version, reactionIds. После успешного PUT приходит ChannelReactionPolicyChanged. Обычная группа не поддерживает PUT политики (400). Изменение политики не удаляет историю; собственную реакцию разрешено снять при любом режиме. + +## Обновление базы и проверка + +Из корня серверного проекта: + +```powershell +dotnet ef database update --project Govor.Domain --startup-project Govor.API +dotnet test Govor.Server.Tests/Govor.Server.Tests.csproj -c Release +``` + +Миграция `20261003101700_ReactionPacksAndChannelPolicies` создаёт каталог, установки, разрешения канала, версии и базовый пак; старые реакции сохраняются. Она подготовлена, но к вашей рабочей БД автоматически не применялась. Локальные тесты используют SQLite и HTTP pipeline с JWT; SignalR-доставка проверяется через mock транспорта. CI также настроен на PostgreSQL. Реальные устройства/сокеты и PostgreSQL локально не проверены. diff --git a/docs/endpoints/session-keys.md b/docs/endpoints/session-keys.md new file mode 100644 index 0000000..8708ed5 --- /dev/null +++ b/docs/endpoints/session-keys.md @@ -0,0 +1,33 @@ +# Ключи сессий — экспериментальный API + +RequireHttps и роль User/Admin обязательны. + +| Метод | Маршрут | Назначение | +| --- | --- | --- | +| POST | /api/session/keys | Привязать публичные ключи текущей сессии | +| GET | /api/session/users/{userId}/keys | Получить ключи друга | +| POST | /api/session/keys/rotate | Пополнить одноразовые ключи | +| GET | /api/session/keys/remaining | { remaining: число } | +| POST | /api/session/keys/{preKeyId}/used | Пометить собственный ключ использованным | + +byte[] в JSON передаются строкой base64. UploadKeysRequest содержит identityKey, signedPreKey, signedPreKeySignature и oneTimePreKeys (массив base64). За запрос допускается максимум 100 одноразовых ключей. Сервис запрещает повторную привязку ключей к сессии и проверяет владельца. + +RotateOneTimePreKeysRequest содержит newOneTimePreKeys. В реализации ротация удаляет использованные записи и добавляет новые, не ограничивая общий размер набора. + +## Неработающие и небезопасные части + +_oneTimePreKeysRotator не передан в конструктор SessionKeysController: rotate и used падают при обращении к null. + +remaining считает все записи, включая IsUsed. Reader выдаёт все OneTimePreKeys и возвращает EF-сущности UserCryptoSession вместо PublicSessionKeysDto. Include(UserSession) может включить внутренние поля, а двусторонние навигации могут привести к циклу сериализации. SignedPreKey не включён явным Include. + +Доступ к чужим ключам ограничен дружбой, но Forbid("текст") ошибочно используется как имя authentication scheme. Атомарной выдачи одного неиспользованного prekey потребителю нет: endpoint used относится к текущей сессии владельца. + +## Статус E2EE + +Это заготовка хранения ключей, не законченный криптографический протокол. Нет доказанной реализации обмена/проверки подписей, одноразового потребления, ratchet и поддержки шифрования на клиенте. Не используйте этот раздел как обещание сквозного шифрования. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Controllers/Authentication/SessionKeysController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/Authentication/SessionKeysController.cs). + diff --git a/docs/endpoints/sessioncontroller.md b/docs/endpoints/sessioncontroller.md index abdc3b8..8d8043d 100644 --- a/docs/endpoints/sessioncontroller.md +++ b/docs/endpoints/sessioncontroller.md @@ -1,157 +1,35 @@ +# Сессии + +Все методы требуют Bearer access token с ролью User или Admin. + +| Метод | Маршрут | Успех | +| --- | --- | --- | +| GET | /api/Session/all | 200, SessionDto[] | +| DELETE | /api/Session/close/{sessionId} | 204, без тела | +| DELETE | /api/Session/close | 204, закрыть sid текущего токена | +| DELETE | /api/Session/close/all | 204, закрыть все сессии пользователя | + +```json +[{ + "id":"11111111-1111-1111-1111-111111111111", + "deviceInfo":"Android test device", + "createdAt":"2026-10-03T00:00:00Z", + "expiresAt":"2026-10-10T00:00:00Z", + "isRevoked":false +}] +``` + +Список фильтруется по UserId и !IsRevoked, но не по ExpiresAt; истекшие сессии могут присутствовать. CreatedAt меняется при refresh. + +Закрытие чужой, неизвестной или уже отозванной сессии возвращает 404 с errorCode UserSession.NotFoundOrUnauthorized. Guid.Empty возвращает 400. CloseAll без активных сессий тоже успешен. + +Отзыв деактивирует связанные push-токены. Успех Unit преобразуется в 204, а не в 200. + +## Ограничение logout + +IsRevoked проверяется при refresh; bearer middleware не сверяет текущий sid с БД. Access token может работать до окончания срока, а существующее соединение SignalR не закрывается этим контроллером. + --- -description: >- - Controller for managing user sessions, including retrieving and closing - sessions. ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. -# SessionController - -### Controller Description - -* **Route**: `api/session` -* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin,User")]`). - -### Endpoints - -#### GetAllSessions - -* **Description**: Retrieves all active sessions for the authenticated user. -* **Route**: `[GET] api/session/all` -* **HTTP Method**: `GET` -* **Request**: None -* **Responses**: - * **200 OK**: Returns a list of user sessions. - - ```json - [ - { - "id": "Guid", - "deviceInfo": "string", - "createdAt": "DateTime", - "expiresAt": "DateTime", - "isRevoked": "boolean" - } - ] - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -#### CloseSession - -* **Description**: Closes a specific session for the authenticated user. -* **Route**: `[DELETE] api/session/close/{sessionId}` -* **HTTP Method**: `DELETE` -* **Request**: - * **Path Parameter**: `sessionId` (Guid, required): ID of the session to close. -* **Responses**: - * **200 OK**: Indicates session was successfully closed. - * No body. - * **400 Bad Request**: If `sessionId` is invalid or operation fails. - - ```json - "string" - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **404 Not Found**: If session is not found. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -#### CloseSession - -* **Description**: Closes a current session for the authenticated user. -* **Route**: `[DELETE] api/session/close/` -* **HTTP Method**: `DELETE` -* **Request**: - * No body. -* **Responses**: - * **200 OK**: Indicates session was successfully closed. - * No body. - * **400 Bad Request**: If `sessionId` is invalid or operation fails. - - ```json - "string" - ``` - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **404 Not Found**: If session is not found. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -#### CloseAllSessions - -* **Description**: Closes all active sessions for the authenticated user. -* **Route**: `[DELETE] api/session/close/all` -* **HTTP Method**: `DELETE` -* **Request**: None -* **Responses**: - * **200 OK**: Indicates all sessions were successfully closed. - * No body. - * **403 Forbidden**: If user lacks authorization. - - ```json - "string" - ``` - * **500 Internal Server Error**: Indicates an unexpected error. - - ```json - "Unexpected Error! Please try again later." - ``` - -### Data Models - -#### SessionDto - -* **Description**: Data transfer object for session information. -* **Structure**: - - ```json - { - "id": "Guid", - "deviceInfo": "string", - "createdAt": "DateTime", - "expiresAt": "DateTime", - "isRevoked": "boolean" - } - ``` - -### Error Handling - -* **Invalid User ID**: Handled by `ICurrentUserService`, aborts if invalid. -* **Invalid Operations**: Returns `400 Bad Request` for `InvalidOperationException`. -* **Unauthorized Access**: Returns `403 Forbidden` for `UnauthorizedAccessException`. -* **Resource Not Found**: Returns `404 Not Found` for `NotFoundException`. -* **Unexpected Errors**: Caught and returned as `500 Internal Server Error`. - -### Logging - -* Logs warnings for `UnauthorizedAccessException` and `NotFoundException`. -* Logs errors for `InvalidOperationException` and unexpected exceptions. +Источник: [Govor.API/Controllers/SessionController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/SessionController.cs). diff --git a/docs/friendshub/README.md b/docs/friendshub/README.md index c52a7a1..916a1be 100644 --- a/docs/friendshub/README.md +++ b/docs/friendshub/README.md @@ -1,235 +1,43 @@ +# FriendsHub — заявки + +Подключение: /hubs/friends с access token, содержащим userId. Атрибут Authorize у класса отсутствует; HubUserAccessor читает claim и бросает исключение при его отсутствии. Это не следует считать полноценной endpoint-политикой авторизации: её нужно добавить явно. + +## Команды + +| Команда | Аргумент | Успех | +| --- | --- | --- | +| SendRequest | Guid targetUserId | status 201, result null | +| AcceptRequest | Guid friendshipId | status 200, result null | +| RejectRequest | Guid friendshipId | status 200, result null | + +SendRequest запрещает заявку себе и повтор при Pending/Accepted/Blocked. После Rejected запись переиспользуется. Accept разрешён только адресату и только Pending; после сохранения дружбы создаётся личный чат. Reject разрешён адресату для Pending/Rejected. + +## Все события + +| Событие | Кому | +| --- | --- | +| FriendRequestReceived | Адресату новой заявки | +| YourFriendRequestReceived | Отправителю | +| FriendRequestAccepted | Принимающему адресату | +| YourFriendRequestAccepted | Отправителю исходной заявки | +| FriendRequestRejected | Отклоняющему адресату | +| YourFriendRequestRejected | Отправителю исходной заявки | + +Каждое событие передаёт **FriendshipDto**, не строку Guid: + +```json +{"id":"11111111-1111-1111-1111-111111111111","requesterId":"22222222-2222-2222-2222-222222222222","addresseeId":"33333333-3333-3333-3333-333333333333","status":0} +``` + +Status: Pending=0, Accepted=1, Rejected=2, Blocked=3. + +## Ошибки и восстановление + +Сервисные Failure в SendRequest преобразуются в status 500; Accept/Reject — в 400. Поэтому не обещайте 409/403/404 для всех соответствующих бизнес-ошибок. + +Дружба сохраняется до создания чата/рассылки; сбой может оставить частично завершённый сценарий. На reconnect перечитывайте /api/friends, /requests, /responses и /api/user/private-chats. Клиенту нужны дедупликация и обновление cache по id. + --- -description: >- - Description: SignalR hub for managing real-time friend request operations, - including sending, accepting, and rejecting friend requests. -icon: wifi ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. -# FriendsHub - -**Route** `hubs/friends` - -**Authorize**: Requires authentication (user must be logged in) - -### Hub Methods - -#### OnConnectedAsync - -**Description**: Automatically invoked when a client establishes a connection to the hub. Adds the user to their personal group for receiving friend request notifications. - -**Behavior**: - -* Retrieves the user's ID from the connection context. -* If the user ID is invalid (`Guid.Empty`), logs a warning and aborts the connection. -* Adds the user to a group named after their user ID (e.g., `userId.ToString()`). -* Logs the connection event with the user ID and connection ID. - -*** - -#### OnDisconnectedAsync - -**Description**: Automatically invoked when a client disconnects from the hub. Removes the user from their personal group. - -**Behavior**: - -* Retrieves the user's ID from the connection context, suppressing exceptions if the ID is unavailable (e.g., due to an early abort). -* If the user ID is valid, removes the user from their personal group. -* Logs the disconnection event with the user ID and connection ID. -* If an exception occurs, logs it as a warning along with the connection ID. -* If no exception occurs but the user ID is invalid, logs the disconnection with the connection ID. - -*** - -#### SendRequest - -**Description**: Sends a friend request to a specified user and notifies the recipient in real-time. - -**Request**: - -* **Method Name**: `SendRequest` -* **Parameters**: - * `targetUserId`: (`Guid`) The ID of the user to whom the friend request is sent. - -**Responses**: - -* **Success (201 Created)**: Friend request sent successfully. - - ```json - { - "status": 201, - "result": null, - "errorMessage": null - } - ``` -* **400 Bad Request**: If the operation is invalid (e.g., sending a request to oneself). - - ```json - { - "status": 400, - "result": null, - "errorMessage": "" - } - ``` -* **401 Unauthorized**: If the user is not authorized. - - ```json - { - "status": 401, - "result": null, - "errorMessage": "" - } - ``` -* **409 Conflict**: If a friend request was already sent. - - ```json - { - "status": 409, - "result": null, - "errorMessage": "" - } - ``` -* **500 Server Error**: Indicates an unexpected error. - - ```json - { - "status": 500, - "result": null, - "errorMessage": "Unexpected error! Please try later!" - } - ``` - -**Client-Side Events**: - -* **FriendRequestReceived**: Triggered on the recipient's client to notify them of a new friend request. - * Payload: `userId` (`Guid`) - The ID of the user who sent the request. - -*** - -#### AcceptRequest - -**Description**: Accepts a friend request and notifies the user in real-time. - -**Request**: - -* **Method Name**: `AcceptRequest` -* **Parameters**: - * `friendshipId`: (`Guid`) The ID of the friend request to accept. - -**Responses**: - -* **Success (200 OK)**: Friend request accepted successfully. - - ```json - { - "status": 200, - "result": null, - "errorMessage": null - } - ``` -* **400 Bad Request**: If the operation is invalid (e.g., invalid friendship ID). - - ```json - { - "status": 400, - "result": null, - "errorMessage": "" - } - ``` -* **401 Unauthorized**: If the user is not authorized to accept the request. - - ```json - { - "status": 401, - "result": null, - "errorMessage": "" - } - ``` -* **500 Server Error**: Indicates an unexpected error. - - ```json - { - "status": 500, - "result": null, - "errorMessage": "Unexpected error! Please try later!" - } - ``` - -**Client-Side Events**: - -* **FriendRequestAccepted**: Triggered on the user's client to confirm the friend request was accepted. - * Payload: `friendshipId` (`Guid`) - The ID of the accepted friend request. - -*** - -#### RejectRequest - -**Description**: Rejects a friend request and notifies the user in real-time. - -**Request**: - -* **Method Name**: `RejectRequest` -* **Parameters**: - * `friendshipId`: (`Guid`) The ID of the friend request to reject. - -**Responses**: - -* **Success (200 OK)**: Friend request rejected successfully. - - ```json - { - "status": 200, - "result": null, - "errorMessage": null - } - ``` -* **400 Bad Request**: If the operation is invalid (e.g., invalid friendship ID). - - ```json - { - "status": 400, - "result": null, - "errorMessage": "" - } - ``` -* **401 Unauthorized**: If the user is not authorized to reject the request. - - ```json - { - "status": 401, - "result": null, - "errorMessage": "" - } - ``` -* **500 Server Error**: Indicates an unexpected error. - - ```json - { - "status": 500, - "result": null, - "errorMessage": "Unexpected error! Please try later!" - } - ``` - -**Client-Side Events**: - -* **FriendRequestRejected**: Triggered on the user's client to confirm the friend request was rejected. - * Payload: `friendshipId` (`Guid`) - The ID of the rejected friend request. - -*** - -### Error Handling - -* **Invalid User ID**: If the user ID is `Guid.Empty` during connection, the connection is aborted with a logged warning. -* **Invalid Operations**: Operations like sending a request to oneself or accepting/rejecting an invalid request return a `BadRequest` result. -* **Unauthorized Access**: Unauthorized actions return an `Unauthorized` result with a logged warning. -* **Conflicts**: Attempting to send a duplicate friend request returns a `Conflict` result. -* **Unexpected Errors**: General exceptions are caught, logged, and returned as a `ServerError` result. - -*** - -### Logging - -* Logs connection and disconnection events with user ID and connection ID. -* Logs friend request operations (send, accept, reject) with success or failure details for monitoring and debugging. - -*** +Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs). diff --git a/docs/friendshub/friendshub-client-java.md b/docs/friendshub/friendshub-client-java.md index e9b616b..691a0c4 100644 --- a/docs/friendshub/friendshub-client-java.md +++ b/docs/friendshub/friendshub-client-java.md @@ -1,384 +1,58 @@ +# Клиент SignalR на C# для MAUI + +Эта страница заменяет устаревший Java-пример: он принимал FriendshipDto как String и не соответствовал серверу. Ниже минимальный пример подключения C#; это пример интеграции, а не проверенный end-to-end тест. + +Используйте Microsoft.AspNetCore.SignalR.Client и Govor.Contracts либо эквивалентные DTO с теми же полями. + +```csharp +using Govor.Contracts.DTOs; +using Govor.Contracts.Responses.SignalR; +using Microsoft.AspNetCore.SignalR.Client; + +var connection = new HubConnectionBuilder() + .WithUrl($"{baseUrl.TrimEnd('/')}/hubs/friends", options => + { + options.AccessTokenProvider = async () => + await jwtProvider.GetAccessTokenAsync(); + }) + .WithAutomaticReconnect() + .Build(); + +using var received = connection.On( + "FriendRequestReceived", dto => + { + MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto)); + }); + +using var accepted = connection.On( + "YourFriendRequestAccepted", dto => + { + MainThread.BeginInvokeOnMainThread(() => ApplyFriendship(dto)); + }); + +await connection.StartAsync(); + +var response = await connection.InvokeAsync>( + "SendRequest", targetUserId); + +if (response.Status != HubResultStatus.Created) + ShowError(response.ErrorMessage); +``` + +baseUrl, jwtProvider, ApplyFriendship, ShowError и targetUserId предоставляет приложение. Зарегистрируйте остальные четыре события аналогично с FriendshipDto. AcceptRequest/RejectRequest получают friendshipId. + +## Жизненный цикл MAUI + +1. Подпишитесь на события до подключения. +2. Первоначальный StartAsync требует собственной обработки повторов; automatic reconnect относится к потерянному соединению. +3. После Reconnected перечитайте HTTP-списки, чтобы восстановить пропущенные события. +4. Изменяйте ObservableCollection на MainThread. +5. Отменяйте повторные попытки при logout и DisposeAsync; не запускайте бесконечный StartAsync из Closed после намеренного StopAsync. +6. AccessTokenProvider должен получать актуальный access token; refresh должен быть сериализован. + +В текущем Govor.Mobile ChatHub фильтрует ReceiveMessage по непустому encryptedContent, поэтому сообщение только с вложением может игнорироваться. Closed пытается перезапуститься даже после намеренного DisconnectAsync. JwtProviderService очищает токены при любом неуспешном HTTP-refresh, включая временную ошибку сервера: это следует исправить отдельно. + --- -description: >- - Description: This sub-documentation provides example Java client code for - interacting with the FriendsHub SignalR hub using the microsoft/signalr - library. It covers connecting to the hub, handling con -icon: java ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. -# FriendsHub Client (Java) - -**Prerequisites**: - -* Include the SignalR Java client library in your project. For Gradle, add the following dependency: - - ```gradle - implementation("com.microsoft.signalr:signalr:9.0.7") - ``` -* Ensure the client has a valid authentication token (JWT) for connecting to the hub, as it requires authentication. - -**Hub Route**: `hubs/friends`\ -**Authorize**: Requires a valid JWT token with a `userId` claim. - -### Setup and Connection - -#### Connecting to the Hub - -This example demonstrates how to establish a connection to the `FriendsHub` with authentication and handle connection events. - -```java -import com.microsoft.signalr.HubConnection; -import com.microsoft.signalr.HubConnectionBuilder; -import io.reactivex.rxjava3.core.Completable; -import io.reactivex.rxjava3.core.Single; - -public class FriendsHubClient { - private final HubConnection hubConnection; - private final String accessToken; // JWT token with userId claim - - public FriendsHubClient(String hubUrl, String accessToken) { - this.accessToken = accessToken; - this.hubConnection = HubConnectionBuilder.create(hubUrl) - .withAccessTokenProvider(Single.just(accessToken)) - .build(); - - // Handle connection established - hubConnection.onConnected(() -> { - System.out.println("Connected to FriendsHub with connection ID: " + hubConnection.getConnectionId()); - }); - - // Handle connection closed - hubConnection.onClosed((exception) -> { - if (exception != null) { - System.err.println("Connection closed with error: " + exception.getMessage()); - } else { - System.out.println("Connection closed normally"); - } - }); - } - - public Completable startConnection() { - return hubConnection.start(); - } - - public Completable stopConnection() { - return hubConnection.stop(); - } -} -``` - -**Usage**: - -```java -String hubUrl = "https://your-api-url/hubs/friends"; -String jwtToken = "your-jwt-token-here"; -FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken); -client.startConnection() - .blockingAwait(); // Wait for connection to establish -``` - -**Notes**: - -* Replace `your-api-url` with the actual server URL. -* The `accessToken` must include a valid JWT with the `userId` claim to avoid connection abortion. -* Use `stopConnection()` to gracefully disconnect when done. - -### Subscribing to Hub Events - -The `FriendsHub` sends three client-side events: `FriendRequestReceived`, `FriendRequestAccepted`, and `FriendRequestRejected`. Below is an example of subscribing to these events. - -```java -public class FriendsHubClient { - // ... (constructor and connection methods as above) - - public void subscribeToEvents() { - // Handle FriendRequestReceived event - hubConnection.on("FriendRequestReceived", (userId) -> { - System.out.println("Received friend request from user ID: " + userId); - // Handle the friend request (e.g., update UI or notify user) - }, String.class); - - // Handle FriendRequestAccepted event - hubConnection.on("FriendRequestAccepted", (friendshipId) -> { - System.out.println("Friend request accepted, friendship ID: " + friendshipId); - // Update UI or local state to reflect new friendship - }, String.class); - - // Handle FriendRequestRejected event - hubConnection.on("FriendRequestRejected", (friendshipId) -> { - System.out.println("Friend request rejected, friendship ID: " + friendshipId); - // Update UI or notify user of rejection - }, String.class); - } -} -``` - -**Usage**: - -```java -FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken); -client.subscribeToEvents(); -client.startConnection().blockingAwait(); -``` - -**Notes**: - -* The `userId` and `friendshipId` parameters are received as strings (representing `Guid` values) due to JSON serialization. Parse them to `UUID` if needed: - - ```java - UUID uuid = UUID.fromString(userId); - ``` -* Call `subscribeToEvents()` before starting the connection to ensure event handlers are registered. - -### Invoking Hub Methods - -#### SendRequest - -Sends a friend request to another user. - -```java -public Completable sendFriendRequest(String targetUserId) { - return hubConnection.invoke(HubResult.class, "SendRequest", targetUserId) - .doOnSuccess(result -> { - switch (result.getStatus()) { - case 201: // Created - System.out.println("Friend request sent successfully"); - break; - case 400: // BadRequest - System.err.println("Bad request: " + result.getErrorMessage()); - break; - case 401: // Unauthorized - System.err.println("Unauthorized: " + result.getErrorMessage()); - break; - case 409: // Conflict - System.err.println("Conflict: " + result.getErrorMessage()); - break; - case 500: // ServerError - System.err.println("Server error: " + result.getErrorMessage()); - break; - default: - System.err.println("Unexpected status: " + result.getStatus()); - } - }) - .ignoreElement(); -} -``` - -**Usage**: - -```java -client.sendFriendRequest("target-user-guid-here") - .blockingAwait(); -``` - -**Notes**: - -* The `targetUserId` should be a valid `Guid` string (e.g., "550e8400-e29b-41d4-a716-446655440000"). -* The response is a `HubResult` with a status code and optional error message. - -#### AcceptRequest - -Accepts a friend request by its friendship ID. - -```java -public Completable acceptFriendRequest(String friendshipId) { - return hubConnection.invoke(HubResult.class, "AcceptRequest", friendshipId) - .doOnSuccess(result -> { - switch (result.getStatus()) { - case 200: // OK - System.out.println("Friend request accepted successfully"); - break; - case 400: // BadRequest - System.err.println("Bad request: " + result.getErrorMessage()); - break; - case 401: // Unauthorized - System.err.println("Unauthorized: " + result.getErrorMessage()); - break; - case 500: // ServerError - System.err.println("Server error: " + result.getErrorMessage()); - break; - default: - System.err.println("Unexpected status: " + result.getStatus()); - } - }) - .ignoreElement(); -} -``` - -**Usage**: - -```java -client.acceptFriendRequest("friendship-guid-here") - .blockingAwait(); -``` - -#### RejectRequest - -Rejects a friend request by its friendship ID. - -```java -public Completable rejectFriendRequest(String friendshipId) { - return hubConnection.invoke(HubResult.class, "RejectRequest", friendshipId) - .doOnSuccess(result -> { - switch (result.getStatus()) { - case 200: // OK - System.out.println("Friend request rejected successfully"); - break; - case 400: // BadRequest - System.err.println("Bad request: " + result.getErrorMessage()); - break; - case 401: // Unauthorized - System.err.println("Unauthorized: " + result.getErrorMessage()); - break; - case 500: // ServerError - System.err.println("Server error: " + result.getErrorMessage()); - break; - default: - System.err.println("Unexpected status: " + result.getStatus()); - } - }) - .ignoreElement(); -} -``` - -**Usage**: - -```java -client.rejectFriendRequest("friendship-guid-here") - .blockingAwait(); -``` - -### Data Model - -The client expects a `HubResult` response from hub methods, which is serialized as JSON: - -```json -{ - "status": "number", // Corresponds to HubResultStatus (e.g., 200, 400, 401, etc.) - "result": null, // Always null for FriendsHub methods - "errorMessage": "string" // Null for success, error message for failures -} -``` - -### Error Handling - -* **Connection Errors**: Handle connection failures in `onClosed` or by catching exceptions from `startConnection()`. -* **Invalid User ID**: If the JWT lacks a valid `userId` claim, the hub aborts the connection, and `onClosed` is triggered with an error. -* **Hub Method Errors**: Check the `status` and `errorMessage` fields in the `HubResult` response to handle specific errors (e.g., `BadRequest`, `Unauthorized`, `Conflict`). - -### Example Full Client - -Below is a complete example combining connection, event subscription, and method invocation. - -```java -import com.microsoft.signalr.HubConnection; -import com.microsoft.signalr.HubConnectionBuilder; -import io.reactivex.rxjava3.core.Completable; -import io.reactivex.rxjava3.core.Single; - -public class FriendsHubClient { - private final HubConnection hubConnection; - private final String accessToken; - - public FriendsHubClient(String hubUrl, String accessToken) { - this.accessToken = accessToken; - this.hubConnection = HubConnectionBuilder.create(hubUrl) - .withAccessTokenProvider(Single.just(accessToken)) - .build(); - - // Connection events - hubConnection.onConnected(() -> { - System.out.println("Connected to FriendsHub with connection ID: " + hubConnection.getConnectionId()); - }); - hubConnection.onClosed((exception) -> { - System.err.println(exception != null ? "Connection closed with error: " + exception.getMessage() : "Connection closed normally"); - }); - - // Subscribe to hub events - hubConnection.on("FriendRequestReceived", (userId) -> { - System.out.println("Received friend request from user ID: " + userId); - }, String.class); - hubConnection.on("FriendRequestAccepted", (friendshipId) -> { - System.out.println("Friend request accepted, friendship ID: " + friendshipId); - }, String.class); - hubConnection.on("FriendRequestRejected", (friendshipId) -> { - System.out.println("Friend request rejected, friendship ID: " + friendshipId); - }, String.class); - } - - public Completable startConnection() { - return hubConnection.start(); - } - - public Completable stopConnection() { - return hubConnection.stop(); - } - - public Completable sendFriendRequest(String targetUserId) { - return hubConnection.invoke(HubResult.class, "SendRequest", targetUserId) - .doOnSuccess(this::handleHubResult) - .ignoreElement(); - } - - public Completable acceptFriendRequest(String friendshipId) { - return hubConnection.invoke(HubResult.class, "AcceptRequest", friendshipId) - .doOnSuccess(this::handleHubResult) - .ignoreElement(); - } - - public Completable rejectFriendRequest(String friendshipId) { - return hubConnection.invoke(HubResult.class, "RejectRequest", friendshipId) - .doOnSuccess(this::handleHubResult) - .ignoreElement(); - } - - private void handleHubResult(HubResult result) { - switch (result.getStatus()) { - case 200: - System.out.println("Operation successful"); - break; - case 201: - System.out.println("Resource created successfully"); - break; - case 400: - System.err.println("Bad request: " + result.getErrorMessage()); - break; - case 401: - System.err.println("Unauthorized: " + result.getErrorMessage()); - break; - case 409: - System.err.println("Conflict: " + result.getErrorMessage()); - break; - case 500: - System.err.println("Server error: " + result.getErrorMessage()); - break; - default: - System.err.println("Unexpected status: " + result.getStatus()); - } - } - - public static void main(String[] args) { - String hubUrl = "https://your-api-url/hubs/friends"; - String jwtToken = "your-jwt-token-here"; - FriendsHubClient client = new FriendsHubClient(hubUrl, jwtToken); - - // Start connection and send a friend request - client.startConnection() - .andThen(client.sendFriendRequest("550e8400-e29b-41d4-a716-446655440000")) - .blockingAwait(); - - // Simulate accepting a friend request - client.acceptFriendRequest("friendship-guid-here") - .blockingAwait(); - - // Stop connection - client.stopConnection().blockingAwait(); - } -} -``` - -**Notes**: - -* Replace `your-api-url` and `your-jwt-token-here` with actual values. -* The `main` method demonstrates a complete workflow, but in a real application, you would integrate this with your UI or event loop. -* Use `UUID.fromString()` to convert string GUIDs to `UUID` objects if needed for internal logic. +Источник: [Govor.API/Hubs/FriendsHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/FriendsHub.cs). diff --git a/docs/getting-started.md b/docs/getting-started.md new file mode 100644 index 0000000..8123f6f --- /dev/null +++ b/docs/getting-started.md @@ -0,0 +1,56 @@ +# Запуск и конфигурация + +## Требования + +.NET SDK 10 с корректной feature band, PostgreSQL, доступ к NuGet, файл `libs/SmartRes.dll`, каталог `Govor.API/configs` и Firebase service account в `Govor.API/secrets/firebase-adminsdk.json`. + +В `global.json` записана некорректная версия SDK `10.0.0`; замените её в отдельном исправлении на установленную версию, например `10.0.400`. Во время диагностики SDK 10.0.400 всё же собрал отдельный проект API. + +## Команды из корня репозитория + +```powershell +dotnet restore Govor.API/Govor.API.csproj +dotnet build Govor.API/Govor.API.csproj --no-restore +dotnet ef database update --project Govor.Domain --startup-project Govor.API +dotnet run --project Govor.API/Govor.API.csproj +``` + +Команда миграции требует установленного инструмента dotnet-ef; она приведена как инструкция и не выполнялась на пользовательской БД. Перед обновлением существующей БД проверьте миграции и резервную копию. + +## Конфигурация + +| Ключ / ресурс | Назначение | +| --- | --- | +| ConnectionStrings:GovorDbContext | PostgreSQL connection string | +| JwtAccessOption:SecretKey | Ключ подписи JWT | +| JwtAccessOption:Minutes | Срок access token в минутах | +| JwtRefreshOption:RefreshTokenLifetimeDays | Срок refresh-сессии | +| MessageEditingOptions:Enabled | Применять ли срок редактирования | +| MessageEditingOptions:MaxEditTimeMinutes | Срок редактирования; значение класса по умолчанию 15 | +| configs/ban_usernames.json | UsernameModeration: BlockedExact, BlockedContains, Reserved | +| secrets/firebase-adminsdk.json | Обязательные учётные данные Firebase при старте | +| uploads/ | Файлы относительно ContentRootPath | + +Не переносите реальные ключи, пароли и service account в документацию или Git. Не рассчитывайте только на переменные окружения: Program.cs повторно добавляет appsettings.json после стандартных провайдеров, поэтому JSON может перекрыть их значения. Это нужно исправить. + +Firebase создаётся безусловно. Наличие NullPushProvider не даёт выключить Firebase конфигурацией в текущем DI. + +## Развёртывание и проверка + +Dockerfile устарел: использует .NET 8 и ссылается на удалённые Govor.Core/Govor.Data. Solution также ссылается на внешний проект SmartRes. До исправления используйте сборку конкретного API-проекта. + +HTTPS redirection отключён; TLS и forwarded headers требуют отдельной настройки. SessionKeysController содержит RequireHttps, поэтому HTTP для его методов не подходит. + +`GET /server/ping` — маршрут проверки доступности, но возвращает MVC OkResult из minimal API (предупреждение ASP0004); не считайте его полноценным health check БД и Firebase. + +Swagger включён во всех окружениях. UseSwagger обслуживает документ через middleware; поздний MapSwagger.RequireAuthorization не является надёжным подтверждением защиты всех Swagger-маршрутов. + +## Что проверено + +Restore API-зависимостей и сборка API завершились. Первая сборка: 90 предупреждений, 0 ошибок. Restore Govor.API.Tests завершился NU1201: net8.0 не может ссылаться на net10.0. Сервер с БД и Firebase не запускался; контейнер и миграции не проверялись. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера. + +Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs). + diff --git a/docs/server-fixes.md b/docs/server-fixes.md new file mode 100644 index 0000000..1899968 --- /dev/null +++ b/docs/server-fixes.md @@ -0,0 +1,54 @@ +# Исправления серверной части — 03.10.2026 + +Этот документ описывает изменения рабочей копии относительно диагностики commit `4603be9`. Криптографический протокол E2EE не добавлялся. Страницы, снабжённые ссылками на этот commit, сохраняют описание исходной версии; нижеприведённые изменения и новый контракт прочтения уточняют её поведение. + +## Доступ и сессии + +Чтение, история, отправка, редактирование, удаление и скачивание вложений проверяют участие в конкретном PrivateChat/ChatGroup. Забаненный участник группы доступа не получает. В канале отправлять могут только его администраторы. Связь replyTo ограничена тем же чатом; вложения отправителя должны принадлежать ему и иметь тип Message. Аватар нельзя назначить из чужого файла или приватного вложения. + +Глобальное удаление разрешено автору либо администратору группы с действующим участием. HideForMe возвращает 400: отдельного механизма скрытия ещё нет, и запрос больше не удаляет сообщение для всех. + +Административные пользователи и приглашения требуют Admin. Хеши паролей исключены из ответа. Изменение пароля: `POST /api/admin/Users/user/{id}/password`, JSON `{"password":""}`; прежний GET с паролем в URL удалён. Успех 204, неизвестный пользователь 404. Смена пароля отзывает сессии и отключает push-токены. + +JWT access проверяется по userId/sid: сессия должна принадлежать пользователю, быть неотозванной и неистёкшей. Refresh JWT не принимается как access. Каждый вход создаёт отдельную сессию; DeviceInfo служит подписью устройства. Refresh получает уникальный jti, а ротация хеша условно-атомарна. Повторно использованный refresh не перезаписывает результат другого запроса. Hub-фильтр перепроверяет сессию перед каждой командой и возвращает объект HubResult. Соединения закрываются при истечении access token. Чат-события адресуются группам активных сессий. + +Исправлены отсутствующие зависимости OnlinePingingController и SessionKeysController. Последний возвращает DTO публичных ключей вместо EF-графа с UserSession. Это исправление существующего экспериментального API, а не реализация E2EE. + +## Уведомления и прочтение + +ReceiveMessage, изменения и квитанции приходят обоим участникам личного чата либо действующим участникам группы. MessageSent синхронизирует исходящее сообщение на устройствах отправителя. Сбой SignalR не превращает сохранённое сообщение в неудачный Send. При восстановлении соединения клиент загружает историю; SignalR не является журналом событий. + +Сохранение сообщения и ChatPushNotification выполняется одним SaveChanges. ChatPushWorker опрашивает очередь каждые 2 секунды; ChatPushDispatcher получает условную двухминутную аренду, отправляет push, удаляет успешные задачи и повторяет ошибки с задержкой 2–300 секунд. После перезапуска задачи остаются в БД. Удаление сообщения каскадно удаляет задачу. При отправке заново проверяются получатели и прочтение; прочитавшим push не отправляется. + +Это доставка как минимум один раз до принятия push провайдером: после прерывания между ответом Firebase и удалением задачи push может повториться. Используйте messageId для дедупликации и tag чата. Принятие Firebase не подтверждает показ уведомления устройством. У сообщения пока нет клиентского ключа идемпотентности: повторять Send после потери ответа следует осторожно. + +FCM разбивается на пачки до 500. Временный отказ провайдера не удаляет все регистрации. Автоматически удаляются только токены Unregistered. Выборка учитывает активность и принадлежность сессии; обновление реактивирует токен, смена аккаунта переносит уникальную регистрацию устройства. + +[Контракт HTTP/SignalR и интеграция со скроллом](endpoints/message-read.md). История включает messageViews и reactions; порядок по времени и ID предотвращает пропуск сообщений с одинаковым временем. + +## Сборка и обновление + +Используйте .NET SDK 10 и `Govor.Server.slnx`: она включает актуальный сервер и Govor.Server.Tests, без удалённых проектов и внешнего исходного проекта SmartRes. Бинарный `libs/SmartRes.dll` используется по существующему правилу репозитория. Legacy-тесты net8 в старой solution не перенесены. + +```powershell +dotnet restore Govor.Server.slnx +dotnet build Govor.Server.slnx --no-restore -c Release +dotnet test Govor.Server.Tests/Govor.Server.Tests.csproj --no-build -c Release +dotnet ef database update --project Govor.Domain --startup-project Govor.API +``` + +Перед запуском новой версии примените миграцию `20261003070406_ReliableChatPush` к серверной PostgreSQL. Она добавляет очередь с FK и индексом; существующие сообщения/прочтения не изменяет. Пользовательская БД в ходе работы не обновлялась. SQL для миграции можно сформировать `dotnet ef migrations script --project Govor.Domain --startup-project Govor.API`. + +Dockerfile обновлён до .NET 10 и текущих проектов; секреты, uploads, bin/obj исключены из build context. Учётные данные Firebase передавайте в контейнер при запуске, например volume `/app/secrets/firebase-adminsdk.json`. Контейнер в данной среде не запускался: Docker daemon недоступен. + +`Firebase:Enabled=false` выключает Firebase и использует NullPushProvider для разработки; при этом реальная push-доставка отключена. Production требует Firebase service account. Переменные окружения имеют стандартный приоритет над appsettings.json. Для веб-клиента задайте `Cors:AllowedOrigins`; нативному MAUI CORS не требуется. Подробные ошибки БД включаются явно через Database:EnableDetailedErrors; значения SQL-параметров не логируются. Swagger UI доступен в Development; production-документ требует авторизации. + +## Проверка и ограничения + +Release-сборка Govor.Server.slnx завершилась без ошибок (88 предупреждений). Все 31 локальных серверных теста прошли; пропущенных тестов нет. EF не обнаружил расхождений модели с последней миграцией. + +Локальные тесты выполняют реальную SQL-запись в SQLite, тестируют HTTP pipeline с JWT и маршруты доставки с mock SignalR/Firebase. Покрыты чужие/забаненные участники, редактура/удаление, media/reply, три режима прочтения, повторения и конкурирующая запись/удаление, очередь/retry, перенос push-токена и отзыв access-сессии. Отдельно проверяется перевод границы в SQL Npgsql и соответствие модели миграции. + +CI запускает эту же серверную suite на SQLite и PostgreSQL 16. Для самостоятельного PostgreSQL запуска задайте TEST_POSTGRES_CONNECTION на отдельную БД с именем, заканчивающимся `_tests`; каждый тест применяет миграции в отдельной временной схеме. Локально PostgreSQL и реальная доставка Firebase/MAUI не запускались. + +Групповой InviteController/IGroupService остаются незавершёнными; это не реализация управления группами. PresenceStore остаётся локальным процессу; для нескольких экземпляров понадобится общая инфраструктура SignalR/presence. Старые журналы с чувствительными SQL-параметрами и уже выданные права нужно оценивать отдельно от этих изменений. diff --git a/docs/signalr/chathub.md b/docs/signalr/chathub.md index 368938f..7d7bd6d 100644 --- a/docs/signalr/chathub.md +++ b/docs/signalr/chathub.md @@ -1,162 +1,58 @@ ---- -icon: wifi ---- +# ChatsHub — сообщения -# ChatHub +Подключение: `/hubs/chats`, Bearer access token и активная сессия. Команды возвращают `HubResult` (status, result, errorMessage); события приходят независимо от ответа команды. Этот раздел описывает рабочую копию с исправлениями от 03.10.2026. -**Route**: `hubs/chats`\ -**Authorize**: Requires authentication (user must be logged in) +## Команды -*** - -### Hub Methods - -#### OnConnectedAsync - -**Description**: Automatically invoked when a client establishes a connection to the hub. Adds the user to their personal group for private messages and notifications. - -**Behavior**: - -* Retrieves the user's ID from the connection context. -* If the user ID is invalid (`Guid.Empty`), logs a warning and aborts the connection. -* Adds the user to a group named after their user ID (e.g., `userId.ToString()`). -* Logs the connection event with the user ID and connection ID. - -**Notes**: - -* Future enhancements may include adding the user to their chat groups (currently a TODO in the code). - -*** - -#### OnDisconnectedAsync - -**Description**: Automatically invoked when a client disconnects from the hub. Removes the user from their personal group. - -**Behavior**: - -* Retrieves the user's ID from the connection context, suppressing exceptions if the ID is unavailable (e.g., due to an early abort). -* If the user ID is valid, removes the user from their personal group. -* Logs the disconnection event with the user ID and connection ID. -* If an exception occurs, logs it as a warning along with the connection ID. -* If no exception occurs but the user ID is invalid, logs the disconnection with the connection ID. - -**Notes**: - -* Future enhancements may include removing the user from their chat groups (currently a TODO in the code). - -*** - -#### Send - -**Description**: Allows a client to send a message to a recipient, which can be either a user or a group. - -**Request**: - -* **Method Name**: `Send` -* **Parameters**: - * `request`: An object of type `MessageRequest` with the following structure: - - ```json - { - "encryptedContent": "string", - "replyToMessageId": "Guid", - "recipientId": "Guid", - "recipientType": "string", // "User" or "Group" - "mediaAttachments": [ - { - "mediaId": "Guid", - "encryptedKey": "string", - "type": "string", - "mimeType": "string" - } - ] - } - ``` - -**Responses**: - -* **Success**: - * Sends the message to the recipient (user or group) via the `ReceiveMessage` event. - * Notifies the sender with a confirmation via the `MessageSent` event. - * Logs the successful message send with the message ID, sender ID, recipient ID, and recipient type. -* **Error**: - * If the message is empty (no `encryptedContent` and no `mediaAttachments`), logs a warning and throws an `ArgumentException`. - * If the message fails to send (e.g., due to an internal error), logs the error and throws a `HubException`. - -**Client-Side Events**: - -* **ReceiveMessage**: Triggered on the recipient's client(s) to deliver the message. - * Payload: `UserMessageResponse` object. -* **MessageSent**: Triggered on the sender's client to confirm the message was sent. - * Payload: `UserMessageResponse` object. - -**Notes**: - -* The message must contain either `encryptedContent` or `mediaAttachments`; otherwise, it is invalid. -* The recipient is determined by `recipientType`: - * `"User"`: Sends to the recipient’s personal group (e.g., `recipientId.ToString()`). - * `"Group"`: Sends to all members of the group (e.g., `group_{recipientId}`). - -*** - -### Data Models - -#### MessageRequest +| Имя | Аргументы | Успешный result | +| --- | --- | --- | +| Send | MessageRequest | UserMessageResponse | +| Read | `{ messageId }` | MessageReadResponse | +| ReadChat | chatId, ReadChatRequest | ChatReadResponse | +| Edit | `{ messageId, newEncryptedContent }` | MessageEditResponse | +| Remove | `{ messageId, requestType }` | MessageRemovedResponse | +| React | messageId, `{ reactionId }` | MessageReactionsChangedResponse | +| RemoveReaction | messageId | MessageReactionsChangedResponse | ```json { - "encryptedContent": "string", - "replyToMessageId": "Guid", - "recipientId": "Guid", - "recipientType": "string", // "User" or "Group" - "mediaAttachments": [ - { - "mediaId": "Guid", - "encryptedKey": "string", - "type": "string", - "mimeType": "string" - } - ] + "recipientId": "11111111-1111-1111-1111-111111111111", + "recipientType": 0, + "encryptedContent": "<содержимое>", + "replyToMessageId": null, + "mediaAttachments": [] } ``` -#### UserMessageResponse +RecipientType.User=0 означает личный чат: recipientId — PrivateChat.Id. Group=1 означает ChatGroup.Id. Вложение: `{ mediaId, encryptedKey }`. Содержимое или вложение обязательно; Send ограничивает текст 50 000 символами. SignalR не выполняет MVC DataAnnotations автоматически. DTO проверки дополняются сервисами доступа. -```json -{ - "messageId": "Guid", - "senderId": "Guid", - "recipientId": "Guid", - "recipientType": "string", - "encryptedContent": "string", - "sentAt": "DateTime", - "isEdited": "bool", - "mediaAttachments": [ - { - "mediaId": "Guid", - "encryptedKey": "string", - "type": "string", - "mimeType": "string" - } - ], - "replyToMessageId": "Guid" -} -``` +Send/Read/React и чтение истории проверяют участие в конкретном чате. В группах заблокированный участник не имеет доступа. Reply и вложения не позволяют ссылаться на чужие закрытые чаты. Edit проверяет автора, доступ и временной лимит редактирования. Remove проверяет автора/права администратора группы; HideForMe пока не реализован и возвращает ошибку, ForceRemove удаляет сообщение. -*** +[ReadChat и три сценария прочтения](../endpoints/message-read.md): видимые messageIds, граница upToMessageId либо весь чат. [React/RemoveReaction, паки и настройки канала](../endpoints/reactions.md) используют тот же сервис, что HTTP API. -### Error Handling +## События -* **Invalid User ID**: If the user ID is `Guid.Empty` during connection, the connection is aborted with a logged warning. -* **Empty Message**: If a message lacks both content and attachments, an `ArgumentException` is thrown with a logged warning. -* **Message Send Failure**: If sending fails (e.g., due to a service error), a `HubException` is thrown with the error logged. +| Имя события (точно) | Payload | +| --- | --- | +| ReceiveMessage | UserMessageResponse | +| MessageSent | UserMessageResponse, подтверждение устройствам отправителя | +| MessageEdited | MessageEditResponse | +| MessageRemoved | MessageRemovedResponse | +| MessageReaded | MessageReadResponse | +| ChatRead | ChatReadResponse | +| MessageReactionsChanged | MessageReactionsChangedResponse | +| ChannelReactionPolicyChanged | ChannelReactionPolicyResponse | -*** +Опечатка MessageReaded сохранена для совместимости. При подключении сервер автоматически добавляет соединение в группу его сессии. События чата направляются активным сессиям участников; заблокированные участники групп исключаются. Не требуется вручную подписываться на SignalR-группу чата. Отзыв сессии прекращает её участие в маршрутизации и проверяется для команд; истечение токена закрывает соединение. -### Logging +UserMessageResponse: messageId, senderId, recipientId, recipientType, encryptedContent, replyToMessageId, sentAt, isEdited, mediaAttachments. История через HTTP также содержит реакции и reactionsVersion. После получения сообщения загрузите снимок реакций при необходимости. -* Logs connection events with user ID and connection ID. -* Logs disconnection events, including exceptions if present. -* Logs message send attempts, successes, and failures for monitoring and debugging. +MessageEditResponse: messageId, editorId, recipientId, recipientType, newEncryptedContent, editedAt. +MessageReadResponse: viewId, messageId, readerId, recipientId, whenWas, recipientType. +MessageRemovedResponse: messageId, senderId, recipientId, requestType, recipientType. -*** +## Доставка и восстановление + +Сохранение в БД и доставка события — разные этапы. После reconnect загрузите историю через HTTP; объединяйте ответ Send и ReceiveMessage по messageId. Для реакций принимайте более новую version и заменяйте counts целиком, затем восстанавливайте состояние видимых сообщений через GET. + +SignalR-события не имеют долговременной очереди. Push сообщений использует серверную очередь и повторные попытки; для реакций и политик каналов push не отправляется. Реальный push требует корректной конфигурации Firebase и зарегистрированного FCM-токена активной сессии. Повтор Send после неоднозначного сетевого сбоя всё ещё может создать дубликат: clientMessageId/idempotency-key для сообщений не реализован. diff --git a/docs/signalr/presencehub.md b/docs/signalr/presencehub.md index eb29710..23d41c7 100644 --- a/docs/signalr/presencehub.md +++ b/docs/signalr/presencehub.md @@ -1,53 +1,27 @@ +# PresenceHub — online и offline + +Подключение: /hubs/presence. Требуется роль User/Admin. + +Публичных команд у хаба нет. На подключении сервер добавляет connectionId в OnlineUserStore и группу userId. Первая связь пользователя вызывает событие UserOnline; отключение последней — UserOffline. + +| Событие | Payload | +| --- | --- | +| UserOnline | Guid пользователя | +| UserOffline | Guid пользователя | + +Получатели определяются IUserNotificationScopeService. Несколько соединений одного пользователя учитываются отдельно. + +## Ограничения + +OnlineUserStore хранится в памяти одного процесса. Перезапуск теряет состояние; несколько серверов не согласованы. Online означает наличие соединения этого хаба, не доступность устройства для push. + +PresenceHub не сохраняет lastSeen в БД при отключении. Для него есть отдельный HTTP ping; нужна единая политика обновления lastSeen. + +Для первоначального экрана получайте доступные данные профиля/друзей; события только изменяют локальный cache. После reconnect перечитайте состояние. HTTP /api/online/status сейчас сломан из-за отсутствующих зависимостей. + +Обработчики должны быть зарегистрированы до StartAsync. Не используйте события присутствия как гарантированный журнал активности. + --- -description: SignalR hub for managing user online presence and notifications. -icon: wifi ---- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. -# PresenceHub - -### Controller Description - -* **Route**: `hubs/presence` -* **Authorize**: Requires authenticated user with roles "Admin" or "User" (`[Authorize(Roles = "Admin, User")]`). - -### Hub Methods - -#### OnConnectedAsync - -* **Description**: Invoked when a client connects, updates online status and notifies friends. -* **Behavior**: - * Retrieves user ID from context. - * Aborts connection if user ID is `Guid.Empty` or user does not exist. - * Adds user to online store and their personal group. - * Notifies friends of user going online via `UserOnline` event. -* **Client-Side Events**: - * **UserOnline**: Triggered for friends with payload `userId` (Guid). -* **Responses**: None (connection aborted on invalid user ID). - -#### OnDisconnectedAsync - -* **Description**: Invoked when a client disconnects, updates offline status and notifies friends. -* **Behavior**: - * Retrieves user ID from context, suppressing exceptions. - * Removes user from personal group if ID is valid. - * Updates user's `WasOnline` timestamp. - * Sets user as offline in store. - * Notifies friends of user going offline via `UserOffline` event. -* **Client-Side Events**: - * **UserOffline**: Triggered for friends with payload `userId` (Guid). -* **Responses**: None. - -### Data Models - -* **N/A**: No specific data models defined for hub methods. - -### Error Handling - -* **Invalid User ID**: Aborts connection with logged warning if `Guid.Empty` or user not found. -* **Unexpected Errors**: Logged, but no specific response (handled by base method). - -### Logging - -* Logs warnings for invalid user ID on connection. -* Logs information for disconnections with user ID and connection ID. -* Logs errors for unexpected exceptions during disconnection. +Источник: [Govor.API/Hubs/PresenceHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/PresenceHub.cs). diff --git a/docs/signalr/profilehub.md b/docs/signalr/profilehub.md new file mode 100644 index 0000000..17b0045 --- /dev/null +++ b/docs/signalr/profilehub.md @@ -0,0 +1,29 @@ +# ProfileHub — изменения профиля + +Подключение: /hubs/profiles; требуется Authorize. + +| Метод | Аргумент | Успех | +| --- | --- | --- | +| SetDescription | string description | HubResult, status=200, result=true | +| SetAvatar | Guid iconId | HubResult, status=200, result=true | + +Описание не может быть null, переносы строк нормализуются, длина после нормализации ≤500; пустая строка допустима для очистки. Avatar требует непустой Guid и существующую запись медиа. + +| Событие | Payload | +| --- | --- | +| DescriptionUpdated | { userId, description } | +| AvatarUpdated | { userId, iconId } | + +Получатели: пользователь, друзья и потенциальные друзья согласно IFriendshipService. Группы имеют префикс user:. + +## Ограничения + +Result от записи профиля не проверяется хабом, поэтому true не всегда подтверждает запись. Ошибка рассылки логируется, но не меняет успешный ответ. + +SetAvatar не проверяет владельца файла. REST UploadAvatar не отправляет AvatarUpdated. Политика приватности не применяется к этой рассылке. После reconnect перечитайте профиль; события не гарантированно сохраняются. + +--- +Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; сервер с БД и Firebase в рамках диагностики не запускался. + +Источник: [Govor.API/Hubs/ProfileHub.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Hubs/ProfileHub.cs). + diff --git a/global.json b/global.json index a11f48e..82dabbb 100644 --- a/global.json +++ b/global.json @@ -1,7 +1,7 @@ { "sdk": { - "version": "10.0.0", - "rollForward": "latestMajor", + "version": "10.0.100", + "rollForward": "latestFeature", "allowPrerelease": true } -} \ No newline at end of file +}