Add reactions, reliable push & session checks

Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
Artemy
2026-10-03 17:42:24 +07:00
parent 4603be9f71
commit 29cc51ee0c
127 changed files with 7290 additions and 2488 deletions
+10
View File
@@ -0,0 +1,10 @@
.git
.codex
.agents
**/bin
**/obj
**/logs
**/uploads
**/secrets
**/appsettings.Development.json
artifacts
+23 -4
View File
@@ -12,6 +12,25 @@ on:
jobs: jobs:
build-and-test: build-and-test:
runs-on: ubuntu-latest 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: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
@@ -19,15 +38,15 @@ jobs:
- name: Setup .NET SDK - name: Setup .NET SDK
uses: actions/setup-dotnet@v4 uses: actions/setup-dotnet@v4
with: with:
dotnet-version: '8.0.x' dotnet-version: '10.0.x'
- name: Restore dependencies - name: Restore dependencies
run: dotnet restore run: dotnet restore Govor.Server.slnx
- name: Build - name: Build
run: dotnet build --no-restore --configuration Release run: dotnet build Govor.Server.slnx --no-restore --configuration Release
- name: Run tests - 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
+8 -16
View File
@@ -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 WORKDIR /src
COPY global.json ./
# Êîïèðóåì òîëüêî .sln è .csproj
COPY *.sln ./
COPY Govor.API/*.csproj ./Govor.API/ COPY Govor.API/*.csproj ./Govor.API/
COPY Govor.Application/*.csproj ./Govor.Application/ COPY Govor.Application/*.csproj ./Govor.Application/
COPY Govor.Core/*.csproj ./Govor.Core/ COPY Govor.Domain/*.csproj ./Govor.Domain/
COPY Govor.Data/*.csproj ./Govor.Data/
COPY Govor.Contracts/*.csproj ./Govor.Contracts/ COPY Govor.Contracts/*.csproj ./Govor.Contracts/
COPY libs/ ./libs/
RUN dotnet restore Govor.API/Govor.API.csproj RUN dotnet restore Govor.API/Govor.API.csproj
# Êîïèðóåì âåñü êîä
COPY . . COPY . .
WORKDIR /src/Govor.API RUN dotnet publish Govor.API/Govor.API.csproj -c Release --no-restore -o /app/publish
RUN dotnet publish -c Release -o /app/publish
# Runtime image FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS final
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app WORKDIR /app
COPY --from=build /app/publish . COPY --from=build /app/publish .
ENV ASPNETCORE_HTTP_PORTS=8080
EXPOSE 8080 EXPOSE 8080
ENTRYPOINT ["dotnet", "Govor.API.dll"]
ENTRYPOINT ["dotnet", "Govor.API.dll"]
@@ -11,6 +11,7 @@ using Govor.Application.Infrastructure.Extensions;
using Govor.Application.Infrastructure.Validators; using Govor.Application.Infrastructure.Validators;
using Govor.Application.Medias; using Govor.Application.Medias;
using Govor.Application.Messages; using Govor.Application.Messages;
using Govor.Application.Reactions;
using Govor.Application.PingHandler; using Govor.Application.PingHandler;
using Govor.Application.PrivateUserChats; using Govor.Application.PrivateUserChats;
using Govor.Application.Profiles; using Govor.Application.Profiles;
@@ -68,6 +69,9 @@ public static class ConfigurationProgramExtensions
//services.AddScoped<IMessageCommandService, MessageCommandService>(); //services.AddScoped<IMessageCommandService, MessageCommandService>();
services.AddScoped<IMessageSendingService, MessageSendingService>(); services.AddScoped<IMessageSendingService, MessageSendingService>();
services.AddScoped<IMessageReadingService, MessageReadingService>(); services.AddScoped<IMessageReadingService, MessageReadingService>();
services.AddScoped<IMessageReactionService, MessageReactionService>();
services.AddScoped<IReactionPackService, ReactionPackService>();
services.AddSingleton<IReactionMediaProcessor, ReactionMediaProcessor>();
services.AddScoped<IMessageEditingService, MessageEditingService>(); services.AddScoped<IMessageEditingService, MessageEditingService>();
services.AddScoped<IMessageRemovingService, MessageRemovingService>(); services.AddScoped<IMessageRemovingService, MessageRemovingService>();
services.AddScoped<IVerifyFriendship, VerifyFriendship>(); services.AddScoped<IVerifyFriendship, VerifyFriendship>();
@@ -91,6 +95,8 @@ public static class ConfigurationProgramExtensions
// Hubs Infrastructure // Hubs Infrastructure
services.AddScoped<IPrivateChatGroupManager, PrivateChatGroupManager>(); services.AddScoped<IPrivateChatGroupManager, PrivateChatGroupManager>();
services.AddScoped<IChatNotificationService, ChatNotificationService>(); services.AddScoped<IChatNotificationService, ChatNotificationService>();
services.AddScoped<ChatPushDispatcher>();
services.AddHostedService<ChatPushWorker>();
services.AddScoped<IConnectionManager, ConnectionManager>(); services.AddScoped<IConnectionManager, ConnectionManager>();
services.AddSingleton<IConnectionStore, ConnectionStore>(); services.AddSingleton<IConnectionStore, ConnectionStore>();
@@ -98,7 +104,10 @@ public static class ConfigurationProgramExtensions
// Pushs // Pushs
services.AddScoped<IPushTokenService, PushTokenService>(); services.AddScoped<IPushTokenService, PushTokenService>();
services.AddScoped<IPushNotificationService, PushNotificationService>(); services.AddScoped<IPushNotificationService, PushNotificationService>();
services.AddSingleton<IPushNotificationProvider, FirebasePushProvider>(); services.AddSingleton<IPushNotificationProvider>(sp =>
sp.GetRequiredService<IConfiguration>().GetValue("Firebase:Enabled", true)
? ActivatorUtilities.CreateInstance<FirebasePushProvider>(sp)
: new NullPushProvider());
// Auto Mapper // Auto Mapper
@@ -133,8 +142,8 @@ public static class ConfigurationProgramExtensions
//options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); //options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
options.EnableSensitiveDataLogging(); if (configuration.GetValue<bool>("Database:EnableDetailedErrors"))
options.EnableDetailedErrors(); options.EnableDetailedErrors();
}); });
} }
} }
@@ -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<T> ToHubResult<T>(this Error error) => error.Type switch
{
ErrorType.NotFound => HubResult<T>.NotFound(error.Message),
ErrorType.Forbidden => HubResult<T>.Forbidden(error.Message),
ErrorType.Unauthorized => HubResult<T>.Unauthorized(error.Message),
ErrorType.Conflict => HubResult<T>.Conflict(error.Message),
ErrorType.ServerError => HubResult<T>.Error("Internal server error."),
_ => HubResult<T>.BadRequest(error.Message)
};
}
@@ -28,6 +28,7 @@ public static class ResultExtensions
ErrorType.Conflict => StatusCodes.Status409Conflict, ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.Unauthorized => StatusCodes.Status401Unauthorized, ErrorType.Unauthorized => StatusCodes.Status401Unauthorized,
ErrorType.Forbidden => StatusCodes.Status403Forbidden, ErrorType.Forbidden => StatusCodes.Status403Forbidden,
ErrorType.ServerError => StatusCodes.Status500InternalServerError,
_ => StatusCodes.Status400BadRequest _ => StatusCodes.Status400BadRequest
}; };
@@ -55,6 +56,7 @@ public static class ResultExtensions
ErrorType.Conflict => "Conflict", ErrorType.Conflict => "Conflict",
ErrorType.Unauthorized => "Unauthorized", ErrorType.Unauthorized => "Unauthorized",
ErrorType.Forbidden => "Forbidden", ErrorType.Forbidden => "Forbidden",
ErrorType.ServerError => "Internal Server Error",
_ => "Bad Request" _ => "Bad Request"
}; };
} }
@@ -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<bool> 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);
}
}
+11 -2
View File
@@ -5,6 +5,10 @@ using Govor.Contracts.Responses;
using Govor.Domain.Models; using Govor.Domain.Models;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users; 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; namespace Govor.API.Common.Mapping;
@@ -12,6 +16,12 @@ public class MappingProfile : Profile
{ {
public MappingProfile() public MappingProfile()
{ {
CreateMap<ChatReadResult, ChatReadResponse>();
CreateMap<ReactionPack, ReactionPackResponse>();
CreateMap<ReactionItem, ReactionItemResponse>();
CreateMap<ReactionCount, ReactionCountResponse>();
CreateMap<MessageReactionState, MessageReactionsChangedResponse>();
CreateMap<ChannelReactionPolicy, ChannelReactionPolicyResponse>();
CreateMap<Message, MessageResponse>(); CreateMap<Message, MessageResponse>();
CreateMap<MediaAttachments, MediaAttachmentResponse>(); CreateMap<MediaAttachments, MediaAttachmentResponse>();
CreateMap<MessageReaction, MessageReactionResponse>(); CreateMap<MessageReaction, MessageReactionResponse>();
@@ -27,6 +37,5 @@ public class MappingProfile : Profile
CreateMap<UserSession, SessionDto>(); CreateMap<UserSession, SessionDto>();
CreateMap<UserProfile, UserProfileDto>();
} }
} }
@@ -2,12 +2,13 @@ using Govor.Application.Infrastructure.AdminsStuff;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
using Govor.Contracts.Requests; using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
namespace Govor.API.Controllers.AdminStuff; namespace Govor.API.Controllers.AdminStuff;
[Route("api/admin/[controller]")] [Route("api/admin/[controller]")]
[ApiController] [ApiController]
//[Authorize(Roles = "Admin")] [Authorize(Roles = "Admin")]
public class InviteUserController : Controller public class InviteUserController : Controller
{ {
private readonly IInvitationGetter _invitationGetter; private readonly IInvitationGetter _invitationGetter;
@@ -144,4 +145,4 @@ public class InviteUserController : Controller
return BadRequest($"An error occured: {e.Message}"); return BadRequest($"An error occured: {e.Message}");
} }
} }
} }
@@ -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<IActionResult> List([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), includeDisabled: true, skip: skip, take: take)));
[HttpGet("{packId:guid}")]
public async Task<IActionResult> Get(Guid packId) => (await packs.GetAsync(packId, includeDisabled: true))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpPost]
public async Task<IActionResult> Create([FromBody] CreateReactionPackRequest request) =>
(await packs.CreateAsync(currentUser.GetCurrentUserId(), request.Name, request.Description))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpPut("{packId:guid}")]
public async Task<IActionResult> Update(Guid packId, [FromBody] UpdateReactionPackRequest request) =>
(await packs.UpdateAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Description, request.IsEnabled))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpDelete("{packId:guid}")]
public async Task<IActionResult> Disable(Guid packId) => (await packs.DisableAsync(currentUser.GetCurrentUserId(), packId)).ToActionResult();
[HttpPost("{packId:guid}/reactions/emoji")]
public async Task<IActionResult> Emoji(Guid packId, [FromBody] CreateEmojiReactionRequest request) =>
(await packs.AddEmojiAsync(currentUser.GetCurrentUserId(), packId, request.Name, request.Emoji))
.Map(r => mapper.Map<ReactionItemResponse>(r)).ToActionResult();
[HttpPost("{packId:guid}/reactions/media")]
[RequestSizeLimit(2_200_000)]
public async Task<IActionResult> 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<ReactionItemResponse>(r)).ToActionResult();
}
[HttpDelete("{packId:guid}/reactions/{reactionId:guid}")]
public async Task<IActionResult> 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; }
}
@@ -3,13 +3,14 @@ using Govor.Contracts.Responses.Admins;
using Govor.Domain.Models.Users; using Govor.Domain.Models.Users;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Govor.Contracts.Requests;
namespace Govor.API.Controllers.AdminStuff; namespace Govor.API.Controllers.AdminStuff;
[ApiController] [ApiController]
[Route("api/admin/[controller]")] [Route("api/admin/[controller]")]
[Authorize]//(Roles = "Admin") [Authorize(Roles = "Admin")]
public class UsersController : Controller public class UsersController : Controller
{ {
private readonly ILogger<UsersController> _logger; private readonly ILogger<UsersController> _logger;
@@ -48,6 +49,8 @@ public class UsersController : Controller
{ {
_logger.LogInformation($"Getting user {id} by administrator"); _logger.LogInformation($"Getting user {id} by administrator");
var read = await _users.GetUserById(id); var read = await _users.GetUserById(id);
if (read is null)
return NotFound();
return Ok(BuildUserDtos([read]).First()); return Ok(BuildUserDtos([read]).First());
} }
catch (Exception e) catch (Exception e)
@@ -57,13 +60,15 @@ public class UsersController : Controller
} }
} }
[HttpGet("user/{id:guid}/setpassword/{password}")] [HttpPost("user/{id:guid}/password")]
public async Task<IActionResult> SetNewPassword(Guid id, string password) public async Task<IActionResult> SetNewPassword(Guid id, [FromBody] SetPasswordRequest request)
{ {
try try
{ {
await _users.SetPasswordAsync(id, password); if (await _users.GetUserById(id) is null)
return Ok(); return NotFound();
await _users.SetPasswordAsync(id, request.Password);
return NoContent();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -78,10 +83,9 @@ public class UsersController : Controller
Description = user.Description, Description = user.Description,
WasOnline = user.WasOnline, WasOnline = user.WasOnline,
IconId = user.IconId, IconId = user.IconId,
PasswordHash = user.PasswordHash,
InviteId = user.InviteId, InviteId = user.InviteId,
CreatedOn = user.CreatedOn, CreatedOn = user.CreatedOn,
IsAdmin = user.Invite?.IsAdmin ?? false, IsAdmin = user.Invite?.IsAdmin ?? false,
}).ToList(); }).ToList();
} }
@@ -4,6 +4,7 @@ using Govor.Application.Users.UserSessions.Crypto;
using Govor.Contracts.Requests; using Govor.Contracts.Requests;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Govor.Contracts.DTOs;
namespace Govor.API.Controllers.Authentication; namespace Govor.API.Controllers.Authentication;
@@ -27,7 +28,8 @@ public class SessionKeysController : Controller
ICurrentUserSessionService currentSession, ICurrentUserSessionService currentSession,
ISessionKeyAttacher sessionKeyAttacher, ISessionKeyAttacher sessionKeyAttacher,
ISessionKeysReader sessionKeysReader, ISessionKeysReader sessionKeysReader,
ICurrentUserService currentUser) ICurrentUserService currentUser,
IOneTimePreKeysRotator oneTimePreKeysRotator)
{ {
_logger = logger; _logger = logger;
_friendshipService = friendshipService; _friendshipService = friendshipService;
@@ -35,6 +37,7 @@ public class SessionKeysController : Controller
_sessionKeyAttacher = sessionKeyAttacher; _sessionKeyAttacher = sessionKeyAttacher;
_sessionKeysReader = sessionKeysReader; _sessionKeysReader = sessionKeysReader;
_currentUser = currentUser; _currentUser = currentUser;
_oneTimePreKeysRotator = oneTimePreKeysRotator;
} }
[HttpPost("keys")] [HttpPost("keys")]
@@ -63,11 +66,24 @@ public class SessionKeysController : Controller
var requesterId = _currentUser.GetCurrentUserId(); var requesterId = _currentUser.GetCurrentUserId();
if (!(await _friendshipService.GetFriendsAsync(userId)).Select(u => u.Id).Contains(requesterId)) 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); 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")] [HttpPost("keys/rotate")]
@@ -106,4 +122,4 @@ public class SessionKeysController : Controller
return Ok("Marked as used."); return Ok("Marked as used.");
} }
} }
@@ -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<IActionResult> Get(Guid groupId) => (await reactions.GetPolicyAsync(currentUser.GetCurrentUserId(), groupId))
.Map(p => mapper.Map<ChannelReactionPolicyResponse>(p)).ToActionResult();
[HttpPut]
public async Task<IActionResult> 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<ChannelReactionPolicyResponse>(result.Value);
await notifier.NotifyChannelReactionPolicyChangedAsync(response);
return Ok(response);
}
}
+3 -3
View File
@@ -41,7 +41,7 @@ public class ChatLoadController : Controller
{ {
try 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."); return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = (await _messagesLoader.LoadMessagesInChatGroup( var result = (await _messagesLoader.LoadMessagesInChatGroup(
@@ -67,7 +67,7 @@ public class ChatLoadController : Controller
{ {
try 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."); return BadRequest("Values must be non-negative and total must not exceed 100.");
var result = (await _messagesLoader.LoadMessagesInUserChat( var result = (await _messagesLoader.LoadMessagesInUserChat(
@@ -86,4 +86,4 @@ public class ChatLoadController : Controller
return StatusCode(500, "Unexpected Error! Please try again later."); return StatusCode(500, "Unexpected Error! Please try again later.");
} }
} }
} }
+4 -1
View File
@@ -37,6 +37,9 @@ public class MediaController : Controller
if (!ModelState.IsValid) if (!ModelState.IsValid)
return BadRequest(ModelState); 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) if (request?.FromFile is null || request.FromFile.Length == 0)
return BadRequest("No file uploaded"); return BadRequest("No file uploaded");
@@ -85,7 +88,7 @@ public class MediaController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -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<IActionResult> Get(Guid messageId) => (await reactions.GetAsync(currentUser.GetCurrentUserId(), messageId))
.Map(s => mapper.Map<MessageReactionsChangedResponse>(s)).ToActionResult();
[HttpPut("me")]
public Task<IActionResult> Set(Guid messageId, [FromBody] SetReactionRequest request) => ChangeAsync(messageId, request.ReactionId);
[HttpDelete("me")]
public Task<IActionResult> Remove(Guid messageId) => ChangeAsync(messageId, null);
private async Task<IActionResult> ChangeAsync(Guid messageId, Guid? reactionId)
{
var result = await reactions.SetAsync(currentUser.GetCurrentUserId(), messageId, reactionId);
if (result.IsFailure) return result.ToActionResult();
var response = mapper.Map<MessageReactionsChangedResponse>(result.Value);
if (result.Value.Changed) await notifier.NotifyMessageReactionsChangedAsync(response);
return Ok(response);
}
}
@@ -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<IActionResult> 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<ChatReadResponse>(result.Value);
await _notifier.NotifyChatReadAsync(response);
return Ok(response);
}
[HttpGet("unread-count")]
public async Task<IActionResult> 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 });
}
}
@@ -19,11 +19,15 @@ public class OnlinePingingController : Controller
public OnlinePingingController(ILogger<OnlinePingingController> logger, public OnlinePingingController(ILogger<OnlinePingingController> logger,
IPingHandlerService ping, IPingHandlerService ping,
ICurrentUserService currentUserService) ICurrentUserService currentUserService,
IUserPresenceReader presenceReader,
IOnlineUserStore userOnlineStore)
{ {
_logger = logger; _logger = logger;
_ping = ping; _ping = ping;
_currentUserService = currentUserService; _currentUserService = currentUserService;
_presenceReader = presenceReader;
_userOnlineStore = userOnlineStore;
} }
@@ -66,4 +70,4 @@ public class OnlinePingingController : Controller
return StatusCode(500, "Internal server error."); return StatusCode(500, "Internal server error.");
} }
} }
} }
@@ -49,7 +49,7 @@ public class PrivateChatController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex.Message); _logger.LogWarning(ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (ArgumentException ex) catch (ArgumentException ex)
{ {
@@ -59,7 +59,7 @@ public class PrivateChatController : Controller
catch (FriendshipException ex) catch (FriendshipException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -87,7 +87,7 @@ public class PrivateChatController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex.Message); _logger.LogWarning(ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -95,4 +95,4 @@ public class PrivateChatController : Controller
return StatusCode(500, "Unexpected Error! Please try again later."); return StatusCode(500, "Unexpected Error! Please try again later.");
} }
} }
} }
+3 -3
View File
@@ -1,4 +1,4 @@
using AutoMapper; using AutoMapper;
using Govor.API.Common.Extensions; using Govor.API.Common.Extensions;
using Govor.API.Hubs; using Govor.API.Hubs;
using Govor.Application.Infrastructure.Extensions; using Govor.Application.Infrastructure.Extensions;
@@ -102,7 +102,7 @@ public class ProfileController : ControllerBase
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex.Message); _logger.LogWarning(ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -124,7 +124,7 @@ public class ProfileController : ControllerBase
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex.Message); _logger.LogWarning(ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -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<IActionResult> List([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), skip: skip, take: take)));
[HttpGet("mine")]
public async Task<IActionResult> Mine([FromQuery, Range(0, int.MaxValue)] int skip = 0,
[FromQuery, Range(1, 100)] int take = 50) =>
Ok(mapper.Map<List<ReactionPackResponse>>(await packs.ListAsync(currentUser.GetCurrentUserId(), installedOnly: true, skip: skip, take: take)));
[HttpGet("{packId:guid}")]
public async Task<IActionResult> Get(Guid packId) => (await packs.GetAsync(packId))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpGet("shared/{shareCode}")]
public async Task<IActionResult> Shared(string shareCode) => (await packs.GetSharedAsync(shareCode))
.Map(p => mapper.Map<ReactionPackResponse>(p)).ToActionResult();
[HttpGet("/api/reactions/{reactionId:guid}")]
public async Task<IActionResult> Reaction(Guid reactionId) => (await packs.GetReactionAsync(reactionId))
.Map(r => mapper.Map<ReactionItemResponse>(r)).ToActionResult();
[HttpPut("{packId:guid}/subscription")]
public async Task<IActionResult> Subscribe(Guid packId) =>
(await packs.SubscribeAsync(currentUser.GetCurrentUserId(), packId, true)).ToActionResult();
[HttpDelete("{packId:guid}/subscription")]
public async Task<IActionResult> 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
});
}
+5 -5
View File
@@ -49,7 +49,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -74,7 +74,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -97,7 +97,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -118,7 +118,7 @@ public class SessionController : Controller
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, ex.Message); _logger.LogWarning(ex, ex.Message);
return Forbid(ex.Message); return Forbid();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -126,4 +126,4 @@ public class SessionController : Controller
return StatusCode(500, "Unexpected Error! Please try again later."); return StatusCode(500, "Unexpected Error! Please try again later.");
} }
} }
} }
+12 -3
View File
@@ -1,15 +1,19 @@
using Govor.Contracts.Responses.SignalR; using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Govor.API.Common.Extensions;
using Govor.Domain;
namespace Govor.API.Filters; namespace Govor.API.Filters;
public class HubExceptionFilter : IHubFilter public class HubExceptionFilter : IHubFilter
{ {
private readonly ILogger<HubExceptionFilter> _logger; private readonly ILogger<HubExceptionFilter> _logger;
private readonly GovorDbContext _context;
public HubExceptionFilter(ILogger<HubExceptionFilter> logger) public HubExceptionFilter(ILogger<HubExceptionFilter> logger, GovorDbContext context)
{ {
_logger = logger; _logger = logger;
_context = context;
} }
public async ValueTask<object?> InvokeMethodAsync( public async ValueTask<object?> InvokeMethodAsync(
@@ -18,6 +22,11 @@ public class HubExceptionFilter : IHubFilter
{ {
try try
{ {
if (!await _context.HasActiveSessionAsync(context.Context.User))
{
context.Context.Abort();
return CreateHubErrorResult(context, HubResultStatus.Unauthorized, "Session revoked or expired.");
}
return await next(context); return await next(context);
} }
catch (ArgumentException ex) catch (ArgumentException ex)
@@ -66,10 +75,10 @@ public class HubExceptionFilter : IHubFilter
hubResultType.GetProperty(nameof(HubResult<object>.ErrorMessage))! hubResultType.GetProperty(nameof(HubResult<object>.ErrorMessage))!
.SetValue(errorResult, message); .SetValue(errorResult, message);
return Task.FromResult(errorResult); return errorResult;
} }
} }
return null; return null;
} }
} }
+3 -2
View File
@@ -9,7 +9,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.2.0" /> <PackageReference Include="BCrypt.Net-Next" Version="4.2.0" />
<PackageReference Include="FirebaseAdmin" Version="3.6.0" /> <PackageReference Include="FirebaseAdmin" Version="3.6.0" />
<PackageReference Include="AutoMapper" Version="16.0.0" /> <PackageReference Include="AutoMapper" Version="16.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" /> <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.10" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" /> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.10" />
@@ -34,7 +34,8 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="uploads\2026.08\" /> <Folder Include="logs\" />
<Folder Include="uploads\" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+80 -13
View File
@@ -1,8 +1,12 @@
using Govor.API.Common.SignalR.Helpers; using Govor.API.Common.SignalR.Helpers;
using Govor.API.Common.Extensions;
using Govor.Contracts.Requests;
using Govor.API.Hubs.Infrastructure; using Govor.API.Hubs.Infrastructure;
using Govor.Application.Exceptions.VerifyFriendship; using Govor.Application.Exceptions.VerifyFriendship;
using Govor.Application.Infrastructure.Common; using Govor.Application.Infrastructure.Common;
using Govor.Application.Messages; using Govor.Application.Messages;
using Govor.Application.Reactions;
using AutoMapper;
using Govor.Application.Messages.Parameters; using Govor.Application.Messages.Parameters;
using Govor.Contracts.Requests.SignalR; using Govor.Contracts.Requests.SignalR;
using Govor.Contracts.Responses.SignalR; using Govor.Contracts.Responses.SignalR;
@@ -24,6 +28,8 @@ public class ChatsHub : Hub
private readonly IChatNotificationService _notifier; private readonly IChatNotificationService _notifier;
private readonly IConnectionManager _connectionManager; private readonly IConnectionManager _connectionManager;
private readonly INowDateTimeProvider _nowDateTimeProvider; private readonly INowDateTimeProvider _nowDateTimeProvider;
private readonly IMessageReactionService _reactions;
private readonly IMapper _mapper;
public ChatsHub(ILogger<ChatsHub> logger, public ChatsHub(ILogger<ChatsHub> logger,
IMessageReadingService messageReadingService, IMessageReadingService messageReadingService,
@@ -33,7 +39,9 @@ public class ChatsHub : Hub
IHubUserAccessor userAccessor, IHubUserAccessor userAccessor,
IChatNotificationService notifier, IChatNotificationService notifier,
INowDateTimeProvider nowDateTimeProvider, INowDateTimeProvider nowDateTimeProvider,
IConnectionManager connectionManager) IConnectionManager connectionManager,
IMessageReactionService reactions,
IMapper mapper)
{ {
_logger = logger; _logger = logger;
_nowDateTimeProvider = nowDateTimeProvider; _nowDateTimeProvider = nowDateTimeProvider;
@@ -44,6 +52,8 @@ public class ChatsHub : Hub
_userAccessor = userAccessor; _userAccessor = userAccessor;
_notifier = notifier; _notifier = notifier;
_connectionManager = connectionManager; _connectionManager = connectionManager;
_reactions = reactions;
_mapper = mapper;
} }
public override async Task OnConnectedAsync() public override async Task OnConnectedAsync()
@@ -56,6 +66,12 @@ public class ChatsHub : Hub
} }
await _connectionManager.OnConnectedAsync(Context.ConnectionId, userId); 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); _logger.LogInformation("User {UserId} connected", userId);
await base.OnConnectedAsync(); await base.OnConnectedAsync();
} }
@@ -84,23 +100,25 @@ public class ChatsHub : Hub
var result = await _messageSendingService.SendMessageAsync(sendParams); var result = await _messageSendingService.SendMessageAsync(sendParams);
if (!result.IsSuccess) 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); var response = MapToResponse(result.Message, request.ReplyToMessageId);
await _notifier.NotifyMessageSentAsync(response); await _notifier.NotifyMessageSentAsync(response);
return HubResult<UserMessageResponse>.Ok(response); return HubResult<UserMessageResponse>.Ok(response);
}, request.RecipientId); }, request?.RecipientId ?? Guid.Empty);
} }
// --- Read --- // --- Read ---
public async Task<HubResult<MessageReadResponse>> Read(ReadMessageRequest request) public async Task<HubResult<MessageReadResponse>> Read(ReadMessageRequest request)
{ {
return await SafeExecute(async (userId) => return await SafeExecute(async (userId) =>
{ {
ArgumentNullException.ThrowIfNull(request);
var result = await _messageReadingService.ReadMessageAsync(userId, request.MessageId); var result = await _messageReadingService.ReadMessageAsync(userId, request.MessageId);
if(!result.IsSuccess) if(!result.IsSuccess)
throw new InvalidOperationException(result.Error.ToString()); return result.Error.ToHubResult<MessageReadResponse>();
var message = result.Value; var message = result.Value;
@@ -119,13 +137,36 @@ public class ChatsHub : Hub
await _notifier.NotifyMessageWasReadAsync(response); await _notifier.NotifyMessageWasReadAsync(response);
return HubResult<MessageReadResponse>.Ok(response); return HubResult<MessageReadResponse>.Ok(response);
}, request.MessageId); }, request?.MessageId ?? Guid.Empty);
} }
// --- REMOVE --- // --- REMOVE ---
public async Task<HubResult<ChatReadResponse>> ReadChat(Guid chatId, ReadChatRequest request)
{
return await SafeExecute(async userId =>
{
if (request is null)
return HubResult<ChatReadResponse>.BadRequest("Request is required.");
var result = await _messageReadingService.ReadChatAsync(userId, chatId,
request.RecipientType, request.MessageIds, request.UpToMessageId);
if (result.IsFailure)
return result.Error.ToHubResult<ChatReadResponse>();
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<ChatReadResponse>.Ok(response);
}, chatId);
}
public async Task<HubResult<MessageRemovedResponse>> Remove(RemoveMessageRequest request) public async Task<HubResult<MessageRemovedResponse>> Remove(RemoveMessageRequest request)
{ {
return await SafeExecute(async (userId) => return await SafeExecute(async (userId) =>
{ {
ArgumentNullException.ThrowIfNull(request);
var deletemessage = new DeleteMessage( var deletemessage = new DeleteMessage(
userId, userId,
request.MessageId, request.MessageId,
@@ -140,7 +181,7 @@ public class ChatsHub : Hub
var result = await _messageRemovingService.DeleteMessageAsync(deletemessage); var result = await _messageRemovingService.DeleteMessageAsync(deletemessage);
if (!result.IsSuccess) if (!result.IsSuccess)
throw new InvalidOperationException(result.Error.ToString()); return result.Error.ToHubResult<MessageRemovedResponse>();
var notification = new MessageRemovedResponse var notification = new MessageRemovedResponse
{ {
@@ -154,7 +195,26 @@ public class ChatsHub : Hub
await _notifier.NotifyMessageRemovedAsync(notification); await _notifier.NotifyMessageRemovedAsync(notification);
return HubResult<MessageRemovedResponse>.Ok(notification); return HubResult<MessageRemovedResponse>.Ok(notification);
}, request.MessageId); }, request?.MessageId ?? Guid.Empty);
}
public Task<HubResult<MessageReactionsChangedResponse>> React(Guid messageId, SetReactionRequest request) =>
SafeExecute(async userId =>
{
ArgumentNullException.ThrowIfNull(request);
return await ChangeReactionAsync(userId, messageId, request.ReactionId);
}, messageId);
public Task<HubResult<MessageReactionsChangedResponse>> RemoveReaction(Guid messageId) =>
SafeExecute(userId => ChangeReactionAsync(userId, messageId, null), messageId);
private async Task<HubResult<MessageReactionsChangedResponse>> ChangeReactionAsync(Guid userId, Guid messageId, Guid? reactionId)
{
var result = await _reactions.SetAsync(userId, messageId, reactionId);
if (result.IsFailure) return result.Error.ToHubResult<MessageReactionsChangedResponse>();
var response = _mapper.Map<MessageReactionsChangedResponse>(result.Value);
if (result.Value.Changed) await _notifier.NotifyMessageReactionsChangedAsync(response);
return HubResult<MessageReactionsChangedResponse>.Ok(response);
} }
// --- EDIT --- // --- EDIT ---
@@ -162,6 +222,7 @@ public class ChatsHub : Hub
{ {
return await SafeExecute(async (userId) => return await SafeExecute(async (userId) =>
{ {
ArgumentNullException.ThrowIfNull(request);
var editParams = new EditMessage( var editParams = new EditMessage(
userId, userId,
request.MessageId, request.MessageId,
@@ -171,7 +232,7 @@ public class ChatsHub : Hub
var result = await _messageEditingService.EditMessageAsync(editParams); var result = await _messageEditingService.EditMessageAsync(editParams);
if (!result.IsSuccess || result.OriginalMessage == null) if (!result.IsSuccess || result.OriginalMessage == null)
throw new InvalidOperationException("Edit message error"); throw result.Exception ?? new InvalidOperationException("Edit message error");
var response = new MessageEditResponse var response = new MessageEditResponse
{ {
@@ -186,20 +247,21 @@ public class ChatsHub : Hub
await _notifier.NotifyMessageEditedAsync(response); await _notifier.NotifyMessageEditedAsync(response);
return HubResult<MessageEditResponse>.Ok(response); return HubResult<MessageEditResponse>.Ok(response);
}, request.MessageId); }, request?.MessageId ?? Guid.Empty);
} }
private async Task<HubResult<T>> SafeExecute<T>(Func<Guid, Task<HubResult<T>>> action, Guid targetIdForLog) private async Task<HubResult<T>> SafeExecute<T>(Func<Guid, Task<HubResult<T>>> action, Guid targetIdForLog)
{ {
var userId = _userAccessor.GetUserId(Context); var userId = Guid.Empty;
try try
{ {
userId = _userAccessor.GetUserId(Context);
return await action(userId); return await action(userId);
} }
catch (UnauthorizedAccessException ex) catch (UnauthorizedAccessException ex)
{ {
_logger.LogWarning(ex, "Unauthorized: {UserId} -> {TargetId}", userId, targetIdForLog); _logger.LogWarning(ex, "Unauthorized: {UserId} -> {TargetId}", userId, targetIdForLog);
return HubResult<T>.Unauthorized("You are not authorized."); return HubResult<T>.Forbidden("You do not have permission to perform this action.");
} }
catch (FriendshipException) catch (FriendshipException)
{ {
@@ -213,6 +275,10 @@ public class ChatsHub : Hub
{ {
return HubResult<T>.NotFound("Resource not found."); return HubResult<T>.NotFound("Resource not found.");
} }
catch (InvalidOperationException ex)
{
return HubResult<T>.BadRequest(ex.Message);
}
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "Error executing hub method for {UserId}", userId); _logger.LogError(ex, "Error executing hub method for {UserId}", userId);
@@ -222,12 +288,13 @@ public class ChatsHub : Hub
private void ValidateMessageRequest(MessageRequest request) private void ValidateMessageRequest(MessageRequest request)
{ {
ArgumentNullException.ThrowIfNull(request);
if (string.IsNullOrWhiteSpace(request.EncryptedContent) && if (string.IsNullOrWhiteSpace(request.EncryptedContent) &&
(request.MediaAttachments == null || !request.MediaAttachments.Any())) (request.MediaAttachments == null || !request.MediaAttachments.Any()))
{ {
throw new ArgumentException("Message must contain content or media."); 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."); throw new ArgumentException("Message is too long.");
} }
@@ -262,4 +329,4 @@ public class ChatsHub : Hub
ReplyToMessageId = replyToId ReplyToMessageId = replyToId
}; };
} }
} }
+3 -1
View File
@@ -5,9 +5,11 @@ using Govor.Application.Friends;
using Govor.Contracts.DTOs; using Govor.Contracts.DTOs;
using Govor.Contracts.Responses.SignalR; using Govor.Contracts.Responses.SignalR;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Authorization;
namespace Govor.API.Hubs; namespace Govor.API.Hubs;
[Authorize(Roles = "Admin,User")]
public class FriendsHub : Hub public class FriendsHub : Hub
{ {
private readonly ILogger<FriendsHub> _logger; private readonly ILogger<FriendsHub> _logger;
@@ -194,4 +196,4 @@ public class FriendsHub : Hub
return HubResult<object>.Error("Unexpected error! Please try later!"); return HubResult<object>.Error("Unexpected error! Please try later!");
} }
} }
} }
@@ -7,8 +7,12 @@ public static class ChatHubConstants
public const string MessageRemoved = "MessageRemoved"; public const string MessageRemoved = "MessageRemoved";
public const string MessageEdited = "MessageEdited"; public const string MessageEdited = "MessageEdited";
public static string MessageRead = "MessageReaded"; 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 GetUserGroup(Guid userId) => userId.ToString();
public static string GetSessionGroup(Guid sessionId) => $"session_{sessionId}";
public static string GetChatGroup(Guid groupId) => $"group_{groupId}"; public static string GetChatGroup(Guid groupId) => $"group_{groupId}";
public static string GetPrivateChat(Guid groupId) => $"private_{groupId}"; public static string GetPrivateChat(Guid groupId) => $"private_{groupId}";
} }
@@ -2,130 +2,161 @@ using Govor.Application.PrivateUserChats;
using Govor.Application.Profiles; using Govor.Application.Profiles;
using Govor.Application.PushNotifications; using Govor.Application.PushNotifications;
using Govor.Contracts.Responses.SignalR; using Govor.Contracts.Responses.SignalR;
using Govor.Domain;
using Govor.Domain.Common;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using Microsoft.AspNetCore.SignalR; using Microsoft.AspNetCore.SignalR;
using Microsoft.EntityFrameworkCore;
namespace Govor.API.Hubs.Infrastructure; namespace Govor.API.Hubs.Infrastructure;
public class ChatNotificationService : IChatNotificationService public class ChatNotificationService : IChatNotificationService
{ {
private readonly IHubContext<ChatsHub> _hubContext; private readonly IHubContext<ChatsHub> _hubContext;
private readonly IPushNotificationService _notificationService; private readonly IPushNotificationService _notificationService;
private readonly IUserPrivateChatsGetterService _userPrivateChatsGetterService; private readonly IUserPrivateChatsGetterService _chats;
private readonly IProfileService _profileService; private readonly IProfileService _profiles;
private readonly GovorDbContext _context;
private readonly ILogger<ChatNotificationService> _logger;
public ChatNotificationService( public ChatNotificationService(IHubContext<ChatsHub> hubContext,
IHubContext<ChatsHub> hubContext, IPushNotificationService notificationService, IUserPrivateChatsGetterService chats,
IPushNotificationService notificationService, IProfileService profiles, GovorDbContext context, ILogger<ChatNotificationService> logger)
IUserPrivateChatsGetterService userPrivateChatsGetterService,
IProfileService profileService)
{ {
_hubContext = hubContext; _hubContext = hubContext;
_notificationService = notificationService; _notificationService = notificationService;
_userPrivateChatsGetterService = userPrivateChatsGetterService; _chats = chats;
_profileService = profileService; _profiles = profiles;
_context = context;
_logger = logger;
} }
public async Task NotifyMessageSentAsync(UserMessageResponse message) 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<bool> DeliverPushAsync(UserMessageResponse message)
{
try
{ {
await _hubContext.Clients.Group(ChatHubConstants.GetPrivateChat(message.RecipientId)) List<Guid> recipients;
.SendAsync(ChatHubConstants.ReceiveMessage, message); if (message.RecipientType == RecipientType.User)
{
await NotifyMessageReceivedInPrivateChatAsync(message); 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<string, string>
{
["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)) _logger.LogError(ex, "Failed to deliver push for message {MessageId}", message.MessageId);
.SendAsync(ChatHubConstants.ReceiveMessage, message); return false;
} }
// await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(message.SenderId))
// .SendAsync(ChatHubConstants.MessageSent, message);
} }
public async Task NotifyMessageWasReadAsync(MessageReadResponse response) public async Task NotifyMessageWasReadAsync(MessageReadResponse response)
{ {
await NotifyParticipantsAsync( // Keep the existing wire name for old clients; new clients can use MessageRead.
response.ReaderId, await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
response.RecipientId, response.RecipientType, ChatHubConstants.MessageRead, response));
response.RecipientType, await TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
ChatHubConstants.MessageRead, response.RecipientType, "MessageRead", response));
response);
} }
private async Task NotifyMessageReceivedInPrivateChatAsync(UserMessageResponse message) public Task NotifyChatReadAsync(ChatReadResponse response) =>
{ TryNotifyAsync(() => NotifyParticipantsAsync(response.ChatId,
response.RecipientType, ChatHubConstants.ChatRead, response));
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<string, string> data = new Dictionary<string, string>();
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 async Task NotifyMessageEditedAsync(MessageEditResponse response) public Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response) =>
{ TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
await NotifyParticipantsAsync( response.RecipientType, ChatHubConstants.MessageReactionsChanged, response));
response.EditorId,
response.RecipientId, public Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response) =>
response.RecipientType, TryNotifyAsync(() => NotifyParticipantsAsync(response.GroupId,
ChatHubConstants.MessageEdited, RecipientType.Group, ChatHubConstants.ChannelReactionPolicyChanged, response));
response);
} public Task NotifyMessageRemovedAsync(MessageRemovedResponse response) =>
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
private async Task NotifyParticipantsAsync(Guid initiatorId, Guid targetId, RecipientType type, string method, object payload) 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<Guid> participants;
if (type == RecipientType.User) if (type == RecipientType.User)
{ {
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(initiatorId)) var result = await _chats.GetPrivateChatAsync(chatId);
.SendAsync(method, payload); if (result.IsFailure)
return;
if (initiatorId != targetId) participants = new[] { result.Value.UserAId, result.Value.UserBId }.Distinct().ToList();
{
await _hubContext.Clients.Group(ChatHubConstants.GetUserGroup(targetId))
.SendAsync(method, payload);
}
} }
else else
{ participants = await _context.GroupMemberships.AsNoTracking()
// to groups .Where(m => m.GroupId == chatId && !m.IsBanned).Select(m => m.UserId).Distinct().ToListAsync();
await _hubContext.Clients.Group(ChatHubConstants.GetChatGroup(targetId))
if (participants.Count > 0)
await NotifyUsersAsync(participants, method, payload);
}
private async Task NotifyUsersAsync(IEnumerable<Guid> 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); .SendAsync(method, payload);
}
private async Task TryNotifyAsync(Func<Task> notify)
{
try
{
await notify();
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to deliver chat notification; clients can resync from history.");
} }
} }
} }
@@ -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);
}
}
}
}
@@ -0,0 +1,33 @@
namespace Govor.API.Hubs.Infrastructure;
public class ChatPushWorker(IServiceScopeFactory scopeFactory, ILogger<ChatPushWorker> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = scopeFactory.CreateScope();
await scope.ServiceProvider.GetRequiredService<ChatPushDispatcher>().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;
}
}
}
}
@@ -5,7 +5,11 @@ namespace Govor.API.Hubs.Infrastructure;
public interface IChatNotificationService public interface IChatNotificationService
{ {
Task NotifyMessageSentAsync(UserMessageResponse message); Task NotifyMessageSentAsync(UserMessageResponse message);
Task<bool> DeliverPushAsync(UserMessageResponse message);
Task NotifyMessageWasReadAsync(MessageReadResponse response); Task NotifyMessageWasReadAsync(MessageReadResponse response);
Task NotifyChatReadAsync(ChatReadResponse response);
Task NotifyMessageReactionsChangedAsync(MessageReactionsChangedResponse response);
Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response);
Task NotifyMessageRemovedAsync(MessageRemovedResponse response); Task NotifyMessageRemovedAsync(MessageRemovedResponse response);
Task NotifyMessageEditedAsync(MessageEditResponse response); Task NotifyMessageEditedAsync(MessageEditResponse response);
} }
+8 -3
View File
@@ -1,5 +1,6 @@
using Govor.API.Common.SignalR.Helpers; using Govor.API.Common.SignalR.Helpers;
using Govor.Application.Friends; using Govor.Application.Friends;
using Govor.API.Common.Extensions;
using Govor.Application.Medias; using Govor.Application.Medias;
using Govor.Application.Profiles; using Govor.Application.Profiles;
using Govor.Application.Synching; using Govor.Application.Synching;
@@ -101,9 +102,11 @@ public sealed class ProfileHub : Hub
try try
{ {
await _profileService.SetDescription( var result = await _profileService.SetDescription(
description, description,
userId); userId);
if (result.IsFailure)
return result.Error.ToHubResult<bool>();
var payload = new DescriptionUpdatePayload var payload = new DescriptionUpdatePayload
{ {
@@ -146,9 +149,11 @@ public sealed class ProfileHub : Hub
return HubResult<bool>.BadRequest( return HubResult<bool>.BadRequest(
"Invalid icon id."); "Invalid icon id.");
await _profileService.SetNewIcon( var result = await _profileService.SetNewIcon(
userId, userId,
iconId); iconId);
if (result.IsFailure)
return result.Error.ToHubResult<bool>();
var payload = new AvatarUpdatePayload var payload = new AvatarUpdatePayload
{ {
@@ -265,4 +270,4 @@ public sealed class ProfileHub : Hub
{ {
return $"{UserGroupPrefix}{userId}"; return $"{UserGroupPrefix}{userId}";
} }
} }
+35 -27
View File
@@ -1,4 +1,4 @@
using System.Text; using System.Text;
using FirebaseAdmin; using FirebaseAdmin;
using Google.Apis.Auth.OAuth2; using Google.Apis.Auth.OAuth2;
using Govor.API.Common.Extensions; using Govor.API.Common.Extensions;
@@ -8,6 +8,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi; using Microsoft.OpenApi;
using Govor.Domain;
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
@@ -18,23 +19,23 @@ builder.AddLogger();// Serilog
builder.Configuration.AddJsonFile("configs/ban_usernames.json", optional: false, reloadOnChange: true); 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 => builder.Services.AddCors(options =>
{ {
options.AddPolicy("AllowFrontend", policy => options.AddPolicy("AllowFrontend", policy =>
{ {
policy.SetIsOriginAllowed(_ => true) var origins = configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
if (origins.Length > 0)
policy.WithOrigins(origins);
policy
.AllowAnyHeader() .AllowAnyHeader()
.AllowAnyMethod() .AllowAnyMethod()
.AllowCredentials(); .AllowCredentials();
@@ -60,6 +61,12 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
}; };
options.Events = new JwtBearerEvents options.Events = new JwtBearerEvents
{ {
OnTokenValidated = async context =>
{
var db = context.HttpContext.RequestServices.GetRequiredService<GovorDbContext>();
if (!await db.HasActiveSessionAsync(context.Principal))
context.Fail("The access session is invalid or revoked.");
},
OnMessageReceived = context => OnMessageReceived = context =>
{ {
var accessToken = context.Request.Query["access_token"]; var accessToken = context.Request.Query["access_token"];
@@ -110,25 +117,24 @@ services.AddSwaggerGen(options =>
//builder.Services.AddOpenApi(); //builder.Services.AddOpenApi();
var app = builder.Build(); if (!builder.Environment.IsDevelopment() && string.IsNullOrWhiteSpace(configuration["urls"]) &&
string.IsNullOrWhiteSpace(configuration["HTTP_PORTS"]))
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{ {
//app.MapOpenApi();
builder.WebHost.UseUrls("http://0.0.0.0:8080"); 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(); var app = builder.Build();
app.UseSwaggerUI();
app.UseCors("AllowFrontend"); if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection(); //app.UseHttpsRedirection();
app.UseRouting(); app.UseRouting();
app.UseCors("AllowFrontend");
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();
@@ -136,16 +142,18 @@ app.UseAuthorization();
app.MapControllers(); app.MapControllers();
app.MapGet("/server/ping", app.MapGet("/server/ping",
() => new OkResult()); () => Results.Ok());
app.MapHub<ChatsHub>("/hubs/chats"); app.MapHub<ChatsHub>("/hubs/chats", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<FriendsHub>("/hubs/friends"); app.MapHub<FriendsHub>("/hubs/friends", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<ProfileHub>("/hubs/profiles"); app.MapHub<ProfileHub>("/hubs/profiles", options => options.CloseOnAuthenticationExpiration = true);
app.MapHub<PresenceHub>("/hubs/presence"); app.MapHub<PresenceHub>("/hubs/presence", options => options.CloseOnAuthenticationExpiration = true);
app.MapSwagger() app.MapSwagger()
.RequireAuthorization(); .RequireAuthorization();
app.Map("/", () => "Not for browsers"); app.Map("/", () => "Not for browsers");
app.Run(); app.Run();
public partial class Program { }
@@ -26,6 +26,7 @@ public class JwtService : IJwtService
{ {
new Claim("userId", user.Id.ToString()), new Claim("userId", user.Id.ToString()),
new Claim("sid", sessionId.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))
//new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String) //new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
}; };
@@ -50,7 +51,8 @@ public class JwtService : IJwtService
var claims = new[] var claims = new[]
{ {
new Claim("userId", user.Id.ToString()), 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( var token = new JwtSecurityToken(
@@ -82,4 +84,4 @@ public class JwtService : IJwtService
return principal; return principal;
} }
} }
@@ -11,6 +11,7 @@
<PackageReference Include="FirebaseAdmin" Version="3.6.0" /> <PackageReference Include="FirebaseAdmin" Version="3.6.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.10" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.10" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.10" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.10" />
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version = "8.19.2"/> <PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version = "8.19.2"/>
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.2" /> <PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.2" />
@@ -34,6 +34,13 @@ public class UsersService : IUsersAdministration
user.PasswordHash = _passwordHasher.Hash(password); 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(); await _context.SaveChangesAsync();
} }
@@ -43,4 +50,4 @@ public class UsersService : IUsersAdministration
return result; return result;
} }
} }
@@ -1,6 +1,7 @@
using Govor.Domain.Models; using Govor.Domain.Models;
using Govor.Domain; using Govor.Domain;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Govor.Domain.Models.Messages;
namespace Govor.Application.Medias; namespace Govor.Application.Medias;
@@ -28,20 +29,23 @@ public class AccesserToDownloadMediaService : IAccesserToDownloadMedia
{ {
MediaOwnerType.Avatar => true, // media.OwnerId == userId MediaOwnerType.Avatar => true, // media.OwnerId == userId
MediaOwnerType.GroupAvatar => await _dbContext.GroupMemberships 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 MediaOwnerType.Message => await _dbContext.MediaAttachments
.AnyAsync(ma => .AnyAsync(ma =>
ma.MediaFileId == mediaId && ma.MediaFileId == mediaId &&
( (
ma.Message.SenderId == userId || (ma.Message.RecipientType == RecipientType.User &&
ma.Message.RecipientId == userId || _dbContext.PrivateChats.Any(c => c.Id == ma.Message.RecipientId &&
_dbContext.GroupMemberships.Any(gm => (c.UserAId == userId || c.UserBId == userId))) ||
gm.GroupId == ma.Message.RecipientId && gm.UserId == userId) (ma.Message.RecipientType == RecipientType.Group &&
_dbContext.GroupMemberships.Any(gm =>
gm.GroupId == ma.Message.RecipientId && gm.UserId == userId && !gm.IsBanned))
)), )),
MediaOwnerType.System => true, MediaOwnerType.System => true,
MediaOwnerType.Reaction => await _dbContext.ReactionItems.AnyAsync(r => r.MediaFileId == mediaId),
_ => false _ => false
}; };
} }
} }
+2 -2
View File
@@ -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[] // Считать поток в byte[]
using var memoryStream = new MemoryStream(); using var memoryStream = new MemoryStream();
@@ -174,4 +174,4 @@ public class MediaService : IMediaService
return new Unit(); return new Unit();
} }
} }
+24
View File
@@ -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<bool> 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)
};
}
}
@@ -1,10 +1,14 @@
using Govor.Domain.Common; using Govor.Domain.Common;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using SmartRes; using SmartRes;
using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
public interface IMessageReadingService public interface IMessageReadingService
{ {
Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId); Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId);
} Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null);
Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type);
}
@@ -37,7 +37,8 @@ public class MessageEditingService : IMessageEditingService
null); null);
} }
if (message.SenderId != editParams.EditorId) if (message.SenderId != editParams.EditorId || !await _dbContext.HasChatAccessAsync(
editParams.EditorId, message.RecipientId, message.RecipientType))
{ {
_logger.LogWarning( _logger.LogWarning(
"User {EditorId} unauthorized to edit message {MessageId}", "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( var editDeadline = message.SentAt.AddMinutes(
_options.MaxEditTimeMinutes); _options.MaxEditTimeMinutes);
@@ -83,6 +84,10 @@ public class MessageEditingService : IMessageEditingService
MediaAttachments = message.MediaAttachments?.ToList() ?? [] 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.EncryptedContent = editParams.NewContent;
message.IsEdited = true; message.IsEdited = true;
message.EditedAt = editParams.EditedAt; message.EditedAt = editParams.EditedAt;
@@ -98,4 +103,4 @@ public class MessageEditingService : IMessageEditingService
null, null,
originalMessageSnapshot); originalMessageSnapshot);
} }
} }
@@ -1,4 +1,5 @@
using Govor.Application.Infrastructure.Common; using Govor.Application.Infrastructure.Common;
using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common; using Govor.Domain.Common;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
@@ -14,10 +15,7 @@ public class MessageReadingService : IMessageReadingService
private readonly ILogger<MessageReadingService> _logger; private readonly ILogger<MessageReadingService> _logger;
private readonly INowDateTimeProvider _dateTimeProvider; private readonly INowDateTimeProvider _dateTimeProvider;
public MessageReadingService(GovorDbContext dbContext, ILogger<MessageReadingService> logger,
public MessageReadingService(
GovorDbContext dbContext,
ILogger<MessageReadingService> logger,
INowDateTimeProvider dateTimeProvider) INowDateTimeProvider dateTimeProvider)
{ {
_dbContext = dbContext; _dbContext = dbContext;
@@ -27,46 +25,127 @@ public class MessageReadingService : IMessageReadingService
public async Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId) public async Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId)
{ {
var message = await _dbContext.Messages var message = await _dbContext.Messages.AsNoTracking()
.Include(msg => msg.MessageViews) .FirstOrDefaultAsync(m => m.Id == messageId);
.FirstOrDefaultAsync(msg => msg.Id == messageId); if (message is null)
return Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message not found."));
if(message is null)
return Result<Message, Error>.Failure(Error.NotFound(
"Message not found",
"Message with id: " + messageId + " was not found.")
);
if (CanReadMessage(readerId, message)) var result = await ReadChatAsync(readerId, message.RecipientId,
{ message.RecipientType, new[] { messageId });
var view = new MessageView() if (result.IsFailure)
{ return Result.Failure<Message>(result.Error);
Id = Guid.NewGuid(),
MessageId = messageId, // Fresh query also returns the existing receipt on repeated calls.
UserId = readerId, var readMessage = await _dbContext.Messages.AsNoTracking().Include(m => m.MessageViews)
ViewedAt = _dateTimeProvider.Now, .FirstOrDefaultAsync(m => m.Id == messageId);
}; return readMessage is null
? Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message was removed."))
_dbContext.MessageViews.Add(view); : Result<Message, Error>.Success(readMessage);
await _dbContext.SaveChangesAsync();
_logger.LogInformation("Message with id: {Id} was read by user {user} at {time}", view.Id, view.UserId, view.ViewedAt);
}
return message;
} }
private bool CanReadMessage(Guid readerId, Message message) public async Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null)
{ {
if (message.RecipientType == RecipientType.User) if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
return Result.Failure<ChatReadResult>(Denied());
if (messageIds is not null && (messageIds.Count == 0 || messageIds.Count > 100 ||
messageIds.Contains(Guid.Empty) || upToMessageId.HasValue))
return Result.Failure<ChatReadResult>(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) && // Validate the whole selection before writing any receipt.
message.MessageViews.All(mv => mv.UserId != readerId); if (await chat.CountAsync(m => ids.Contains(m.Id)) != ids.Length)
return Result.Failure<ChatReadResult>(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<ChatReadResult>(Error.Validation("Message.Read.OwnMessage",
"Only incoming messages can be marked as read."));
} }
else 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<ChatReadResult>(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<string>();
var parameters = new List<object>();
using var command = _dbContext.Database.GetDbConnection().CreateCommand();
foreach (var id in pending)
{
var names = new List<string>();
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);
} }
}
public async Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type)
{
if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
return Result.Failure<int>(Denied());
return await CountUnreadAsync(readerId, _dbContext.Messages.AsNoTracking()
.Where(m => m.RecipientId == chatId && m.RecipientType == type));
}
private Task<int> CountUnreadAsync(Guid readerId, IQueryable<Message> 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.");
}
@@ -1,4 +1,4 @@
using Govor.Application.Messages.Parameters; using DeleteMessage = Govor.Application.Messages.Parameters.DeleteMessage;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common; using Govor.Domain.Common;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
@@ -13,75 +13,38 @@ public class MessageRemovingService : IMessageRemovingService
private readonly GovorDbContext _govorDbContext; private readonly GovorDbContext _govorDbContext;
private readonly ILogger<MessageRemovingService> _logger; private readonly ILogger<MessageRemovingService> _logger;
public MessageRemovingService public MessageRemovingService(GovorDbContext govorDbContext, ILogger<MessageRemovingService> logger)
(GovorDbContext govorDbContext,
ILogger<MessageRemovingService> logger)
{ {
_govorDbContext = govorDbContext; _govorDbContext = govorDbContext;
_logger = logger; _logger = logger;
} }
public async Task<Result<Message,Error>> DeleteMessageAsync(DeleteMessage deleteParams) public async Task<Result<Message, Error>> DeleteMessageAsync(DeleteMessage deleteParams)
{ {
var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId); var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
if (message is null)
if (message == null) return Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message not found."));
return Result<Message, Error>.Failure(
Error.NotFound(
"MessageRemoving",
"Message with given id doesn't exist")
);
var result = message.RecipientType switch if (!await _govorDbContext.HasChatAccessAsync(deleteParams.DeleterId,
{ message.RecipientId, message.RecipientType))
RecipientType.Group => await ValidateGroupRecipientAsync(message, deleteParams), return Result.Failure<Message>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
RecipientType.User => await ValidateUserRecipientAsync(message, deleteParams),
_ => Result<Message, Error>.Failure(Error.Failure(
"MessageRemoving.ArgumentOutOfRangeException",
$"Argument out of range: {nameof(message.RecipientType)}"
)
)
};
return result;
}
private async Task<Result<Message,Error>> ValidateGroupRecipientAsync(Message message, DeleteMessage deleteParams) // Do not silently turn a local hide into deletion for everyone.
{ if (!deleteParams.ForceRemove)
if (deleteParams.DeleterId == message.RecipientId) return Result.Failure<Message>(Error.Validation("Message.HideNotSupported",
{ "HideForMe is not supported. Use ForceRemove to delete a message for everyone."));
return await ForceRemoveAsync(message);
}
else
{
// TODO made admin rules
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
$"You do not have permission to delete message {message.Id}"
));
}
}
private async Task<Result<Message,Error>> ValidateUserRecipientAsync(Message message, DeleteMessage deleteParams) var canDelete = message.SenderId == deleteParams.DeleterId ||
{ (message.RecipientType == RecipientType.Group &&
if (deleteParams.DeleterId == message.SenderId) await _govorDbContext.GroupAdmins.AnyAsync(a =>
{ a.GroupId == message.RecipientId && a.UserId == deleteParams.DeleterId));
return await ForceRemoveAsync(message); if (!canDelete)
} return Result.Failure<Message>(Error.Forbidden("Message.Remove.AccessDenied",
else "Only the author or a group administrator can delete this message."));
{
// TODO made hide rules
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
$"You do not have permission to delete message {message.Id}"
));
}
}
private async Task<Result<Message, Error>> ForceRemoveAsync(Message message)
{
_govorDbContext.Messages.Remove(message); _govorDbContext.Messages.Remove(message);
await _govorDbContext.SaveChangesAsync(); await _govorDbContext.SaveChangesAsync();
_logger.LogInformation("Message {MessageId} removed by {UserId}", message.Id, deleteParams.DeleterId);
return message; return message;
} }
} }
@@ -2,6 +2,7 @@ using Govor.Application.Messages.Parameters;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Models.Messages; using Govor.Domain.Models.Messages;
using Govor.Domain.Models;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
namespace Govor.Application.Messages; namespace Govor.Application.Messages;
@@ -19,9 +20,14 @@ public class MessageSendingService : IMessageSendingService
public async Task<SendMessageResult> SendMessageAsync(SendMessage sendParams) public async Task<SendMessageResult> 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 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), RecipientType.Group => await ValidateGroupRecipientAsync(sendParams.FromUserId, sendParams.RecipientId),
_ => (Success: false, Error: "Invalid recipient type.") _ => (Success: false, Error: "Invalid recipient type.")
}; };
@@ -29,9 +35,20 @@ public class MessageSendingService : IMessageSendingService
if (!validationResult.Success) if (!validationResult.Success)
{ {
_logger.LogWarning("Message send failed: {Error}", validationResult.Error); _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 messageId = Guid.NewGuid();
var message = new Message var message = new Message
{ {
@@ -39,38 +56,51 @@ public class MessageSendingService : IMessageSendingService
SenderId = sendParams.FromUserId, SenderId = sendParams.FromUserId,
RecipientId = sendParams.RecipientId, RecipientId = sendParams.RecipientId,
RecipientType = sendParams.RecipientType, RecipientType = sendParams.RecipientType,
EncryptedContent = sendParams.EncryptContent, EncryptedContent = sendParams.EncryptContent ?? string.Empty,
SentAt = sendParams.SendAt, SentAt = sendParams.SendAt,
IsEdited = false, IsEdited = false,
ReplyToMessageId = sendParams.ReplyToMessageId, ReplyToMessageId = sendParams.ReplyToMessageId,
MediaAttachments = sendParams.Media?.Select(m => new MediaAttachments MediaAttachments = files.Select(file => new MediaAttachments
{ {
Id = Guid.NewGuid(), Id = Guid.NewGuid(),
MessageId = messageId, MessageId = messageId,
MediaFileId = m.MediaId MediaFileId = file.Id,
}).ToList() ?? [] MediaFile = file
}).ToList()
}; };
await _dbContext.Messages.AddAsync(message); 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(); await _dbContext.SaveChangesAsync();
_logger.LogInformation("Message {MessageId} sent successfully.", messageId); _logger.LogInformation("Message {MessageId} sent successfully.", messageId);
return new SendMessageResult(true, null, message); 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); var chat = await _dbContext.PrivateChats.AsNoTracking().FirstOrDefaultAsync(c => c.Id == chatId &&
return chatExists ? (true, null) : (false, $"Private chat {chatId} not found."); (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) private async Task<(bool Success, string Error)> ValidateGroupRecipientAsync(Guid userId, Guid groupId)
{ {
var groupExists = await _dbContext.ChatGroups.AnyAsync(g => g.Id == groupId); var group = await _dbContext.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == groupId);
if (!groupExists) return (false, $"Group {groupId} not found."); 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 (!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); return (true, null);
} }
+17 -8
View File
@@ -26,12 +26,13 @@ public class MessagesLoader : IMessagesLoader
if (privateChatId == Guid.Empty) if (privateChatId == Guid.Empty)
return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"PrivateChatId id cannot be empty.")); return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"PrivateChatId id cannot be empty."));
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId); if (!await _dbContext.HasChatAccessAsync(currentUser, privateChatId, RecipientType.User))
if (!chatExists) return Result.Failure<List<Message>>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
return new List<Message>(0);
var query = _dbContext.Messages var query = _dbContext.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.MessageViews)
.Include(m => m.Reactions)
.Include(m => m.MediaAttachments) .Include(m => m.MediaAttachments)
.ThenInclude(m => m.MediaFile) .ThenInclude(m => m.MediaFile)
.Where(m => m.RecipientType == RecipientType.User && m.RecipientId == privateChatId); .Where(m => m.RecipientType == RecipientType.User && m.RecipientId == privateChatId);
@@ -50,13 +51,15 @@ public class MessagesLoader : IMessagesLoader
return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"Chat id cannot be empty.")); return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"Chat id cannot be empty."));
var isMember = await _dbContext.GroupMemberships 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) if (!isMember)
return new List<Message>(0); return Result.Failure<List<Message>>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
var query = _dbContext.Messages var query = _dbContext.Messages
.AsNoTracking() .AsNoTracking()
.Include(m => m.MessageViews)
.Include(m => m.Reactions)
.Include(m => m.MediaAttachments) .Include(m => m.MediaAttachments)
.ThenInclude(m => m.MediaFile) .ThenInclude(m => m.MediaFile)
.AsSplitQuery() .AsSplitQuery()
@@ -75,8 +78,10 @@ public class MessagesLoader : IMessagesLoader
{ {
return await baseQuery return await baseQuery
.OrderByDescending(m => m.SentAt) .OrderByDescending(m => m.SentAt)
.ThenByDescending(m => m.Id)
.Take(before) .Take(before)
.OrderBy(m => m.SentAt) .OrderBy(m => m.SentAt)
.ThenBy(m => m.Id)
.ToListAsync(); .ToListAsync();
} }
@@ -85,14 +90,18 @@ public class MessagesLoader : IMessagesLoader
return []; return [];
var beforeMessages = await baseQuery 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) .OrderByDescending(m => m.SentAt)
.ThenByDescending(m => m.Id)
.Take(before) .Take(before)
.ToListAsync(); .ToListAsync();
var afterMessages = await baseQuery 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) .OrderBy(m => m.SentAt)
.ThenBy(m => m.Id)
.Take(after) .Take(after)
.ToListAsync(); .ToListAsync();
@@ -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<Guid>? MessageIds, int ReadCount, int UnreadCount);
@@ -30,8 +30,8 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService
if (res == null) if (res == null)
return Result.Failure<PrivateChat>( return Result.Failure<PrivateChat>(
Error.Failure( Error.NotFound(
nameof(InvalidOperationException), "PrivateChat.NotFound",
"PrivateChat not found.") "PrivateChat not found.")
); );
@@ -46,4 +46,4 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService
(p.UserBId == userIdA && p.UserAId == userIdB) (p.UserBId == userIdA && p.UserAId == userIdB)
); );
} }
} }
@@ -1,5 +1,6 @@
using Govor.Domain; using Govor.Domain;
using Govor.Domain.Common; using Govor.Domain.Common;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using SmartRes; using SmartRes;
@@ -61,6 +62,10 @@ public class ProfileService : IProfileService
{ {
_logger.LogInformation("Updating icon for user {UserId}", userId); _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<Unit, Error>.Failure(Error.Forbidden("Profile.IconAccess", "Only your uploaded avatar can be used."));
var updatedRows = await _context.Users var updatedRows = await _context.Users
.Where(u => u.Id == userId) .Where(u => u.Id == userId)
@@ -40,6 +40,21 @@ public class FirebasePushProvider : IPushNotificationProvider
{ {
if (tokens.Count == 0) if (tokens.Count == 0)
return new SendPushResult(0, 0, []); return new SendPushResult(0, 0, []);
if (tokens.Count > 500)
{
var success = 0;
var failure = 0;
var invalid = new List<string>();
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 var multicastMsg = new MulticastMessage
{ {
@@ -89,7 +104,7 @@ public class FirebasePushProvider : IPushNotificationProvider
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "FCM multicast failed"); _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) private static bool IsInvalidTokenError(FirebaseMessagingException ex)
{ {
return ex.MessagingErrorCode is MessagingErrorCode.Unregistered return ex.MessagingErrorCode is MessagingErrorCode.Unregistered;
or MessagingErrorCode.InvalidArgument
or MessagingErrorCode.SenderIdMismatch;
} }
} }
@@ -9,11 +9,11 @@ public class NullPushProvider : IPushNotificationProvider
public Task<SendPushResult> SendToTokenAsync(string token, PushMessage message) public Task<SendPushResult> SendToTokenAsync(string token, PushMessage message)
{ {
throw new NotImplementedException(); return Task.FromResult(new SendPushResult(0, 0, []));
} }
public Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message) public Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
{ {
throw new NotImplementedException(); return Task.FromResult(new SendPushResult(0, 0, []));
} }
} }
@@ -75,6 +75,8 @@ public class PushNotificationService : IPushNotificationService
_logger.LogWarning("Removed {Count} invalid FCM tokens for session {SessionId}", result.FailureCount, sessionId); _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(); return Result.Success();
} }
catch (Exception ex) catch (Exception ex)
@@ -97,6 +99,8 @@ public class PushNotificationService : IPushNotificationService
_logger.LogWarning("Removed {Count} invalid FCM tokens for target: {Target}", result.FailureCount, targetInfo); _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(); return Result.Success();
} }
catch (Exception ex) catch (Exception ex)
@@ -117,4 +121,4 @@ public class PushNotificationService : IPushNotificationService
ChannelId = channelId ChannelId = channelId
}; };
} }
} }
@@ -63,8 +63,10 @@ public class PushTokenService : IPushTokenService
{ {
var tokens = await _context.UserPushTokens var tokens = await _context.UserPushTokens
.AsNoTracking() .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) .Select(t => t.Token)
.Distinct()
.ToListAsync(); .ToListAsync();
return tokens; return tokens;
@@ -82,8 +84,10 @@ public class PushTokenService : IPushTokenService
{ {
var tokens = await _context.UserPushTokens var tokens = await _context.UserPushTokens
.AsNoTracking() .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) .Select(t => t.Token)
.Distinct()
.ToListAsync(); .ToListAsync();
return tokens; return tokens;
@@ -101,7 +105,8 @@ public class PushTokenService : IPushTokenService
{ {
var token = await _context.UserPushTokens var token = await _context.UserPushTokens
.AsNoTracking() .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) .Select(t => t.Token)
.FirstOrDefaultAsync(); .FirstOrDefaultAsync();
@@ -138,13 +143,22 @@ public class PushTokenService : IPushTokenService
public async Task<Result<Unit, Error>> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform) public async Task<Result<Unit, Error>> 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<Unit, Error>.Failure(Error.Failure("PushToken.Empty", "Push token cannot be empty.")); return Result<Unit, Error>.Failure(Error.Failure("PushToken.Empty", "Push token cannot be empty."));
} }
var existingToken = await _context.UserPushTokens if (!await _context.UserSessions.AnyAsync(s => s.Id == sessionId && s.UserId == userId &&
.FirstOrDefaultAsync(t => t.Platform == platform && t.UserId == userId && t.UserSessionId == sessionId); !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now))
return Result<Unit, Error>.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) if (existingToken is null)
{ {
@@ -167,6 +181,8 @@ public class PushTokenService : IPushTokenService
existingToken.Platform = platform; existingToken.Platform = platform;
existingToken.Token = token; existingToken.Token = token;
existingToken.UpdatedAt = _nowDateTimeProvider.Now; existingToken.UpdatedAt = _nowDateTimeProvider.Now;
existingToken.IsActive = true;
_context.Entry(existingToken).Property(t => t.IsActive).IsModified = true;
} }
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@@ -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<ReactionCount> Counts, bool Changed = false);
public record ChannelReactionPolicy(Guid GroupId, ChannelReactionMode Mode, long Version, IReadOnlyList<Guid> ReactionIds);
public interface IMessageReactionService
{
Task<Result<MessageReactionState, Error>> GetAsync(Guid userId, Guid messageId);
Task<Result<MessageReactionState, Error>> SetAsync(Guid userId, Guid messageId, Guid? reactionId);
Task<Result<ChannelReactionPolicy, Error>> GetPolicyAsync(Guid userId, Guid groupId);
Task<Result<ChannelReactionPolicy, Error>> SetPolicyAsync(Guid userId, Guid groupId, ChannelReactionMode mode, IReadOnlyCollection<Guid> reactionIds);
}
@@ -0,0 +1,20 @@
using Govor.Domain.Common;
using Govor.Domain.Models.Reactions;
using SmartRes;
namespace Govor.Application.Reactions;
public interface IReactionPackService
{
Task<List<ReactionPack>> ListAsync(Guid userId, bool installedOnly = false, bool includeDisabled = false, int skip = 0, int take = 50);
Task<Result<ReactionPack, Error>> GetAsync(Guid packId, bool includeDisabled = false);
Task<Result<ReactionPack, Error>> GetSharedAsync(string shareCode);
Task<Result<ReactionItem, Error>> GetReactionAsync(Guid reactionId);
Task<Result<Unit, Error>> SubscribeAsync(Guid userId, Guid packId, bool subscribe);
Task<Result<ReactionPack, Error>> CreateAsync(Guid actorId, string name, string description);
Task<Result<ReactionPack, Error>> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled);
Task<Result<Unit, Error>> DisableAsync(Guid actorId, Guid packId);
Task<Result<ReactionItem, Error>> AddEmojiAsync(Guid actorId, Guid packId, string name, string emoji);
Task<Result<ReactionItem, Error>> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data, CancellationToken cancellationToken = default);
Task<Result<Unit, Error>> DisableReactionAsync(Guid actorId, Guid packId, Guid reactionId);
}
@@ -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<Result<MessageReactionState, Error>> GetAsync(Guid userId, Guid messageId)
{
var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId);
if (message is null) return Result.Failure<MessageReactionState>(Missing());
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
return Result.Failure<MessageReactionState>(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<MessageReactionState>(Denied());
var state = await StateAsync(messageId, userId);
await transaction.CommitAsync();
return state is null ? Result.Failure<MessageReactionState>(Missing()) : Result.Success(state);
});
}
public async Task<Result<MessageReactionState, Error>> SetAsync(Guid userId, Guid messageId, Guid? reactionId)
{
if (reactionId == Guid.Empty)
return Result.Failure<MessageReactionState>(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<MessageReactionState>(Missing());
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
return Result.Failure<MessageReactionState>(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<MessageReactionState>(Missing());
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
return Result.Failure<MessageReactionState>(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<MessageReactionState>(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<MessageReactionState>(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<MessageReactionState?> 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<Result<ChannelReactionPolicy, Error>> GetPolicyAsync(Guid userId, Guid groupId)
{
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group))
return Result.Failure<ChannelReactionPolicy>(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<Result<ChannelReactionPolicy, Error>> SetPolicyAsync(Guid userId, Guid groupId,
ChannelReactionMode mode, IReadOnlyCollection<Guid> reactionIds)
{
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) ||
!await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId))
return Result.Failure<ChannelReactionPolicy>(Denied());
if (!Enum.IsDefined(mode) || reactionIds is null || reactionIds.Count > 100 || reactionIds.Contains(Guid.Empty) ||
(mode != ChannelReactionMode.Selected && reactionIds.Count > 0))
return Result.Failure<ChannelReactionPolicy>(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<ChannelReactionPolicy>(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<ChannelReactionPolicy>(Denied());
if (await context.ReactionItems.CountAsync(r => ids.Contains(r.Id) && r.IsEnabled && r.Pack.IsEnabled) != ids.Length)
return Result.Failure<ChannelReactionPolicy>(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<ChannelReactionPolicy> 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.");
}
@@ -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<Result<ProcessedReactionMedia, Error>> ProcessAsync(byte[] data, CancellationToken cancellationToken = default);
}
public class ReactionMediaProcessor : IReactionMediaProcessor
{
public async Task<Result<ProcessedReactionMedia, Error>> 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<Rgba32>(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<ProcessedReactionMedia, Error> Invalid(string message) =>
Result<ProcessedReactionMedia, Error>.Failure(Error.Validation("Reaction.Media.Invalid", message));
}
@@ -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<ReactionPackService> logger) : IReactionPackService
{
public async Task<List<ReactionPack>> 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<Result<ReactionPack, Error>> 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<ReactionPack>(Missing()) : Result.Success(pack);
}
public async Task<Result<ReactionPack, Error>> 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<ReactionPack>(Missing());
}
// Definitions remain readable after disabling so historical reactions still render.
public async Task<Result<ReactionItem, Error>> GetReactionAsync(Guid reactionId)
{
var item = await context.ReactionItems.AsNoTracking().FirstOrDefaultAsync(r => r.Id == reactionId);
return item is null ? Result.Failure<ReactionItem>(Missing()) : Result.Success(item);
}
public async Task<Result<Unit, Error>> 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<Result<ReactionPack, Error>> CreateAsync(Guid actorId, string name, string description)
{
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionPack>(Denied());
if (!ValidText(name, description)) return Result.Failure<ReactionPack>(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<Result<ReactionPack, Error>> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled)
{
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionPack>(Denied());
if (!ValidText(name, description)) return Result.Failure<ReactionPack>(Invalid("Invalid name or description."));
var pack = await context.ReactionPacks.FirstOrDefaultAsync(p => p.Id == packId);
if (pack is null) return Result.Failure<ReactionPack>(Missing());
if (pack.IsDefault) return Result.Failure<ReactionPack>(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<Result<Unit, Error>> 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<Result<ReactionItem, Error>> 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<ReactionItem>(Invalid("Provide a single emoji grapheme."));
return await AddAsync(actorId, packId, name, emoji, null);
}
public async Task<Result<ReactionItem, Error>> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data,
CancellationToken cancellationToken = default)
{
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionItem>(Denied());
if (!await context.ReactionPacks.AnyAsync(p => p.Id == packId && !p.IsDefault && p.IsEnabled))
return Result.Failure<ReactionItem>(Invalid("An active custom pack is required."));
var processed = await processor.ProcessAsync(data, cancellationToken);
if (processed.IsFailure) return Result.Failure<ReactionItem>(processed.Error);
return await AddAsync(actorId, packId, name, null, processed.Value);
}
private async Task<Result<ReactionItem, Error>> AddAsync(Guid actorId, Guid packId, string name,
string? emoji, ProcessedReactionMedia? media)
{
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionItem>(Denied());
if (!ValidText(name, "")) return Result.Failure<ReactionItem>(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<ReactionItem>(Invalid("An active custom pack is required."));
if (await context.ReactionItems.CountAsync(r => r.PackId == packId) >= 100)
return Result.Failure<ReactionItem>(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<Result<Unit, Error>> 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<bool> 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.");
}
@@ -30,7 +30,7 @@ public class SessionKeysReader : ISessionKeysReader
return await _context.UserCryptoSessions return await _context.UserCryptoSessions
.AsNoTracking() .AsNoTracking()
.Include(c => c.OneTimePreKeys) .Include(c => c.OneTimePreKeys)
.Include(c => c.UserSession) .Include(c => c.SignedPreKey)
.Where(c => c.UserSession.UserId == userId .Where(c => c.UserSession.UserId == userId
&& !c.UserSession.IsRevoked && !c.UserSession.IsRevoked
&& c.UserSession.ExpiresAt > now) && c.UserSession.ExpiresAt > now)
@@ -44,7 +44,7 @@ public class SessionKeysReader : ISessionKeysReader
return await _context.OneTimePreKeys return await _context.OneTimePreKeys
.AsNoTracking() .AsNoTracking()
.Include(f => f.UserCryptoSession) .Include(f => f.UserCryptoSession)
.CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId); .CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId && !f.IsUsed);
} }
public async Task<UserCryptoSession?> GetKeysBySessionIdAsync(Guid sessionId) public async Task<UserCryptoSession?> GetKeysBySessionIdAsync(Guid sessionId)
@@ -57,4 +57,4 @@ public class SessionKeysReader : ISessionKeysReader
.Include(c => c.UserSession) .Include(c => c.UserSession)
.FirstOrDefaultAsync(c => c.UserSessionId == sessionId); .FirstOrDefaultAsync(c => c.UserSessionId == sessionId);
} }
} }
@@ -45,21 +45,10 @@ public class UserSessionOpener : IUserSessionOpener
return Result.Failure<RefreshResult>(result.Error); return Result.Failure<RefreshResult>(result.Error);
} }
var sessions = result.Value;
var existingSession = sessions.FirstOrDefault(s => s.DeviceInfo == deviceInfo);
try try
{ {
RefreshResult refreshResult; // DeviceInfo is a display label, not a device identity. Never reuse another sid.
var refreshResult = await CreateNewSessionAsync(user, deviceInfo ?? string.Empty);
if (existingSession is not null)
{
refreshResult = await UpdateExistingSessionAsync(user, deviceInfo, existingSession);
}
else
{
refreshResult = await CreateNewSessionAsync(user, deviceInfo);
}
await _context.SaveChangesAsync(); await _context.SaveChangesAsync();
@@ -120,4 +109,4 @@ public class UserSessionOpener : IUserSessionOpener
var refreshToken = await _jwtService.GenerateRefreshTokenAsync(user); var refreshToken = await _jwtService.GenerateRefreshTokenAsync(user);
return (accessToken, refreshToken); return (accessToken, refreshToken);
} }
} }
@@ -61,11 +61,15 @@ public class UserSessionRefresher : IUserSessionRefresher
var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(session.User); var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(session.User);
var newRefreshTokenHash = _jwtTokenHasher.HashToken(newRefreshToken); var newRefreshTokenHash = _jwtTokenHasher.HashToken(newRefreshToken);
session.RefreshTokenHash = newRefreshTokenHash; var now = DateTime.UtcNow;
session.CreatedAt = DateTime.UtcNow; var updated = await _context.UserSessions.Where(s => s.Id == session.Id &&
session.ExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays); s.RefreshTokenHash == hashedToken && !s.IsRevoked && s.ExpiresAt > now)
.ExecuteUpdateAsync(setters => setters
await _context.SaveChangesAsync(); .SetProperty(s => s.RefreshTokenHash, newRefreshTokenHash)
.SetProperty(s => s.ExpiresAt, now.AddDays(_options.RefreshTokenLifetimeDays)));
if (updated == 0)
return Result.Failure<RefreshResult>(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); _logger.LogInformation("Successfully refreshed session {SessionId} for user {UserId}", session.Id, session.UserId);
@@ -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<Guid> ReactionIds { get; set; } = [];
}
@@ -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<Guid>? MessageIds { get; set; }
public Guid? UpToMessageId { get; set; }
}
@@ -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;
}
@@ -5,10 +5,9 @@ public class UserResponse
public Guid Id { get; set; } public Guid Id { get; set; }
public string Username { get; set; } public string Username { get; set; }
public string Description { get; set; } public string Description { get; set; }
public string PasswordHash { get; set; }
public DateTime WasOnline { get; set; } public DateTime WasOnline { get; set; }
public DateOnly CreatedOn { get; set; } public DateOnly CreatedOn { get; set; }
public Guid IconId {get; set;} public Guid IconId {get; set;}
public Guid InviteId {get; set;} public Guid InviteId {get; set;}
public bool IsAdmin {get; set;} public bool IsAdmin {get; set;}
} }
@@ -5,6 +5,7 @@ public class MessageReactionResponse
public Guid Id { get; set; } public Guid Id { get; set; }
public Guid MessageId { get; set; } public Guid MessageId { get; set; }
public Guid UserId { get; set; } public Guid UserId { get; set; }
public Guid? ReactionId { get; set; }
public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:" public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:"
public DateTime ReactedAt { get; set; } = DateTime.UtcNow; public DateTime ReactedAt { get; set; } = DateTime.UtcNow;
} }
+2 -1
View File
@@ -13,8 +13,9 @@ public class MessageResponse
public bool IsEdited { get; set; } = false; public bool IsEdited { get; set; } = false;
public DateTime? EditedAt { get; set; } public DateTime? EditedAt { get; set; }
public Guid? ReplyToMessageId { get; set; } public Guid? ReplyToMessageId { get; set; }
public long ReactionsVersion { get; set; }
public List<MediaAttachmentResponse> MediaAttachments { get; set; } = new(); public List<MediaAttachmentResponse> MediaAttachments { get; set; } = new();
public List<MessageReactionResponse> Reactions { get; set; } = new(); public List<MessageReactionResponse> Reactions { get; set; } = new();
public List<MessageViewResponse> MessageViews { get; set; } = new(); public List<MessageViewResponse> MessageViews { get; set; } = new();
} }
@@ -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<ReactionItemResponse> 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; }
}
@@ -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<Guid>? MessageIds { get; set; }
public int ReadCount { get; set; }
public int UnreadCount { get; set; }
}
@@ -49,6 +49,12 @@ public class HubResult<T>
ErrorMessage = message, ErrorMessage = message,
}; };
public static HubResult<T> Forbidden(string message) => new()
{
Status = HubResultStatus.Forbidden,
ErrorMessage = message
};
public static HubResult<T> UnprocessableEntity(string message) => new() public static HubResult<T> UnprocessableEntity(string message) => new()
{ {
Status = HubResultStatus.UnprocessableEntity, Status = HubResultStatus.UnprocessableEntity,
@@ -69,8 +75,9 @@ public enum HubResultStatus : int
NoContent = 204, NoContent = 204,
BadRequest = 400, BadRequest = 400,
Unauthorized = 401, Unauthorized = 401,
Forbidden = 403,
NotFound = 404, NotFound = 404,
Conflict = 409, Conflict = 409,
UnprocessableEntity = 422, UnprocessableEntity = 422,
ServerError = 500, ServerError = 500,
} }
@@ -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<ReactionCountResponse> Counts { get; set; } = [];
}
public class ChannelReactionPolicyResponse
{
public Guid GroupId { get; set; }
public ChannelReactionMode Mode { get; set; }
public long Version { get; set; }
public List<Guid> ReactionIds { get; set; } = [];
}
@@ -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<ChatPushNotification>
{
public void Configure(EntityTypeBuilder<ChatPushNotification> builder)
{
builder.HasKey(n => n.MessageId);
builder.HasIndex(n => n.NextAttemptAt);
builder.HasOne<Message>().WithMany().HasForeignKey(n => n.MessageId)
.OnDelete(DeleteBehavior.Cascade);
}
}
@@ -9,6 +9,8 @@ public class MessageReactionConfiguration : IEntityTypeConfiguration<MessageReac
public void Configure(EntityTypeBuilder<MessageReaction> builder) public void Configure(EntityTypeBuilder<MessageReaction> builder)
{ {
builder.HasKey(r => r.Id); builder.HasKey(r => r.Id);
builder.HasOne<Govor.Domain.Models.Reactions.ReactionItem>().WithMany()
.HasForeignKey(r => r.ReactionId).OnDelete(DeleteBehavior.Restrict);
builder.HasIndex(r => new { r.MessageId, r.UserId }).IsUnique(); // Одна реакция от одного юзера builder.HasIndex(r => new { r.MessageId, r.UserId }).IsUnique(); // Одна реакция от одного юзера
@@ -21,4 +23,4 @@ public class MessageReactionConfiguration : IEntityTypeConfiguration<MessageReac
.HasForeignKey(r => r.UserId) .HasForeignKey(r => r.UserId)
.OnDelete(DeleteBehavior.Cascade); .OnDelete(DeleteBehavior.Cascade);
} }
} }
@@ -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<ReactionPack>
{
public void Configure(EntityTypeBuilder<ReactionPack> 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<User>().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<ReactionItem>
{
public void Configure(EntityTypeBuilder<ReactionItem> 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<MediaFile>().WithMany().HasForeignKey(r => r.MediaFileId).OnDelete(DeleteBehavior.Restrict);
builder.HasData(DefaultReactionPack.Items());
}
}
public class UserReactionPackConfiguration : IEntityTypeConfiguration<UserReactionPack>
{
public void Configure(EntityTypeBuilder<UserReactionPack> builder)
{
builder.HasKey(p => new { p.UserId, p.PackId });
builder.HasOne<User>().WithMany().HasForeignKey(p => p.UserId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<ReactionPack>().WithMany().HasForeignKey(p => p.PackId).OnDelete(DeleteBehavior.Cascade);
}
}
public class ChannelAllowedReactionConfiguration : IEntityTypeConfiguration<ChannelAllowedReaction>
{
public void Configure(EntityTypeBuilder<ChannelAllowedReaction> builder)
{
builder.HasKey(r => new { r.GroupId, r.ReactionId });
builder.HasOne<ChatGroup>().WithMany().HasForeignKey(r => r.GroupId).OnDelete(DeleteBehavior.Cascade);
builder.HasOne<ReactionItem>().WithMany().HasForeignKey(r => r.ReactionId).OnDelete(DeleteBehavior.Restrict);
}
}
+12 -1
View File
@@ -3,6 +3,7 @@ using Govor.Domain.Models.Messages;
using Govor.Domain.Models.Users; using Govor.Domain.Models.Users;
using Govor.Domain.Models.Users.Crypto; using Govor.Domain.Models.Users.Crypto;
using Govor.Domain.Configurations; using Govor.Domain.Configurations;
using Govor.Domain.Models.Reactions;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
namespace Govor.Domain; namespace Govor.Domain;
@@ -22,6 +23,11 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
public virtual DbSet<Invitation> Invitations { get; set; } public virtual DbSet<Invitation> Invitations { get; set; }
public virtual DbSet<Message> Messages { get; set; } public virtual DbSet<Message> Messages { get; set; }
public virtual DbSet<ReactionPack> ReactionPacks { get; set; }
public virtual DbSet<ReactionItem> ReactionItems { get; set; }
public virtual DbSet<UserReactionPack> UserReactionPacks { get; set; }
public virtual DbSet<ChannelAllowedReaction> ChannelAllowedReactions { get; set; }
public virtual DbSet<ChatPushNotification> ChatPushNotifications { get; set; }
public virtual DbSet<MessageView> MessageViews { get; set; } public virtual DbSet<MessageView> MessageViews { get; set; }
public virtual DbSet<MessageReaction> MessageReactions { get; set; } public virtual DbSet<MessageReaction> MessageReactions { get; set; }
public virtual DbSet<MediaAttachments> MediaAttachments { get; set; } public virtual DbSet<MediaAttachments> MediaAttachments { get; set; }
@@ -40,7 +46,12 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
modelBuilder.ApplyConfiguration(new InvitationConfiguration()); modelBuilder.ApplyConfiguration(new InvitationConfiguration());
modelBuilder.ApplyConfiguration(new AdminConfiguration()); modelBuilder.ApplyConfiguration(new AdminConfiguration());
modelBuilder.ApplyConfiguration(new MessagesConfiguration()); modelBuilder.ApplyConfiguration(new MessagesConfiguration());
modelBuilder.ApplyConfiguration(new ChatPushNotificationConfiguration());
modelBuilder.ApplyConfiguration(new MessageReactionConfiguration()); 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 MediaAttachmentsConfiguration());
modelBuilder.ApplyConfiguration(new MessageViewConfiguration()); modelBuilder.ApplyConfiguration(new MessageViewConfiguration());
modelBuilder.ApplyConfiguration(new MediaFileConfiguration()); modelBuilder.ApplyConfiguration(new MediaFileConfiguration());
@@ -56,4 +67,4 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
modelBuilder.ApplyConfiguration(new UserPushTokenConfiguration()); modelBuilder.ApplyConfiguration(new UserPushTokenConfiguration());
base.OnModelCreating(modelBuilder); base.OnModelCreating(modelBuilder);
} }
} }
@@ -0,0 +1,878 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<Guid>("ImageId")
.HasColumnType("uuid");
b.Property<bool>("IsChannel")
.HasColumnType("boolean");
b.Property<bool>("IsPrivate")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.HasKey("Id");
b.ToTable("ChatGroups");
});
modelBuilder.Entity("Govor.Domain.Models.Friendship", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("AddresseeId")
.HasColumnType("uuid");
b.Property<Guid>("RequesterId")
.HasColumnType("uuid");
b.Property<int>("Status")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("AddresseeId");
b.HasIndex("RequesterId");
b.ToTable("Friendships");
});
modelBuilder.Entity("Govor.Domain.Models.GroupAdmins", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("GroupId");
b.ToTable("GroupAdmins");
});
modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<DateTime>("EndDate")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<string>("InvitationCode")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)");
b.Property<int>("MaxParticipants")
.HasColumnType("integer");
b.Property<Guid>("UserMakerId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("GroupId");
b.HasIndex("UserMakerId");
b.ToTable("GroupInvitations");
});
modelBuilder.Entity("Govor.Domain.Models.GroupMembership", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("ChatGroupId")
.HasColumnType("uuid");
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<Guid?>("InvitationId")
.HasColumnType("uuid");
b.Property<bool>("IsBanned")
.HasColumnType("boolean");
b.Property<DateTime>("MemberSince")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Code")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("DateCreated")
.HasColumnType("timestamp with time zone");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text");
b.Property<DateTime>("EndDate")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<bool>("IsAdmin")
.HasColumnType("boolean");
b.Property<int>("MaxParticipants")
.HasColumnType("integer");
b.Property<int>("Participants")
.HasColumnType("integer");
b.HasKey("Id");
b.ToTable("Invitations");
});
modelBuilder.Entity("Govor.Domain.Models.MediaFile", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("DateCreated")
.HasColumnType("timestamp with time zone");
b.Property<string>("MediaType")
.IsRequired()
.HasColumnType("text");
b.Property<string>("MineType")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<Guid?>("OwnerId")
.HasColumnType("uuid");
b.Property<int>("OwnerType")
.HasColumnType("integer");
b.Property<Guid>("UploaderId")
.HasColumnType("uuid");
b.Property<string>("Url")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.ToTable("MediaFiles");
});
modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b =>
{
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<int>("Attempts")
.HasColumnType("integer");
b.Property<DateTime>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("MediaFileId")
.HasColumnType("uuid");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid?>("ChatGroupId")
.HasColumnType("uuid");
b.Property<DateTime?>("EditedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("EncryptedContent")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("IsEdited")
.HasColumnType("boolean");
b.Property<Guid?>("PrivateChatId")
.HasColumnType("uuid");
b.Property<Guid>("RecipientId")
.HasColumnType("uuid");
b.Property<int>("RecipientType")
.HasColumnType("integer");
b.Property<Guid?>("ReplyToMessageId")
.HasColumnType("uuid");
b.Property<Guid>("SenderId")
.HasColumnType("uuid");
b.Property<DateTime>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<DateTime>("ReactedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("ReactionCode")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<DateTime>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<Guid>("UserAId")
.HasColumnType("uuid");
b.Property<Guid>("UserBId")
.HasColumnType("uuid");
b.HasKey("Id");
b.ToTable("PrivateChats");
});
modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b =>
{
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.HasKey("UserId");
b.ToTable("Admins");
});
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.OneTimePreKey", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<bool>("IsUsed")
.ValueGeneratedOnAdd()
.HasColumnType("boolean")
.HasDefaultValue(false);
b.Property<byte[]>("PublicKey")
.IsRequired()
.HasColumnType("bytea");
b.Property<DateTime>("UploadedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<byte[]>("PublicSignedPreKey")
.IsRequired()
.HasColumnType("bytea");
b.Property<byte[]>("SignedPreKeySignature")
.IsRequired()
.HasColumnType("bytea");
b.Property<Guid>("UserCryptoSessionId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserCryptoSessionId")
.IsUnique();
b.ToTable("SignedPreKeys");
});
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<byte[]>("PublicIdentityKey")
.IsRequired()
.HasColumnType("bytea");
b.Property<Guid>("UserSessionId")
.HasColumnType("uuid");
b.HasKey("Id");
b.HasIndex("UserSessionId")
.IsUnique();
b.ToTable("UserCryptoSessions");
});
modelBuilder.Entity("Govor.Domain.Models.Users.User", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateOnly>("CreatedOn")
.HasColumnType("date");
b.Property<string>("Description")
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<Guid>("IconId")
.HasColumnType("uuid");
b.Property<Guid>("InviteId")
.HasColumnType("uuid");
b.Property<string>("PasswordHash")
.IsRequired()
.HasMaxLength(128)
.HasColumnType("character varying(128)");
b.Property<string>("Username")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<DateTime>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsActive")
.HasColumnType("boolean");
b.Property<DateTime?>("LastUsedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("Platform")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Provider")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)");
b.Property<string>("Token")
.IsRequired()
.HasMaxLength(512)
.HasColumnType("character varying(512)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<string>("DeviceInfo")
.IsRequired()
.HasMaxLength(256)
.HasColumnType("character varying(256)");
b.Property<DateTime>("ExpiresAt")
.HasColumnType("timestamp with time zone");
b.Property<bool>("IsRevoked")
.HasColumnType("boolean");
b.Property<string>("RefreshTokenHash")
.IsRequired()
.HasColumnType("text");
b.Property<Guid>("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
}
}
}
@@ -0,0 +1,46 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Govor.Domain.Migrations
{
/// <inheritdoc />
public partial class ReliableChatPush : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ChatPushNotifications",
columns: table => new
{
MessageId = table.Column<Guid>(type: "uuid", nullable: false),
NextAttemptAt = table.Column<DateTime>(type: "timestamp with time zone", nullable: false),
Attempts = table.Column<int>(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");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ChatPushNotifications");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -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
{
/// <inheritdoc />
public partial class ReactionPacksAndChannelPolicies : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<long>(
name: "ReactionsVersion",
table: "Messages",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.AddColumn<Guid>(
name: "ReactionId",
table: "MessageReactions",
type: "uuid",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "ReactionMode",
table: "ChatGroups",
type: "integer",
nullable: false,
defaultValue: 0);
migrationBuilder.AddColumn<long>(
name: "ReactionPolicyVersion",
table: "ChatGroups",
type: "bigint",
nullable: false,
defaultValue: 0L);
migrationBuilder.CreateTable(
name: "ReactionPacks",
columns: table => new
{
Id = table.Column<Guid>(type: "uuid", nullable: false),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
Description = table.Column<string>(type: "character varying(500)", maxLength: 500, nullable: false),
ShareCode = table.Column<string>(type: "character varying(32)", maxLength: 32, nullable: false),
IsDefault = table.Column<bool>(type: "boolean", nullable: false),
IsEnabled = table.Column<bool>(type: "boolean", nullable: false),
CreatedByUserId = table.Column<Guid>(type: "uuid", nullable: true),
CreatedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
PackId = table.Column<Guid>(type: "uuid", nullable: false),
Code = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
Name = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
Kind = table.Column<int>(type: "integer", nullable: false),
Emoji = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: true),
MediaFileId = table.Column<Guid>(type: "uuid", nullable: true),
Width = table.Column<int>(type: "integer", nullable: false),
Height = table.Column<int>(type: "integer", nullable: false),
SizeBytes = table.Column<int>(type: "integer", nullable: false),
DurationMilliseconds = table.Column<int>(type: "integer", nullable: false),
IsEnabled = table.Column<bool>(type: "boolean", nullable: false),
CreatedAt = table.Column<DateTime>(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<Guid>(type: "uuid", nullable: false),
PackId = table.Column<Guid>(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<Guid>(type: "uuid", nullable: false),
ReactionId = table.Column<Guid>(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');
""");
}
/// <inheritdoc />
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");
}
}
}
@@ -47,6 +47,12 @@ namespace Govor.Domain.Migrations
.HasMaxLength(100) .HasMaxLength(100)
.HasColumnType("character varying(100)"); .HasColumnType("character varying(100)");
b.Property<int>("ReactionMode")
.HasColumnType("integer");
b.Property<long>("ReactionPolicyVersion")
.HasColumnType("bigint");
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("ChatGroups"); b.ToTable("ChatGroups");
@@ -243,6 +249,24 @@ namespace Govor.Domain.Migrations
b.ToTable("MediaFiles"); b.ToTable("MediaFiles");
}); });
modelBuilder.Entity("Govor.Domain.Models.Messages.ChatPushNotification", b =>
{
b.Property<Guid>("MessageId")
.HasColumnType("uuid");
b.Property<int>("Attempts")
.HasColumnType("integer");
b.Property<DateTime>("NextAttemptAt")
.HasColumnType("timestamp with time zone");
b.HasKey("MessageId");
b.HasIndex("NextAttemptAt");
b.ToTable("ChatPushNotifications");
});
modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b => modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b =>
{ {
b.Property<Guid>("Id") b.Property<Guid>("Id")
@@ -286,6 +310,9 @@ namespace Govor.Domain.Migrations
b.Property<Guid?>("PrivateChatId") b.Property<Guid?>("PrivateChatId")
.HasColumnType("uuid"); .HasColumnType("uuid");
b.Property<long>("ReactionsVersion")
.HasColumnType("bigint");
b.Property<Guid>("RecipientId") b.Property<Guid>("RecipientId")
.HasColumnType("uuid"); .HasColumnType("uuid");
@@ -329,11 +356,16 @@ namespace Govor.Domain.Migrations
.HasMaxLength(64) .HasMaxLength(64)
.HasColumnType("character varying(64)"); .HasColumnType("character varying(64)");
b.Property<Guid?>("ReactionId")
.HasColumnType("uuid");
b.Property<Guid>("UserId") b.Property<Guid>("UserId")
.HasColumnType("uuid"); .HasColumnType("uuid");
b.HasKey("Id"); b.HasKey("Id");
b.HasIndex("ReactionId");
b.HasIndex("UserId"); b.HasIndex("UserId");
b.HasIndex("MessageId", "UserId") b.HasIndex("MessageId", "UserId")
@@ -382,6 +414,336 @@ namespace Govor.Domain.Migrations
b.ToTable("PrivateChats"); b.ToTable("PrivateChats");
}); });
modelBuilder.Entity("Govor.Domain.Models.Reactions.ChannelAllowedReaction", b =>
{
b.Property<Guid>("GroupId")
.HasColumnType("uuid");
b.Property<Guid>("ReactionId")
.HasColumnType("uuid");
b.HasKey("GroupId", "ReactionId");
b.HasIndex("ReactionId");
b.ToTable("ChannelAllowedReactions");
});
modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionItem", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<string>("Code")
.IsRequired()
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<int>("DurationMilliseconds")
.HasColumnType("integer");
b.Property<string>("Emoji")
.HasMaxLength(64)
.HasColumnType("character varying(64)");
b.Property<int>("Height")
.HasColumnType("integer");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<int>("Kind")
.HasColumnType("integer");
b.Property<Guid?>("MediaFileId")
.HasColumnType("uuid");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<Guid>("PackId")
.HasColumnType("uuid");
b.Property<int>("SizeBytes")
.HasColumnType("integer");
b.Property<int>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid");
b.Property<DateTime>("CreatedAt")
.HasColumnType("timestamp with time zone");
b.Property<Guid?>("CreatedByUserId")
.HasColumnType("uuid");
b.Property<string>("Description")
.IsRequired()
.HasMaxLength(500)
.HasColumnType("character varying(500)");
b.Property<bool>("IsDefault")
.HasColumnType("boolean");
b.Property<bool>("IsEnabled")
.HasColumnType("boolean");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)");
b.Property<string>("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<Guid>("UserId")
.HasColumnType("uuid");
b.Property<Guid>("PackId")
.HasColumnType("uuid");
b.HasKey("UserId", "PackId");
b.HasIndex("PackId");
b.ToTable("UserReactionPacks");
});
modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b => modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b =>
{ {
b.Property<Guid>("UserId") b.Property<Guid>("UserId")
@@ -668,6 +1030,15 @@ namespace Govor.Domain.Migrations
b.Navigation("ChatGroup"); 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 => modelBuilder.Entity("Govor.Domain.Models.Messages.MediaAttachments", b =>
{ {
b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile") b.HasOne("Govor.Domain.Models.MediaFile", "MediaFile")
@@ -706,6 +1077,11 @@ namespace Govor.Domain.Migrations
.OnDelete(DeleteBehavior.Cascade) .OnDelete(DeleteBehavior.Cascade)
.IsRequired(); .IsRequired();
b.HasOne("Govor.Domain.Models.Reactions.ReactionItem", null)
.WithMany()
.HasForeignKey("ReactionId")
.OnDelete(DeleteBehavior.Restrict);
b.HasOne("Govor.Domain.Models.Users.User", "User") b.HasOne("Govor.Domain.Models.Users.User", "User")
.WithMany() .WithMany()
.HasForeignKey("UserId") .HasForeignKey("UserId")
@@ -726,6 +1102,60 @@ namespace Govor.Domain.Migrations
.IsRequired(); .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 => modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b =>
{ {
b.HasOne("Govor.Domain.Models.Users.User", "User") b.HasOne("Govor.Domain.Models.Users.User", "User")
@@ -822,6 +1252,11 @@ namespace Govor.Domain.Migrations
b.Navigation("Messages"); b.Navigation("Messages");
}); });
modelBuilder.Entity("Govor.Domain.Models.Reactions.ReactionPack", b =>
{
b.Navigation("Reactions");
});
modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b => modelBuilder.Entity("Govor.Domain.Models.Users.Crypto.UserCryptoSession", b =>
{ {
b.Navigation("OneTimePreKeys"); b.Navigation("OneTimePreKeys");
+3 -1
View File
@@ -9,6 +9,8 @@ public class ChatGroup
public string Description { get; set; } public string Description { get; set; }
public Guid ImageId { get; set; } public Guid ImageId { get; set; }
public bool IsChannel { 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 bool IsPrivate { get; set; }
public List<GroupAdmins> Admins { get; set; } = new(); public List<GroupAdmins> Admins { get; set; } = new();
public List<GroupMembership> Members { get; set; } = new(); public List<GroupMembership> Members { get; set; } = new();
@@ -26,4 +28,4 @@ public class ChatGroup
IsChannel == chatGroup.IsChannel && IsChannel == chatGroup.IsChannel &&
IsPrivate == chatGroup.IsPrivate; IsPrivate == chatGroup.IsPrivate;
} }
} }
+3 -2
View File
@@ -20,5 +20,6 @@ public enum MediaOwnerType
Message = 0, Message = 0,
Avatar = 1, Avatar = 1,
GroupAvatar = 2, GroupAvatar = 2,
System = 3 // (Emoge, icons � e.t.c) System = 3, // (Emoge, icons and other system assets)
} Reaction = 4
}
@@ -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; }
}
+2 -1
View File
@@ -15,6 +15,7 @@ public class Message
public List<MessageView> MessageViews { get; set; } = new List<MessageView>(); public List<MessageView> MessageViews { get; set; } = new List<MessageView>();
public Guid? ReplyToMessageId { get; set; } public Guid? ReplyToMessageId { get; set; }
public long ReactionsVersion { get; set; }
public override bool Equals(object? obj) public override bool Equals(object? obj)
{ {
@@ -36,4 +37,4 @@ public enum RecipientType
{ {
User, User,
Group Group
} }
@@ -13,5 +13,6 @@ public class MessageReaction
public User User { get; set; } public User User { get; set; }
public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:" public string ReactionCode { get; set; } // "❤️", "🔥", "👍", ":custom_emoji:"
public Guid? ReactionId { get; set; }
public DateTime ReactedAt { get; set; } = DateTime.UtcNow; public DateTime ReactedAt { get; set; } = DateTime.UtcNow;
} }
@@ -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();
}
@@ -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; }
}
@@ -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<ReactionItem> Reactions { get; set; } = [];
}
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="NUnit" Version="4.4.0-beta.1" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
<PackageReference Include="Moq" Version="4.20.72" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.10" />
<PackageReference Include="SQLitePCLRaw.bundle_e_sqlite3" Version="3.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.10" />
<Using Include="NUnit.Framework" />
<ProjectReference Include="../Govor.API/Govor.API.csproj" />
<Reference Include="SmartRes"><HintPath>../libs/SmartRes.dll</HintPath></Reference>
</ItemGroup>
</Project>
+37
View File
@@ -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<HubCallerContext>();
var hub = new StubHub();
var invocation = new HubInvocationContext(caller.Object, Mock.Of<IServiceProvider>(), hub,
typeof(StubHub).GetMethod(nameof(StubHub.Echo))!, Array.Empty<object?>());
var filter = new HubExceptionFilter(NullLogger<HubExceptionFilter>.Instance, db.Context);
var invoked = false;
var response = await filter.InvokeMethodAsync(invocation, _ =>
{
invoked = true;
return ValueTask.FromResult<object?>(HubResult<string>.Ok("unexpected"));
});
Assert.That(invoked, Is.False);
Assert.That(response, Is.TypeOf<HubResult<string>>());
Assert.That(((HubResult<string>)response!).Status, Is.EqualTo(HubResultStatus.Unauthorized));
caller.Verify(c => c.Abort(), Times.Once);
}
private sealed class StubHub : Hub
{
public Task<HubResult<string>> Echo() => Task.FromResult(HubResult<string>.Ok("ok"));
}
}
+218
View File
@@ -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<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(_now);
_reader = new MessageReadingService(_db.Context, NullLogger<MessageReadingService>.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<MessageSendingService>.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<MessageRemovingService>.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<MessageEditingService>.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<MessageRemovingService>.Instance);
var removed = await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true));
Assert.That(edited.Exception, Is.TypeOf<UnauthorizedAccessException>());
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<MessageSendingService>.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<UnauthorizedAccessException>());
}
[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<MessageSendingService>.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<UnauthorizedAccessException>());
Assert.That(reply.Exception, Is.TypeOf<ArgumentException>());
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
}
+162
View File
@@ -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<IPushNotificationService> _push = null!;
private Mock<IClientProxy> _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<IClientProxy>();
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
.Callback<string, object?[], CancellationToken>((method, _, _) => _events.Add((method, _targetGroups)))
.Returns(Task.CompletedTask);
var clients = new Mock<IHubClients>();
clients.Setup(c => c.Groups(It.IsAny<IReadOnlyList<string>>()))
.Callback<IReadOnlyList<string>>(groups => _targetGroups = groups.ToArray())
.Returns(_proxy.Object);
var hub = new Mock<IHubContext<ChatsHub>>();
hub.SetupGet(h => h.Clients).Returns(clients.Object);
var chats = new Mock<IUserPrivateChatsGetterService>();
chats.Setup(c => c.GetPrivateChatAsync(_db.ChatId))
.ReturnsAsync(Result<PrivateChat, Error>.Success(_db.Context.PrivateChats.Single()));
var profiles = new Mock<IProfileService>();
profiles.Setup(p => p.GetUserProfileAsync(_db.Alice))
.ReturnsAsync(Result<UserProfile, Error>.Success(new UserProfile { Id = _db.Alice, Username = "Alice" }));
_push = new Mock<IPushNotificationService>();
_push.Setup(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
.ReturnsAsync(Govor.Domain.Common.Result.Success());
_notifier = new ChatNotificationService(hub.Object, _push.Object, chats.Object, profiles.Object,
_db.Context, NullLogger<ChatNotificationService>.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<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _db.Bob })),
"Alice", "hello", "chat_messages", $"chat_{_db.ChatId}",
It.Is<Dictionary<string, string>?>(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<IEnumerable<Guid>>(ids => ids.SequenceEqual(new[] { _db.Bob })),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<Dictionary<string, string>?>()), Times.Once);
}
[Test]
public async Task SignalRFailureStillAttemptsPushAndProviderFailureDoesNotFailSavedSend()
{
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
.ThrowsAsync(new InvalidOperationException("offline"));
_push.Setup(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()))
.ThrowsAsync(new InvalidOperationException("provider unavailable"));
await _notifier.NotifyMessageSentAsync(Message());
Assert.That(await _notifier.DeliverPushAsync(Message()), Is.False);
_push.Verify(p => p.SendToUsersAsync(It.IsAny<IEnumerable<Guid>>(), It.IsAny<string>(), It.IsAny<string>(),
It.IsAny<string>(), It.IsAny<string>(), It.IsAny<Dictionary<string, string>?>()), 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"
};
}
+122
View File
@@ -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<INowDateTimeProvider> _clock = null!;
private PushTokenService _tokens = null!;
private DateTime _now;
[SetUp]
public void SetUp()
{
_db = new TestDatabase();
_now = DateTime.UtcNow.AddMinutes(1);
_clock = new Mock<INowDateTimeProvider>();
_clock.SetupGet(c => c.Now).Returns(() => _now);
_tokens = new PushTokenService(_db.Context, _clock.Object, NullLogger<PushTokenService>.Instance);
}
[TearDown]
public void TearDown() => _db.Dispose();
[Test]
public async Task SavedMessageHasDurablePushAndFailureRetriesAfterBackoff()
{
var sender = new MessageSendingService(_db.Context, NullLogger<MessageSendingService>.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<IChatNotificationService>();
notifier.SetupSequence(n => n.DeliverPushAsync(It.IsAny<UserMessageResponse>())).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<UserMessageResponse>()), 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<UserMessageResponse>()), 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<ProfileService>.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;
}
}
+81
View File
@@ -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<Rgba32>(512, 256, Color.Red.ToPixel<Rgba32>());
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("<svg xmlns='http://www.w3.org/2000/svg'/>"u8.ToArray())).IsFailure, Is.True);
Assert.That((await _processor.ProcessAsync(new byte[ReactionMediaLimits.MaxUploadBytes + 1])).IsFailure, Is.True);
using var source = new Image<Rgba32>(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<byte[]> GifAsync(int frames, int delay, int dimension = 16)
{
using var image = new Image<Rgba32>(dimension, dimension, Color.Red.ToPixel<Rgba32>());
image.Frames.RootFrame.Metadata.GetGifMetadata().FrameDelay = delay;
for (var i = 1; i < frames; i++)
{
using var next = new Image<Rgba32>(dimension, dimension, (i % 2 == 0 ? Color.Red : Color.Blue).ToPixel<Rgba32>());
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();
}
}
+194
View File
@@ -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<INowDateTimeProvider>();
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<ReactionPackService>.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<Guid>());
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<Guid>())).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<Guid>())).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<string, byte[]> Files { get; } = new();
public Task<string> SaveAsync(byte[] data, string fileName)
{
var path = Guid.NewGuid().ToString("N") + fileName;
Files.Add(path, data.ToArray());
return Task.FromResult(path);
}
public Task<Stream> LoadAsync(string url) => Task.FromResult<Stream>(new MemoryStream(Files[url], writable: false));
public Task RemoveAsync(string url) { Files.Remove(url); return Task.CompletedTask; }
}
+236
View File
@@ -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<IChatNotificationService> _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<IChatNotificationService>();
_notifier.Setup(n => n.NotifyChatReadAsync(It.IsAny<ChatReadResponse>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyMessageReactionsChangedAsync(It.IsAny<MessageReactionsChangedResponse>())).Returns(Task.CompletedTask);
_notifier.Setup(n => n.NotifyChannelReactionPolicyChangedAsync(It.IsAny<ChannelReactionPolicyResponse>())).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<ChatReadResponse>();
Assert.That(body!.ReadCount, Is.EqualTo(1));
Assert.That(body.UnreadCount, Is.Zero);
_notifier.Verify(n => n.NotifyChatReadAsync(It.Is<ChatReadResponse>(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<List<ReactionPackResponse>>("/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<MessageReactionsChangedResponse>();
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<MessageReactionsChangedResponse>()), 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<MessageReactionsChangedResponse>(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<ReactionPackResponse>())!;
using var image = new Image<Rgba32>(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<ReactionItemResponse>())!;
Assert.That(item.Kind, Is.EqualTo(ReactionKind.Image));
Assert.That(item.Width, Is.EqualTo(128));
Authorize();
var shared = await _client.GetFromJsonAsync<ReactionPackResponse>(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<ChatsHub>(scope.ServiceProvider);
var caller = new Mock<HubCallerContext>();
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<Program>
{
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<DbContextOptions<GovorDbContext>>();
services.RemoveAll<IDbContextOptionsConfiguration<GovorDbContext>>();
services.AddDbContext<GovorDbContext>(db.ConfigureOptions);
services.RemoveAll<IChatNotificationService>();
services.AddSingleton(notifier);
services.RemoveAll<IStorageService>();
services.AddSingleton<IStorageService>(new TestReactionStorage());
});
}
}
}
@@ -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<INowDateTimeProvider>();
clock.SetupGet(c => c.Now).Returns(DateTime.UtcNow);
using var other = db.CreateContext();
var competingReader = new MessageReadingService(other, NullLogger<MessageReadingService>.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<MessageReadingService>.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<INowDateTimeProvider>();
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<MessageReadingService>.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<GovorDbContext>()
.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<Task> callback) : DbCommandInterceptor
{
private bool _invoked;
public override async ValueTask<InterceptionResult<int>> NonQueryExecutingAsync(DbCommand command,
CommandEventData eventData, InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
if (!_invoked && command.CommandText.StartsWith("INSERT INTO \"MessageViews\"", StringComparison.Ordinal))
{
_invoked = true;
await callback();
}
return result;
}
}
}
+106
View File
@@ -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<GovorDbContext>();
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();
}
}
+7
View File
@@ -0,0 +1,7 @@
<Solution>
<Project Path="Govor.API/Govor.API.csproj" />
<Project Path="Govor.Application/Govor.Application.csproj" />
<Project Path="Govor.Contracts/Govor.Contracts.csproj" />
<Project Path="Govor.Domain/Govor.Domain.csproj" />
<Project Path="Govor.Server.Tests/Govor.Server.Tests.csproj" />
</Solution>
+38 -46
View File
@@ -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 Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
coverY: 0
---
# The invitation code RU Источник: [Govor.API/Program.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Program.cs).
### Что это такое
**Код приглашения** — это временный механизм доступа, действующий на этапах **альфа-** и **бета-тестирования** мессенджера **Говор**.\
Он используется для **ограничения количества аккаунтов** и **контроля числа пользователей**, получающих ранний доступ к продукту.
Пока Говор находится в стадии активной разработки и внутреннего тестирования, регистрация новых пользователей возможна **только при наличии действующего кода приглашения**.
### Как получить код приглашения
Коды приглашения **создаются администрацией проекта** и **выдаются вручную** по мере готовности новых тестовых слотов.
Чтобы запросить код приглашения:
1. Свяжитесь с командой разработчиков.
2. Кратко опишите, зачем вы хотите протестировать Говор.
3. Дождитесь ответа с вашим уникальным кодом.
📩 **Контакт для запроса:**\
`BurntRoostersOfficial@protonmail.com`
### Как выглядит код
Код приглашения представляет собой **уникальный случайно сгенерированный идентификатор** (объект `Guid`).\
Пример:
```
c7a5f1b3-8c64-47e2-9e3e-b7df6a2b021f
```
### Ограничения
Каждый код приглашения имеет:
* 🔹 **Ограниченное количество регистраций.**\
После достижения лимита использование кода становится невозможным.
* ⏳ **Ограниченный срок действия.**\
По истечении времени жизни код автоматически теряет актуальность.
### После официального релиза
После выхода **первой стабильной версии Говора** система кодов приглашений будет **отключена**, и регистрация станет **открытой для всех пользователей**.
+28 -28
View File
@@ -1,29 +1,29 @@
# Table of contents # Оглавление
* [The invitation code RU](README.md) * [Govor.API — обзор](README.md)
* [Исправления серверной части](server-fixes.md)
## Endpoints * [Запуск и конфигурация](getting-started.md)
* [Архитектура и границы](architecture.md)
* [Authentication](endpoints/authentication/README.md) * [Аутентификация](endpoints/authentication/README.md)
* [AuthController](endpoints/authentication/authcontroller.md) * [Регистрация и вход](endpoints/authentication/authcontroller.md)
* [RefreshController](endpoints/authentication/refreshcontroller.md) * [Обновление токенов](endpoints/authentication/refreshcontroller.md)
* [SessionController](endpoints/sessioncontroller.md) * [Сессии](endpoints/sessioncontroller.md)
* [FriendshipController](endpoints/friendshipcontroller.md) * [Друзья и поиск](endpoints/friendshipcontroller.md)
* [FriendsRequestQueryController](endpoints/friendsrequestquerycontroller.md) * [Списки заявок в друзья](endpoints/friendsrequestquerycontroller.md)
* [MediaController](endpoints/mediacontroller.md) * [Личные чаты](endpoints/private-chats.md)
* [ChatLoadController](endpoints/chatloadcontroller.md) * [История сообщений](endpoints/chatloadcontroller.md)
* [OnlinePingingController(не работает)](endpoints/onlinepingingcontroller-ne-rabotaet.md) * [Прочтение сообщений и счётчики](endpoints/message-read.md)
* [Реакции, паки и настройки каналов](endpoints/reactions.md)
## SignalR * [Медиа](endpoints/mediacontroller.md)
* [Профиль и аватар](endpoints/profile.md)
* [PresenceHub](signalr/presencehub.md) * [Push-уведомления](endpoints/push.md)
* [ChatHub](signalr/chathub.md) * [HTTP-присутствие — ограничения](endpoints/onlinepingingcontroller-ne-rabotaet.md)
* [Ключи сессий — экспериментальный API](endpoints/session-keys.md)
*** * [Администрирование и незавершённые группы](endpoints/admin-and-groups.md)
* [ChatsHub — сообщения](signalr/chathub.md)
* [FriendsHub](friendshub/README.md) * [PresenceHub — online и offline](signalr/presencehub.md)
* [FriendsHub Client (Java)](friendshub/friendshub-client-java.md) * [FriendsHub — заявки](friendshub/README.md)
* [Клиент SignalR на C# для MAUI](friendshub/friendshub-client-java.md)
## Code Docs * [ProfileHub — изменения профиля](signalr/profilehub.md)
* [Ответы, ошибки и сериализация](code-docs/hubresult-less-than-t-greater-than.md)
* [HubResult\<T>](code-docs/hubresult-less-than-t-greater-than.md) * [Диагностика и порядок исправлений](diagnostics.md)

Some files were not shown because too many files have changed in this diff Show More