mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 21:09:00 +00:00
Add primitive groups and required channel
Adds server-side group and channel management, private invitations, member moderation, avatar handling, and required-channel configuration. This change also introduces SignalR group profile/member notifications, updates registration to atomically join required channels, and adds EF migration and test coverage for group membership, permissions, and invitation expiry rules.
This commit is contained in:
@@ -65,6 +65,8 @@ public static class ConfigurationProgramExtensions
|
||||
services.AddScoped<IPingHandlerService, PingHandlerService>();
|
||||
|
||||
services.AddScoped<IUserGroupsGetterService, UserGroupsGetterService>();
|
||||
services.AddScoped<IGroupManagementService, GroupManagementService>();
|
||||
services.AddScoped<IGroupAvatarService, GroupAvatarService>();
|
||||
|
||||
//services.AddScoped<IMessageCommandService, MessageCommandService>();
|
||||
services.AddScoped<IMessageSendingService, MessageSendingService>();
|
||||
|
||||
@@ -9,6 +9,7 @@ using Govor.Application.Messages.Parameters;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Application.Reactions;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using Govor.Application.Groups;
|
||||
|
||||
namespace Govor.API.Common.Mapping;
|
||||
|
||||
@@ -22,6 +23,11 @@ public class MappingProfile : Profile
|
||||
CreateMap<ReactionCount, ReactionCountResponse>();
|
||||
CreateMap<MessageReactionState, MessageReactionsChangedResponse>();
|
||||
CreateMap<ChannelReactionPolicy, ChannelReactionPolicyResponse>();
|
||||
CreateMap<GroupSummary, GroupResponse>()
|
||||
.IncludeMembers(s => s.Group);
|
||||
CreateMap<ChatGroup, GroupResponse>();
|
||||
CreateMap<GroupMember, GroupMemberResponse>();
|
||||
CreateMap<GroupInvitation, GroupInvitationResponse>();
|
||||
CreateMap<Message, MessageResponse>();
|
||||
CreateMap<MediaAttachments, MediaAttachmentResponse>();
|
||||
CreateMap<MessageReaction, MessageReactionResponse>();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Application.Infrastructure.Extensions;
|
||||
using Govor.Contracts.Requests;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Govor.API.Controllers.AdminStuff;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin")]
|
||||
[Route("api/admin/required-channel")]
|
||||
public class RequiredChannelController(IGroupManagementService groups, ICurrentUserService currentUser,
|
||||
IChatNotificationService notifier) : ControllerBase
|
||||
{
|
||||
[HttpGet]
|
||||
public async Task<IActionResult> Get() => (await groups.GetRequiredChannelAsync(currentUser.GetCurrentUserId()))
|
||||
.Map(s => new { channelId = s.RequiredChannelId, allowLeave = s.AllowLeave }).ToActionResult();
|
||||
|
||||
[HttpPut]
|
||||
public async Task<IActionResult> Set([FromBody] RequiredChannelRequest request)
|
||||
{
|
||||
var actorId = currentUser.GetCurrentUserId();
|
||||
var previous = await groups.GetRequiredChannelAsync(actorId);
|
||||
if (previous.IsFailure) return previous.ToActionResult();
|
||||
var result = await groups.SetRequiredChannelAsync(actorId, request.ChannelId, request.AllowLeave);
|
||||
if (result.IsSuccess)
|
||||
foreach (var channelId in new[] { previous.Value.RequiredChannelId, result.Value.RequiredChannelId }.OfType<Guid>().Distinct())
|
||||
await notifier.NotifyGroupProfileChangedAsync(channelId);
|
||||
return result.Map(s => new { channelId = s.RequiredChannelId, allowLeave = s.AllowLeave }).ToActionResult();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Authentication;
|
||||
using Govor.Application.Users.UserSessions;
|
||||
using Govor.Contracts.Requests;
|
||||
@@ -17,17 +18,20 @@ public class AuthController : Controller
|
||||
private IInvitesService _invitesService;
|
||||
private IAccountService _accountService;
|
||||
private ILogger<AuthController> _logger;
|
||||
private readonly IChatNotificationService _notifier;
|
||||
|
||||
public AuthController(
|
||||
IAccountService accountService,
|
||||
IInvitesService invitesService,
|
||||
IUserSessionOpener userSessionOpener,
|
||||
ILogger<AuthController> logger)
|
||||
ILogger<AuthController> logger,
|
||||
IChatNotificationService notifier)
|
||||
{
|
||||
_userSession = userSessionOpener;
|
||||
_accountService = accountService;
|
||||
_invitesService = invitesService;
|
||||
_logger = logger;
|
||||
_notifier = notifier;
|
||||
}
|
||||
|
||||
[HttpPost("register")] // api/auth/register
|
||||
@@ -38,7 +42,12 @@ public class AuthController : Controller
|
||||
var result = await _invitesService.ValidateAsync(request.InviteLink)
|
||||
.BindAsync(invite => _accountService.RegistrationAsync(request.Name, request.Password, invite))
|
||||
.TapAsync(user => _logger.LogInformation("User {Username} ({Id}) registered successfully", user.Username, user.Id))
|
||||
.BindAsync(user => _userSession.OpenSessionAsync(user, request.DeviceInfo));
|
||||
.BindAsync(async user =>
|
||||
{
|
||||
// Registration has committed the required-channel membership at this point.
|
||||
await _notifier.NotifyUserJoinedGroupsAsync(user.Id);
|
||||
return await _userSession.OpenSessionAsync(user, request.DeviceInfo);
|
||||
});
|
||||
|
||||
if (result.IsFailure)
|
||||
{
|
||||
@@ -74,4 +83,4 @@ public class AuthController : Controller
|
||||
|
||||
return result.ToActionResult();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using AutoMapper;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Application.Infrastructure.Extensions;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using Govor.Application.Reactions;
|
||||
using Govor.Contracts.Requests;
|
||||
using Govor.Contracts.Responses;
|
||||
using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
[Route("api/groups")]
|
||||
public class GroupsController(IGroupManagementService groups, ICurrentUserService currentUser, IMapper mapper,
|
||||
GovorDbContext context, IMessageRemovingService remover, IChatNotificationService notifier, IGroupAvatarService avatars) : ControllerBase
|
||||
{
|
||||
private Guid ActorId => currentUser.GetCurrentUserId();
|
||||
|
||||
[HttpPost]
|
||||
public async Task<IActionResult> Create([FromBody] CreateGroupRequest request)
|
||||
{
|
||||
var result = await groups.CreateAsync(ActorId, request.Name, request.Description, request.IsPrivate, request.IsChannel);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupMemberChangedAsync(result.Value.Group.Id, ActorId);
|
||||
return result.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
}
|
||||
|
||||
[HttpGet("search")]
|
||||
public async Task<IActionResult> Search([FromQuery, MaxLength(100)] string q = "",
|
||||
[FromQuery, Range(0, int.MaxValue)] int skip = 0, [FromQuery, Range(1, 100)] int take = 50) =>
|
||||
Ok(mapper.Map<List<GroupResponse>>(await groups.SearchAsync(ActorId, q, skip, 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<GroupResponse>>(await groups.MineAsync(ActorId, skip, take)));
|
||||
|
||||
[HttpGet("{groupId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid groupId) => (await groups.GetAsync(ActorId, groupId))
|
||||
.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
|
||||
[HttpPut("{groupId:guid}")]
|
||||
public async Task<IActionResult> Update(Guid groupId, [FromBody] UpdateGroupRequest request)
|
||||
{
|
||||
var result = await groups.UpdateAsync(ActorId, groupId, request.Name, request.Description, request.IsPrivate);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupProfileChangedAsync(groupId);
|
||||
return result.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
}
|
||||
|
||||
[HttpPost("{groupId:guid}/join")]
|
||||
public async Task<IActionResult> Join(Guid groupId)
|
||||
{
|
||||
var result = await groups.JoinPublicAsync(ActorId, groupId);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupMemberChangedAsync(groupId, ActorId);
|
||||
return result.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
}
|
||||
|
||||
[HttpPost("{groupId:guid}/avatar")]
|
||||
[RequestSizeLimit(2_200_000)]
|
||||
public async Task<IActionResult> UploadAvatar(Guid groupId, [FromForm] GroupAvatarUploadRequest request)
|
||||
{
|
||||
if (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);
|
||||
var result = await avatars.UploadAsync(ActorId, groupId, buffer.ToArray(), HttpContext.RequestAborted);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupProfileChangedAsync(groupId);
|
||||
return result.Map(id => new { imageId = id, mediaUrl = $"/api/media/download/{id}" }).ToActionResult();
|
||||
}
|
||||
|
||||
[HttpDelete("{groupId:guid}/avatar")]
|
||||
public async Task<IActionResult> RemoveAvatar(Guid groupId)
|
||||
{
|
||||
var result = await avatars.RemoveAsync(ActorId, groupId);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupProfileChangedAsync(groupId);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
|
||||
[HttpDelete("{groupId:guid}/members/me")]
|
||||
public Task<IActionResult> Leave(Guid groupId) => ChangeMemberAsync(groupId, ActorId, groups.LeaveAsync(ActorId, groupId));
|
||||
|
||||
[HttpGet("{groupId:guid}/members")]
|
||||
public async Task<IActionResult> Members(Guid groupId, [FromQuery] bool bannedOnly = false,
|
||||
[FromQuery, Range(0, int.MaxValue)] int skip = 0, [FromQuery, Range(1, 100)] int take = 50) =>
|
||||
(await groups.MembersAsync(ActorId, groupId, bannedOnly, skip, take))
|
||||
.Map(m => mapper.Map<List<GroupMemberResponse>>(m)).ToActionResult();
|
||||
|
||||
[HttpPut("{groupId:guid}/members/{userId:guid}/administrator")]
|
||||
public Task<IActionResult> Promote(Guid groupId, Guid userId) => ChangeMemberAsync(groupId, userId, groups.SetAdministratorAsync(ActorId, groupId, userId, true));
|
||||
|
||||
[HttpDelete("{groupId:guid}/members/{userId:guid}/administrator")]
|
||||
public Task<IActionResult> Demote(Guid groupId, Guid userId) => ChangeMemberAsync(groupId, userId, groups.SetAdministratorAsync(ActorId, groupId, userId, false));
|
||||
|
||||
[HttpPut("{groupId:guid}/members/{userId:guid}/ban")]
|
||||
public Task<IActionResult> Ban(Guid groupId, Guid userId) => ChangeMemberAsync(groupId, userId, groups.SetBanAsync(ActorId, groupId, userId, true));
|
||||
|
||||
[HttpDelete("{groupId:guid}/members/{userId:guid}/ban")]
|
||||
public Task<IActionResult> Unban(Guid groupId, Guid userId) => ChangeMemberAsync(groupId, userId, groups.SetBanAsync(ActorId, groupId, userId, false));
|
||||
|
||||
[HttpPost("{groupId:guid}/ownership/{userId:guid}")]
|
||||
public async Task<IActionResult> Transfer(Guid groupId, Guid userId)
|
||||
{
|
||||
var result = await groups.TransferOwnershipAsync(ActorId, groupId, userId);
|
||||
if (result.IsSuccess)
|
||||
{
|
||||
await notifier.NotifyGroupProfileChangedAsync(groupId);
|
||||
await notifier.NotifyGroupMemberChangedAsync(groupId, ActorId);
|
||||
await notifier.NotifyGroupMemberChangedAsync(groupId, userId);
|
||||
}
|
||||
return result.ToActionResult();
|
||||
}
|
||||
|
||||
private async Task<IActionResult> ChangeMemberAsync(Guid groupId, Guid userId, Task<Result<Unit, Error>> mutation)
|
||||
{
|
||||
var result = await mutation;
|
||||
if (result.IsSuccess) await notifier.NotifyGroupMemberChangedAsync(groupId, userId);
|
||||
return result.ToActionResult();
|
||||
}
|
||||
|
||||
[HttpPost("{groupId:guid}/invitations")]
|
||||
public async Task<IActionResult> CreateInvitation(Guid groupId, [FromBody] CreateGroupInvitationRequest request) =>
|
||||
(await groups.CreateInvitationAsync(ActorId, groupId, request.ValidForDays, request.MaxParticipants, request.Description))
|
||||
.Map(i => mapper.Map<GroupInvitationResponse>(i)).ToActionResult();
|
||||
|
||||
[HttpGet("{groupId:guid}/invitations")]
|
||||
public async Task<IActionResult> Invitations(Guid groupId) => (await groups.InvitationsAsync(ActorId, groupId))
|
||||
.Map(i => mapper.Map<List<GroupInvitationResponse>>(i)).ToActionResult();
|
||||
|
||||
[HttpDelete("{groupId:guid}/invitations/{invitationId:guid}")]
|
||||
public async Task<IActionResult> RevokeInvitation(Guid groupId, Guid invitationId) =>
|
||||
(await groups.RevokeInvitationAsync(ActorId, groupId, invitationId)).ToActionResult();
|
||||
|
||||
[HttpDelete("{groupId:guid}/messages/{messageId:guid}")]
|
||||
public async Task<IActionResult> RemoveMessage(Guid groupId, Guid messageId)
|
||||
{
|
||||
if (!await context.Messages.AnyAsync(m => m.Id == messageId && m.RecipientId == groupId && m.RecipientType == RecipientType.Group))
|
||||
return NotFound();
|
||||
var result = await remover.DeleteMessageAsync(new DeleteMessage(ActorId, messageId, ForceRemove: true));
|
||||
if (result.IsFailure) return result.ToActionResult();
|
||||
var message = result.Value;
|
||||
await notifier.NotifyMessageRemovedAsync(new MessageRemovedResponse
|
||||
{
|
||||
MessageId = message.Id, SenderId = message.SenderId, RecipientId = groupId,
|
||||
RecipientType = RecipientType.Group, RequestType = Govor.Contracts.Requests.SignalR.RemoveMessageRequestType.ForceRemove
|
||||
});
|
||||
return NoContent();
|
||||
}
|
||||
}
|
||||
|
||||
public class GroupAvatarUploadRequest
|
||||
{
|
||||
[Required] public IFormFile File { get; set; }
|
||||
}
|
||||
@@ -1,45 +1,33 @@
|
||||
using AutoMapper;
|
||||
using Govor.API.Common.Extensions;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Application.Infrastructure.Extensions;
|
||||
using Govor.Contracts.Responses;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Govor.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("invite")]
|
||||
public class InviteController : ControllerBase
|
||||
[Authorize(Roles = "Admin,User")]
|
||||
[Route("api/group-invites")]
|
||||
public class InviteController(IGroupManagementService groups, ICurrentUserService currentUser, IMapper mapper,
|
||||
IChatNotificationService notifier) : ControllerBase
|
||||
{
|
||||
private readonly IGroupService _groupService;
|
||||
private readonly ILogger<InviteController> _logger;
|
||||
private readonly ICurrentUserService _currentUser;
|
||||
public InviteController(IGroupService groupService,
|
||||
ILogger<InviteController> logger)
|
||||
{
|
||||
_groupService = groupService;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[Authorize]
|
||||
// GET only previews: link scanners/prefetch must not join an account to a group.
|
||||
[HttpGet("{code}")]
|
||||
public async Task<IActionResult> JoinGroup(string code)
|
||||
{
|
||||
try
|
||||
{
|
||||
var groupRes = await _groupService.AddUserToGroupByInvitationAsync(_currentUser.GetCurrentUserId(), code);
|
||||
|
||||
var group = _groupService.GetGroupByInviteCode(code);
|
||||
[HttpGet("/invite/{code}")]
|
||||
public async Task<IActionResult> Preview(string code) => (await groups.PreviewInvitationAsync(currentUser.GetCurrentUserId(), code))
|
||||
.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
groupId = group.Id,
|
||||
name = group.Name,
|
||||
isChannel = group.IsChannel
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, ex.Message);
|
||||
return StatusCode(500, ex.Message);
|
||||
}
|
||||
[HttpPost("{code}/join")]
|
||||
[HttpPost("/invite/{code}/join")]
|
||||
public async Task<IActionResult> Join(string code)
|
||||
{
|
||||
var actorId = currentUser.GetCurrentUserId();
|
||||
var result = await groups.JoinByInvitationAsync(actorId, code);
|
||||
if (result.IsSuccess) await notifier.NotifyGroupMemberChangedAsync(result.Value.Group.Id, actorId);
|
||||
return result.Map(g => mapper.Map<GroupResponse>(g)).ToActionResult();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ public static class ChatHubConstants
|
||||
public const string ChatRead = "ChatRead";
|
||||
public const string MessageReactionsChanged = "MessageReactionsChanged";
|
||||
public const string ChannelReactionPolicyChanged = "ChannelReactionPolicyChanged";
|
||||
public const string GroupProfileChanged = "GroupProfileChanged";
|
||||
public const string GroupMemberChanged = "GroupMemberChanged";
|
||||
|
||||
public static string GetUserGroup(Guid userId) => userId.ToString();
|
||||
public static string GetSessionGroup(Guid sessionId) => $"session_{sessionId}";
|
||||
|
||||
@@ -5,6 +5,7 @@ using Govor.Contracts.Responses.SignalR;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
@@ -117,7 +118,40 @@ public class ChatNotificationService : IChatNotificationService
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(response.RecipientId,
|
||||
response.RecipientType, ChatHubConstants.MessageEdited, response));
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid chatId, RecipientType type, string method, object payload)
|
||||
public Task NotifyGroupProfileChangedAsync(Guid groupId) =>
|
||||
TryNotifyAsync(() => NotifyParticipantsAsync(groupId, RecipientType.Group,
|
||||
ChatHubConstants.GroupProfileChanged, new GroupProfileChangedResponse { GroupId = groupId }));
|
||||
|
||||
public Task NotifyGroupMemberChangedAsync(Guid groupId, Guid userId) => TryNotifyAsync(async () =>
|
||||
{
|
||||
var member = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == groupId && m.UserId == userId)
|
||||
.Select(m => new
|
||||
{
|
||||
m.IsBanned,
|
||||
IsOwner = _context.ChatGroups.Any(g => g.Id == groupId && g.OwnerUserId == userId),
|
||||
IsAdmin = _context.GroupAdmins.Any(a => a.GroupId == groupId && a.UserId == userId)
|
||||
}).FirstOrDefaultAsync();
|
||||
var response = new GroupMemberChangedResponse
|
||||
{
|
||||
GroupId = groupId, UserId = userId,
|
||||
Status = member is null ? GroupMemberStatus.Left : member.IsBanned ? GroupMemberStatus.Banned : GroupMemberStatus.Active,
|
||||
Role = member is null || member.IsBanned ? null : member.IsOwner ? GroupRole.Owner : member.IsAdmin ? GroupRole.Admin : GroupRole.Member
|
||||
};
|
||||
// The affected user must learn about a ban/leave even after losing membership.
|
||||
// Only this membership event includes them; profile and chat events do not.
|
||||
await NotifyParticipantsAsync(groupId, RecipientType.Group, ChatHubConstants.GroupMemberChanged, response, userId);
|
||||
});
|
||||
|
||||
public Task NotifyUserJoinedGroupsAsync(Guid userId) => TryNotifyAsync(async () =>
|
||||
{
|
||||
var groupIds = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.UserId == userId && !m.IsBanned).Select(m => m.GroupId).ToListAsync();
|
||||
foreach (var groupId in groupIds)
|
||||
await NotifyGroupMemberChangedAsync(groupId, userId);
|
||||
});
|
||||
|
||||
private async Task NotifyParticipantsAsync(Guid chatId, RecipientType type, string method, object payload, Guid? affectedUserId = null)
|
||||
{
|
||||
// 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.
|
||||
@@ -133,6 +167,8 @@ public class ChatNotificationService : IChatNotificationService
|
||||
participants = await _context.GroupMemberships.AsNoTracking()
|
||||
.Where(m => m.GroupId == chatId && !m.IsBanned).Select(m => m.UserId).Distinct().ToListAsync();
|
||||
|
||||
if (affectedUserId.HasValue)
|
||||
participants.Add(affectedUserId.Value);
|
||||
if (participants.Count > 0)
|
||||
await NotifyUsersAsync(participants, method, payload);
|
||||
}
|
||||
@@ -142,7 +178,7 @@ public class ChatNotificationService : IChatNotificationService
|
||||
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();
|
||||
.Select(s => s.Id).Distinct().ToListAsync();
|
||||
if (sessions.Count > 0)
|
||||
await _hubContext.Clients.Groups(sessions.Select(ChatHubConstants.GetSessionGroup).ToList())
|
||||
.SendAsync(method, payload);
|
||||
@@ -156,7 +192,7 @@ public class ChatNotificationService : IChatNotificationService
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Failed to deliver chat notification; clients can resync from history.");
|
||||
_logger.LogError(ex, "Failed to deliver chat notification; clients can resync through HTTP.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,4 +12,7 @@ public interface IChatNotificationService
|
||||
Task NotifyChannelReactionPolicyChangedAsync(ChannelReactionPolicyResponse response);
|
||||
Task NotifyMessageRemovedAsync(MessageRemovedResponse response);
|
||||
Task NotifyMessageEditedAsync(MessageEditResponse response);
|
||||
Task NotifyGroupProfileChangedAsync(Guid groupId);
|
||||
Task NotifyGroupMemberChangedAsync(Guid groupId, Guid userId);
|
||||
Task NotifyUserJoinedGroupsAsync(Guid userId);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Govor.Application.Authentication.Exceptions;
|
||||
using Govor.Application.Infrastructure.Validators;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Users;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
@@ -16,17 +17,20 @@ public class AuthService : IAccountService
|
||||
private readonly IPasswordHasher _passwordHasher;
|
||||
private readonly IUserNameExistValidator _userNameExistValidator;
|
||||
private readonly IUsernameValidator _usernameValidator;
|
||||
private readonly INowDateTimeProvider _clock;
|
||||
|
||||
public AuthService(
|
||||
GovorDbContext context,
|
||||
IUserNameExistValidator existValidator,
|
||||
IPasswordHasher passwordHasher,
|
||||
IUsernameValidator usernameValidator)
|
||||
IUsernameValidator usernameValidator,
|
||||
INowDateTimeProvider clock)
|
||||
{
|
||||
_context = context;
|
||||
_userNameExistValidator = existValidator;
|
||||
_passwordHasher = passwordHasher;
|
||||
_usernameValidator = usernameValidator;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
public async Task<Result<User, Error>> RegistrationAsync(string name, string password, Invitation invitation)
|
||||
@@ -46,30 +50,63 @@ public class AuthService : IAccountService
|
||||
|
||||
var passwordHash = _passwordHasher.Hash(password);
|
||||
|
||||
var user = new User
|
||||
var operationId = Guid.NewGuid();
|
||||
return await _context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Username = name,
|
||||
PasswordHash = passwordHash,
|
||||
Description = string.Empty,
|
||||
CreatedOn = DateOnly.FromDateTime(DateTime.UtcNow),
|
||||
IconId = Guid.Empty,
|
||||
WasOnline = DateTime.UtcNow,
|
||||
InviteId = invitation.Id
|
||||
};
|
||||
|
||||
|
||||
await _context.Users.AddAsync(user);
|
||||
|
||||
await SetRoleAsync(user, invitation);
|
||||
|
||||
invitation.Participants += 1;
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return user; // Success
|
||||
var completed = await _context.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Id == operationId);
|
||||
if (completed is not null) return Result.Success(completed);
|
||||
await using var transaction = await _context.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
// Serialize configuration changes with registration: account and membership commit together.
|
||||
await _context.ServerCommunitySettings.Where(s => s.Id == 1)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(s => s.AllowLeave, s => s.AllowLeave));
|
||||
|
||||
var settings = await _context.ServerCommunitySettings.AsNoTracking().SingleAsync(s => s.Id == 1);
|
||||
|
||||
if (settings.RequiredChannelId.HasValue &&
|
||||
!await _context.ChatGroups.AnyAsync(g => g.Id == settings.RequiredChannelId && g.IsChannel))
|
||||
return Result.Failure<User>(Error.Validation("Auth.RequiredChannelUnavailable", "The required channel is unavailable."));
|
||||
|
||||
var now = _clock.Now;
|
||||
|
||||
var reserved = await _context.Invitations.Where(i => i.Id == invitation.Id &&
|
||||
i.IsActive && i.EndDate > now && i.Participants < i.MaxParticipants &&
|
||||
_context.Users.Count(u => u.InviteId == i.Id) < i.MaxParticipants)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(i => i.Participants, i => i.Participants + 1));
|
||||
|
||||
if (reserved == 0)
|
||||
return Result.Failure<User>(Error.Validation("Auth.InvitationUnavailable", "Registration invitation is expired or full."));
|
||||
|
||||
var user = new User
|
||||
{
|
||||
Id = operationId, Username = name, PasswordHash = passwordHash, Description = string.Empty,
|
||||
CreatedOn = DateOnly.FromDateTime(now), IconId = Guid.Empty, WasOnline = now, InviteId = invitation.Id
|
||||
};
|
||||
|
||||
await _context.Users.AddAsync(user);
|
||||
await SetRoleAsync(user, invitation);
|
||||
|
||||
if (settings.RequiredChannelId.HasValue)
|
||||
{
|
||||
_context.GroupMemberships.Add(new GroupMembership
|
||||
{
|
||||
Id = Guid.NewGuid(), GroupId = settings.RequiredChannelId.Value, UserId = user.Id, MemberSince = now
|
||||
});
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
await transaction.CommitAsync();
|
||||
|
||||
return Result.Success(user);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_context.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<Result<User, Error>> LoginAsync(string name, string password)
|
||||
{
|
||||
var user = await _context.Users
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Govor.Domain;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Users;
|
||||
@@ -10,10 +11,12 @@ namespace Govor.Application.Authentication;
|
||||
public class InvitesService : IInvitesService
|
||||
{
|
||||
private readonly GovorDbContext _context;
|
||||
private readonly INowDateTimeProvider _clock;
|
||||
|
||||
public InvitesService(GovorDbContext context)
|
||||
public InvitesService(GovorDbContext context, INowDateTimeProvider clock)
|
||||
{
|
||||
_context = context;
|
||||
_clock = clock;
|
||||
}
|
||||
|
||||
public async Task<string> GetRoleNameAsync(User user)
|
||||
@@ -40,7 +43,7 @@ public class InvitesService : IInvitesService
|
||||
if (invite == null)
|
||||
return Result.Failure<Invitation>(Error.NotFound("Auth.LinkNotFount","Invitation not found."));
|
||||
|
||||
if (invite.EndDate < DateTime.Now || invite.MaxParticipants <= invite.Users.Count || invite.MaxParticipants <= invite.Participants)
|
||||
if (!invite.IsActive || invite.EndDate <= _clock.Now || invite.MaxParticipants <= invite.Users.Count || invite.MaxParticipants <= invite.Participants)
|
||||
{
|
||||
invite.IsActive = false;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Application.Groups;
|
||||
|
||||
public static class GroupAccess
|
||||
{
|
||||
public static Task<bool> IsGroupAdministratorAsync(this GovorDbContext context, Guid groupId, Guid userId) =>
|
||||
context.ChatGroups.AnyAsync(g => g.Id == groupId &&
|
||||
context.GroupMemberships.Any(m => m.GroupId == groupId && m.UserId == userId && !m.IsBanned) &&
|
||||
(g.OwnerUserId == userId || context.GroupAdmins.Any(a => a.GroupId == groupId && a.UserId == userId)));
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
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.Messages;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Groups;
|
||||
|
||||
public interface IGroupAvatarService
|
||||
{
|
||||
Task<Result<Guid, Error>> UploadAsync(Guid actorId, Guid groupId, byte[] data, CancellationToken cancellationToken = default);
|
||||
Task<Result<Unit, Error>> RemoveAsync(Guid actorId, Guid groupId);
|
||||
}
|
||||
|
||||
public class GroupAvatarService (GovorDbContext context,
|
||||
INowDateTimeProvider clock,
|
||||
IReactionMediaProcessor processor,
|
||||
IStorageService storage,
|
||||
ILogger<GroupAvatarService> logger) : IGroupAvatarService
|
||||
{
|
||||
public async Task<Result<Guid, Error>> UploadAsync(Guid actorId, Guid groupId, byte[] data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!await IsOwnerAsync(actorId, groupId)) return Result.Failure<Guid>(Denied());
|
||||
var processed = await processor.ProcessAsync(data, cancellationToken);
|
||||
if (processed.IsFailure) return Result.Failure<Guid>(processed.Error);
|
||||
if (processed.Value.Kind == ReactionKind.Gif)
|
||||
return Result.Failure<Guid>(Error.Validation("Group.Avatar.Invalid", "A static PNG, JPEG or WebP image is required."));
|
||||
var operationId = Guid.NewGuid();
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
var completed = await context.MediaFiles.AsNoTracking().FirstOrDefaultAsync(f => f.Id == operationId);
|
||||
if (completed is not null) return Result.Success(completed.Id);
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
if (!await IsOwnerAsync(actorId, groupId)) return Result.Failure<Guid>(Denied());
|
||||
string? path = null;
|
||||
try
|
||||
{
|
||||
path = await storage.SaveAsync(processed.Value.Data, operationId.ToString("N") + ".png");
|
||||
context.MediaFiles.Add(new MediaFile
|
||||
{
|
||||
Id = operationId, UploaderId = actorId, OwnerType = MediaOwnerType.GroupAvatar, OwnerId = groupId,
|
||||
DateCreated = clock.Now, MineType = "image/png", MediaType = MediaType.Image, Url = path
|
||||
});
|
||||
await context.SaveChangesAsync();
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.ImageId, operationId));
|
||||
}
|
||||
catch
|
||||
{
|
||||
context.ChangeTracker.Clear();
|
||||
if (path is not null)
|
||||
try { await storage.RemoveAsync(path); }
|
||||
catch (Exception ex) { logger.LogError(ex, "Cannot remove failed group avatar {MediaId}", operationId); }
|
||||
throw;
|
||||
}
|
||||
// Preserve the file if commit has an ambiguous outcome; retry checks operationId.
|
||||
try { await transaction.CommitAsync(); }
|
||||
catch { context.ChangeTracker.Clear(); throw; }
|
||||
return Result.Success(operationId);
|
||||
});
|
||||
}
|
||||
|
||||
public Task<Result<Unit, Error>> RemoveAsync(Guid actorId, Guid groupId) => context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
if (!await IsOwnerAsync(actorId, groupId)) return Result.Failure(Denied());
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.ImageId, Guid.Empty));
|
||||
await transaction.CommitAsync();
|
||||
return Result.Success();
|
||||
});
|
||||
|
||||
private Task<bool> IsOwnerAsync(Guid actorId, Guid groupId) => context.ChatGroups.AnyAsync(g => g.Id == groupId && g.OwnerUserId == actorId &&
|
||||
context.GroupMemberships.Any(m => m.GroupId == groupId && m.UserId == actorId && !m.IsBanned));
|
||||
private static Error Denied() => Error.Forbidden("Group.Avatar.OwnerRequired", "Only the active group owner can change its avatar.");
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Groups;
|
||||
|
||||
public class GroupManagementService(GovorDbContext context, INowDateTimeProvider clock) : IGroupManagementService
|
||||
{
|
||||
public async Task<Result<GroupSummary, Error>> CreateAsync(Guid actorId, string name, string description, bool isPrivate, bool isChannel)
|
||||
{
|
||||
if (!ValidText(name, description)) return Result.Failure<GroupSummary>(Invalid("Invalid group profile."));
|
||||
if (!await context.Users.AnyAsync(u => u.Id == actorId)) return Result.Failure<GroupSummary>(Denied());
|
||||
var group = new ChatGroup
|
||||
{
|
||||
Id = Guid.NewGuid(), Name = name.Trim(), Description = description.Trim(), IsPrivate = isPrivate,
|
||||
IsChannel = isChannel, OwnerUserId = actorId, CreatedAt = clock.Now
|
||||
};
|
||||
group.Members.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = group.Id, UserId = actorId, MemberSince = clock.Now });
|
||||
context.ChatGroups.Add(group);
|
||||
await context.SaveChangesAsync();
|
||||
return await SummaryAsync(group, actorId);
|
||||
}
|
||||
|
||||
public async Task<Result<GroupSummary, Error>> GetAsync(Guid actorId, Guid groupId)
|
||||
{
|
||||
var group = await context.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == groupId);
|
||||
if (group is null || await IsBannedAsync(groupId, actorId) ||
|
||||
(group.IsPrivate && !await IsMemberAsync(groupId, actorId))) return Result.Failure<GroupSummary>(Missing());
|
||||
return await SummaryAsync(group, actorId);
|
||||
}
|
||||
|
||||
public async Task<List<GroupSummary>> SearchAsync(Guid actorId, string query, int skip = 0, int take = 50)
|
||||
{
|
||||
query = (query ?? "").Trim().ToLowerInvariant();
|
||||
var groups = await context.ChatGroups.AsNoTracking().Where(g => !g.IsPrivate &&
|
||||
!context.GroupMemberships.Any(m => m.GroupId == g.Id && m.UserId == actorId && m.IsBanned) &&
|
||||
(query == "" || g.Name.ToLower().Contains(query) || g.Description.ToLower().Contains(query)))
|
||||
.OrderBy(g => g.Name).ThenBy(g => g.Id).Skip(Math.Max(0, skip)).Take(Math.Clamp(take, 1, 100)).ToListAsync();
|
||||
var result = new List<GroupSummary>();
|
||||
foreach (var group in groups) result.Add(await SummaryAsync(group, actorId));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<List<GroupSummary>> MineAsync(Guid actorId, int skip = 0, int take = 50)
|
||||
{
|
||||
var groups = await context.ChatGroups.AsNoTracking().Where(g => context.GroupMemberships
|
||||
.Any(m => m.GroupId == g.Id && m.UserId == actorId && !m.IsBanned))
|
||||
.OrderBy(g => g.Name).ThenBy(g => g.Id).Skip(Math.Max(0, skip)).Take(Math.Clamp(take, 1, 100)).ToListAsync();
|
||||
var result = new List<GroupSummary>();
|
||||
foreach (var group in groups) result.Add(await SummaryAsync(group, actorId));
|
||||
return result;
|
||||
}
|
||||
|
||||
public async Task<Result<GroupSummary, Error>> UpdateAsync(Guid actorId, Guid groupId, string name, string description, bool isPrivate)
|
||||
{
|
||||
if (!ValidText(name, description)) return Result.Failure<GroupSummary>(Invalid("Invalid group profile."));
|
||||
var changed = await MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await IsOwnerAsync(group, actorId)) return Result.Failure(Denied());
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s =>
|
||||
s.SetProperty(g => g.Name, name.Trim()).SetProperty(g => g.Description, description.Trim())
|
||||
.SetProperty(g => g.IsPrivate, isPrivate));
|
||||
return Result.Success();
|
||||
});
|
||||
return changed.IsFailure ? Result.Failure<GroupSummary>(changed.Error) : await GetAsync(actorId, groupId);
|
||||
}
|
||||
|
||||
public Task<Result<GroupSummary, Error>> JoinPublicAsync(Guid actorId, Guid groupId) => JoinAsync(actorId, groupId, null);
|
||||
|
||||
public async Task<Result<GroupSummary, Error>> JoinByInvitationAsync(Guid actorId, string code)
|
||||
{
|
||||
var groupId = await context.GroupInvitations.Where(i => i.InvitationCode == code)
|
||||
.Select(i => (Guid?)i.GroupId).FirstOrDefaultAsync();
|
||||
return groupId.HasValue ? await JoinAsync(actorId, groupId.Value, code) : Result.Failure<GroupSummary>(Missing());
|
||||
}
|
||||
|
||||
public async Task<Result<GroupSummary, Error>> PreviewInvitationAsync(Guid actorId, string code)
|
||||
{
|
||||
var invitation = await context.GroupInvitations.AsNoTracking().FirstOrDefaultAsync(i => i.InvitationCode == code);
|
||||
if (invitation is null || !Usable(invitation) || await IsBannedAsync(invitation.GroupId, actorId))
|
||||
return Result.Failure<GroupSummary>(Missing());
|
||||
var group = await context.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == invitation.GroupId);
|
||||
return group is null ? Result.Failure<GroupSummary>(Missing()) : Result.Success(await SummaryAsync(group, actorId));
|
||||
}
|
||||
|
||||
private async Task<Result<GroupSummary, Error>> JoinAsync(Guid actorId, Guid groupId, string? code)
|
||||
{
|
||||
var joined = await MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await context.Users.AnyAsync(u => u.Id == actorId)) return Result.Failure(Denied());
|
||||
var membership = await context.GroupMemberships.AsNoTracking()
|
||||
.FirstOrDefaultAsync(m => m.GroupId == groupId && m.UserId == actorId);
|
||||
if (membership?.IsBanned == true) return Result.Failure(Denied());
|
||||
GroupInvitation? invitation = null;
|
||||
if (code is not null)
|
||||
{
|
||||
invitation = await context.GroupInvitations.AsNoTracking()
|
||||
.FirstOrDefaultAsync(i => i.GroupId == groupId && i.InvitationCode == code);
|
||||
if (invitation is null || invitation.IsRevoked || invitation.EndDate <= clock.Now) return Result.Failure(Missing());
|
||||
}
|
||||
else if (group.IsPrivate) return Result.Failure(Denied());
|
||||
if (membership is not null) return Result.Success();
|
||||
if (invitation is not null && !Usable(invitation)) return Result.Failure(Invalid("Invitation has reached its usage limit."));
|
||||
var id = Guid.NewGuid();
|
||||
Guid? invitationId = invitation?.Id;
|
||||
var now = clock.Now;
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"GroupMemberships\" (\"Id\", \"GroupId\", \"UserId\", \"InvitationId\", \"IsBanned\", \"MemberSince\") VALUES ({id}, {groupId}, {actorId}, {invitationId}, {false}, {now})");
|
||||
if (invitation is not null)
|
||||
await context.GroupInvitations.Where(i => i.Id == invitation.Id)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(i => i.UsedCount, i => i.UsedCount + 1));
|
||||
return Result.Success();
|
||||
});
|
||||
return joined.IsFailure ? Result.Failure<GroupSummary>(joined.Error) : await GetAsync(actorId, groupId);
|
||||
}
|
||||
|
||||
public Task<Result<Unit, Error>> LeaveAsync(Guid actorId, Guid groupId) => MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await IsMemberAsync(groupId, actorId)) return Result.Failure(Denied());
|
||||
if (group.OwnerUserId == actorId) return Result.Failure(Invalid("Transfer ownership before leaving."));
|
||||
if (await context.ServerCommunitySettings.AnyAsync(s => s.Id == 1 && s.RequiredChannelId == groupId && !s.AllowLeave))
|
||||
return Result.Failure(Denied("Leaving the required channel is disabled."));
|
||||
await context.GroupAdmins.Where(a => a.GroupId == groupId && a.UserId == actorId).ExecuteDeleteAsync();
|
||||
await context.GroupMemberships.Where(m => m.GroupId == groupId && m.UserId == actorId).ExecuteDeleteAsync();
|
||||
return Result.Success();
|
||||
});
|
||||
|
||||
public async Task<Result<List<GroupMember>, Error>> MembersAsync(Guid actorId, Guid groupId, bool bannedOnly, int skip, int take)
|
||||
{
|
||||
if (!await IsMemberAsync(groupId, actorId) || (bannedOnly && !await context.IsGroupAdministratorAsync(groupId, actorId)))
|
||||
return Result.Failure<List<GroupMember>>(Denied());
|
||||
var group = await context.ChatGroups.AsNoTracking().FirstAsync(g => g.Id == groupId);
|
||||
var members = await (from m in context.GroupMemberships.AsNoTracking()
|
||||
join u in context.Users on m.UserId equals u.Id
|
||||
where m.GroupId == groupId && m.IsBanned == bannedOnly
|
||||
orderby m.MemberSince, m.UserId
|
||||
select new { m.UserId, u.Username, m.MemberSince, m.IsBanned,
|
||||
Admin = context.GroupAdmins.Any(a => a.GroupId == groupId && a.UserId == m.UserId) })
|
||||
.Skip(Math.Max(0, skip)).Take(Math.Clamp(take, 1, 100)).ToListAsync();
|
||||
return members.Select(m => new GroupMember(m.UserId, m.Username,
|
||||
group.OwnerUserId == m.UserId ? GroupRole.Owner : m.Admin ? GroupRole.Admin : GroupRole.Member,
|
||||
m.IsBanned, m.MemberSince)).ToList();
|
||||
}
|
||||
|
||||
public Task<Result<Unit, Error>> SetAdministratorAsync(Guid actorId, Guid groupId, Guid targetId, bool isAdmin) =>
|
||||
MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await IsOwnerAsync(group, actorId)) return Result.Failure(Denied());
|
||||
if (group.OwnerUserId == targetId || !await IsMemberAsync(groupId, targetId))
|
||||
return Result.Failure(Invalid("Choose an active member other than the owner."));
|
||||
if (isAdmin)
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"GroupAdmins\" (\"Id\", \"GroupId\", \"UserId\") VALUES ({id}, {groupId}, {targetId}) ON CONFLICT (\"GroupId\", \"UserId\") DO NOTHING");
|
||||
}
|
||||
else await context.GroupAdmins.Where(a => a.GroupId == groupId && a.UserId == targetId).ExecuteDeleteAsync();
|
||||
return Result.Success();
|
||||
});
|
||||
|
||||
public Task<Result<Unit, Error>> SetBanAsync(Guid actorId, Guid groupId, Guid targetId, bool banned) => MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await context.IsGroupAdministratorAsync(groupId, actorId)) return Result.Failure(Denied());
|
||||
if (targetId == actorId || group.OwnerUserId == targetId ||
|
||||
(group.OwnerUserId != actorId && await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == targetId)))
|
||||
return Result.Failure(Denied("Administrators cannot moderate the owner or another administrator."));
|
||||
if (!await context.GroupMemberships.AnyAsync(m => m.GroupId == groupId && m.UserId == targetId))
|
||||
return Result.Failure(Missing());
|
||||
await context.GroupMemberships.Where(m => m.GroupId == groupId && m.UserId == targetId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.IsBanned, banned));
|
||||
if (banned) await context.GroupAdmins.Where(a => a.GroupId == groupId && a.UserId == targetId).ExecuteDeleteAsync();
|
||||
return Result.Success();
|
||||
});
|
||||
|
||||
public Task<Result<Unit, Error>> TransferOwnershipAsync(Guid actorId, Guid groupId, Guid targetId) => MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await IsOwnerAsync(group, actorId)) return Result.Failure(Denied());
|
||||
if (targetId == actorId || !await IsMemberAsync(groupId, targetId)) return Result.Failure(Invalid("Choose another active member."));
|
||||
await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.OwnerUserId, targetId));
|
||||
var id = Guid.NewGuid();
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"GroupAdmins\" (\"Id\", \"GroupId\", \"UserId\") VALUES ({id}, {groupId}, {actorId}) ON CONFLICT (\"GroupId\", \"UserId\") DO NOTHING");
|
||||
await context.GroupAdmins.Where(a => a.GroupId == groupId && a.UserId == targetId).ExecuteDeleteAsync();
|
||||
return Result.Success();
|
||||
});
|
||||
|
||||
public async Task<Result<GroupInvitation, Error>> CreateInvitationAsync(Guid actorId, Guid groupId, int days, int maxParticipants, string description)
|
||||
{
|
||||
if (days is < 1 or > 365 || maxParticipants is < 0 or > 1000000 || description is null || description.Length > 500)
|
||||
return Result.Failure<GroupInvitation>(Invalid("Invalid invitation limits."));
|
||||
var invitation = new GroupInvitation
|
||||
{
|
||||
Id = Guid.NewGuid(), GroupId = groupId, UserMakerId = actorId, InvitationCode = Guid.NewGuid().ToString("N"),
|
||||
Description = description.Trim(), CreatedAt = clock.Now, EndDate = clock.Now.AddDays(days), MaxParticipants = maxParticipants
|
||||
};
|
||||
var result = await MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await context.IsGroupAdministratorAsync(groupId, actorId)) return Result.Failure(Denied());
|
||||
// A stable ID makes an execution-strategy retry safe after an ambiguous commit.
|
||||
if (!await context.GroupInvitations.AnyAsync(i => i.Id == invitation.Id))
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"GroupInvitations\" (\"Id\", \"GroupId\", \"UserMakerId\", \"InvitationCode\", \"Description\", \"CreatedAt\", \"EndDate\", \"MaxParticipants\", \"UsedCount\", \"IsRevoked\") VALUES ({invitation.Id}, {groupId}, {actorId}, {invitation.InvitationCode}, {invitation.Description}, {invitation.CreatedAt}, {invitation.EndDate}, {maxParticipants}, {0}, {false})");
|
||||
return Result.Success();
|
||||
});
|
||||
return result.IsFailure ? Result.Failure<GroupInvitation>(result.Error) : Result.Success(invitation);
|
||||
}
|
||||
|
||||
public async Task<Result<List<GroupInvitation>, Error>> InvitationsAsync(Guid actorId, Guid groupId)
|
||||
{
|
||||
if (!await context.IsGroupAdministratorAsync(groupId, actorId)) return Result.Failure<List<GroupInvitation>>(Denied());
|
||||
return await context.GroupInvitations.AsNoTracking().Where(i => i.GroupId == groupId)
|
||||
.OrderByDescending(i => i.CreatedAt).ThenBy(i => i.Id).Take(100).ToListAsync();
|
||||
}
|
||||
|
||||
public Task<Result<Unit, Error>> RevokeInvitationAsync(Guid actorId, Guid groupId, Guid invitationId) => MutateAsync(groupId, async group =>
|
||||
{
|
||||
if (!await context.IsGroupAdministratorAsync(groupId, actorId)) return Result.Failure(Denied());
|
||||
var count = await context.GroupInvitations.Where(i => i.Id == invitationId && i.GroupId == groupId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(i => i.IsRevoked, true));
|
||||
return count == 0 ? Result.Failure(Missing()) : Result.Success();
|
||||
});
|
||||
|
||||
public async Task<Result<ServerCommunitySettings, Error>> GetRequiredChannelAsync(Guid actorId)
|
||||
{
|
||||
if (!await IsServerAdminAsync(actorId)) return Result.Failure<ServerCommunitySettings>(Denied());
|
||||
return await context.ServerCommunitySettings.AsNoTracking().SingleAsync(s => s.Id == 1);
|
||||
}
|
||||
|
||||
public async Task<Result<ServerCommunitySettings, Error>> SetRequiredChannelAsync(Guid actorId, Guid? channelId, bool allowLeave)
|
||||
{
|
||||
if (channelId == Guid.Empty) return Result.Failure<ServerCommunitySettings>(Invalid("Use a valid channel ID or null."));
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
await context.ServerCommunitySettings.Where(s => s.Id == 1)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(s => s.AllowLeave, s => s.AllowLeave));
|
||||
if (!await IsServerAdminAsync(actorId)) return Result.Failure<ServerCommunitySettings>(Denied());
|
||||
if (channelId.HasValue && !await context.ChatGroups.AnyAsync(g => g.Id == channelId && g.IsChannel && g.OwnerUserId != null))
|
||||
return Result.Failure<ServerCommunitySettings>(Invalid("Choose an existing channel with an owner."));
|
||||
await context.ServerCommunitySettings.Where(s => s.Id == 1).ExecuteUpdateAsync(s =>
|
||||
s.SetProperty(s => s.RequiredChannelId, channelId).SetProperty(s => s.AllowLeave, allowLeave));
|
||||
var settings = await context.ServerCommunitySettings.AsNoTracking().SingleAsync(s => s.Id == 1);
|
||||
await transaction.CommitAsync();
|
||||
return Result.Success(settings);
|
||||
});
|
||||
}
|
||||
|
||||
// Every membership/role/invitation decision is serialized on its group row.
|
||||
private Task<Result<Unit, Error>> MutateAsync(Guid groupId, Func<ChatGroup, Task<Result<Unit, Error>>> mutation) =>
|
||||
context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
var count = await context.ChatGroups.Where(g => g.Id == groupId).ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
if (count == 0) return Result.Failure(Missing());
|
||||
var group = await context.ChatGroups.AsNoTracking().SingleAsync(g => g.Id == groupId);
|
||||
var result = await mutation(group);
|
||||
if (result.IsSuccess) await transaction.CommitAsync();
|
||||
return result;
|
||||
});
|
||||
|
||||
private async Task<GroupSummary> SummaryAsync(ChatGroup group, Guid actorId)
|
||||
{
|
||||
var member = await IsMemberAsync(group.Id, actorId);
|
||||
GroupRole? role = member ? group.OwnerUserId == actorId ? GroupRole.Owner :
|
||||
await context.GroupAdmins.AnyAsync(a => a.GroupId == group.Id && a.UserId == actorId) ? GroupRole.Admin : GroupRole.Member : null;
|
||||
var settings = await context.ServerCommunitySettings.AsNoTracking().SingleAsync(s => s.Id == 1);
|
||||
var required = settings.RequiredChannelId == group.Id;
|
||||
return new GroupSummary(group, await context.GroupMemberships.CountAsync(m => m.GroupId == group.Id && !m.IsBanned),
|
||||
role, required, member && group.OwnerUserId != actorId && (!required || settings.AllowLeave));
|
||||
}
|
||||
|
||||
private Task<bool> IsMemberAsync(Guid groupId, Guid userId) => context.GroupMemberships.AnyAsync(m => m.GroupId == groupId && m.UserId == userId && !m.IsBanned);
|
||||
private Task<bool> IsBannedAsync(Guid groupId, Guid userId) => context.GroupMemberships.AnyAsync(m => m.GroupId == groupId && m.UserId == userId && m.IsBanned);
|
||||
private async Task<bool> IsOwnerAsync(ChatGroup group, Guid userId) => group.OwnerUserId == userId && await IsMemberAsync(group.Id, userId);
|
||||
private Task<bool> IsServerAdminAsync(Guid userId) => context.Users.AnyAsync(u => u.Id == userId && u.Invite != null && u.Invite.IsAdmin);
|
||||
private bool Usable(GroupInvitation invitation) => !invitation.IsRevoked && invitation.EndDate > clock.Now &&
|
||||
(invitation.MaxParticipants == 0 || invitation.UsedCount < invitation.MaxParticipants);
|
||||
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("Group.Invalid", message);
|
||||
private static Error Missing() => Error.NotFound("Group.NotFound", "Group or invitation not found.");
|
||||
private static Error Denied(string message = "You do not have permission for this group operation.") => Error.Forbidden("Group.AccessDenied", message);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Groups;
|
||||
|
||||
public record GroupSummary(ChatGroup Group, int MemberCount, GroupRole? MyRole, bool IsRequiredChannel, bool CanLeave);
|
||||
public record GroupMember(Guid UserId, string Username, GroupRole Role, bool IsBanned, DateTime MemberSince);
|
||||
|
||||
public interface IGroupManagementService
|
||||
{
|
||||
Task<Result<GroupSummary, Error>> CreateAsync(Guid actorId, string name, string description, bool isPrivate, bool isChannel);
|
||||
Task<Result<GroupSummary, Error>> GetAsync(Guid actorId, Guid groupId);
|
||||
Task<List<GroupSummary>> SearchAsync(Guid actorId, string query, int skip = 0, int take = 50);
|
||||
Task<List<GroupSummary>> MineAsync(Guid actorId, int skip = 0, int take = 50);
|
||||
Task<Result<GroupSummary, Error>> UpdateAsync(Guid actorId, Guid groupId, string name, string description, bool isPrivate);
|
||||
Task<Result<GroupSummary, Error>> JoinPublicAsync(Guid actorId, Guid groupId);
|
||||
Task<Result<GroupSummary, Error>> JoinByInvitationAsync(Guid actorId, string code);
|
||||
Task<Result<GroupSummary, Error>> PreviewInvitationAsync(Guid actorId, string code);
|
||||
Task<Result<Unit, Error>> LeaveAsync(Guid actorId, Guid groupId);
|
||||
Task<Result<List<GroupMember>, Error>> MembersAsync(Guid actorId, Guid groupId, bool bannedOnly, int skip, int take);
|
||||
Task<Result<Unit, Error>> SetAdministratorAsync(Guid actorId, Guid groupId, Guid targetId, bool isAdmin);
|
||||
Task<Result<Unit, Error>> SetBanAsync(Guid actorId, Guid groupId, Guid targetId, bool banned);
|
||||
Task<Result<Unit, Error>> TransferOwnershipAsync(Guid actorId, Guid groupId, Guid targetId);
|
||||
Task<Result<GroupInvitation, Error>> CreateInvitationAsync(Guid actorId, Guid groupId, int days, int maxParticipants, string description);
|
||||
Task<Result<List<GroupInvitation>, Error>> InvitationsAsync(Guid actorId, Guid groupId);
|
||||
Task<Result<Unit, Error>> RevokeInvitationAsync(Guid actorId, Guid groupId, Guid invitationId);
|
||||
Task<Result<ServerCommunitySettings, Error>> GetRequiredChannelAsync(Guid actorId);
|
||||
Task<Result<ServerCommunitySettings, Error>> SetRequiredChannelAsync(Guid actorId, Guid? channelId, bool allowLeave);
|
||||
}
|
||||
@@ -17,9 +17,9 @@ public class UserGroupsGetterService : IUserGroupsGetterService
|
||||
{
|
||||
return await _context.GroupMemberships
|
||||
.AsNoTracking()
|
||||
.Where(m => m.UserId == userId)
|
||||
.Where(m => m.UserId == userId && !m.IsBanned)
|
||||
.Select(m => m.ChatGroup)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,10 @@ public class AccesserToDownloadMediaService : IAccesserToDownloadMedia
|
||||
return media.OwnerType switch
|
||||
{
|
||||
MediaOwnerType.Avatar => true, // media.OwnerId == userId
|
||||
MediaOwnerType.GroupAvatar => await _dbContext.GroupMemberships
|
||||
.AnyAsync(gm => gm.GroupId == media.OwnerId && gm.UserId == userId && !gm.IsBanned),
|
||||
MediaOwnerType.GroupAvatar => await _dbContext.ChatGroups.AnyAsync(g => g.Id == media.OwnerId &&
|
||||
!_dbContext.GroupMemberships.Any(m => m.GroupId == g.Id && m.UserId == userId && m.IsBanned) &&
|
||||
((!g.IsPrivate && g.ImageId == mediaId) || _dbContext.GroupMemberships
|
||||
.Any(m => m.GroupId == g.Id && m.UserId == userId && !m.IsBanned))),
|
||||
|
||||
MediaOwnerType.Message => await _dbContext.MediaAttachments
|
||||
.AnyAsync(ma =>
|
||||
|
||||
@@ -2,6 +2,7 @@ using Govor.Application.Messages.Parameters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Application.Groups;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
@@ -24,6 +25,25 @@ public class MessageEditingService : IMessageEditingService
|
||||
}
|
||||
|
||||
public async Task<EditMessageResult> EditMessageAsync(EditMessage editParams)
|
||||
{
|
||||
var target = await _dbContext.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == editParams.MessageId);
|
||||
if (target?.RecipientType != RecipientType.Group) return await EditCoreAsync(editParams);
|
||||
return await _dbContext.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await _dbContext.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
await _dbContext.ChatGroups.Where(g => g.Id == target.RecipientId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
var result = await EditCoreAsync(editParams);
|
||||
if (result.IsSuccess) await transaction.CommitAsync();
|
||||
return result;
|
||||
}
|
||||
catch { _dbContext.ChangeTracker.Clear(); throw; }
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<EditMessageResult> EditCoreAsync(EditMessage editParams)
|
||||
{
|
||||
var message = await _dbContext.Messages
|
||||
.Include(m => m.MediaAttachments)
|
||||
@@ -38,7 +58,10 @@ public class MessageEditingService : IMessageEditingService
|
||||
}
|
||||
|
||||
if (message.SenderId != editParams.EditorId || !await _dbContext.HasChatAccessAsync(
|
||||
editParams.EditorId, message.RecipientId, message.RecipientType))
|
||||
editParams.EditorId, message.RecipientId, message.RecipientType) ||
|
||||
(message.RecipientType == RecipientType.Group &&
|
||||
await _dbContext.ChatGroups.AnyAsync(g => g.Id == message.RecipientId && g.IsChannel) &&
|
||||
!await _dbContext.IsGroupAdministratorAsync(message.RecipientId, editParams.EditorId)))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"User {EditorId} unauthorized to edit message {MessageId}",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using DeleteMessage = Govor.Application.Messages.Parameters.DeleteMessage;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -20,6 +21,25 @@ public class MessageRemovingService : IMessageRemovingService
|
||||
}
|
||||
|
||||
public async Task<Result<Message, Error>> DeleteMessageAsync(DeleteMessage deleteParams)
|
||||
{
|
||||
var target = await _govorDbContext.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
|
||||
if (target?.RecipientType != RecipientType.Group) return await DeleteCoreAsync(deleteParams);
|
||||
return await _govorDbContext.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await _govorDbContext.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
await _govorDbContext.ChatGroups.Where(g => g.Id == target.RecipientId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
var result = await DeleteCoreAsync(deleteParams);
|
||||
if (result.IsSuccess) await transaction.CommitAsync();
|
||||
return result;
|
||||
}
|
||||
catch { _govorDbContext.ChangeTracker.Clear(); throw; }
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<Result<Message, Error>> DeleteCoreAsync(DeleteMessage deleteParams)
|
||||
{
|
||||
var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
|
||||
if (message is null)
|
||||
@@ -36,8 +56,7 @@ public class MessageRemovingService : IMessageRemovingService
|
||||
|
||||
var canDelete = message.SenderId == deleteParams.DeleterId ||
|
||||
(message.RecipientType == RecipientType.Group &&
|
||||
await _govorDbContext.GroupAdmins.AnyAsync(a =>
|
||||
a.GroupId == message.RecipientId && a.UserId == deleteParams.DeleterId));
|
||||
await _govorDbContext.IsGroupAdministratorAsync(message.RecipientId, deleteParams.DeleterId));
|
||||
if (!canDelete)
|
||||
return Result.Failure<Message>(Error.Forbidden("Message.Remove.AccessDenied",
|
||||
"Only the author or a group administrator can delete this message."));
|
||||
|
||||
@@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Application.Groups;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
@@ -19,6 +20,30 @@ public class MessageSendingService : IMessageSendingService
|
||||
}
|
||||
|
||||
public async Task<SendMessageResult> SendMessageAsync(SendMessage sendParams)
|
||||
{
|
||||
var operationId = Guid.NewGuid();
|
||||
if (sendParams.RecipientType != RecipientType.Group)
|
||||
return await SendCoreAsync(sendParams, operationId);
|
||||
return await _dbContext.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await _dbContext.Database.BeginTransactionAsync();
|
||||
try
|
||||
{
|
||||
// Same group lock as moderation: bans/demotion cannot race a channel post.
|
||||
await _dbContext.ChatGroups.Where(g => g.Id == sendParams.RecipientId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.Name, g => g.Name));
|
||||
var completed = await _dbContext.Messages.AsNoTracking().Include(m => m.MediaAttachments)
|
||||
.FirstOrDefaultAsync(m => m.Id == operationId);
|
||||
if (completed is not null) return new SendMessageResult(true, null, completed);
|
||||
var result = await SendCoreAsync(sendParams, operationId);
|
||||
if (result.IsSuccess) await transaction.CommitAsync();
|
||||
return result;
|
||||
}
|
||||
catch { _dbContext.ChangeTracker.Clear(); throw; }
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<SendMessageResult> SendCoreAsync(SendMessage sendParams, Guid operationId)
|
||||
{
|
||||
var media = sendParams.Media?.ToArray() ?? [];
|
||||
if ((string.IsNullOrWhiteSpace(sendParams.EncryptContent) && media.Length == 0) ||
|
||||
@@ -49,7 +74,7 @@ public class MessageSendingService : IMessageSendingService
|
||||
m.RecipientType == sendParams.RecipientType))
|
||||
return new SendMessageResult(false, new ArgumentException("Reply must belong to the same chat."), default);
|
||||
|
||||
var messageId = Guid.NewGuid();
|
||||
var messageId = operationId;
|
||||
var message = new Message
|
||||
{
|
||||
Id = messageId,
|
||||
@@ -98,8 +123,7 @@ public class MessageSendingService : IMessageSendingService
|
||||
|
||||
var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId && !gm.IsBanned);
|
||||
if (!isMember) return (false, "Sender is not a member of the group.");
|
||||
if (group.IsChannel && !await _dbContext.GroupAdmins.AnyAsync(a =>
|
||||
a.GroupId == groupId && a.UserId == userId))
|
||||
if (group.IsChannel && !await _dbContext.IsGroupAdministratorAsync(groupId, userId))
|
||||
return (false, "Only channel administrators can send messages.");
|
||||
|
||||
return (true, null);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
@@ -117,7 +118,7 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
ChannelReactionMode mode, IReadOnlyCollection<Guid> reactionIds)
|
||||
{
|
||||
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) ||
|
||||
!await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId))
|
||||
!await context.IsGroupAdministratorAsync(groupId, 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))
|
||||
@@ -131,7 +132,7 @@ public class MessageReactionService(GovorDbContext context, INowDateTimeProvider
|
||||
.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))
|
||||
!await context.IsGroupAdministratorAsync(groupId, 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."));
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace Govor.Contracts.Requests;
|
||||
|
||||
public class CreateGroupRequest
|
||||
{
|
||||
[Required, MaxLength(100)] public string Name { get; set; } = string.Empty;
|
||||
[MaxLength(500)] public string Description { get; set; } = string.Empty;
|
||||
public bool IsPrivate { get; set; } = true;
|
||||
public bool IsChannel { get; set; }
|
||||
}
|
||||
|
||||
public class UpdateGroupRequest
|
||||
{
|
||||
[Required, MaxLength(100)] public string Name { get; set; } = string.Empty;
|
||||
[MaxLength(500)] public string Description { get; set; } = string.Empty;
|
||||
public bool IsPrivate { get; set; }
|
||||
}
|
||||
|
||||
public class CreateGroupInvitationRequest
|
||||
{
|
||||
[Range(1, 365)] public int ValidForDays { get; set; } = 7;
|
||||
[Range(0, 1000000)] public int MaxParticipants { get; set; }
|
||||
[MaxLength(500)] public string Description { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
public class RequiredChannelRequest
|
||||
{
|
||||
public Guid? ChannelId { get; set; }
|
||||
public bool AllowLeave { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using Govor.Domain.Models;
|
||||
|
||||
namespace Govor.Contracts.Responses;
|
||||
|
||||
public class GroupResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Name { get; set; } = string.Empty;
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public Guid ImageId { get; set; }
|
||||
public string? ImageUrl => ImageId == Guid.Empty ? null : $"/api/media/download/{ImageId}";
|
||||
public bool IsPrivate { get; set; }
|
||||
public bool IsChannel { get; set; }
|
||||
public Guid? OwnerUserId { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public int MemberCount { get; set; }
|
||||
public GroupRole? MyRole { get; set; }
|
||||
public bool IsRequiredChannel { get; set; }
|
||||
public bool CanLeave { get; set; }
|
||||
}
|
||||
|
||||
public class GroupMemberResponse
|
||||
{
|
||||
public Guid UserId { get; set; }
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public GroupRole Role { get; set; }
|
||||
public bool IsBanned { get; set; }
|
||||
public DateTime MemberSince { get; set; }
|
||||
}
|
||||
|
||||
public class GroupInvitationResponse
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Guid GroupId { get; set; }
|
||||
public string InvitationCode { get; set; } = string.Empty;
|
||||
public string SharePath => $"/invite/{InvitationCode}";
|
||||
public string JoinPath => $"/api/group-invites/{InvitationCode}/join";
|
||||
public string PreviewPath => $"/api/group-invites/{InvitationCode}";
|
||||
public string Description { get; set; } = string.Empty;
|
||||
public DateTime EndDate { get; set; }
|
||||
public int MaxParticipants { get; set; }
|
||||
public int UsedCount { get; set; }
|
||||
public bool IsRevoked { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using Govor.Domain.Models;
|
||||
|
||||
namespace Govor.Contracts.Responses.SignalR;
|
||||
|
||||
public class GroupProfileChangedResponse
|
||||
{
|
||||
public Guid GroupId { get; set; }
|
||||
}
|
||||
|
||||
public enum GroupMemberStatus { Active, Banned, Left }
|
||||
|
||||
public class GroupMemberChangedResponse
|
||||
{
|
||||
public Guid GroupId { get; set; }
|
||||
public Guid UserId { get; set; }
|
||||
public GroupMemberStatus Status { get; set; }
|
||||
public GroupRole? Role { get; set; }
|
||||
}
|
||||
@@ -12,9 +12,11 @@ public class ChatGroupConfigurator : IEntityTypeConfiguration<ChatGroup>
|
||||
|
||||
builder.Property(e => e.Name).IsRequired().HasMaxLength(100);
|
||||
builder.Property(e => e.Description).HasMaxLength(500);
|
||||
builder.HasOne<Govor.Domain.Models.Users.User>().WithMany()
|
||||
.HasForeignKey(e => e.OwnerUserId).OnDelete(DeleteBehavior.Restrict);
|
||||
|
||||
builder.HasMany(e => e.Members)
|
||||
.WithOne()
|
||||
.WithOne(e => e.ChatGroup)
|
||||
.HasForeignKey(e => e.GroupId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
@@ -28,4 +30,4 @@ public class ChatGroupConfigurator : IEntityTypeConfiguration<ChatGroup>
|
||||
.HasForeignKey(e => e.GroupId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,11 @@ public class GroupAdminsConfiguration : IEntityTypeConfiguration<GroupAdmins>
|
||||
public void Configure(EntityTypeBuilder<GroupAdmins> builder)
|
||||
{
|
||||
builder.HasKey(e => e.Id);
|
||||
builder.HasIndex(e => new { e.GroupId, e.UserId }).IsUnique();
|
||||
builder.HasOne<Govor.Domain.Models.Users.User>().WithMany()
|
||||
.HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(e => e.UserId).IsRequired();
|
||||
builder.Property(e => e.GroupId).IsRequired();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ public class GroupInvitationConfiguration : IEntityTypeConfiguration<GroupInvita
|
||||
builder.HasKey(e => e.Id);
|
||||
|
||||
builder.Property(e => e.InvitationCode).IsRequired().HasMaxLength(200);
|
||||
builder.HasIndex(e => e.InvitationCode).IsUnique();
|
||||
builder.Property(e => e.Description).HasMaxLength(500);
|
||||
builder.Property(e => e.EndDate).IsRequired();
|
||||
builder.Property(e => e.CreatedAt).IsRequired();
|
||||
@@ -23,4 +24,4 @@ public class GroupInvitationConfiguration : IEntityTypeConfiguration<GroupInvita
|
||||
|
||||
builder.Ignore(e => e.GroupMemberships);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,13 +9,16 @@ public class GroupMembershipConfiguration : IEntityTypeConfiguration<GroupMember
|
||||
public void Configure(EntityTypeBuilder<GroupMembership> builder)
|
||||
{
|
||||
builder.HasKey(e => e.Id);
|
||||
builder.HasIndex(e => new { e.GroupId, e.UserId }).IsUnique();
|
||||
builder.HasOne<Govor.Domain.Models.Users.User>().WithMany()
|
||||
.HasForeignKey(e => e.UserId).OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
builder.Property(e => e.UserId).IsRequired();
|
||||
builder.Property(e => e.GroupId).IsRequired();
|
||||
builder.Property(e => e.InvitationId).IsRequired(false);
|
||||
|
||||
builder.HasOne(e => e.ChatGroup)
|
||||
.WithMany()
|
||||
.WithMany(g => g.Members)
|
||||
.HasForeignKey(e => e.GroupId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
|
||||
@@ -26,4 +29,4 @@ public class GroupMembershipConfiguration : IEntityTypeConfiguration<GroupMember
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Metadata.Builders;
|
||||
|
||||
namespace Govor.Domain.Configurations;
|
||||
|
||||
public class ServerCommunitySettingsConfiguration : IEntityTypeConfiguration<ServerCommunitySettings>
|
||||
{
|
||||
public void Configure(EntityTypeBuilder<ServerCommunitySettings> builder)
|
||||
{
|
||||
builder.HasKey(s => s.Id);
|
||||
builder.Property(s => s.Id).ValueGeneratedNever();
|
||||
builder.HasOne<ChatGroup>().WithMany().HasForeignKey(s => s.RequiredChannelId).OnDelete(DeleteBehavior.Restrict);
|
||||
builder.HasData(new ServerCommunitySettings { Id = 1, AllowLeave = true });
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
|
||||
public virtual DbSet<GroupInvitation> GroupInvitations { get; set; }
|
||||
public virtual DbSet<GroupMembership> GroupMemberships { get; set; }
|
||||
public virtual DbSet<GroupAdmins> GroupAdmins { get; set; }
|
||||
public virtual DbSet<ServerCommunitySettings> ServerCommunitySettings { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
@@ -59,6 +60,7 @@ public class GovorDbContext(DbContextOptions<GovorDbContext> options) : DbContex
|
||||
modelBuilder.ApplyConfiguration(new GroupInvitationConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new GroupMembershipConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new GroupAdminsConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new ServerCommunitySettingsConfiguration());
|
||||
|
||||
modelBuilder.ApplyConfiguration(new OneTimePreKeyConfiguration());
|
||||
modelBuilder.ApplyConfiguration(new UserCryptoSessionConfiguration());
|
||||
|
||||
+1353
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,267 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace Govor.Domain.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class PrimitiveGroupsAndRequiredChannel : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_GroupMemberships_ChatGroups_ChatGroupId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupMemberships_ChatGroupId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupMemberships_GroupId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupAdmins_GroupId",
|
||||
table: "GroupAdmins");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "ChatGroupId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsRevoked",
|
||||
table: "GroupInvitations",
|
||||
type: "boolean",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
|
||||
migrationBuilder.AddColumn<int>(
|
||||
name: "UsedCount",
|
||||
table: "GroupInvitations",
|
||||
type: "integer",
|
||||
nullable: false,
|
||||
defaultValue: 0);
|
||||
|
||||
migrationBuilder.AddColumn<DateTime>(
|
||||
name: "CreatedAt",
|
||||
table: "ChatGroups",
|
||||
type: "timestamp with time zone",
|
||||
nullable: false,
|
||||
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "OwnerUserId",
|
||||
table: "ChatGroups",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ServerCommunitySettings",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "integer", nullable: false),
|
||||
RequiredChannelId = table.Column<Guid>(type: "uuid", nullable: true),
|
||||
AllowLeave = table.Column<bool>(type: "boolean", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ServerCommunitySettings", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ServerCommunitySettings_ChatGroups_RequiredChannelId",
|
||||
column: x => x.RequiredChannelId,
|
||||
principalTable: "ChatGroups",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "ServerCommunitySettings",
|
||||
columns: new[] { "Id", "AllowLeave", "RequiredChannelId" },
|
||||
values: new object[] { 1, true, null });
|
||||
|
||||
// Preserve bans when consolidating legacy duplicate memberships; remove orphan rows
|
||||
// before adding user foreign keys. Invitation codes that were ambiguous are revoked.
|
||||
migrationBuilder.Sql("""
|
||||
DELETE FROM "GroupMemberships" WHERE "UserId" NOT IN (SELECT "Id" FROM "Users");
|
||||
DELETE FROM "GroupAdmins" WHERE "UserId" NOT IN (SELECT "Id" FROM "Users");
|
||||
DELETE FROM "GroupMemberships" WHERE "Id" IN (
|
||||
SELECT "Id" FROM (SELECT "Id", ROW_NUMBER() OVER (
|
||||
PARTITION BY "GroupId", "UserId" ORDER BY "IsBanned" DESC, "MemberSince", "Id") AS rn
|
||||
FROM "GroupMemberships") AS duplicates WHERE rn > 1);
|
||||
DELETE FROM "GroupAdmins" WHERE "Id" IN (
|
||||
SELECT "Id" FROM (SELECT "Id", ROW_NUMBER() OVER (
|
||||
PARTITION BY "GroupId", "UserId" ORDER BY "Id") AS rn
|
||||
FROM "GroupAdmins") AS duplicates WHERE rn > 1);
|
||||
DELETE FROM "GroupAdmins" AS a WHERE NOT EXISTS (
|
||||
SELECT 1 FROM "GroupMemberships" AS m WHERE m."GroupId" = a."GroupId"
|
||||
AND m."UserId" = a."UserId" AND NOT m."IsBanned");
|
||||
UPDATE "GroupInvitations" SET "IsRevoked" = TRUE,
|
||||
"InvitationCode" = REPLACE(CAST("Id" AS TEXT), '-', '')
|
||||
WHERE "InvitationCode" IN (SELECT "InvitationCode" FROM "GroupInvitations"
|
||||
GROUP BY "InvitationCode" HAVING COUNT(*) > 1);
|
||||
UPDATE "GroupInvitations" AS i SET "UsedCount" = (
|
||||
SELECT COUNT(*) FROM "GroupMemberships" AS m WHERE m."InvitationId" = i."Id");
|
||||
UPDATE "ChatGroups" AS g SET "OwnerUserId" = (
|
||||
SELECT m."UserId" FROM "GroupMemberships" AS m
|
||||
WHERE m."GroupId" = g."Id" AND NOT m."IsBanned"
|
||||
ORDER BY CASE WHEN EXISTS (SELECT 1 FROM "GroupAdmins" AS a
|
||||
WHERE a."GroupId" = m."GroupId" AND a."UserId" = m."UserId") THEN 0 ELSE 1 END,
|
||||
m."MemberSince", m."UserId" LIMIT 1);
|
||||
UPDATE "ChatGroups" AS g SET "CreatedAt" = COALESCE((
|
||||
SELECT MIN(m."MemberSince") FROM "GroupMemberships" AS m
|
||||
WHERE m."GroupId" = g."Id"), CURRENT_TIMESTAMP);
|
||||
""");
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupMemberships_GroupId_UserId",
|
||||
table: "GroupMemberships",
|
||||
columns: new[] { "GroupId", "UserId" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupMemberships_UserId",
|
||||
table: "GroupMemberships",
|
||||
column: "UserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupInvitations_InvitationCode",
|
||||
table: "GroupInvitations",
|
||||
column: "InvitationCode",
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupAdmins_GroupId_UserId",
|
||||
table: "GroupAdmins",
|
||||
columns: new[] { "GroupId", "UserId" },
|
||||
unique: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupAdmins_UserId",
|
||||
table: "GroupAdmins",
|
||||
column: "UserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ChatGroups_OwnerUserId",
|
||||
table: "ChatGroups",
|
||||
column: "OwnerUserId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ServerCommunitySettings_RequiredChannelId",
|
||||
table: "ServerCommunitySettings",
|
||||
column: "RequiredChannelId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_ChatGroups_Users_OwnerUserId",
|
||||
table: "ChatGroups",
|
||||
column: "OwnerUserId",
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Restrict);
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_GroupAdmins_Users_UserId",
|
||||
table: "GroupAdmins",
|
||||
column: "UserId",
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_GroupMemberships_Users_UserId",
|
||||
table: "GroupMemberships",
|
||||
column: "UserId",
|
||||
principalTable: "Users",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_ChatGroups_Users_OwnerUserId",
|
||||
table: "ChatGroups");
|
||||
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_GroupAdmins_Users_UserId",
|
||||
table: "GroupAdmins");
|
||||
|
||||
migrationBuilder.DropForeignKey(
|
||||
name: "FK_GroupMemberships_Users_UserId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "ServerCommunitySettings");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupMemberships_GroupId_UserId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupMemberships_UserId",
|
||||
table: "GroupMemberships");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupInvitations_InvitationCode",
|
||||
table: "GroupInvitations");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupAdmins_GroupId_UserId",
|
||||
table: "GroupAdmins");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_GroupAdmins_UserId",
|
||||
table: "GroupAdmins");
|
||||
|
||||
migrationBuilder.DropIndex(
|
||||
name: "IX_ChatGroups_OwnerUserId",
|
||||
table: "ChatGroups");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsRevoked",
|
||||
table: "GroupInvitations");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "UsedCount",
|
||||
table: "GroupInvitations");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "CreatedAt",
|
||||
table: "ChatGroups");
|
||||
|
||||
migrationBuilder.DropColumn(
|
||||
name: "OwnerUserId",
|
||||
table: "ChatGroups");
|
||||
|
||||
migrationBuilder.AddColumn<Guid>(
|
||||
name: "ChatGroupId",
|
||||
table: "GroupMemberships",
|
||||
type: "uuid",
|
||||
nullable: true);
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupMemberships_ChatGroupId",
|
||||
table: "GroupMemberships",
|
||||
column: "ChatGroupId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupMemberships_GroupId",
|
||||
table: "GroupMemberships",
|
||||
column: "GroupId");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_GroupAdmins_GroupId",
|
||||
table: "GroupAdmins",
|
||||
column: "GroupId");
|
||||
|
||||
migrationBuilder.AddForeignKey(
|
||||
name: "FK_GroupMemberships_ChatGroups_ChatGroupId",
|
||||
table: "GroupMemberships",
|
||||
column: "ChatGroupId",
|
||||
principalTable: "ChatGroups",
|
||||
principalColumn: "Id");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,9 @@ namespace Govor.Domain.Migrations
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<DateTime>("CreatedAt")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<string>("Description")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
@@ -47,6 +50,9 @@ namespace Govor.Domain.Migrations
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("character varying(100)");
|
||||
|
||||
b.Property<Guid?>("OwnerUserId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("ReactionMode")
|
||||
.HasColumnType("integer");
|
||||
|
||||
@@ -55,6 +61,8 @@ namespace Govor.Domain.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("OwnerUserId");
|
||||
|
||||
b.ToTable("ChatGroups");
|
||||
});
|
||||
|
||||
@@ -96,7 +104,10 @@ namespace Govor.Domain.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("GroupId");
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.HasIndex("GroupId", "UserId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("GroupAdmins");
|
||||
});
|
||||
@@ -126,9 +137,15 @@ namespace Govor.Domain.Migrations
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("character varying(200)");
|
||||
|
||||
b.Property<bool>("IsRevoked")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<int>("MaxParticipants")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("UsedCount")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<Guid>("UserMakerId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
@@ -136,6 +153,9 @@ namespace Govor.Domain.Migrations
|
||||
|
||||
b.HasIndex("GroupId");
|
||||
|
||||
b.HasIndex("InvitationCode")
|
||||
.IsUnique();
|
||||
|
||||
b.HasIndex("UserMakerId");
|
||||
|
||||
b.ToTable("GroupInvitations");
|
||||
@@ -147,9 +167,6 @@ namespace Govor.Domain.Migrations
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid?>("ChatGroupId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<Guid>("GroupId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
@@ -167,12 +184,13 @@ namespace Govor.Domain.Migrations
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("ChatGroupId");
|
||||
|
||||
b.HasIndex("GroupId");
|
||||
|
||||
b.HasIndex("InvitationId");
|
||||
|
||||
b.HasIndex("UserId");
|
||||
|
||||
b.HasIndex("GroupId", "UserId")
|
||||
.IsUnique();
|
||||
|
||||
b.ToTable("GroupMemberships");
|
||||
});
|
||||
|
||||
@@ -744,6 +762,31 @@ namespace Govor.Domain.Migrations
|
||||
b.ToTable("UserReactionPacks");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<bool>("AllowLeave")
|
||||
.HasColumnType("boolean");
|
||||
|
||||
b.Property<Guid?>("RequiredChannelId")
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RequiredChannelId");
|
||||
|
||||
b.ToTable("ServerCommunitySettings");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AllowLeave = true
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b =>
|
||||
{
|
||||
b.Property<Guid>("UserId")
|
||||
@@ -965,6 +1008,14 @@ namespace Govor.Domain.Migrations
|
||||
b.ToTable("UserSessions");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.ChatGroup", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.Users.User", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("OwnerUserId")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Friendship", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.Users.User", "Addressee")
|
||||
@@ -991,6 +1042,12 @@ namespace Govor.Domain.Migrations
|
||||
.HasForeignKey("GroupId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("Govor.Domain.Models.Users.User", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.GroupInvitation", b =>
|
||||
@@ -1012,12 +1069,8 @@ namespace Govor.Domain.Migrations
|
||||
|
||||
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()
|
||||
.WithMany("Members")
|
||||
.HasForeignKey("GroupId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
@@ -1027,6 +1080,12 @@ namespace Govor.Domain.Migrations
|
||||
.HasForeignKey("InvitationId")
|
||||
.OnDelete(DeleteBehavior.SetNull);
|
||||
|
||||
b.HasOne("Govor.Domain.Models.Users.User", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("UserId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("ChatGroup");
|
||||
});
|
||||
|
||||
@@ -1156,6 +1215,14 @@ namespace Govor.Domain.Migrations
|
||||
.IsRequired();
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.ServerCommunitySettings", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.ChatGroup", null)
|
||||
.WithMany()
|
||||
.HasForeignKey("RequiredChannelId")
|
||||
.OnDelete(DeleteBehavior.Restrict);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Govor.Domain.Models.Users.Admin", b =>
|
||||
{
|
||||
b.HasOne("Govor.Domain.Models.Users.User", "User")
|
||||
|
||||
@@ -12,6 +12,8 @@ public class ChatGroup
|
||||
public Govor.Domain.Models.Reactions.ChannelReactionMode ReactionMode { get; set; }
|
||||
public long ReactionPolicyVersion { get; set; }
|
||||
public bool IsPrivate { get; set; }
|
||||
public Guid? OwnerUserId { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public List<GroupAdmins> Admins { get; set; } = new();
|
||||
public List<GroupMembership> Members { get; set; } = new();
|
||||
public List<GroupInvitation> InviteCodes { get; set; } = new();
|
||||
|
||||
@@ -12,6 +12,8 @@ public class GroupInvitation
|
||||
public DateTime EndDate { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public int MaxParticipants { get; set; }
|
||||
public int UsedCount { get; set; }
|
||||
public bool IsRevoked { get; set; }
|
||||
public List<Guid> GroupMemberships { get; set; } = new();
|
||||
public User? UserMaker { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Govor.Domain.Models;
|
||||
|
||||
public enum GroupRole { Member, Admin, Owner }
|
||||
|
||||
public class ServerCommunitySettings
|
||||
{
|
||||
public int Id { get; set; } = 1;
|
||||
public Guid? RequiredChannelId { get; set; }
|
||||
public bool AllowLeave { get; set; } = true;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
using Govor.Domain.Migrations;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.EntityFrameworkCore.Migrations.Operations;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class GroupMigrationTests
|
||||
{
|
||||
[Test]
|
||||
public async Task LegacyCleanupPreservesBansChoosesActiveAdminAndRevokesAmbiguousLinks()
|
||||
{
|
||||
await using var connection = new SqliteConnection("Data Source=:memory:");
|
||||
await connection.OpenAsync();
|
||||
await using var command = connection.CreateCommand();
|
||||
command.CommandText = """
|
||||
CREATE TABLE "Users" ("Id" TEXT PRIMARY KEY);
|
||||
CREATE TABLE "ChatGroups" ("Id" TEXT PRIMARY KEY, "OwnerUserId" TEXT, "CreatedAt" TEXT);
|
||||
CREATE TABLE "GroupMemberships" ("Id" TEXT, "GroupId" TEXT, "UserId" TEXT, "IsBanned" INTEGER, "MemberSince" TEXT, "InvitationId" TEXT);
|
||||
CREATE TABLE "GroupAdmins" ("Id" TEXT, "GroupId" TEXT, "UserId" TEXT);
|
||||
CREATE TABLE "GroupInvitations" ("Id" TEXT, "InvitationCode" TEXT, "IsRevoked" INTEGER, "UsedCount" INTEGER);
|
||||
INSERT INTO "Users" VALUES ('alice'), ('bob'), ('carol');
|
||||
INSERT INTO "ChatGroups" VALUES ('group', NULL, NULL);
|
||||
INSERT INTO "GroupInvitations" VALUES ('inv-1', 'same', 0, 0), ('inv-2', 'same', 0, 0);
|
||||
INSERT INTO "GroupMemberships" VALUES
|
||||
('a', 'group', 'alice', 0, '2026-01-02', NULL),
|
||||
('b1', 'group', 'bob', 0, '2026-01-01', 'inv-1'),
|
||||
('b2', 'group', 'bob', 1, '2026-01-03', 'inv-1'),
|
||||
('c', 'group', 'carol', 0, '2026-01-01', 'inv-1'),
|
||||
('orphan', 'group', 'missing', 0, '2026-01-01', NULL);
|
||||
INSERT INTO "GroupAdmins" VALUES
|
||||
('a1', 'group', 'alice'), ('a2', 'group', 'alice'),
|
||||
('b', 'group', 'bob'), ('orphan', 'group', 'missing');
|
||||
""";
|
||||
await command.ExecuteNonQueryAsync();
|
||||
var migration = new PrimitiveGroupsAndRequiredChannel();
|
||||
command.CommandText = migration.UpOperations.OfType<SqlOperation>().Single().Sql;
|
||||
await command.ExecuteNonQueryAsync();
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupMemberships\"";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(3));
|
||||
command.CommandText = "SELECT \"IsBanned\" FROM \"GroupMemberships\" WHERE \"UserId\" = 'bob'";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(1));
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupAdmins\"";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(1));
|
||||
command.CommandText = "SELECT \"OwnerUserId\" FROM \"ChatGroups\"";
|
||||
Assert.That(await command.ExecuteScalarAsync(), Is.EqualTo("alice"));
|
||||
command.CommandText = "SELECT COUNT(*) FROM \"GroupInvitations\" WHERE \"IsRevoked\" = 1";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(2));
|
||||
command.CommandText = "SELECT \"UsedCount\" FROM \"GroupInvitations\" WHERE \"Id\" = 'inv-1'";
|
||||
Assert.That(Convert.ToInt32(await command.ExecuteScalarAsync()), Is.EqualTo(2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
using Govor.Application.Authentication;
|
||||
using Govor.Application.Groups;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Infrastructure.Validators;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using Govor.Application.Reactions;
|
||||
using Govor.Application.Users;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using Govor.Domain;
|
||||
using System.Data.Common;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Moq;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class GroupTests
|
||||
{
|
||||
private TestDatabase _db = null!;
|
||||
private GroupManagementService _groups = null!;
|
||||
private Mock<INowDateTimeProvider> _clock = null!;
|
||||
private readonly DateTime _now = new(2026, 10, 3, 13, 0, 0, DateTimeKind.Utc);
|
||||
|
||||
[SetUp]
|
||||
public void SetUp()
|
||||
{
|
||||
_db = new TestDatabase();
|
||||
_clock = new Mock<INowDateTimeProvider>();
|
||||
_clock.SetupGet(c => c.Now).Returns(_now);
|
||||
_groups = new GroupManagementService(_db.Context, _clock.Object);
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void TearDown() => _db.Dispose();
|
||||
|
||||
private async Task<Guid> Create(bool isPrivate = false, bool channel = false) =>
|
||||
(await _groups.CreateAsync(_db.Alice, "Community", "Description", isPrivate, channel)).Value.Group.Id;
|
||||
|
||||
[Test]
|
||||
public async Task PublicSearchDoesNotExposePrivateGroupsOrPrivateHistory()
|
||||
{
|
||||
var publicId = await Create();
|
||||
var privateId = await Create(isPrivate: true);
|
||||
Assert.That((await _groups.SearchAsync(_db.Bob, "comm")).Select(g => g.Group.Id), Is.EqualTo(new[] { publicId }));
|
||||
Assert.That((await _groups.GetAsync(_db.Bob, privateId)).Error.Type, Is.EqualTo(ErrorType.NotFound));
|
||||
Assert.That((await _groups.JoinPublicAsync(_db.Bob, privateId)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
var before = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(publicId, _db.Bob, null);
|
||||
Assert.That(before.Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await _groups.JoinPublicAsync(_db.Bob, publicId)).Value.MyRole, Is.EqualTo(GroupRole.Member));
|
||||
Assert.That((await _groups.MineAsync(_db.Bob)).Single().Group.Id, Is.EqualTo(publicId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InvitationPreviewDoesNotJoinAndUsageDoesNotResetAfterLeaving()
|
||||
{
|
||||
var id = await Create(isPrivate: true);
|
||||
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 1, "one use")).Value;
|
||||
Assert.That((await _groups.PreviewInvitationAsync(_db.Bob, invite.InvitationCode)).IsSuccess, Is.True);
|
||||
Assert.That(await _db.Context.GroupMemberships.CountAsync(), Is.EqualTo(1));
|
||||
await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode);
|
||||
await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode);
|
||||
Assert.That(await _db.Context.GroupMemberships.CountAsync(), Is.EqualTo(2));
|
||||
Assert.That((await _groups.InvitationsAsync(_db.Alice, id)).Value.Single().UsedCount, Is.EqualTo(1));
|
||||
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, invite.InvitationCode)).Error.Type, Is.EqualTo(ErrorType.Validation));
|
||||
await _groups.LeaveAsync(_db.Bob, id);
|
||||
Assert.That((await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode)).IsFailure, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ExpiredAndRevokedInvitationsAreRejectedAndMembersCannotIssueThem()
|
||||
{
|
||||
var id = await Create();
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
Assert.That((await _groups.CreateInvitationAsync(_db.Bob, id, 7, 0, "")).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 0, "")).Value;
|
||||
await _groups.RevokeInvitationAsync(_db.Alice, id, invite.Id);
|
||||
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, invite.InvitationCode)).IsFailure, Is.True);
|
||||
var expired = (await _groups.CreateInvitationAsync(_db.Alice, id, 1, 0, "")).Value;
|
||||
_clock.SetupGet(c => c.Now).Returns(_now.AddDays(2));
|
||||
Assert.That((await _groups.JoinByInvitationAsync(_db.Outsider, expired.InvitationCode)).IsFailure, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OwnerControlsProfileAndAdminsCannotEscalateOrBanOwner()
|
||||
{
|
||||
var id = await Create();
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
await _groups.JoinPublicAsync(_db.Outsider, id);
|
||||
Assert.That((await _groups.SetAdministratorAsync(_db.Bob, id, _db.Bob, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
|
||||
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Admin));
|
||||
Assert.That((await _groups.UpdateAsync(_db.Bob, id, "Hijacked", "", true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await _groups.SetBanAsync(_db.Bob, id, _db.Alice, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Outsider, true);
|
||||
Assert.That((await _groups.SetBanAsync(_db.Bob, id, _db.Outsider, true)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await _groups.UpdateAsync(_db.Alice, id, "Renamed", "new", true)).Value.Group.Name, Is.EqualTo("Renamed"));
|
||||
Assert.That(await _groups.SearchAsync(_db.Bob, ""), Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task BanBlocksRejoiningHistoryPostingReadingAndReactingAndRemovesAdminRole()
|
||||
{
|
||||
var id = await Create();
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
|
||||
var invite = (await _groups.CreateInvitationAsync(_db.Alice, id, 7, 0, "")).Value;
|
||||
var message = _db.AddMessage(chat: id, type: RecipientType.Group);
|
||||
await _groups.SetBanAsync(_db.Alice, id, _db.Bob, true);
|
||||
Assert.That(await _db.Context.GroupAdmins.AnyAsync(a => a.UserId == _db.Bob && a.GroupId == id), Is.False);
|
||||
Assert.That((await _groups.JoinPublicAsync(_db.Bob, id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await _groups.JoinByInvitationAsync(_db.Bob, invite.InvitationCode)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(id, _db.Bob, null)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await Sender().SendMessageAsync(new SendMessage("test", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
|
||||
var reader = new MessageReadingService(_db.Context, NullLogger<MessageReadingService>.Instance, _clock.Object);
|
||||
Assert.That((await reader.ReadMessageAsync(_db.Bob, message.Id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
var reactions = new MessageReactionService(_db.Context, _clock.Object);
|
||||
Assert.That((await reactions.SetAsync(_db.Bob, message.Id, DefaultReactionPack.Items()[0].Id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
Assert.That((await _groups.MembersAsync(_db.Alice, id, true, 0, 50)).Value.Single().UserId, Is.EqualTo(_db.Bob));
|
||||
await _groups.SetBanAsync(_db.Alice, id, _db.Bob, false);
|
||||
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Member));
|
||||
Assert.That((await _groups.MineAsync(_db.Bob)).Count, Is.EqualTo(1));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OwnerAndAdminCanPostInChannelAndDemotionRevokesPostingAndPolicy()
|
||||
{
|
||||
var id = await Create(channel: true);
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
Assert.That((await Sender().SendMessageAsync(new SendMessage("owner", null, id, RecipientType.Group, _db.Alice, _now, []))).IsSuccess, Is.True);
|
||||
Assert.That((await Sender().SendMessageAsync(new SendMessage("member", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
|
||||
var reactions = new MessageReactionService(_db.Context, _clock.Object);
|
||||
Assert.That((await reactions.SetPolicyAsync(_db.Alice, id, ChannelReactionMode.Selected, new[] { DefaultReactionPack.Items()[0].Id })).IsSuccess, Is.True);
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
|
||||
var post = await Sender().SendMessageAsync(new SendMessage("admin", null, id, RecipientType.Group, _db.Bob, _now, []));
|
||||
Assert.That(post.IsSuccess, Is.True);
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, false);
|
||||
Assert.That((await Sender().SendMessageAsync(new SendMessage("demoted", null, id, RecipientType.Group, _db.Bob, _now, []))).IsSuccess, Is.False);
|
||||
Assert.That((await reactions.SetPolicyAsync(_db.Bob, id, ChannelReactionMode.None, Array.Empty<Guid>())).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
var editor = new MessageEditingService(_db.Context, NullLogger<MessageEditingService>.Instance, Options.Create(new MessageEditingOptions()));
|
||||
Assert.That((await editor.EditMessageAsync(new EditMessage(_db.Bob, post.Message.Id, "demoted edit", _now))).IsSuccess, Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GroupAdminsCanDeleteMembersMessagesButMembersCannotDeleteOthers()
|
||||
{
|
||||
var id = await Create();
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
await _groups.JoinPublicAsync(_db.Outsider, id);
|
||||
var message = _db.AddMessage(sender: _db.Outsider, chat: id, type: RecipientType.Group);
|
||||
var remover = new MessageRemovingService(_db.Context, NullLogger<MessageRemovingService>.Instance);
|
||||
Assert.That((await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true))).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
await _groups.SetAdministratorAsync(_db.Alice, id, _db.Bob, true);
|
||||
await _groups.SetBanAsync(_db.Bob, id, _db.Outsider, true);
|
||||
Assert.That((await remover.DeleteMessageAsync(new DeleteMessage(_db.Bob, message.Id, true))).IsSuccess, Is.True);
|
||||
Assert.That(await _db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task OwnershipTransferKeepsOwnerUntilAnActiveSuccessorIsChosen()
|
||||
{
|
||||
var id = await Create();
|
||||
Assert.That((await _groups.LeaveAsync(_db.Alice, id)).Error.Type, Is.EqualTo(ErrorType.Validation));
|
||||
Assert.That((await _groups.TransferOwnershipAsync(_db.Alice, id, _db.Bob)).IsFailure, Is.True);
|
||||
await _groups.JoinPublicAsync(_db.Bob, id);
|
||||
await _groups.TransferOwnershipAsync(_db.Alice, id, _db.Bob);
|
||||
Assert.That((await _groups.GetAsync(_db.Bob, id)).Value.MyRole, Is.EqualTo(GroupRole.Owner));
|
||||
Assert.That((await _groups.GetAsync(_db.Alice, id)).Value.MyRole, Is.EqualTo(GroupRole.Admin));
|
||||
Assert.That((await _groups.LeaveAsync(_db.Alice, id)).IsSuccess, Is.True);
|
||||
Assert.That(await _db.Context.IsGroupAdministratorAsync(id, _db.Alice), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ServerAdminConfiguresRequiredChannelAndRegistrationJoinsAtomically()
|
||||
{
|
||||
var id = await Create(isPrivate: true, channel: true);
|
||||
Assert.That((await _groups.SetRequiredChannelAsync(_db.Bob, id, false)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
|
||||
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
|
||||
var registered = await Account().RegistrationAsync("NewUser", "password", invite);
|
||||
Assert.That(registered.IsSuccess, Is.True);
|
||||
Assert.That(registered.Value.WasOnline, Is.EqualTo(_now));
|
||||
Assert.That((await _groups.MineAsync(registered.Value.Id)).Single().Group.Id, Is.EqualTo(id));
|
||||
Assert.That((await _groups.GetAsync(registered.Value.Id, id)).Value.CanLeave, Is.False);
|
||||
Assert.That((await _groups.LeaveAsync(registered.Value.Id, id)).Error.Type, Is.EqualTo(ErrorType.Forbidden));
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, id, true);
|
||||
Assert.That((await _groups.LeaveAsync(registered.Value.Id, id)).IsSuccess, Is.True);
|
||||
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == _db.Bob && m.GroupId == id), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RequiredChannelRejectsOrdinaryGroupAndCanBeDisabledForNewRegistrations()
|
||||
{
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
|
||||
var groupId = await Create();
|
||||
Assert.That((await _groups.SetRequiredChannelAsync(_db.Alice, groupId, false)).Error.Type, Is.EqualTo(ErrorType.Validation));
|
||||
var channelId = await Create(channel: true);
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, channelId, false);
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, null, true);
|
||||
var registered = await Account().RegistrationAsync("OtherUser", "password", _db.Context.Invitations.Single(i => i.Code == "test"));
|
||||
Assert.That(registered.IsSuccess, Is.True);
|
||||
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == registered.Value.Id), Is.False);
|
||||
}
|
||||
|
||||
[TestCase(0)]
|
||||
[TestCase(2)]
|
||||
public async Task RegistrationFailureDoesNotConsumeInvitationOrCreateMembership(int maxParticipants)
|
||||
{
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
|
||||
var id = await Create(channel: true);
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
|
||||
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
|
||||
await _db.Context.Invitations.Where(i => i.Id == invite.Id).ExecuteUpdateAsync(s => s.SetProperty(i => i.MaxParticipants, maxParticipants));
|
||||
var registered = await Account().RegistrationAsync("Unavailable", "password", invite);
|
||||
Assert.That(registered.IsFailure, Is.True);
|
||||
Assert.That(await _db.Context.Users.AnyAsync(u => u.Username == "Unavailable"), Is.False);
|
||||
Assert.That(await _db.Context.GroupMemberships.CountAsync(m => m.GroupId == id), Is.EqualTo(1));
|
||||
Assert.That(await _db.Context.Invitations.Where(i => i.Id == invite.Id).Select(i => i.Participants).SingleAsync(), Is.Zero);
|
||||
}
|
||||
|
||||
private MessageSendingService Sender() => new(_db.Context, NullLogger<MessageSendingService>.Instance);
|
||||
|
||||
[Test]
|
||||
public async Task RequiredMembershipWriteFailureRollsBackAccountAndInvitation()
|
||||
{
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Alice);
|
||||
var id = await Create(channel: true);
|
||||
await _groups.SetRequiredChannelAsync(_db.Alice, id, false);
|
||||
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
|
||||
using var failing = _db.CreateContext(new FailMembershipInsert());
|
||||
Assert.ThrowsAsync<DbUpdateException>(async () =>
|
||||
await Account(failing).RegistrationAsync("FailedUser", "password", invite));
|
||||
Assert.That(await _db.Context.Users.AnyAsync(u => u.Username == "FailedUser"), Is.False);
|
||||
Assert.That(await _db.Context.Invitations.Where(i => i.Id == invite.Id).Select(i => i.Participants).SingleAsync(), Is.Zero);
|
||||
Assert.That(await _db.Context.GroupMemberships.CountAsync(m => m.GroupId == id), Is.EqualTo(1));
|
||||
}
|
||||
|
||||
private sealed class FailMembershipInsert : DbCommandInterceptor
|
||||
{
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command,
|
||||
CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (command.CommandText.Contains("INSERT INTO \"GroupMemberships\"", StringComparison.Ordinal))
|
||||
throw new InvalidOperationException("Simulated required membership persistence failure.");
|
||||
return ValueTask.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
private AuthService Account(GovorDbContext? context = null)
|
||||
{
|
||||
var username = new Mock<IUsernameValidator>();
|
||||
username.Setup(v => v.Validate(It.IsAny<string>())).Returns(Govor.Domain.Common.Result.Success());
|
||||
var exists = new Mock<IUserNameExistValidator>();
|
||||
exists.Setup(v => v.IsUsernameExistsAsync(It.IsAny<string>())).ReturnsAsync(false);
|
||||
var hash = new Mock<IPasswordHasher>();
|
||||
hash.Setup(h => h.Hash(It.IsAny<string>())).Returns("test hash");
|
||||
return new AuthService(context ?? _db.Context, exists.Object, hash.Object, username.Object, _clock.Object);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Govor.Application.Authentication;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Moq;
|
||||
|
||||
namespace Govor.Server.Tests;
|
||||
|
||||
[TestFixture]
|
||||
public class InvitationClockTests
|
||||
{
|
||||
[TestCase(-1, false)]
|
||||
[TestCase(0, false)]
|
||||
[TestCase(1, true)]
|
||||
public async Task ExpirationUsesInjectedClockIncludingExactBoundary(int offsetMinutes, bool expectedSuccess)
|
||||
{
|
||||
using var db = new TestDatabase();
|
||||
var now = new DateTime(2026, 11, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
var invitation = await db.Context.Invitations.SingleAsync(i => i.Code == "test");
|
||||
invitation.EndDate = now.AddMinutes(offsetMinutes);
|
||||
await db.Context.SaveChangesAsync();
|
||||
var clock = new Mock<INowDateTimeProvider>();
|
||||
clock.SetupGet(c => c.Now).Returns(now);
|
||||
var service = new InvitesService(db.Context, clock.Object);
|
||||
Assert.That((await service.ValidateAsync("test")).IsSuccess, Is.EqualTo(expectedSuccess));
|
||||
clock.VerifyGet(c => c.Now, Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InactiveInvitationIsRejectedEvenWhenItExpiresInTheFuture()
|
||||
{
|
||||
using var db = new TestDatabase();
|
||||
var now = new DateTime(2026, 11, 1, 12, 0, 0, DateTimeKind.Utc);
|
||||
var invitation = await db.Context.Invitations.SingleAsync(i => i.Code == "test");
|
||||
invitation.IsActive = false;
|
||||
invitation.EndDate = now.AddDays(1);
|
||||
await db.Context.SaveChangesAsync();
|
||||
var clock = new Mock<INowDateTimeProvider>();
|
||||
clock.SetupGet(c => c.Now).Returns(now);
|
||||
Assert.That((await new InvitesService(db.Context, clock.Object).ValidateAsync("test")).IsFailure, Is.True);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Users;
|
||||
using Microsoft.AspNetCore.SignalR;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Moq;
|
||||
using SmartRes;
|
||||
@@ -22,7 +23,7 @@ public class NotificationTests
|
||||
private Mock<IPushNotificationService> _push = null!;
|
||||
private Mock<IClientProxy> _proxy = null!;
|
||||
private ChatNotificationService _notifier = null!;
|
||||
private readonly List<(string Method, string[] Groups)> _events = [];
|
||||
private readonly List<(string Method, string[] Groups, object Payload)> _events = [];
|
||||
private string[] _targetGroups = [];
|
||||
private Guid _aliceSession;
|
||||
private Guid _bobSession;
|
||||
@@ -38,7 +39,7 @@ public class NotificationTests
|
||||
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)))
|
||||
.Callback<string, object?[], CancellationToken>((method, args, _) => _events.Add((method, _targetGroups, args[0]!)))
|
||||
.Returns(Task.CompletedTask);
|
||||
var clients = new Mock<IHubClients>();
|
||||
clients.Setup(c => c.Groups(It.IsAny<IReadOnlyList<string>>()))
|
||||
@@ -146,6 +147,80 @@ public class NotificationTests
|
||||
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GroupProfileChangeReachesAllActiveDevicesWithoutLeakingToBannedOrForeignUsers()
|
||||
{
|
||||
var group = AddGroup();
|
||||
var secondDevice = AddSession(_db.Bob);
|
||||
var expired = AddSession(_db.Bob);
|
||||
await _db.Context.UserSessions.Where(s => s.Id == expired)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(s => s.ExpiresAt, DateTime.UtcNow.AddMinutes(-1)));
|
||||
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
|
||||
Assert.That(_events.Single().Method, Is.EqualTo(ChatHubConstants.GroupProfileChanged));
|
||||
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
|
||||
{
|
||||
ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession),
|
||||
ChatHubConstants.GetSessionGroup(secondDevice)
|
||||
}));
|
||||
Assert.That(((GroupProfileChangedResponse)_events.Single().Payload).GroupId, Is.EqualTo(group.Id));
|
||||
}
|
||||
|
||||
[TestCase(GroupMemberStatus.Active, GroupRole.Member)]
|
||||
[TestCase(GroupMemberStatus.Active, GroupRole.Admin)]
|
||||
[TestCase(GroupMemberStatus.Active, GroupRole.Owner)]
|
||||
[TestCase(GroupMemberStatus.Banned, null)]
|
||||
[TestCase(GroupMemberStatus.Left, null)]
|
||||
public async Task MembershipEventReportsCommittedStatusAndStillReachesAffectedUser(GroupMemberStatus status, GroupRole? role)
|
||||
{
|
||||
var group = AddGroup();
|
||||
if (status == GroupMemberStatus.Banned)
|
||||
await _db.Context.GroupMemberships.Where(m => m.GroupId == group.Id && m.UserId == _db.Bob)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.IsBanned, true));
|
||||
if (status == GroupMemberStatus.Left)
|
||||
await _db.Context.GroupMemberships.Where(m => m.GroupId == group.Id && m.UserId == _db.Bob).ExecuteDeleteAsync();
|
||||
if (role == GroupRole.Admin)
|
||||
{
|
||||
_db.Context.GroupAdmins.Add(new GroupAdmins { Id = Guid.NewGuid(), GroupId = group.Id, UserId = _db.Bob });
|
||||
await _db.Context.SaveChangesAsync();
|
||||
}
|
||||
if (role == GroupRole.Owner)
|
||||
await _db.Context.ChatGroups.Where(g => g.Id == group.Id).ExecuteUpdateAsync(s => s.SetProperty(g => g.OwnerUserId, _db.Bob));
|
||||
await _notifier.NotifyGroupMemberChangedAsync(group.Id, _db.Bob);
|
||||
var change = (GroupMemberChangedResponse)_events.Single().Payload;
|
||||
Assert.That(change.GroupId, Is.EqualTo(group.Id));
|
||||
Assert.That(change.UserId, Is.EqualTo(_db.Bob));
|
||||
Assert.That(change.Status, Is.EqualTo(status));
|
||||
Assert.That(change.Role, Is.EqualTo(role));
|
||||
Assert.That(_events.Single().Groups, Is.EquivalentTo(new[]
|
||||
{ ChatHubConstants.GetSessionGroup(_aliceSession), ChatHubConstants.GetSessionGroup(_bobSession) }));
|
||||
_events.Clear();
|
||||
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
|
||||
Assert.That(_events.Single().Groups.Contains(ChatHubConstants.GetSessionGroup(_bobSession)),
|
||||
Is.EqualTo(status == GroupMemberStatus.Active));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GroupEventDeliveryFailureDoesNotFailTheAlreadyCommittedOperation()
|
||||
{
|
||||
var group = AddGroup();
|
||||
_proxy.Setup(p => p.SendCoreAsync(It.IsAny<string>(), It.IsAny<object?[]>(), It.IsAny<CancellationToken>()))
|
||||
.ThrowsAsync(new InvalidOperationException("offline"));
|
||||
await _notifier.NotifyGroupProfileChangedAsync(group.Id);
|
||||
await _notifier.NotifyGroupMemberChangedAsync(group.Id, _db.Bob);
|
||||
await _notifier.NotifyUserJoinedGroupsAsync(_db.Bob);
|
||||
}
|
||||
|
||||
private ChatGroup AddGroup()
|
||||
{
|
||||
var group = new ChatGroup { Id = Guid.NewGuid(), Name = "Private", Description = "", IsPrivate = true, OwnerUserId = _db.Alice };
|
||||
_db.Context.ChatGroups.Add(group);
|
||||
foreach (var userId in new[] { _db.Alice, _db.Bob, _db.Outsider })
|
||||
_db.Context.GroupMemberships.Add(new GroupMembership
|
||||
{ Id = Guid.NewGuid(), GroupId = group.Id, UserId = userId, IsBanned = userId == _db.Outsider });
|
||||
_db.Context.SaveChanges();
|
||||
return group;
|
||||
}
|
||||
|
||||
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) };
|
||||
|
||||
@@ -2,8 +2,10 @@ using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using System.Net.WebSockets;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Govor.API.Hubs.Infrastructure;
|
||||
using Govor.API.Hubs;
|
||||
using Govor.Application.Storage;
|
||||
@@ -52,6 +54,9 @@ public class ReadApiTests
|
||||
_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);
|
||||
_notifier.Setup(n => n.NotifyGroupProfileChangedAsync(It.IsAny<Guid>())).Returns(Task.CompletedTask);
|
||||
_notifier.Setup(n => n.NotifyGroupMemberChangedAsync(It.IsAny<Guid>(), It.IsAny<Guid>())).Returns(Task.CompletedTask);
|
||||
_notifier.Setup(n => n.NotifyUserJoinedGroupsAsync(It.IsAny<Guid>())).Returns(Task.CompletedTask);
|
||||
_factory = new TestFactory(_db, _notifier.Object);
|
||||
_client = _factory.CreateClient();
|
||||
}
|
||||
@@ -200,18 +205,291 @@ public class ReadApiTests
|
||||
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")
|
||||
[Test]
|
||||
public async Task PrivateGroupHttpInvitationPreviewJoinAndRolesRespectPermissions()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "PrivateGroup", description = "test", isPrivate = true });
|
||||
Assert.That(created.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
|
||||
Assert.That(group.MyRole, Is.EqualTo(Govor.Domain.Models.GroupRole.Owner));
|
||||
Assert.That(group.MemberCount, Is.EqualTo(1));
|
||||
var invitation = await _client.PostAsJsonAsync($"/api/groups/{group.Id}/invitations", new { maxParticipants = 1 });
|
||||
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync($"/api/groups/{group.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
Assert.That((await _client.GetFromJsonAsync<List<GroupResponse>>("/api/groups/search?q=PrivateGroup")), Is.Empty);
|
||||
Assert.That((await _client.GetAsync(link.PreviewPath)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.GroupId == group.Id && m.UserId == _db.Alice), Is.False);
|
||||
Assert.That((await _client.PostAsync(link.JoinPath, null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{group.Id}", new { name = "Hijacked" })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Authorize();
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Bob}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _client.GetAsync($"/api/groups/{group.Id}/messages")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ChannelOwnerControlsReactionsAndModerationHttpNotifiesDeletion()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Channel", isPrivate = false, isChannel = true });
|
||||
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
|
||||
var id = group.Id;
|
||||
var policy = await _client.PutAsJsonAsync($"/api/groups/{id}/reactions", new
|
||||
{ mode = 2, reactionIds = new[] { DefaultReactionPack.Items()[0].Id } });
|
||||
Assert.That(policy.StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyChannelReactionPolicyChangedAsync(It.Is<ChannelReactionPolicyResponse>(p => p.GroupId == id)), Times.Once);
|
||||
Authorize(userId: _db.Alice);
|
||||
await _client.PostAsync($"/api/groups/{id}/join", null);
|
||||
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}/reactions", new { mode = 1 })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Authorize();
|
||||
var own = _db.AddMessage(sender: _db.Bob, chat: id, type: Govor.Domain.Models.Messages.RecipientType.Group);
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{Guid.NewGuid()}/messages/{own.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/messages/{own.Id}")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
_notifier.Verify(n => n.NotifyMessageRemovedAsync(It.Is<MessageRemovedResponse>(m => m.MessageId == own.Id && m.RecipientId == id)), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RequiredChannelHttpRequiresServerAdminAndRegistrationAddsMembership()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Required", isPrivate = true, isChannel = true });
|
||||
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Authorize(role: "Admin");
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Bob);
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = id, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
var invite = _db.Context.Invitations.Single(i => i.Code == "test");
|
||||
invite.Code = Guid.NewGuid().ToString("N");
|
||||
await _db.Context.SaveChangesAsync();
|
||||
_client.DefaultRequestHeaders.Authorization = null;
|
||||
var registered = await _client.PostAsJsonAsync("/api/auth/register", new
|
||||
{ name = "НовыйУчастник123", password = "Secure-test123!", inviteLink = invite.Code, deviceInfo = "test" });
|
||||
Assert.That(registered.StatusCode, Is.EqualTo(HttpStatusCode.OK), await registered.Content.ReadAsStringAsync());
|
||||
var user = await _db.Context.Users.AsNoTracking().SingleAsync(u => u.Username == "НовыйУчастник123");
|
||||
_notifier.Verify(n => n.NotifyUserJoinedGroupsAsync(user.Id), Times.Once);
|
||||
Assert.That(await _db.Context.GroupMemberships.AnyAsync(m => m.UserId == user.Id && m.GroupId == id && !m.IsBanned), Is.True);
|
||||
Authorize(userId: user.Id);
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GroupAvatarIsOwnerControlledAndPrivateFilesAreProtected()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "AvatarGroup", isPrivate = false });
|
||||
var group = (await created.Content.ReadFromJsonAsync<GroupResponse>())!;
|
||||
using var image = new Image<Rgba32>(256, 256);
|
||||
using var bytes = new MemoryStream();
|
||||
await image.SaveAsPngAsync(bytes);
|
||||
using var form = new MultipartFormDataContent();
|
||||
form.Add(new ByteArrayContent(bytes.ToArray()), "file", "avatar.png");
|
||||
Assert.That((await _client.PostAsync($"/api/groups/{group.Id}/avatar", form)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Once);
|
||||
var updated = (await _client.GetFromJsonAsync<GroupResponse>($"/api/groups/{group.Id}"))!;
|
||||
Assert.That(updated.ImageId, Is.Not.EqualTo(Guid.Empty));
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/avatar")).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Once);
|
||||
Authorize();
|
||||
await _client.PutAsJsonAsync($"/api/groups/{group.Id}", new { name = "AvatarGroup", isPrivate = true });
|
||||
var invitation = await _client.PostAsJsonAsync($"/api/groups/{group.Id}/invitations", new { });
|
||||
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
await _client.PostAsync(link.JoinPath, null);
|
||||
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Authorize();
|
||||
await _client.PutAsync($"/api/groups/{group.Id}/members/{_db.Alice}/ban", null);
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync(updated.ImageUrl)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Authorize();
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{group.Id}/avatar")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(group.Id), Times.Exactly(3));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task GroupCommandsNotifyAfterSuccessAndDeniedCommandsDoNotNotify()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Live", isPrivate = false });
|
||||
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Once);
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.PostAsync($"/api/groups/{id}/join", null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
|
||||
_notifier.Invocations.Clear();
|
||||
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Forbidden", isPrivate = false })).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Bob}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Bob}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.Forbidden));
|
||||
Assert.That(_notifier.Invocations, Is.Empty);
|
||||
Authorize();
|
||||
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Renamed", isPrivate = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(id), Times.Once);
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/{_db.Alice}/administrator")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/{_db.Alice}/ban")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Exactly(4));
|
||||
_notifier.Invocations.Clear();
|
||||
Assert.That((await _client.PostAsync($"/api/groups/{id}/ownership/{_db.Alice}", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(id), Times.Once);
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Once);
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
|
||||
Assert.That((await _client.DeleteAsync($"/api/groups/{id}/members/me")).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Bob), Times.Exactly(2));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task InvitationPreviewDoesNotNotifyAndSuccessfulJoinDoes()
|
||||
{
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Invite", isPrivate = true });
|
||||
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
var invitation = await _client.PostAsJsonAsync($"/api/groups/{id}/invitations", new { });
|
||||
var link = (await invitation.Content.ReadFromJsonAsync<GroupInvitationResponse>())!;
|
||||
_notifier.Invocations.Clear();
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync(link.PreviewPath)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
Assert.That((await _client.PostAsync("/api/group-invites/invalid/join", null)).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
Assert.That(_notifier.Invocations, Is.Empty);
|
||||
Assert.That((await _client.PostAsync(link.JoinPath, null)).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupMemberChangedAsync(id, _db.Alice), Times.Once);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RequiredChannelChangeNotifiesOldAndNewChannelButFailedChangeDoesNot()
|
||||
{
|
||||
ReactionTests.MakeAdmin(_db.Context, _db.Bob);
|
||||
Authorize(role: "Admin");
|
||||
var first = await _client.PostAsJsonAsync("/api/groups", new { name = "First", isChannel = true });
|
||||
var second = await _client.PostAsJsonAsync("/api/groups", new { name = "Second", isChannel = true });
|
||||
var firstId = (await first.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
var secondId = (await second.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
_notifier.Invocations.Clear();
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = firstId, allowLeave = false })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(firstId), Times.Once);
|
||||
_notifier.Invocations.Clear();
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = secondId, allowLeave = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(firstId), Times.Once);
|
||||
_notifier.Verify(n => n.NotifyGroupProfileChangedAsync(secondId), Times.Once);
|
||||
_notifier.Invocations.Clear();
|
||||
Assert.That((await _client.PutAsJsonAsync("/api/admin/required-channel", new { channelId = Guid.NewGuid() })).StatusCode, Is.EqualTo(HttpStatusCode.BadRequest));
|
||||
Assert.That(_notifier.Invocations, Is.Empty);
|
||||
}
|
||||
|
||||
private void Authorize(string tokenType = "access", string role = "User", Guid? userId = null)
|
||||
{
|
||||
var actorId = userId ?? _db.Bob;
|
||||
var sessionId = _session;
|
||||
if (actorId != _db.Bob)
|
||||
{
|
||||
var session = new UserSession { UserId = actorId, RefreshTokenHash = Guid.NewGuid().ToString("N"), ExpiresAt = DateTime.UtcNow.AddDays(1) };
|
||||
_db.Context.UserSessions.Add(session);
|
||||
_db.Context.SaveChanges();
|
||||
sessionId = session.Id;
|
||||
}
|
||||
var token = new JwtSecurityToken(claims: new[]
|
||||
{
|
||||
new Claim("userId", _db.Bob.ToString()), new Claim("sid", _session.ToString()),
|
||||
new Claim("userId", actorId.ToString()), new Claim("sid", sessionId.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>
|
||||
[Test]
|
||||
public async Task GroupChangesArriveOverRealSignalRConnectionsForBothParticipants()
|
||||
{
|
||||
_client.Dispose();
|
||||
_factory.Dispose();
|
||||
_factory = new TestFactory(_db, null);
|
||||
_client = _factory.CreateClient();
|
||||
Authorize();
|
||||
var created = await _client.PostAsJsonAsync("/api/groups", new { name = "Realtime", isPrivate = false });
|
||||
var id = (await created.Content.ReadFromJsonAsync<GroupResponse>())!.Id;
|
||||
Authorize(userId: _db.Alice);
|
||||
await _client.PostAsync($"/api/groups/{id}/join", null);
|
||||
using var alice = await ConnectHubAsync();
|
||||
Authorize();
|
||||
using var bob = await ConnectHubAsync();
|
||||
Assert.That((await _client.PutAsJsonAsync($"/api/groups/{id}", new { name = "Live profile", isPrivate = true })).StatusCode, Is.EqualTo(HttpStatusCode.OK));
|
||||
foreach (var connection in new[] { alice, bob })
|
||||
{
|
||||
var frame = await connection.ReadAsync();
|
||||
Assert.That(frame.GetProperty("target").GetString(), Is.EqualTo("GroupProfileChanged"));
|
||||
Assert.That(frame.GetProperty("arguments")[0].GetProperty("groupId").GetGuid(), Is.EqualTo(id));
|
||||
}
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/administrator", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
foreach (var connection in new[] { alice, bob })
|
||||
{
|
||||
var frame = await connection.ReadAsync();
|
||||
Assert.That(frame.GetProperty("target").GetString(), Is.EqualTo("GroupMemberChanged"));
|
||||
var change = frame.GetProperty("arguments")[0];
|
||||
Assert.That(change.GetProperty("userId").GetGuid(), Is.EqualTo(_db.Alice));
|
||||
Assert.That(change.GetProperty("status").GetInt32(), Is.Zero);
|
||||
Assert.That(change.GetProperty("role").GetInt32(), Is.EqualTo(1));
|
||||
}
|
||||
Assert.That((await _client.PutAsync($"/api/groups/{id}/members/{_db.Alice}/ban", null)).StatusCode, Is.EqualTo(HttpStatusCode.NoContent));
|
||||
foreach (var connection in new[] { alice, bob })
|
||||
{
|
||||
var change = (await connection.ReadAsync()).GetProperty("arguments")[0];
|
||||
Assert.That(change.GetProperty("status").GetInt32(), Is.EqualTo(1));
|
||||
Assert.That(change.GetProperty("role").ValueKind, Is.EqualTo(JsonValueKind.Null));
|
||||
}
|
||||
Authorize(userId: _db.Alice);
|
||||
Assert.That((await _client.GetAsync($"/api/groups/{id}")).StatusCode, Is.EqualTo(HttpStatusCode.NotFound));
|
||||
}
|
||||
|
||||
private async Task<TestHubConnection> ConnectHubAsync()
|
||||
{
|
||||
var client = _factory.Server.CreateWebSocketClient();
|
||||
var authorization = _client.DefaultRequestHeaders.Authorization;
|
||||
client.ConfigureRequest = request => request.Headers.Authorization = authorization!.ToString();
|
||||
var connection = new TestHubConnection(await client.ConnectAsync(new Uri("ws://localhost/hubs/chats"), CancellationToken.None));
|
||||
await connection.SendAsync("{\"protocol\":\"json\",\"version\":1}");
|
||||
Assert.That((await connection.ReadAsync()).EnumerateObject().Count(), Is.Zero);
|
||||
// A completion proves OnConnectedAsync has finished joining the session group.
|
||||
await connection.SendAsync("{\"type\":1,\"invocationId\":\"ready\",\"target\":\"Unknown\",\"arguments\":[]}");
|
||||
Assert.That((await connection.ReadAsync()).GetProperty("type").GetInt32(), Is.EqualTo(3));
|
||||
return connection;
|
||||
}
|
||||
|
||||
private sealed class TestHubConnection(WebSocket socket) : IDisposable
|
||||
{
|
||||
private string _pending = "";
|
||||
public Task SendAsync(string json) => socket.SendAsync(Encoding.UTF8.GetBytes(json + '\u001e'), WebSocketMessageType.Text, true, CancellationToken.None);
|
||||
|
||||
public async Task<JsonElement> ReadAsync()
|
||||
{
|
||||
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
|
||||
var buffer = new byte[4096];
|
||||
while (true)
|
||||
{
|
||||
var separator = _pending.IndexOf('\u001e');
|
||||
if (separator >= 0)
|
||||
{
|
||||
using var document = JsonDocument.Parse(_pending[..separator]);
|
||||
_pending = _pending[(separator + 1)..];
|
||||
if (document.RootElement.TryGetProperty("type", out var type) && type.GetInt32() == 6) continue;
|
||||
return document.RootElement.Clone();
|
||||
}
|
||||
var result = await socket.ReceiveAsync(buffer, timeout.Token);
|
||||
Assert.That(result.MessageType, Is.EqualTo(WebSocketMessageType.Text));
|
||||
_pending += Encoding.UTF8.GetString(buffer, 0, result.Count);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => socket.Dispose();
|
||||
}
|
||||
|
||||
private sealed class TestFactory(TestDatabase db, IChatNotificationService? notifier) : WebApplicationFactory<Program>
|
||||
{
|
||||
protected override void ConfigureWebHost(IWebHostBuilder builder)
|
||||
{
|
||||
@@ -221,13 +499,18 @@ public class ReadApiTests
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddDataProtection().UseEphemeralDataProtectionProvider();
|
||||
services.RemoveAll<IDataProtectionProvider>();
|
||||
services.AddSingleton<IDataProtectionProvider>(new EphemeralDataProtectionProvider());
|
||||
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);
|
||||
if (notifier is not null)
|
||||
{
|
||||
services.RemoveAll<IChatNotificationService>();
|
||||
services.AddSingleton(notifier);
|
||||
}
|
||||
services.RemoveAll<IStorageService>();
|
||||
services.AddSingleton<IStorageService>(new TestReactionStorage());
|
||||
});
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ Govor — мессенджер на ASP.NET Core и .NET MAUI. Эта докум
|
||||
| Профиль | Описание, аватар, загрузка профиля и события изменений |
|
||||
| Присутствие | События подключения/отключения; исправлены зависимости HTTP status |
|
||||
| Медиа и push | Доступ к вложениям, привязка FCM к сессии, очередь и повторные попытки |
|
||||
| Группы | Модели и часть сервисов сообщений; полноценный сценарий управления не завершён |
|
||||
| Группы и каналы | [Публичный поиск, приватные приглашения, владелец/админы/участники, баны, модерация и обязательный канал](endpoints/groups.md) |
|
||||
| Шифрование | Есть хранение публичных ключей, но готового E2EE нет |
|
||||
|
||||
## Как читать
|
||||
@@ -28,7 +28,7 @@ Govor — мессенджер на ASP.NET Core и .NET MAUI. Эта докум
|
||||
|
||||
## Границы готовности
|
||||
|
||||
Текущая версия не готова к открытому развёртыванию: обнаружены критичные ошибки авторизации и доступа к личным чатам. Контракты ниже полезны для разработки, но не являются подтверждением безопасности.
|
||||
Документация новых групп и реакций описывает рабочую серверную копию с исправлениями доступа. Проверки HTTP/JWT, SQL и прав выполняются автоматическими тестами; реальная доставка на устройства и производственное развёртывание требуют отдельной проверки. Страницы с commit `4603be9` фиксируют старую диагностику и не описывают все текущие исправления.
|
||||
|
||||
Эффект стекла относится к MAUI-интерфейсу. API передаёт данные и события; производительность размытия, контрастность и анимации нужно проверять отдельно на устройствах.
|
||||
|
||||
|
||||
+2
-1
@@ -14,12 +14,13 @@
|
||||
* [История сообщений](endpoints/chatloadcontroller.md)
|
||||
* [Прочтение сообщений и счётчики](endpoints/message-read.md)
|
||||
* [Реакции, паки и настройки каналов](endpoints/reactions.md)
|
||||
* [Группы и каналы](endpoints/groups.md)
|
||||
* [Медиа](endpoints/mediacontroller.md)
|
||||
* [Профиль и аватар](endpoints/profile.md)
|
||||
* [Push-уведомления](endpoints/push.md)
|
||||
* [HTTP-присутствие — ограничения](endpoints/onlinepingingcontroller-ne-rabotaet.md)
|
||||
* [Ключи сессий — экспериментальный API](endpoints/session-keys.md)
|
||||
* [Администрирование и незавершённые группы](endpoints/admin-and-groups.md)
|
||||
* [Администрирование сервера](endpoints/admin-and-groups.md)
|
||||
* [ChatsHub — сообщения](signalr/chathub.md)
|
||||
* [PresenceHub — online и offline](signalr/presencehub.md)
|
||||
* [FriendsHub — заявки](friendshub/README.md)
|
||||
|
||||
+12
-29
@@ -1,41 +1,24 @@
|
||||
# Архитектура и границы
|
||||
|
||||
## Поток запроса
|
||||
MAUI → HTTP Controller / SignalR Hub → Application service → GovorDbContext → PostgreSQL. Бинарные файлы хранятся через IStorageService; транспорт событий и push вынесен в ChatNotificationService.
|
||||
|
||||
MAUI → HTTP Controller / SignalR Hub → Application service → GovorDbContext → PostgreSQL. Медиа-сервис сохраняет бинарные данные через LocalStorageService; ChatNotificationService отправляет SignalR-события и push через Firebase.
|
||||
|
||||
| Проект | Ответственность сейчас |
|
||||
| Проект | Ответственность |
|
||||
| --- | --- |
|
||||
| Govor.API | Маршруты, хабы, авторизация, DI, преобразование ошибок и DTO |
|
||||
| Govor.Application | Сценарии пользователей, друзей, сообщений, медиа и push |
|
||||
| Govor.Contracts | HTTP/SignalR запросы, ответы и DTO |
|
||||
| Govor.API | Маршруты, хабы, активные access-сессии, DI, ошибки, DTO и уведомления |
|
||||
| Govor.Application | Пользователи, группы/каналы, права, сообщения, реакции, медиа и push |
|
||||
| Govor.Contracts | HTTP/SignalR запросы и ответы |
|
||||
| Govor.Domain | Сущности, DbContext, EF-конфигурации и миграции |
|
||||
|
||||
Это многослойное приложение, но Domain уже зависит от EF Core и содержит инфраструктуру БД. Не следует описывать его как полностью независимую доменную модель.
|
||||
Domain зависит от EF Core и содержит инфраструктуру БД. PrivateChat связывает двух пользователей; Message.RecipientId указывает на PrivateChat при RecipientType.User=0 либо ChatGroup при Group=1. Это ID чата, а не получателя-пользователя.
|
||||
|
||||
## Хранение и идентификаторы
|
||||
Роль сервера в JWT берётся из Invitation.IsAdmin. Роль группы вычисляется отдельно: ChatGroup.OwnerUserId — владелец, GroupAdmins — админы, активная GroupMembership — участники. GroupAccess объединяет права владельца/админа с незаблокированным членством; ChatAccess проверяет доступ к конкретному чату. Уникальные индексы запрещают дубли членства и административных ролей.
|
||||
|
||||
PrivateChat связывает UserAId и UserBId. Message хранит SenderId и полиморфный RecipientId: ID PrivateChat для RecipientType.User или ID ChatGroup для RecipientType.Group. Ошибки возникают там, где этот ID сравнивают с ID пользователя.
|
||||
GroupManagementService сериализует изменения членства, ролей и ссылок на строке группы. Публикации, редактура, удаление, реакции и настройки канала используют тот же порядок блокировки. GroupAvatarService меняет аватар только для действующего владельца. Регистрация атомарно создаёт пользователя, расходует приглашение и добавляет членство в обязательном канале из ServerCommunitySettings; изменение этой настройки сериализуется с регистрацией.
|
||||
|
||||
Роль access token получается из приглашения пользователя (`Invite.IsAdmin`), хотя есть отдельная сущность Admin. Нужен один источник истины для ролей.
|
||||
Соединения ChatsHub автоматически входят в группы сессий. SignalR-события направляются активным сессиям действующих участников из БД; заблокированные участники исключаются. ConnectionStore и OnlineUserStore остаются в памяти одного процесса; для нескольких экземпляров нужна общая инфраструктура SignalR/presence.
|
||||
|
||||
## Состояние соединений
|
||||
Сообщение и задача push сохраняются атомарно; ChatPushWorker повторяет неудачные доставки. После успешного HTTP сохранения ChatNotificationService отправляет GroupProfileChanged и GroupMemberChanged через ChatsHub. Профиль перечитывается индивидуально через HTTP; статус/роль членства читаются после команды. При бане/выходе только событие собственного членства дополнительно доставляется пользователю, потерявшему доступ. Остальные события по-прежнему получают действующие участники. Отказ в правах/валидации не создаёт событий; сбой доставки не отменяет сохранение.
|
||||
|
||||
ConnectionStore и OnlineUserStore — singleton в памяти одного процесса. Подключения автоматически вступают в группы пользователя, его чатов и групп. Перезапуск очищает это состояние; несколько инстансов без общего решения для SignalR и presence не имеют согласованного состояния.
|
||||
|
||||
## Рекомендуемые решения
|
||||
|
||||
1. Ввести общую проверку участия в конкретном чате и применять её к истории, Send, Read, медиа и событиям.
|
||||
2. Разделить команды и чтение: создание чата и смена пароля не должны выполняться GET-запросами.
|
||||
3. Возвращать только DTO, особенно для криптосессий и медиа.
|
||||
4. Описать ошибки единым контрактом, сохранив совместимость с MAUI.
|
||||
5. Для доставки отделить сохранение сообщения от внешних уведомлений: outbox и повторная доставка с дедупликацией.
|
||||
6. Принять отдельное решение о E2EE: протокол, проверка ключей, несколько устройств, восстановление и миграция существующих сообщений.
|
||||
|
||||
Это предложения, они не внедрены в рамках переписывания документации.
|
||||
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
|
||||
Источник: [Govor.Domain/GovorDbContext.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.Domain/GovorDbContext.cs).
|
||||
SignalR-события не имеют долговременной очереди. Клиент восстанавливает историю, прочтение, версии реакций, свои группы, открытый профиль и участников после reconnect через HTTP. Для реакций/политик и изменений сообществ push не отправляется. При параллельных командах порядок событий не гарантирован, поэтому актуальные права берутся из HTTP состояния, а не из последнего полученного уведомления.
|
||||
|
||||
[Группы и каналы](endpoints/groups.md), [реакции](endpoints/reactions.md), [прочтение](endpoints/message-read.md) описывают текущую рабочую версию. E2EE, согласованное присутствие между инстансами и ключ идемпотентности отправки сообщений остаются отдельными задачами.
|
||||
|
||||
@@ -1,35 +1,20 @@
|
||||
# Администрирование и незавершённые группы
|
||||
# Администрирование сервера
|
||||
|
||||
## Административные маршруты
|
||||
Серверные административные маршруты требуют роль Admin и активную access-сессию. Администратор сервера и админ группы — разные права: роль в группе не открывает маршруты `/api/admin`.
|
||||
|
||||
Следующая таблица показывает фактические атрибуты, а не требуемую безопасную политику.
|
||||
|
||||
| Метод | Маршрут | Защита сейчас |
|
||||
| Метод | Маршрут | Назначение |
|
||||
| --- | --- | --- |
|
||||
| POST | /api/admin/InviteUser/Invitation | Без Authorize |
|
||||
| GET | /api/admin/InviteUser | Без Authorize |
|
||||
| GET | /api/admin/InviteUser/GetAllActiveInvitations | Без Authorize |
|
||||
| GET | /api/admin/InviteUser/{id} | Без Authorize |
|
||||
| GET | /api/admin/Users/all | Любой аутентифицированный пользователь |
|
||||
| GET | /api/admin/Users/{id} | Любой аутентифицированный пользователь |
|
||||
| GET | /api/admin/Users/user/{id}/setpassword/{password} | Любой аутентифицированный пользователь |
|
||||
| POST | `/api/admin/InviteUser/Invitation` | Приглашение регистрации: endDate, maxParticipants, isAdmin, description |
|
||||
| GET | `/api/admin/InviteUser` | Список приглашений |
|
||||
| GET | `/api/admin/InviteUser/GetAllActiveInvitations` | Активные приглашения |
|
||||
| GET | `/api/admin/InviteUser/{id}` | Приглашение по ID |
|
||||
| GET | `/api/admin/Users/all` | До 50 пользователей |
|
||||
| GET | `/api/admin/Users/{id}` | Пользователь по ID |
|
||||
| POST | `/api/admin/Users/user/{id}/password` | `{ "password": "..." }`; 204, отзыв сессий и push-токенов |
|
||||
| GET / PUT | `/api/admin/required-channel` | Канал для всех новых пользователей, право выхода |
|
||||
|
||||
CreateInvitationRequest: endDate, maxParticipants, isAdmin, description. Генератор возвращает строковый код в JSON (200). Списки приглашений возвращают id, description, isAdmin, maxParticipants, code, createdAt, endAt, isActive, participantCount.
|
||||
UserResponse не содержит passwordHash. Старый GET смены пароля с паролем в URL удалён. JWT роль Admin формируется по Invitation.IsAdmin пользователя. Настройки обязательного канала и изменения паков реакций дополнительно проверяют это право в БД.
|
||||
|
||||
Users/all фактически ограничен 50 записями без стабильной пагинации. Ответ UserResponse включает passwordHash, что недопустимо для клиентского контракта. Смена пароля выполняется GET и кладёт пароль в URL.
|
||||
|
||||
Эти маршруты нужно закрыть ролью Admin до публичного использования. Создание административного приглашения вместе с регистрацией позволяет получить роль Admin. Не подключайте их к пользовательскому интерфейсу.
|
||||
|
||||
## Группы
|
||||
|
||||
GET /invite/{code} задуман как вход в группу и требует Authorize. IGroupService не зарегистрирован в AddServices, а _currentUser не присваивается. Маршрут не является рабочим сценарием вступления.
|
||||
|
||||
GroupsHub пуст и не подключён MapHub. Административный FriendshipsController содержит только закомментированные действия, поэтому рабочих endpoints у него нет.
|
||||
|
||||
Наличие моделей ChatGroup/GroupMembership/GroupInvitation и проверки участия в групповом Send не подтверждает готовый продуктовый сценарий групп и каналов.
|
||||
|
||||
---
|
||||
Проверено по исходникам на 03.10.2026, commit `4603be9`. Описано текущее поведение; успешная сборка не означает проверку работающего сервера.
|
||||
|
||||
Источник: [Govor.API/Controllers/AdminStuff/UsersController.cs](https://github.com/Govor-team/Govor/blob/4603be9f714135e0af72d505d17f3d1709834bea/Govor.API/Controllers/AdminStuff/UsersController.cs).
|
||||
Паки: [административный API реакций](reactions.md). Обязательный канал, владелец/админы, приглашения и модерация: [группы и каналы](groups.md).
|
||||
|
||||
Создание административных приглашений выдаёт возможность зарегистрировать серверного администратора, поэтому этот API предназначен только для доверенных администраторов сервера. Административный FriendshipsController и пустой GroupsHub остаются неиспользуемыми заготовками.
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
# Группы и каналы
|
||||
|
||||
Рабочий серверный API от 04.10.2026. Все маршруты требуют access token и активную сессию. Группа — чат с публикацией для всех активных участников; канал — группа с IsChannel=true, где публиковать и редактировать свои публикации могут только владелец и админы. Тип сообщества задаётся при создании и не меняется через профиль.
|
||||
|
||||
Публичные сообщества доступны поиску Govor и вступлению по ID. Приватные сообщества не появляются в поиске: вступление выполняется по действующей ссылке. История, участники, закрытые аватары и команды сообщений доступны только незаблокированным участникам, даже если само сообщество публично.
|
||||
|
||||
## Создание, поиск и профиль
|
||||
|
||||
| Метод | Маршрут | Тело / результат |
|
||||
| --- | --- | --- |
|
||||
| POST | `/api/groups` | name, description, isPrivate, isChannel; GroupResponse |
|
||||
| GET | `/api/groups/search?q=...&skip=0&take=50` | Публичные группы и каналы, поиск по имени/описанию |
|
||||
| GET | `/api/groups/mine?skip=0&take=50` | Сообщества текущего пользователя без банов |
|
||||
| GET | `/api/groups/{groupId}` | Профиль; приватный профиль только участникам |
|
||||
| PUT | `/api/groups/{groupId}` | name, description, isPrivate; только владелец |
|
||||
| POST | `/api/groups/{groupId}/join` | Вступить в публичное сообщество |
|
||||
| DELETE | `/api/groups/{groupId}/members/me` | Выйти; HTTP 204 |
|
||||
| POST | `/api/groups/{groupId}/avatar` | multipart/form-data с file; только владелец |
|
||||
| DELETE | `/api/groups/{groupId}/avatar` | Убрать текущий аватар; только владелец, 204 |
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "Новости Govor",
|
||||
"description": "Обновления проекта",
|
||||
"isPrivate": false,
|
||||
"isChannel": true
|
||||
}
|
||||
```
|
||||
|
||||
POST/PUT/Join возвращают 200, остальные успешные команды без DTO — 204. name — 1–100 символов, description — до 500; q — до 100. skip >= 0, take — 1–100. По умолчанию новое сообщество приватное; создатель автоматически становится участником и владельцем.
|
||||
|
||||
GroupResponse: id, name, description, imageId, imageUrl, isPrivate, isChannel, ownerUserId, createdAt, memberCount, myRole, isRequiredChannel, canLeave. myRole: Member=0, Admin=1, Owner=2, null — не участник. memberCount не включает заблокированных. canLeave учитывает владение и запрет выхода из обязательного канала.
|
||||
|
||||
Аватар: статичный PNG/JPEG/WebP, исходный файл до 2 МиБ и сторон до 2048 px; после обработки PNG до 128×128 и 256 КиБ. GIF не принимается. Загрузка возвращает imageId и mediaUrl. Скачать можно через `/api/media/download/{imageId}` с Bearer token. Текущий публичный аватар доступен всем авторизованным незаблокированным пользователям; приватный — только активным участникам. Старые файлы не удаляются автоматически, но не выдаются посторонним как публичный аватар.
|
||||
|
||||
## Роли и модерация
|
||||
|
||||
| Возможность | Владелец | Админ | Участник |
|
||||
| --- | --- | --- | --- |
|
||||
| Читать и реагировать | Да | Да | Да |
|
||||
| Писать в обычную группу | Да | Да | Да |
|
||||
| Публиковать/редактировать свои сообщения канала | Да | Да | Нет |
|
||||
| Менять имя, описание, приватность, аватар | Да | Нет | Нет |
|
||||
| Назначать/снимать админов | Да | Нет | Нет |
|
||||
| Выпускать/отзывать ссылки | Да | Да | Нет |
|
||||
| Банить/разбанивать участников | Да | Да | Нет |
|
||||
| Банить других админов | Да | Нет | Нет |
|
||||
| Удалять сообщения других участников | Да | Да | Нет |
|
||||
| Выбирать реакции канала | Да | Да | Нет |
|
||||
| Передавать владение | Да | Нет | Нет |
|
||||
|
||||
Глобальная роль серверного Admin не заменяет роль в группе. Владельца и самого себя банить нельзя. Назначение админа требует активного участника. Бан админа владельцем снимает его административную роль; после разбана он возвращается как участник. При выходе роль админа снимается.
|
||||
|
||||
| Метод | Маршрут | Назначение |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/groups/{groupId}/members?bannedOnly=false&skip=0&take=50` | Активные участники; список bannedOnly=true только модераторам |
|
||||
| PUT | `/api/groups/{groupId}/members/{userId}/administrator` | Назначить админа, только владелец |
|
||||
| DELETE | `/api/groups/{groupId}/members/{userId}/administrator` | Снять админа, только владелец |
|
||||
| PUT | `/api/groups/{groupId}/members/{userId}/ban` | Заблокировать |
|
||||
| DELETE | `/api/groups/{groupId}/members/{userId}/ban` | Разблокировать |
|
||||
| DELETE | `/api/groups/{groupId}/messages/{messageId}` | Удалить сообщение для всех; автор либо модератор |
|
||||
| POST | `/api/groups/{groupId}/ownership/{userId}` | Передать владение активному участнику |
|
||||
|
||||
Участник в списке: userId, username, role, isBanned, memberSince. Пароли/токены и сущности User не возвращаются. Удаление сообщения проверяет его принадлежность именно указанной группе и отправляет существующее событие MessageRemoved.
|
||||
|
||||
Бан сохраняет запись участника, поэтому повторное вступление через поиск или другую ссылку его не обходит. Он блокирует историю, чтение, отправку, редактуру, реакции и файлы сообщества. События и push фильтруются по действующим участникам. Разбан возвращает членство; автоматического удаления старых сообщений при бане нет — модератор удаляет их отдельными командами.
|
||||
|
||||
Владелец не может выйти, пока не передаст владение. При передаче прежний владелец становится админом и затем может выйти. Владение всегда у одного пользователя.
|
||||
|
||||
## Приглашение по ссылке
|
||||
|
||||
```http
|
||||
POST /api/groups/{groupId}/invitations
|
||||
Authorization: Bearer <access-token>
|
||||
Content-Type: application/json
|
||||
|
||||
{ "validForDays": 7, "maxParticipants": 100, "description": "Приглашение" }
|
||||
```
|
||||
|
||||
Ответ GroupInvitationResponse содержит id, groupId, invitationCode, sharePath, previewPath, joinPath, description, endDate, maxParticipants, usedCount, isRevoked. sharePath имеет вид `/invite/{code}`; добавьте доверенный API base URL, чтобы передать полную ссылку. Клиент, открывший ссылку, извлекает code, показывает preview и выполняет POST join после действия пользователя. Все запросы используют его access token; ссылка не является токеном авторизации аккаунта.
|
||||
|
||||
| Метод | Маршрут | Назначение |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/groups/{groupId}/invitations` | До 100 последних ссылок, только модераторы |
|
||||
| DELETE | `/api/groups/{groupId}/invitations/{invitationId}` | Отозвать ссылку, 204 |
|
||||
| GET | `/api/group-invites/{code}` | Превью профиля по действующему коду, без вступления |
|
||||
| POST | `/api/group-invites/{code}/join` | Вступление, GroupResponse |
|
||||
|
||||
Совместимые пути: GET `/invite/{code}` — только превью, POST `/invite/{code}/join` — вступление. Старый побочный эффект вступления через GET устранён: сканеры ссылок и предварительная загрузка не добавляют участников.
|
||||
|
||||
validForDays — 1–365 (по умолчанию 7), maxParticipants — 0–1 000 000; 0 означает без лимита. usedCount — число успешных вступлений по ссылке, а не текущий размер группы. Повтор POST уже вступившего пользователя не расходует лимит; выход не освобождает использованный слот. Просроченная или отозванная ссылка не работает. Отзыв не удаляет ранее вступивших участников.
|
||||
|
||||
## Сообщения и реакции
|
||||
|
||||
Используйте `/hubs/chats`: Send с recipientType=1 и recipientId=groupId. История — GET `/api/groups/{groupId}/messages`; прочтение — [существующий API](message-read.md). Публичность сообщества не даёт доступ к его истории без вступления.
|
||||
|
||||
В канале владелец/админ задаёт политику через PUT `/api/groups/{groupId}/reactions`: All=0, None=1, Selected=2 с reactionIds. GET возвращает текущую политику; изменения приходят как ChannelReactionPolicyChanged. Эмодзи, изображения/GIF, HTTP/SignalR установка реакции описаны в [реакциях](reactions.md). Бан и снятие админа применяются к этим же сервисам.
|
||||
|
||||
## Обновления группы через SignalR
|
||||
|
||||
С 04.10.2026 изменения сообщества приходят через тот же `/hubs/chats`. Нужны Bearer access token и активная сессия. Дополнительная подписка на группу не требуется: сервер доставляет события всем активным сессиям действующих участников, включая другие устройства автора команды. Старый пустой GroupsHub не используется; команды управления остаются HTTP API и подходят будущему боту.
|
||||
|
||||
| Событие | Payload | Когда отправляется |
|
||||
| --- | --- | --- |
|
||||
| GroupProfileChanged | `{ groupId }` | Имя, описание, приватность, загрузка/удаление аватара, передача владения, настройка обязательного канала |
|
||||
| GroupMemberChanged | `{ groupId, userId, status, role }` | Создание группы, вступление через поиск/ссылку, выход, назначение/снятие админа, бан/разбан, передача владения, автоматическое добавление нового аккаунта в обязательный канал |
|
||||
|
||||
status: Active=0, Banned=1, Left=2. role: Member=0, Admin=1, Owner=2; null для заблокированного или вышедшего. Статус/роль читаются из БД после завершения команды. При передаче владения отправляются GroupProfileChanged и два GroupMemberChanged: прежний владелец становится Admin, новый — Owner.
|
||||
|
||||
Заблокированный или вышедший пользователь получает GroupMemberChanged о **себе** на свои активные сессии вместе с оставшимися участниками. После этого ему не направляются изменения профиля, чужого членства и события сообщений. Остальные заблокированные, посторонние пользователи, отозванные и истёкшие сессии исключены. При разбане статус Active с ролью Member; автоматическое вступление при регистрации уведомляет уже подключённых участников обязательного канала.
|
||||
|
||||
GroupProfileChanged — сигнал перечитать GET `/api/groups/{groupId}`. Он не содержит общий GroupResponse: myRole и canLeave зависят от конкретного пользователя. Клиент обновляет имя/описание, аватар, приватность, владельца, свои права и возможность выхода из полученного HTTP ответа. Смена обязательного канала уведомляет участников прежнего и нового канала; смена allowLeave — участников текущего.
|
||||
|
||||
При GroupMemberChanged перечитайте профиль и видимую страницу участников; это обновляет memberCount и myRole. Если событие касается текущего пользователя, пересчитайте доступность кнопок отправки и модерации. Если профиль публичного сообщества вернул myRole=null, членство уже потеряно, даже при HTTP 200. Ответ 403/404 также означает потерю доступа: закройте экран сообщества, уберите его из локального списка и перечитайте `/api/groups/mine`. Обновляйте UI MAUI на главном потоке. Все серверные команды независимо проверяют действующие права в БД.
|
||||
|
||||
Пример регистрации обработчиков в .NET-клиенте (Reload — методы приложения, выполняющие описанные HTTP запросы):
|
||||
|
||||
```csharp
|
||||
hub.On<GroupProfileChangedResponse>("GroupProfileChanged",
|
||||
change => ReloadGroupAsync(change.GroupId));
|
||||
hub.On<GroupMemberChangedResponse>("GroupMemberChanged",
|
||||
change => ReloadGroupAndMembersAsync(change.GroupId));
|
||||
```
|
||||
|
||||
Событие отправляется только после успешного сохранения, отказ в правах/валидации не создаёт события. Повтор успешной идемпотентной команды может повторить уведомление: обработчики должны быть идемпотентными. SignalR не хранит очередь и не гарантирует порядок между параллельными HTTP командами; payload членства — подсказка, актуальный HTTP ответ является источником прав. После reconnect перечитайте mine, открытый профиль и участников. Ошибка доставки логируется, но не отменяет уже сохранённое изменение и не превращает успешную команду в ошибку. Для этих событий push не отправляется.
|
||||
|
||||
## Обязательный канал сервера
|
||||
|
||||
Требуется серверная роль Admin; сервис дополнительно проверяет Invite.IsAdmin пользователя в БД.
|
||||
|
||||
```http
|
||||
PUT /api/admin/required-channel
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer <admin-access-token>
|
||||
|
||||
{ "channelId": "<GUID канала>", "allowLeave": false }
|
||||
```
|
||||
|
||||
GET `/api/admin/required-channel` возвращает channelId и allowLeave. PUT принимает существующий канал с владельцем; обычная группа не подходит. Канал может быть приватным. `{ "channelId": null, "allowLeave": true }` отключает автоматическое добавление.
|
||||
|
||||
После включения все новые зарегистрированные пользователи становятся обычными участниками выбранного канала, без расходования приглашения группы. Создание аккаунта, расходование приглашения регистрации и членство сохраняются одной транзакцией; сбой записи не оставляет частичную регистрацию. allowLeave=false запрещает выход из текущего обязательного канала, true разрешает выход обычным участникам/админам. Владелец сначала передаёт владение независимо от этой настройки.
|
||||
|
||||
Существующие пользователи автоматически не добавляются. Настройка выхода действует на всех текущих участников выбранного канала. Смена канала не удаляет старое членство, а ограничение выхода относится только к новому выбранному каналу. Статус обязательного канала не выдаёт административных прав и не отменяет модерацию.
|
||||
|
||||
## Миграция и проверка
|
||||
|
||||
```powershell
|
||||
dotnet ef database update --project Govor.Domain --startup-project Govor.API
|
||||
dotnet test Govor.Server.Tests/Govor.Server.Tests.csproj -c Release
|
||||
```
|
||||
|
||||
Миграция `20261003131521_PrimitiveGroupsAndRequiredChannel` добавляет владельца, время создания, настройки сервера, лимиты/отзыв ссылок и уникальные индексы членства/админов/кодов. Старые дубли членства объединяются с сохранением бана; удаляются ссылки на отсутствующих пользователей и роли неактивных участников. Неоднозначные старые коды приглашений отзываются. Известное использование старых ссылок восстанавливается по сохранённым членствам; сведения о ранее вышедших пользователях в старой модели отсутствовали.
|
||||
|
||||
Для существующей группы владельцем выбирается самый ранний активный админ, а при его отсутствии — самый ранний активный участник. Пустые сообщества без активных участников остаются без владельца; для них миграция не назначает владельца произвольно. Новые сообщества всегда создаются с владельцем. Исправляется лишняя связь членства с теневым ChatGroupId; основной GroupId сохраняется.
|
||||
|
||||
Удаление сообщества, заявки на вступление, тонкие разрешения админов и UI MAUI в этот примитивный серверный сценарий не входят. Миграция подготовлена, но к рабочей пользовательской БД автоматически не применялась. Локально проверяются SQLite, реальные HTTP/JWT запросы и обработка файлов; PostgreSQL тестируется в существующем CI при его запуске.
|
||||
@@ -45,10 +45,10 @@ Dockerfile обновлён до .NET 10 и текущих проектов; с
|
||||
|
||||
## Проверка и ограничения
|
||||
|
||||
Release-сборка Govor.Server.slnx завершилась без ошибок (88 предупреждений). Все 31 локальных серверных теста прошли; пропущенных тестов нет. EF не обнаружил расхождений модели с последней миграцией.
|
||||
Исходный набор этих исправлений был проверен Release-сборкой и 31 серверным тестом. Новые проверки реакций и групп добавлены в ту же suite Govor.Server.Tests. EF не обнаружил расхождений модели с последней миграцией.
|
||||
|
||||
Локальные тесты выполняют реальную SQL-запись в SQLite, тестируют HTTP pipeline с JWT и маршруты доставки с mock SignalR/Firebase. Покрыты чужие/забаненные участники, редактура/удаление, media/reply, три режима прочтения, повторения и конкурирующая запись/удаление, очередь/retry, перенос push-токена и отзыв access-сессии. Отдельно проверяется перевод границы в SQL Npgsql и соответствие модели миграции.
|
||||
|
||||
CI запускает эту же серверную suite на SQLite и PostgreSQL 16. Для самостоятельного PostgreSQL запуска задайте TEST_POSTGRES_CONNECTION на отдельную БД с именем, заканчивающимся `_tests`; каждый тест применяет миграции в отдельной временной схеме. Локально PostgreSQL и реальная доставка Firebase/MAUI не запускались.
|
||||
|
||||
Групповой InviteController/IGroupService остаются незавершёнными; это не реализация управления группами. PresenceStore остаётся локальным процессу; для нескольких экземпляров понадобится общая инфраструктура SignalR/presence. Старые журналы с чувствительными SQL-параметрами и уже выданные права нужно оценивать отдельно от этих изменений.
|
||||
Примитивное управление группами и каналами, приглашениями, ролями и обязательным каналом добавлено отдельным этапом: [контракт групп](endpoints/groups.md). PresenceStore остаётся локальным процессу; для нескольких экземпляров понадобится общая инфраструктура SignalR/presence. Старые журналы с чувствительными SQL-параметрами и уже выданные права нужно оценивать отдельно от этих изменений.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ChatsHub — сообщения
|
||||
|
||||
Подключение: `/hubs/chats`, Bearer access token и активная сессия. Команды возвращают `HubResult<T>` (status, result, errorMessage); события приходят независимо от ответа команды. Этот раздел описывает рабочую копию с исправлениями от 03.10.2026.
|
||||
Подключение: `/hubs/chats`, Bearer access token и активная сессия. Команды возвращают `HubResult<T>` (status, result, errorMessage); события приходят независимо от ответа команды. Этот раздел описывает рабочую копию с исправлениями от 04.10.2026.
|
||||
|
||||
## Команды
|
||||
|
||||
@@ -42,6 +42,8 @@ Send/Read/React и чтение истории проверяют участие
|
||||
| ChatRead | ChatReadResponse |
|
||||
| MessageReactionsChanged | MessageReactionsChangedResponse |
|
||||
| ChannelReactionPolicyChanged | ChannelReactionPolicyResponse |
|
||||
| GroupProfileChanged | GroupProfileChangedResponse: `{ groupId }` |
|
||||
| GroupMemberChanged | GroupMemberChangedResponse: `{ groupId, userId, status, role }` |
|
||||
|
||||
Опечатка MessageReaded сохранена для совместимости. При подключении сервер автоматически добавляет соединение в группу его сессии. События чата направляются активным сессиям участников; заблокированные участники групп исключаются. Не требуется вручную подписываться на SignalR-группу чата. Отзыв сессии прекращает её участие в маршрутизации и проверяется для команд; истечение токена закрывает соединение.
|
||||
|
||||
@@ -53,6 +55,10 @@ MessageRemovedResponse: messageId, senderId, recipientId, requestType, recipient
|
||||
|
||||
## Доставка и восстановление
|
||||
|
||||
GroupProfileChanged сообщает об изменении имени, описания, приватности, аватара, владельца и настроек обязательного канала. Загрузите GET `/api/groups/{groupId}`: myRole и canLeave индивидуальны, поэтому событие содержит только groupId. GroupMemberChanged сообщает о вступлении/выходе, бане/разбане и роли участника. status: Active=0, Banned=1, Left=2; role: Member=0, Admin=1, Owner=2, null без активного членства. Перечитайте профиль и видимых участников; при потере доступа удалите сообщество из локального списка. Передача владения обновляет профиль и роли обоих пользователей.
|
||||
|
||||
Эти события доставляются после успешного HTTP сохранения. Заблокированный/вышедший пользователь получает только изменение собственного членства; последующие события сообщества ему не отправляются. Ошибочные команды не создают событий. Повтор успешной команды может повторить уведомление. [Группы и каналы](../endpoints/groups.md) описывают все причины событий и клиентское восстановление. Порядок параллельных уведомлений не гарантирован; HTTP состояние определяет актуальные права. После reconnect обновите mine, профиль открытой группы и список участников.
|
||||
|
||||
Сохранение в БД и доставка события — разные этапы. После reconnect загрузите историю через HTTP; объединяйте ответ Send и ReceiveMessage по messageId. Для реакций принимайте более новую version и заменяйте counts целиком, затем восстанавливайте состояние видимых сообщений через GET.
|
||||
|
||||
SignalR-события не имеют долговременной очереди. Push сообщений использует серверную очередь и повторные попытки; для реакций и политик каналов push не отправляется. Реальный push требует корректной конфигурации Firebase и зарегистрированного FCM-токена активной сессии. Повтор Send после неоднозначного сетевого сбоя всё ещё может создать дубликат: clientMessageId/idempotency-key для сообщений не реализован.
|
||||
SignalR-события не имеют долговременной очереди. Push сообщений использует серверную очередь и повторные попытки; для реакций, политик каналов и изменений сообществ push не отправляется. Реальный push требует корректной конфигурации Firebase и зарегистрированного FCM-токена активной сессии. Повтор Send после неоднозначного сетевого сбоя всё ещё может создать дубликат: clientMessageId/idempotency-key для сообщений не реализован.
|
||||
|
||||
Reference in New Issue
Block a user