Add forwarding, friend controls, and benefits

Add message forwarding and reply lookup, friend removal and blocking endpoints, and database-backed Govor+ privileges with customizable profile tags. Include migrations, integration tests, and updated API and operations documentation.
This commit is contained in:
Artemy
2026-10-31 18:29:40 +07:00
parent a3401ceedf
commit 632ac04b56
78 changed files with 5284 additions and 720 deletions
@@ -0,0 +1,31 @@
using Govor.Application.Friends;
using Govor.Domain.Models;
using Microsoft.EntityFrameworkCore;
namespace Govor.Application.Tests.Integration.Friends;
[TestFixture]
public sealed class FriendRemovalTests
{
[TestCase(FriendshipStatus.Pending)]
[TestCase(FriendshipStatus.Blocked)]
[TestCase(FriendshipStatus.Rejected)]
[TestCase(FriendshipStatus.Accepted)]
public async Task RemovalChangesOnlyAcceptedFriendshipAndRetainsHistory(FriendshipStatus status)
{
using var db = new TestDatabase();
db.Context.Friendships.Add(new Friendship { Id = Guid.NewGuid(), RequesterId = db.Alice, AddresseeId = db.Bob, Status = status });
await db.Context.SaveChangesAsync();
var message = db.AddMessage();
var service = new FriendshipService(db.Context);
await service.RemoveFriendAsync(db.Bob, db.Alice);
await service.RemoveFriendAsync(db.Alice, db.Bob);
Assert.That((await db.Context.Friendships.AsNoTracking().SingleAsync()).Status,
Is.EqualTo(status == FriendshipStatus.Accepted ? FriendshipStatus.Rejected : status));
Assert.That(await db.Context.Messages.AnyAsync(m => m.Id == message.Id), Is.True);
Assert.That(await db.Context.PrivateChats.AnyAsync(c => c.Id == db.ChatId), Is.True);
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(db.Alice, db.Alice));
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(Guid.Empty, db.Alice));
Assert.ThrowsAsync<ArgumentException>(() => service.RemoveFriendAsync(db.Alice, Guid.Empty));
}
}
@@ -0,0 +1,74 @@
using Govor.Application.Messages;
using Govor.Application.Messages.Parameters;
using Govor.Domain.Models;
using Govor.Domain.Models.Messages;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
namespace Govor.Application.Tests.Integration.Messages;
[TestFixture]
public sealed class ReplyAndForwardTests
{
private TestDatabase _db = null!;
private Guid _group;
private MessageSendingService _sender = null!;
[SetUp]
public void SetUp()
{
_db = new(); _group = Guid.NewGuid();
_db.Context.ChatGroups.Add(new ChatGroup { Id = _group, Name = "public", Description = "", OwnerUserId = _db.Alice });
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = _group, UserId = _db.Alice });
_db.Context.SaveChanges();
_sender = new(_db.Context, NullLogger<MessageSendingService>.Instance);
}
[TearDown] public void TearDown() => _db.Dispose();
private SendMessage Request(Guid? reply = null, Guid? forward = null) =>
new("content", reply, _group, RecipientType.Group, _db.Alice, DateTime.UtcNow, [], forward);
[Test]
public async Task ReplyPersistsAndAppearsInHistoryWhileCrossChatReplyIsRejected()
{
var source = _db.AddMessage(chat: _group, type: RecipientType.Group);
var reply = await _sender.SendMessageAsync(Request(reply: source.Id));
Assert.That(reply.IsSuccess, Is.True);
var history = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(_group, _db.Alice, null);
Assert.That(history.Value.Single(m => m.Id == reply.Message.Id).ReplyToMessageId, Is.EqualTo(source.Id));
var other = _db.AddMessage();
Assert.That((await _sender.SendMessageAsync(Request(reply: other.Id))).IsSuccess, Is.False);
Assert.That((await _sender.SendMessageAsync(Request(reply: Guid.Empty))).IsSuccess, Is.False);
}
[Test]
public async Task ForwardSnapshotsAuthorAndDateSurvivesSourceDeletionAndAppearsInHistory()
{
var source = _db.AddMessage(sender: _db.Bob);
var result = await _sender.SendMessageAsync(Request(forward: source.Id));
Assert.That(result.IsSuccess, Is.True);
Assert.That(result.Message.SenderId, Is.EqualTo(_db.Alice));
Assert.That(result.Message.ForwardedFromUserId, Is.EqualTo(_db.Bob));
Assert.That(result.Message.ForwardedFromSentAt, Is.EqualTo(source.SentAt));
await _db.Context.Messages.Where(m => m.Id == source.Id).ExecuteDeleteAsync();
var history = await new MessagesLoader(_db.Context).LoadMessagesInChatGroup(_group, _db.Alice, null);
Assert.That(history.Value.Single().ForwardedFromMessageId, Is.EqualTo(source.Id));
Assert.That(await _db.Context.ChatPushNotifications.AnyAsync(p => p.MessageId == result.Message.Id), Is.True);
}
[TestCase("missing")]
[TestCase("outsider")]
[TestCase("banned")]
public async Task CannotForwardMissingOrInaccessibleSource(string reason)
{
var otherGroup = Guid.NewGuid();
_db.Context.ChatGroups.Add(new ChatGroup { Id = otherGroup, Name = "other", Description = "", OwnerUserId = _db.Bob });
if (reason == "banned")
_db.Context.GroupMemberships.Add(new GroupMembership { Id = Guid.NewGuid(), GroupId = otherGroup, UserId = _db.Alice, IsBanned = true });
_db.Context.SaveChanges();
var id = reason == "missing" ? Guid.NewGuid() : _db.AddMessage(chat: otherGroup, type: RecipientType.Group).Id;
var before = await _db.Context.Messages.CountAsync();
var result = await _sender.SendMessageAsync(Request(forward: id));
Assert.That(result.IsSuccess, Is.False);
Assert.That(await _db.Context.Messages.CountAsync(), Is.EqualTo(before));
Assert.That(await _db.Context.ChatPushNotifications.CountAsync(), Is.Zero);
}
}
@@ -0,0 +1,128 @@
using Govor.Application.Profiles;
using Govor.Application.Tests.Support;
using Govor.Domain.Models.Users;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
namespace Govor.Application.Tests.Integration.Profiles;
[TestFixture]
public sealed class UserBenefitsTests
{
private TestDatabase _db = null!;
private UserBenefitsService _service = null!;
[SetUp] public void SetUp() { _db = new(); _service = new(_db.Context); }
[TearDown] public void TearDown() => _db.Dispose();
[Test]
public async Task GrantCustomizeRevokeAndRegrantUseLiveDatabaseRights()
{
Assert.That((await _service.GetAsync(_db.Alice)).Tag, Is.Null);
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.SetTagAsync(_db.Alice, new()));
var granted = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus);
Assert.That(granted.IsGovorPlus, Is.True);
Assert.That(granted.Tag!.Text, Is.EqualTo("Govor+"));
var style = new ProfileTagStyle { Text = "Тест 👑", TextGradientEndColor = "#112233", GradientEndColor = "#998877",
BorderGradientEndColor = "#ABCDEF80", ShadowBlur = 20, FontFamily = "Roboto", FontSize = 24 };
var customized = await _service.SetTagAsync(_db.Alice, style);
Assert.That(customized.Tag, Is.EqualTo(style));
Assert.That(customized.Revision, Is.GreaterThan(granted.Revision));
var revoked = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.None);
Assert.That(revoked.Tag, Is.Null);
Assert.That(revoked.CanCustomizeProfileTag, Is.False);
Assert.ThrowsAsync<UnauthorizedAccessException>(() => _service.SetTagAsync(_db.Alice, style));
var restored = await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.CustomProfileTag);
Assert.That(restored.IsGovorPlus, Is.False);
Assert.That(restored.Tag, Is.EqualTo(style));
Assert.That((await _service.SetTagAsync(_db.Alice, null)).Tag, Is.Null);
Assert.That((await _service.GetAsync(_db.Bob)).Privileges, Is.EqualTo(UserPrivileges.None));
}
[TestCase("text")]
[TestCase("blank")]
[TestCase("control")]
[TestCase("color")]
[TestCase("color-newline")]
[TestCase("gradient")]
[TestCase("text-gradient")]
[TestCase("border-gradient")]
[TestCase("font")]
[TestCase("weight")]
[TestCase("size")]
[TestCase("border")]
[TestCase("blur")]
[TestCase("offset")]
[TestCase("nan")]
[TestCase("angle")]
public async Task InvalidAppearanceCannotReplacePersistedTag(string reason)
{
await _service.SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus);
var good = new ProfileTagStyle { Text = "saved" };
await _service.SetTagAsync(_db.Alice, good);
var bad = reason switch
{
"text" => good with { Text = new string('x', 33) },
"blank" => good with { Text = " " },
"control" => good with { Text = "a\nb" },
"color" => good with { TextColor = "url(evil)" },
"color-newline" => good with { TextColor = "#FFFFFF\n" },
"gradient" => good with { GradientEndColor = "red" },
"text-gradient" => good with { TextGradientEndColor = "#fff" },
"border-gradient" => good with { BorderGradientEndColor = "#abc" },
"font" => good with { FontFamily = "url(evil)" },
"weight" => good with { FontWeight = 650 },
"size" => good with { FontSize = 99 },
"border" => good with { BorderWidth = -1 },
"blur" => good with { ShadowBlur = 21 },
"offset" => good with { ShadowOffsetX = -11 },
"nan" => good with { ShadowOffsetY = double.NaN },
_ => good with { GradientAngle = 361 }
};
Assert.ThrowsAsync<ArgumentException>(() => _service.SetTagAsync(_db.Alice, bad));
Assert.That((await _service.GetAsync(_db.Alice)).Tag, Is.EqualTo(good));
}
[Test]
public async Task UnknownRightsAndUsersAreRejectedAndDeletingUserCascadesBenefits()
{
Assert.ThrowsAsync<ArgumentException>(() => _service.SetPrivilegesAsync(_db.Alice, (UserPrivileges)4));
Assert.ThrowsAsync<KeyNotFoundException>(() => _service.SetPrivilegesAsync(Guid.NewGuid(), UserPrivileges.GovorPlus));
Assert.ThrowsAsync<KeyNotFoundException>(() => _service.GetAsync(Guid.NewGuid()));
await _service.SetPrivilegesAsync(_db.Outsider, UserPrivileges.GovorPlus);
await _db.Context.Users.Where(u => u.Id == _db.Outsider).ExecuteDeleteAsync();
Assert.That(await _db.Context.UserBenefits.AnyAsync(), Is.False);
}
[Test]
public async Task ConcurrentFirstGrantReturnsConflictWithoutOverwritingWinner()
{
using var competing = _db.CreateContext(new BeforeSave(async () =>
{
_db.Context.UserBenefits.Add(new UserBenefits { UserId = _db.Alice, Privileges = UserPrivileges.CustomProfileTag, Revision = 1 });
await _db.Context.SaveChangesAsync();
}));
Assert.ThrowsAsync<DbUpdateConcurrencyException>(() =>
new UserBenefitsService(competing).SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus));
Assert.That((await _service.GetAsync(_db.Alice)).Privileges, Is.EqualTo(UserPrivileges.CustomProfileTag));
Assert.That(competing.ChangeTracker.Entries(), Is.Empty);
}
[Test]
public async Task FailedInitialGrantDoesNotCreatePrivileges()
{
using var failed = _db.CreateContext(new FailDatabaseCommand(sql => sql.Contains("INSERT INTO \"UserBenefits\"", StringComparison.Ordinal)));
Assert.ThrowsAsync<DbUpdateException>(() => new UserBenefitsService(failed).SetPrivilegesAsync(_db.Alice, UserPrivileges.GovorPlus));
Assert.That((await _service.GetAsync(_db.Alice)).Privileges, Is.EqualTo(UserPrivileges.None));
Assert.That(failed.ChangeTracker.Entries(), Is.Empty);
}
private sealed class BeforeSave(Func<Task> action) : SaveChangesInterceptor
{
public override async ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData,
InterceptionResult<int> result, CancellationToken cancellationToken = default)
{
await action();
return result;
}
}
}