mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-18 21:34:56 +00:00
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:
@@ -13,6 +13,17 @@ public class FriendshipService : IFriendshipService
|
||||
{
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public async Task RemoveFriendAsync(Guid userId, Guid currentUserId)
|
||||
{
|
||||
if (userId == Guid.Empty || currentUserId == Guid.Empty || userId == currentUserId)
|
||||
throw new ArgumentException("Two distinct users are required.");
|
||||
// A removal must never clear a block or cancel a pending request.
|
||||
await _context.Friendships.Where(f => f.Status == FriendshipStatus.Accepted &&
|
||||
((f.RequesterId == userId && f.AddresseeId == currentUserId) ||
|
||||
(f.RequesterId == currentUserId && f.AddresseeId == userId)))
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(f => f.Status, FriendshipStatus.Rejected));
|
||||
}
|
||||
|
||||
public async Task<List<User>> SearchUsersAsync(string query, Guid currentId)
|
||||
{
|
||||
@@ -59,4 +70,4 @@ public class FriendshipService : IFriendshipService
|
||||
|
||||
return friends;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@ namespace Govor.Application.Friends;
|
||||
|
||||
public interface IFriendshipService
|
||||
{
|
||||
Task RemoveFriendAsync(Guid userId, Guid currentUserId);
|
||||
Task<List<User>> GetFriendsAsync(Guid userId);
|
||||
Task<List<User>> GetPotentialFriendsAsync(Guid userId);
|
||||
Task<List<User>> SearchUsersAsync(string query, Guid currentId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,11 +71,22 @@ public class MessageSendingService : IMessageSendingService
|
||||
return completed.SenderId == sendParams.FromUserId && completed.EncryptedContent == sendParams.EncryptContent &&
|
||||
completed.RecipientId == sendParams.RecipientId && completed.RecipientType == sendParams.RecipientType &&
|
||||
completed.ReplyToMessageId == sendParams.ReplyToMessageId &&
|
||||
completed.ForwardedFromMessageId == sendParams.ForwardedFromMessageId &&
|
||||
completed.MediaAttachments.Select(a => a.MediaFileId).Order().SequenceEqual(media.Select(a => a.MediaId).Order()) &&
|
||||
(!E2eeProtocol.IsEncrypted(sendParams.EncryptContent) || media.All(m => string.IsNullOrEmpty(m.EncryptedKey)))
|
||||
? new SendMessageResult(true, null, completed)
|
||||
: new SendMessageResult(false, new ArgumentException("Message ID already exists."), default);
|
||||
|
||||
Message? source = null;
|
||||
if (sendParams.ForwardedFromMessageId is { } sourceId)
|
||||
{
|
||||
source = await _dbContext.Messages.AsNoTracking().SingleOrDefaultAsync(m => m.Id == sourceId);
|
||||
if (source is null || !await _dbContext.HasChatAccessAsync(sendParams.FromUserId,
|
||||
source.RecipientId, source.RecipientType))
|
||||
return new SendMessageResult(false, new UnauthorizedAccessException("Forward source is unavailable."), default);
|
||||
// E2EE validation below binds the fresh envelope to its destination; attachments require owned uploads.
|
||||
}
|
||||
|
||||
var mediaIds = media.Select(m => m.MediaId).Distinct().ToArray();
|
||||
var files = await _dbContext.MediaFiles.Where(m => mediaIds.Contains(m.Id) &&
|
||||
m.UploaderId == sendParams.FromUserId && m.OwnerType == MediaOwnerType.Message).ToListAsync();
|
||||
@@ -111,6 +122,9 @@ public class MessageSendingService : IMessageSendingService
|
||||
SentAt = sendParams.SendAt,
|
||||
IsEdited = false,
|
||||
ReplyToMessageId = sendParams.ReplyToMessageId,
|
||||
ForwardedFromMessageId = source?.Id,
|
||||
ForwardedFromUserId = source?.SenderId,
|
||||
ForwardedFromSentAt = source?.SentAt,
|
||||
MediaAttachments = files.Select(file => new MediaAttachments
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
|
||||
@@ -9,4 +9,5 @@ public record SendMessage(
|
||||
RecipientType RecipientType,
|
||||
Guid FromUserId,
|
||||
DateTime SendAt,
|
||||
IEnumerable<SendMedia> Media);
|
||||
IEnumerable<SendMedia> Media,
|
||||
Guid? ForwardedFromMessageId = null);
|
||||
|
||||
@@ -39,6 +39,7 @@ public class ProfileService : IProfileService
|
||||
return Result.Failure<UserProfile>(CreateNotFoundError(userId));
|
||||
}
|
||||
|
||||
profile.Benefits = await new UserBenefitsService(_context).GetAsync(userId);
|
||||
return profile;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models.Users;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Application.Profiles;
|
||||
|
||||
/// <summary>Privileges are read from the database on every operation so revocation takes effect immediately.</summary>
|
||||
public sealed class UserBenefitsService(GovorDbContext db)
|
||||
{
|
||||
private const UserPrivileges Known = UserPrivileges.GovorPlus | UserPrivileges.CustomProfileTag;
|
||||
private static readonly string[] SupportedFonts = ["Inter", "Roboto", "Arial", "Noto Sans", "serif", "sans-serif", "monospace"];
|
||||
|
||||
public async Task<UserBenefitsView> GetAsync(Guid userId)
|
||||
{
|
||||
if (!await db.Users.AnyAsync(u => u.Id == userId)) throw new KeyNotFoundException("User not found.");
|
||||
var row = await db.UserBenefits.AsNoTracking().SingleOrDefaultAsync(x => x.UserId == userId);
|
||||
return View(row);
|
||||
}
|
||||
|
||||
// Call only from an administrator-authorized boundary. No self-service grant endpoint exists.
|
||||
public async Task<UserBenefitsView> SetPrivilegesAsync(Guid userId, UserPrivileges privileges)
|
||||
{
|
||||
if ((privileges & ~Known) != 0) throw new ArgumentException("Unknown privilege bits.");
|
||||
if (!await db.Users.AnyAsync(u => u.Id == userId)) throw new KeyNotFoundException("User not found.");
|
||||
var count = await db.UserBenefits.Where(x => x.UserId == userId).ExecuteUpdateAsync(s =>
|
||||
s.SetProperty(x => x.Privileges, privileges).SetProperty(x => x.Revision, x => x.Revision + 1));
|
||||
if (count == 0)
|
||||
{
|
||||
db.UserBenefits.Add(new UserBenefits { UserId = userId, Privileges = privileges, Revision = 1 });
|
||||
try { await db.SaveChangesAsync(); }
|
||||
catch (DbUpdateException)
|
||||
{
|
||||
db.ChangeTracker.Clear();
|
||||
// Concurrent first grants compete on the user PK; don't silently overwrite the winner.
|
||||
if (await db.UserBenefits.AnyAsync(x => x.UserId == userId))
|
||||
throw new DbUpdateConcurrencyException("Privileges were created concurrently.");
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return await GetAsync(userId);
|
||||
}
|
||||
|
||||
public async Task<UserBenefitsView> SetTagAsync(Guid userId, ProfileTagStyle? tag)
|
||||
{
|
||||
if (tag is not null) Validate(tag);
|
||||
// Conditional UPDATE makes revocation and customization serialize at the row in the database.
|
||||
var json = tag is null ? null : JsonSerializer.Serialize(tag);
|
||||
var count = await db.UserBenefits.Where(x => x.UserId == userId && (x.Privileges & Known) != 0)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(x => x.TagJson, json).SetProperty(x => x.Revision, x => x.Revision + 1));
|
||||
if (count == 0) throw new UnauthorizedAccessException("CustomProfileTag privilege or Govor+ is required.");
|
||||
return await GetAsync(userId);
|
||||
}
|
||||
|
||||
private static UserBenefitsView View(UserBenefits? row)
|
||||
{
|
||||
var privileges = row?.Privileges ?? UserPrivileges.None;
|
||||
var plus = privileges.HasFlag(UserPrivileges.GovorPlus);
|
||||
var custom = (privileges & Known) != 0;
|
||||
var tag = custom && row?.TagJson is { } json ? JsonSerializer.Deserialize<ProfileTagStyle>(json) :
|
||||
plus ? new ProfileTagStyle() : null;
|
||||
return new(privileges, plus, custom, tag, row?.Revision ?? 0);
|
||||
}
|
||||
|
||||
private static void Validate(ProfileTagStyle tag)
|
||||
{
|
||||
static bool Color(string? value) => value is not null && Regex.IsMatch(value, @"\A#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?\z", RegexOptions.CultureInvariant);
|
||||
static bool Range(double value, double min, double max) => double.IsFinite(value) && value >= min && value <= max;
|
||||
if (string.IsNullOrWhiteSpace(tag.Text) || tag.Text.Length > 32 || tag.Text.Any(char.IsControl) ||
|
||||
!Color(tag.TextColor) || !Color(tag.BackgroundColor) || !Color(tag.BorderColor) || !Color(tag.ShadowColor) ||
|
||||
(tag.GradientEndColor is not null && !Color(tag.GradientEndColor)) || tag.GradientAngle is < 0 or > 360 ||
|
||||
(tag.TextGradientEndColor is not null && !Color(tag.TextGradientEndColor)) ||
|
||||
(tag.BorderGradientEndColor is not null && !Color(tag.BorderGradientEndColor)) ||
|
||||
!Range(tag.BorderWidth, 0, 4) || !Range(tag.ShadowBlur, 0, 20) ||
|
||||
!Range(tag.ShadowOffsetX, -10, 10) || !Range(tag.ShadowOffsetY, -10, 10) ||
|
||||
!SupportedFonts.Contains(tag.FontFamily, StringComparer.Ordinal) ||
|
||||
tag.FontSize is < 10 or > 24 || tag.FontWeight is < 100 or > 900 || tag.FontWeight % 100 != 0)
|
||||
throw new ArgumentException("Invalid tag text, color, font or appearance range.");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
public class UserProfile
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public Govor.Domain.Models.Users.UserBenefitsView Benefits { get; set; } = new(0, false, false, null);
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string? Description { get; set; }
|
||||
public Guid? IconId { get; set; }
|
||||
|
||||
Reference in New Issue
Block a user