mirror of
https://github.com/Govor-team/Govor.git
synced 2026-11-17 21:09:00 +00:00
Add reactions, reliable push & session checks
Implements message reactions and reaction packs (domain models, services, admin HTTP API, media processing via ImageSharp and limits) and adds reliable push delivery (ChatPushNotification, ChatPushDispatcher, ChatPushWorker, improved ChatNotificationService). Enhances message reading (ReadChat API, unread counts, concurrency-safe receipts) and tightens session security (access-token session validation in JWT, hub filter, SessionAuthorization). Improves SignalR behavior (session groups, reaction/channel events, hub/error mappings). Adds EF migrations, many controller fixes (Forbid handling, password API), tests (Govor.Server.Tests), docs, CI and tooling updates (Dockerfile → .NET 10, GH Actions matrix for sqlite/postgres, Govor.Server.slnx, global.json), and small infra changes (AutoMapper bump, NullPushProvider, storage/token handling).
This commit is contained in:
@@ -26,6 +26,7 @@ public class JwtService : IJwtService
|
||||
{
|
||||
new Claim("userId", user.Id.ToString()),
|
||||
new Claim("sid", sessionId.ToString()),
|
||||
new Claim("tokenType", "access"),
|
||||
new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user))
|
||||
//new Claim(ClaimTypes.Role, await _invitesService.GetRoleNameAsync(user), ClaimValueTypes.String)
|
||||
};
|
||||
@@ -50,7 +51,8 @@ public class JwtService : IJwtService
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim("userId", user.Id.ToString()),
|
||||
new Claim("tokenType", "refresh")
|
||||
new Claim("tokenType", "refresh"),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
@@ -82,4 +84,4 @@ public class JwtService : IJwtService
|
||||
return principal;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<PackageReference Include="FirebaseAdmin" Version="3.6.0" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="10.0.10" />
|
||||
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.12" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="10.0.10" />
|
||||
<PackageReference Include="Microsoft.IdentityModel.JsonWebTokens" Version = "8.19.2"/>
|
||||
<PackageReference Include="Microsoft.IdentityModel.Tokens" Version="8.19.2" />
|
||||
|
||||
@@ -34,6 +34,13 @@ public class UsersService : IUsersAdministration
|
||||
|
||||
user.PasswordHash = _passwordHasher.Hash(password);
|
||||
|
||||
var sessions = await _context.UserSessions.Where(s => s.UserId == userId && !s.IsRevoked).ToListAsync();
|
||||
foreach (var session in sessions)
|
||||
session.IsRevoked = true;
|
||||
var pushTokens = await _context.UserPushTokens.Where(t => t.UserId == userId).ToListAsync();
|
||||
foreach (var token in pushTokens)
|
||||
token.IsActive = false;
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
|
||||
@@ -43,4 +50,4 @@ public class UsersService : IUsersAdministration
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Govor.Domain.Models.Messages;
|
||||
|
||||
namespace Govor.Application.Medias;
|
||||
|
||||
@@ -28,20 +29,23 @@ public class AccesserToDownloadMediaService : IAccesserToDownloadMedia
|
||||
{
|
||||
MediaOwnerType.Avatar => true, // media.OwnerId == userId
|
||||
MediaOwnerType.GroupAvatar => await _dbContext.GroupMemberships
|
||||
.AnyAsync(gm => gm.GroupId == media.OwnerId && gm.UserId == userId),
|
||||
.AnyAsync(gm => gm.GroupId == media.OwnerId && gm.UserId == userId && !gm.IsBanned),
|
||||
|
||||
MediaOwnerType.Message => await _dbContext.MediaAttachments
|
||||
.AnyAsync(ma =>
|
||||
ma.MediaFileId == mediaId &&
|
||||
(
|
||||
ma.Message.SenderId == userId ||
|
||||
ma.Message.RecipientId == userId ||
|
||||
_dbContext.GroupMemberships.Any(gm =>
|
||||
gm.GroupId == ma.Message.RecipientId && gm.UserId == userId)
|
||||
(ma.Message.RecipientType == RecipientType.User &&
|
||||
_dbContext.PrivateChats.Any(c => c.Id == ma.Message.RecipientId &&
|
||||
(c.UserAId == userId || c.UserBId == userId))) ||
|
||||
(ma.Message.RecipientType == RecipientType.Group &&
|
||||
_dbContext.GroupMemberships.Any(gm =>
|
||||
gm.GroupId == ma.Message.RecipientId && gm.UserId == userId && !gm.IsBanned))
|
||||
)),
|
||||
|
||||
MediaOwnerType.System => true,
|
||||
MediaOwnerType.Reaction => await _dbContext.ReactionItems.AnyAsync(r => r.MediaFileId == mediaId),
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ public class MediaService : IMediaService
|
||||
}
|
||||
|
||||
// Загрузить бинарные данные из хранилища
|
||||
Stream dataStream = await _storageService.LoadAsync(mediaFile.Url);
|
||||
await using Stream dataStream = await _storageService.LoadAsync(mediaFile.Url);
|
||||
|
||||
// Считать поток в byte[]
|
||||
using var memoryStream = new MemoryStream();
|
||||
@@ -174,4 +174,4 @@ public class MediaService : IMediaService
|
||||
|
||||
return new Unit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
public static class ChatAccess
|
||||
{
|
||||
public static Task<bool> HasChatAccessAsync(this GovorDbContext context,
|
||||
Guid userId, Guid chatId, RecipientType type)
|
||||
{
|
||||
if (userId == Guid.Empty || chatId == Guid.Empty)
|
||||
return Task.FromResult(false);
|
||||
|
||||
return type switch
|
||||
{
|
||||
RecipientType.User => context.PrivateChats.AnyAsync(c => c.Id == chatId &&
|
||||
(c.UserAId == userId || c.UserBId == userId)),
|
||||
RecipientType.Group => context.GroupMemberships.AnyAsync(m =>
|
||||
m.GroupId == chatId && m.UserId == userId && !m.IsBanned),
|
||||
_ => Task.FromResult(false)
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,14 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using SmartRes;
|
||||
using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
|
||||
public interface IMessageReadingService
|
||||
{
|
||||
Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId);
|
||||
}
|
||||
Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
|
||||
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null);
|
||||
Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type);
|
||||
}
|
||||
|
||||
@@ -37,7 +37,8 @@ public class MessageEditingService : IMessageEditingService
|
||||
null);
|
||||
}
|
||||
|
||||
if (message.SenderId != editParams.EditorId)
|
||||
if (message.SenderId != editParams.EditorId || !await _dbContext.HasChatAccessAsync(
|
||||
editParams.EditorId, message.RecipientId, message.RecipientType))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"User {EditorId} unauthorized to edit message {MessageId}",
|
||||
@@ -52,7 +53,7 @@ public class MessageEditingService : IMessageEditingService
|
||||
}
|
||||
|
||||
// Проверяем время, прошедшее с момента отправки
|
||||
var now = DateTime.UtcNow;
|
||||
var now = editParams.EditedAt;
|
||||
var editDeadline = message.SentAt.AddMinutes(
|
||||
_options.MaxEditTimeMinutes);
|
||||
|
||||
@@ -83,6 +84,10 @@ public class MessageEditingService : IMessageEditingService
|
||||
MediaAttachments = message.MediaAttachments?.ToList() ?? []
|
||||
};
|
||||
|
||||
if (editParams.NewContent is null || editParams.NewContent.Length > 50_000 ||
|
||||
(string.IsNullOrWhiteSpace(editParams.NewContent) && message.MediaAttachments.Count == 0))
|
||||
return new EditMessageResult(false, new ArgumentException("Invalid message content."), null);
|
||||
|
||||
message.EncryptedContent = editParams.NewContent;
|
||||
message.IsEdited = true;
|
||||
message.EditedAt = editParams.EditedAt;
|
||||
@@ -98,4 +103,4 @@ public class MessageEditingService : IMessageEditingService
|
||||
null,
|
||||
originalMessageSnapshot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using ChatReadResult = Govor.Application.Messages.Parameters.ChatReadResult;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
@@ -14,10 +15,7 @@ public class MessageReadingService : IMessageReadingService
|
||||
private readonly ILogger<MessageReadingService> _logger;
|
||||
private readonly INowDateTimeProvider _dateTimeProvider;
|
||||
|
||||
|
||||
public MessageReadingService(
|
||||
GovorDbContext dbContext,
|
||||
ILogger<MessageReadingService> logger,
|
||||
public MessageReadingService(GovorDbContext dbContext, ILogger<MessageReadingService> logger,
|
||||
INowDateTimeProvider dateTimeProvider)
|
||||
{
|
||||
_dbContext = dbContext;
|
||||
@@ -27,46 +25,127 @@ public class MessageReadingService : IMessageReadingService
|
||||
|
||||
public async Task<Result<Message, Error>> ReadMessageAsync(Guid readerId, Guid messageId)
|
||||
{
|
||||
var message = await _dbContext.Messages
|
||||
.Include(msg => msg.MessageViews)
|
||||
.FirstOrDefaultAsync(msg => msg.Id == messageId);
|
||||
|
||||
if(message is null)
|
||||
return Result<Message, Error>.Failure(Error.NotFound(
|
||||
"Message not found",
|
||||
"Message with id: " + messageId + " was not found.")
|
||||
);
|
||||
var message = await _dbContext.Messages.AsNoTracking()
|
||||
.FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
if (message is null)
|
||||
return Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message not found."));
|
||||
|
||||
if (CanReadMessage(readerId, message))
|
||||
{
|
||||
var view = new MessageView()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
MessageId = messageId,
|
||||
UserId = readerId,
|
||||
ViewedAt = _dateTimeProvider.Now,
|
||||
};
|
||||
|
||||
_dbContext.MessageViews.Add(view);
|
||||
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Message with id: {Id} was read by user {user} at {time}", view.Id, view.UserId, view.ViewedAt);
|
||||
}
|
||||
|
||||
return message;
|
||||
var result = await ReadChatAsync(readerId, message.RecipientId,
|
||||
message.RecipientType, new[] { messageId });
|
||||
if (result.IsFailure)
|
||||
return Result.Failure<Message>(result.Error);
|
||||
|
||||
// Fresh query also returns the existing receipt on repeated calls.
|
||||
var readMessage = await _dbContext.Messages.AsNoTracking().Include(m => m.MessageViews)
|
||||
.FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
return readMessage is null
|
||||
? Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message was removed."))
|
||||
: Result<Message, Error>.Success(readMessage);
|
||||
}
|
||||
|
||||
private bool CanReadMessage(Guid readerId, Message message)
|
||||
public async Task<Result<ChatReadResult, Error>> ReadChatAsync(Guid readerId, Guid chatId,
|
||||
RecipientType type, IReadOnlyCollection<Guid>? messageIds = null, Guid? upToMessageId = null)
|
||||
{
|
||||
if (message.RecipientType == RecipientType.User)
|
||||
if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
|
||||
return Result.Failure<ChatReadResult>(Denied());
|
||||
|
||||
if (messageIds is not null && (messageIds.Count == 0 || messageIds.Count > 100 ||
|
||||
messageIds.Contains(Guid.Empty) || upToMessageId.HasValue))
|
||||
return Result.Failure<ChatReadResult>(Error.Validation("Message.Read.InvalidSelection",
|
||||
"Provide 1 to 100 message IDs or an inclusive message boundary, not both."));
|
||||
|
||||
var chat = _dbContext.Messages.AsNoTracking()
|
||||
.Where(m => m.RecipientId == chatId && m.RecipientType == type);
|
||||
Guid[]? ids = messageIds?.Distinct().ToArray();
|
||||
Message? boundary = null;
|
||||
if (ids is not null)
|
||||
{
|
||||
return _dbContext.PrivateChats.Any(pr => pr.UserAId == readerId || pr.UserBId == readerId) &&
|
||||
message.MessageViews.All(mv => mv.UserId != readerId);
|
||||
// Validate the whole selection before writing any receipt.
|
||||
if (await chat.CountAsync(m => ids.Contains(m.Id)) != ids.Length)
|
||||
return Result.Failure<ChatReadResult>(Error.NotFound("Message.Read.InvalidSelection",
|
||||
"One or more messages do not belong to this chat."));
|
||||
if (await chat.AnyAsync(m => ids.Contains(m.Id) && m.SenderId == readerId))
|
||||
return Result.Failure<ChatReadResult>(Error.Validation("Message.Read.OwnMessage",
|
||||
"Only incoming messages can be marked as read."));
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
boundary = upToMessageId.HasValue
|
||||
? await chat.FirstOrDefaultAsync(m => m.Id == upToMessageId.Value)
|
||||
: await chat.OrderByDescending(m => m.SentAt).ThenByDescending(m => m.Id)
|
||||
.FirstOrDefaultAsync();
|
||||
if (upToMessageId.HasValue && boundary is null)
|
||||
return Result.Failure<ChatReadResult>(Error.NotFound("Message.Read.BoundaryNotFound",
|
||||
"The boundary message does not belong to this chat."));
|
||||
}
|
||||
|
||||
var readAt = _dateTimeProvider.Now;
|
||||
var readCount = 0;
|
||||
var selected = chat.Where(m => m.SenderId != readerId);
|
||||
if (ids is not null)
|
||||
selected = selected.Where(m => ids.Contains(m.Id));
|
||||
else if (boundary is not null)
|
||||
{
|
||||
var sentAt = boundary.SentAt;
|
||||
var id = boundary.Id;
|
||||
selected = selected.Where(m => m.SentAt < sentAt ||
|
||||
(m.SentAt == sentAt && m.Id.CompareTo(id) <= 0));
|
||||
}
|
||||
else
|
||||
selected = selected.Where(m => false);
|
||||
|
||||
// Small bounded batches; PostgreSQL/SQLite ON CONFLICT handles concurrent devices
|
||||
// against the existing unique (MessageId, UserId) index without losing receipts.
|
||||
while (true)
|
||||
{
|
||||
var pending = await selected.Where(m => !_dbContext.MessageViews
|
||||
.Any(v => v.MessageId == m.Id && v.UserId == readerId))
|
||||
.Select(m => m.Id).Take(200).ToListAsync();
|
||||
if (pending.Count == 0)
|
||||
break;
|
||||
|
||||
var values = new List<string>();
|
||||
var parameters = new List<object>();
|
||||
using var command = _dbContext.Database.GetDbConnection().CreateCommand();
|
||||
foreach (var id in pending)
|
||||
{
|
||||
var names = new List<string>();
|
||||
foreach (var value in new object[] { Guid.NewGuid(), id, readerId, readAt })
|
||||
{
|
||||
var parameter = command.CreateParameter();
|
||||
parameter.ParameterName = "p" + parameters.Count;
|
||||
parameter.Value = value;
|
||||
parameters.Add(parameter);
|
||||
names.Add("@" + parameter.ParameterName);
|
||||
}
|
||||
values.Add("SELECT " + string.Join(", ", names) +
|
||||
" WHERE EXISTS (SELECT 1 FROM \"Messages\" WHERE \"Id\" = " + names[1] + ")");
|
||||
}
|
||||
var sql = "INSERT INTO \"MessageViews\" (\"Id\", \"MessageId\", \"UserId\", \"ViewedAt\") " +
|
||||
string.Join(" UNION ALL ", values) + " ON CONFLICT (\"MessageId\", \"UserId\") DO NOTHING";
|
||||
readCount += await _dbContext.Database.ExecuteSqlRawAsync(sql, parameters);
|
||||
}
|
||||
|
||||
var unreadCount = await CountUnreadAsync(readerId, chat);
|
||||
_logger.LogInformation("User {ReaderId} marked {Count} messages read in chat {ChatId}",
|
||||
readerId, readCount, chatId);
|
||||
return new ChatReadResult(chatId, type, readerId, readAt,
|
||||
boundary?.Id, boundary?.SentAt, ids, readCount, unreadCount);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<Result<int, Error>> GetUnreadCountAsync(Guid readerId, Guid chatId, RecipientType type)
|
||||
{
|
||||
if (!await _dbContext.HasChatAccessAsync(readerId, chatId, type))
|
||||
return Result.Failure<int>(Denied());
|
||||
|
||||
return await CountUnreadAsync(readerId, _dbContext.Messages.AsNoTracking()
|
||||
.Where(m => m.RecipientId == chatId && m.RecipientType == type));
|
||||
}
|
||||
|
||||
private Task<int> CountUnreadAsync(Guid readerId, IQueryable<Message> chat) =>
|
||||
chat.CountAsync(m => m.SenderId != readerId &&
|
||||
!_dbContext.MessageViews.Any(v => v.MessageId == m.Id && v.UserId == readerId));
|
||||
|
||||
private static Error Denied() => Error.Forbidden("Chat.AccessDenied",
|
||||
"You are not a member of this chat.");
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using Govor.Application.Messages.Parameters;
|
||||
using DeleteMessage = Govor.Application.Messages.Parameters.DeleteMessage;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
@@ -13,75 +13,38 @@ public class MessageRemovingService : IMessageRemovingService
|
||||
private readonly GovorDbContext _govorDbContext;
|
||||
private readonly ILogger<MessageRemovingService> _logger;
|
||||
|
||||
public MessageRemovingService
|
||||
(GovorDbContext govorDbContext,
|
||||
ILogger<MessageRemovingService> logger)
|
||||
public MessageRemovingService(GovorDbContext govorDbContext, ILogger<MessageRemovingService> logger)
|
||||
{
|
||||
_govorDbContext = govorDbContext;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
public async Task<Result<Message,Error>> DeleteMessageAsync(DeleteMessage deleteParams)
|
||||
public async Task<Result<Message, Error>> DeleteMessageAsync(DeleteMessage deleteParams)
|
||||
{
|
||||
var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
|
||||
|
||||
if (message == null)
|
||||
return Result<Message, Error>.Failure(
|
||||
Error.NotFound(
|
||||
"MessageRemoving",
|
||||
"Message with given id doesn't exist")
|
||||
);
|
||||
var message = await _govorDbContext.Messages.FirstOrDefaultAsync(m => m.Id == deleteParams.MessageId);
|
||||
if (message is null)
|
||||
return Result.Failure<Message>(Error.NotFound("Message.NotFound", "Message not found."));
|
||||
|
||||
var result = message.RecipientType switch
|
||||
{
|
||||
RecipientType.Group => await ValidateGroupRecipientAsync(message, deleteParams),
|
||||
RecipientType.User => await ValidateUserRecipientAsync(message, deleteParams),
|
||||
|
||||
_ => Result<Message, Error>.Failure(Error.Failure(
|
||||
"MessageRemoving.ArgumentOutOfRangeException",
|
||||
$"Argument out of range: {nameof(message.RecipientType)}"
|
||||
)
|
||||
)
|
||||
};
|
||||
|
||||
return result;
|
||||
}
|
||||
if (!await _govorDbContext.HasChatAccessAsync(deleteParams.DeleterId,
|
||||
message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<Message>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
|
||||
|
||||
private async Task<Result<Message,Error>> ValidateGroupRecipientAsync(Message message, DeleteMessage deleteParams)
|
||||
{
|
||||
if (deleteParams.DeleterId == message.RecipientId)
|
||||
{
|
||||
return await ForceRemoveAsync(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO made admin rules
|
||||
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
|
||||
$"You do not have permission to delete message {message.Id}"
|
||||
));
|
||||
}
|
||||
}
|
||||
// Do not silently turn a local hide into deletion for everyone.
|
||||
if (!deleteParams.ForceRemove)
|
||||
return Result.Failure<Message>(Error.Validation("Message.HideNotSupported",
|
||||
"HideForMe is not supported. Use ForceRemove to delete a message for everyone."));
|
||||
|
||||
private async Task<Result<Message,Error>> ValidateUserRecipientAsync(Message message, DeleteMessage deleteParams)
|
||||
{
|
||||
if (deleteParams.DeleterId == message.SenderId)
|
||||
{
|
||||
return await ForceRemoveAsync(message);
|
||||
}
|
||||
else
|
||||
{
|
||||
// TODO made hide rules
|
||||
return Result<Message, Error>.Failure(Error.Failure("MessageRemoving.HaveNoPermission",
|
||||
$"You do not have permission to delete message {message.Id}"
|
||||
));
|
||||
}
|
||||
}
|
||||
var canDelete = message.SenderId == deleteParams.DeleterId ||
|
||||
(message.RecipientType == RecipientType.Group &&
|
||||
await _govorDbContext.GroupAdmins.AnyAsync(a =>
|
||||
a.GroupId == message.RecipientId && a.UserId == deleteParams.DeleterId));
|
||||
if (!canDelete)
|
||||
return Result.Failure<Message>(Error.Forbidden("Message.Remove.AccessDenied",
|
||||
"Only the author or a group administrator can delete this message."));
|
||||
|
||||
private async Task<Result<Message, Error>> ForceRemoveAsync(Message message)
|
||||
{
|
||||
_govorDbContext.Messages.Remove(message);
|
||||
await _govorDbContext.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Message {MessageId} removed by {UserId}", message.Id, deleteParams.DeleterId);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ using Govor.Application.Messages.Parameters;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Govor.Application.Messages;
|
||||
@@ -19,9 +20,14 @@ public class MessageSendingService : IMessageSendingService
|
||||
|
||||
public async Task<SendMessageResult> SendMessageAsync(SendMessage sendParams)
|
||||
{
|
||||
var media = sendParams.Media?.ToArray() ?? [];
|
||||
if ((string.IsNullOrWhiteSpace(sendParams.EncryptContent) && media.Length == 0) ||
|
||||
(sendParams.EncryptContent?.Length ?? 0) > 50_000 || media.Length > 100)
|
||||
return new SendMessageResult(false, new ArgumentException("Invalid message content or attachment count."), default);
|
||||
|
||||
var validationResult = sendParams.RecipientType switch
|
||||
{
|
||||
RecipientType.User => await ValidateUserRecipientAsync(sendParams.RecipientId),
|
||||
RecipientType.User => await ValidateUserRecipientAsync(sendParams.FromUserId, sendParams.RecipientId),
|
||||
RecipientType.Group => await ValidateGroupRecipientAsync(sendParams.FromUserId, sendParams.RecipientId),
|
||||
_ => (Success: false, Error: "Invalid recipient type.")
|
||||
};
|
||||
@@ -29,9 +35,20 @@ public class MessageSendingService : IMessageSendingService
|
||||
if (!validationResult.Success)
|
||||
{
|
||||
_logger.LogWarning("Message send failed: {Error}", validationResult.Error);
|
||||
return new SendMessageResult(false, new InvalidOperationException(validationResult.Error), default);
|
||||
return new SendMessageResult(false, new UnauthorizedAccessException(validationResult.Error), default);
|
||||
}
|
||||
|
||||
var mediaIds = media.Select(m => m.MediaId).Distinct().ToArray();
|
||||
var files = await _dbContext.MediaFiles.Where(m => mediaIds.Contains(m.Id) &&
|
||||
m.UploaderId == sendParams.FromUserId && m.OwnerType == MediaOwnerType.Message).ToListAsync();
|
||||
if (files.Count != mediaIds.Length)
|
||||
return new SendMessageResult(false, new UnauthorizedAccessException("Invalid media ownership."), default);
|
||||
|
||||
if (sendParams.ReplyToMessageId.HasValue && !await _dbContext.Messages.AnyAsync(m =>
|
||||
m.Id == sendParams.ReplyToMessageId && m.RecipientId == sendParams.RecipientId &&
|
||||
m.RecipientType == sendParams.RecipientType))
|
||||
return new SendMessageResult(false, new ArgumentException("Reply must belong to the same chat."), default);
|
||||
|
||||
var messageId = Guid.NewGuid();
|
||||
var message = new Message
|
||||
{
|
||||
@@ -39,38 +56,51 @@ public class MessageSendingService : IMessageSendingService
|
||||
SenderId = sendParams.FromUserId,
|
||||
RecipientId = sendParams.RecipientId,
|
||||
RecipientType = sendParams.RecipientType,
|
||||
EncryptedContent = sendParams.EncryptContent,
|
||||
EncryptedContent = sendParams.EncryptContent ?? string.Empty,
|
||||
SentAt = sendParams.SendAt,
|
||||
IsEdited = false,
|
||||
ReplyToMessageId = sendParams.ReplyToMessageId,
|
||||
MediaAttachments = sendParams.Media?.Select(m => new MediaAttachments
|
||||
MediaAttachments = files.Select(file => new MediaAttachments
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
MessageId = messageId,
|
||||
MediaFileId = m.MediaId
|
||||
}).ToList() ?? []
|
||||
MediaFileId = file.Id,
|
||||
MediaFile = file
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
await _dbContext.Messages.AddAsync(message);
|
||||
// Save message and pending push atomically so a restart/provider outage cannot lose the push.
|
||||
_dbContext.ChatPushNotifications.Add(new ChatPushNotification
|
||||
{ MessageId = messageId, NextAttemptAt = DateTime.UtcNow });
|
||||
await _dbContext.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Message {MessageId} sent successfully.", messageId);
|
||||
return new SendMessageResult(true, null, message);
|
||||
}
|
||||
|
||||
private async Task<(bool Success, string Error)> ValidateUserRecipientAsync(Guid chatId)
|
||||
private async Task<(bool Success, string Error)> ValidateUserRecipientAsync(Guid userId, Guid chatId)
|
||||
{
|
||||
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == chatId);
|
||||
return chatExists ? (true, null) : (false, $"Private chat {chatId} not found.");
|
||||
var chat = await _dbContext.PrivateChats.AsNoTracking().FirstOrDefaultAsync(c => c.Id == chatId &&
|
||||
(c.UserAId == userId || c.UserBId == userId));
|
||||
if (chat is null)
|
||||
return (false, "You are not a member of this chat.");
|
||||
var blocked = await _dbContext.Friendships.AnyAsync(f => f.Status == FriendshipStatus.Blocked &&
|
||||
((f.RequesterId == chat.UserAId && f.AddresseeId == chat.UserBId) ||
|
||||
(f.RequesterId == chat.UserBId && f.AddresseeId == chat.UserAId)));
|
||||
return blocked ? (false, "This conversation is blocked.") : (true, null);
|
||||
}
|
||||
|
||||
private async Task<(bool Success, string Error)> ValidateGroupRecipientAsync(Guid userId, Guid groupId)
|
||||
{
|
||||
var groupExists = await _dbContext.ChatGroups.AnyAsync(g => g.Id == groupId);
|
||||
if (!groupExists) return (false, $"Group {groupId} not found.");
|
||||
var group = await _dbContext.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == groupId);
|
||||
if (group is null) return (false, "Group not found.");
|
||||
|
||||
var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId);
|
||||
var isMember = await _dbContext.GroupMemberships.AnyAsync(gm => gm.UserId == userId && gm.GroupId == groupId && !gm.IsBanned);
|
||||
if (!isMember) return (false, "Sender is not a member of the group.");
|
||||
if (group.IsChannel && !await _dbContext.GroupAdmins.AnyAsync(a =>
|
||||
a.GroupId == groupId && a.UserId == userId))
|
||||
return (false, "Only channel administrators can send messages.");
|
||||
|
||||
return (true, null);
|
||||
}
|
||||
|
||||
@@ -26,12 +26,13 @@ public class MessagesLoader : IMessagesLoader
|
||||
if (privateChatId == Guid.Empty)
|
||||
return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"PrivateChatId id cannot be empty."));
|
||||
|
||||
var chatExists = await _dbContext.PrivateChats.AnyAsync(c => c.Id == privateChatId);
|
||||
if (!chatExists)
|
||||
return new List<Message>(0);
|
||||
if (!await _dbContext.HasChatAccessAsync(currentUser, privateChatId, RecipientType.User))
|
||||
return Result.Failure<List<Message>>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
|
||||
|
||||
var query = _dbContext.Messages
|
||||
.AsNoTracking()
|
||||
.Include(m => m.MessageViews)
|
||||
.Include(m => m.Reactions)
|
||||
.Include(m => m.MediaAttachments)
|
||||
.ThenInclude(m => m.MediaFile)
|
||||
.Where(m => m.RecipientType == RecipientType.User && m.RecipientId == privateChatId);
|
||||
@@ -50,13 +51,15 @@ public class MessagesLoader : IMessagesLoader
|
||||
return Result.Failure<List<Message>>(Error.Failure(nameof(ArgumentException),"Chat id cannot be empty."));
|
||||
|
||||
var isMember = await _dbContext.GroupMemberships
|
||||
.AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId);
|
||||
.AnyAsync(gm => gm.UserId == currentUser && gm.GroupId == chatId && !gm.IsBanned);
|
||||
|
||||
if (!isMember)
|
||||
return new List<Message>(0);
|
||||
if (!isMember)
|
||||
return Result.Failure<List<Message>>(Error.Forbidden("Chat.AccessDenied", "You are not a member of this chat."));
|
||||
|
||||
var query = _dbContext.Messages
|
||||
.AsNoTracking()
|
||||
.Include(m => m.MessageViews)
|
||||
.Include(m => m.Reactions)
|
||||
.Include(m => m.MediaAttachments)
|
||||
.ThenInclude(m => m.MediaFile)
|
||||
.AsSplitQuery()
|
||||
@@ -75,8 +78,10 @@ public class MessagesLoader : IMessagesLoader
|
||||
{
|
||||
return await baseQuery
|
||||
.OrderByDescending(m => m.SentAt)
|
||||
.ThenByDescending(m => m.Id)
|
||||
.Take(before)
|
||||
.OrderBy(m => m.SentAt)
|
||||
.ThenBy(m => m.Id)
|
||||
.ToListAsync();
|
||||
}
|
||||
|
||||
@@ -85,14 +90,18 @@ public class MessagesLoader : IMessagesLoader
|
||||
return [];
|
||||
|
||||
var beforeMessages = await baseQuery
|
||||
.Where(m => m.SentAt < startMessage.SentAt)
|
||||
.Where(m => m.SentAt < startMessage.SentAt ||
|
||||
(m.SentAt == startMessage.SentAt && m.Id.CompareTo(startMessage.Id) < 0))
|
||||
.OrderByDescending(m => m.SentAt)
|
||||
.ThenByDescending(m => m.Id)
|
||||
.Take(before)
|
||||
.ToListAsync();
|
||||
|
||||
var afterMessages = await baseQuery
|
||||
.Where(m => m.SentAt > startMessage.SentAt)
|
||||
.Where(m => m.SentAt > startMessage.SentAt ||
|
||||
(m.SentAt == startMessage.SentAt && m.Id.CompareTo(startMessage.Id) > 0))
|
||||
.OrderBy(m => m.SentAt)
|
||||
.ThenBy(m => m.Id)
|
||||
.Take(after)
|
||||
.ToListAsync();
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
using Govor.Domain.Models.Messages;
|
||||
|
||||
namespace Govor.Application.Messages.Parameters;
|
||||
|
||||
public record ChatReadResult(Guid ChatId, RecipientType RecipientType, Guid ReaderId,
|
||||
DateTime ReadAt, Guid? UpToMessageId, DateTime? UpToSentAt,
|
||||
IReadOnlyList<Guid>? MessageIds, int ReadCount, int UnreadCount);
|
||||
@@ -30,8 +30,8 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService
|
||||
|
||||
if (res == null)
|
||||
return Result.Failure<PrivateChat>(
|
||||
Error.Failure(
|
||||
nameof(InvalidOperationException),
|
||||
Error.NotFound(
|
||||
"PrivateChat.NotFound",
|
||||
"PrivateChat not found.")
|
||||
);
|
||||
|
||||
@@ -46,4 +46,4 @@ public class UserPrivateChatsGetter : IUserPrivateChatsGetterService
|
||||
(p.UserBId == userIdA && p.UserAId == userIdB)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmartRes;
|
||||
@@ -61,6 +62,10 @@ public class ProfileService : IProfileService
|
||||
{
|
||||
_logger.LogInformation("Updating icon for user {UserId}", userId);
|
||||
|
||||
if (!await _context.MediaFiles.AnyAsync(f => f.Id == iconId && f.UploaderId == userId &&
|
||||
f.OwnerType == MediaOwnerType.Avatar))
|
||||
return Result<Unit, Error>.Failure(Error.Forbidden("Profile.IconAccess", "Only your uploaded avatar can be used."));
|
||||
|
||||
|
||||
var updatedRows = await _context.Users
|
||||
.Where(u => u.Id == userId)
|
||||
|
||||
@@ -40,6 +40,21 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
{
|
||||
if (tokens.Count == 0)
|
||||
return new SendPushResult(0, 0, []);
|
||||
|
||||
if (tokens.Count > 500)
|
||||
{
|
||||
var success = 0;
|
||||
var failure = 0;
|
||||
var invalid = new List<string>();
|
||||
foreach (var batch in tokens.Distinct().Chunk(500))
|
||||
{
|
||||
var result = await SendMulticastAsync(batch, message);
|
||||
success += result.SuccessCount;
|
||||
failure += result.FailureCount;
|
||||
invalid.AddRange(result.FailedTokens);
|
||||
}
|
||||
return new SendPushResult(success, failure, invalid);
|
||||
}
|
||||
|
||||
var multicastMsg = new MulticastMessage
|
||||
{
|
||||
@@ -89,7 +104,7 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "FCM multicast failed");
|
||||
return new SendPushResult(0, tokens.Count, tokens.ToList());
|
||||
throw; // A provider outage does not invalidate device tokens.
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,8 +139,6 @@ public class FirebasePushProvider : IPushNotificationProvider
|
||||
|
||||
private static bool IsInvalidTokenError(FirebaseMessagingException ex)
|
||||
{
|
||||
return ex.MessagingErrorCode is MessagingErrorCode.Unregistered
|
||||
or MessagingErrorCode.InvalidArgument
|
||||
or MessagingErrorCode.SenderIdMismatch;
|
||||
return ex.MessagingErrorCode is MessagingErrorCode.Unregistered;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,11 +9,11 @@ public class NullPushProvider : IPushNotificationProvider
|
||||
|
||||
public Task<SendPushResult> SendToTokenAsync(string token, PushMessage message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
return Task.FromResult(new SendPushResult(0, 0, []));
|
||||
}
|
||||
|
||||
public Task<SendPushResult> SendMulticastAsync(IReadOnlyList<string> tokens, PushMessage message)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
return Task.FromResult(new SendPushResult(0, 0, []));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,8 @@ public class PushNotificationService : IPushNotificationService
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for session {SessionId}", result.FailureCount, sessionId);
|
||||
}
|
||||
|
||||
if (result.FailureCount > result.FailedTokens.Count())
|
||||
return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily."));
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -97,6 +99,8 @@ public class PushNotificationService : IPushNotificationService
|
||||
_logger.LogWarning("Removed {Count} invalid FCM tokens for target: {Target}", result.FailureCount, targetInfo);
|
||||
}
|
||||
|
||||
if (result.FailureCount > result.FailedTokens.Count())
|
||||
return Result.Failure(Error.ServerError("Push.DeliveryFailed", "Push delivery failed temporarily."));
|
||||
return Result.Success();
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -117,4 +121,4 @@ public class PushNotificationService : IPushNotificationService
|
||||
ChannelId = channelId
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,8 +63,10 @@ public class PushTokenService : IPushTokenService
|
||||
{
|
||||
var tokens = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => t.UserId == userId && t.IsActive)
|
||||
.Where(t => t.UserId == userId && t.IsActive && _context.UserSessions.Any(s =>
|
||||
s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now))
|
||||
.Select(t => t.Token)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
return tokens;
|
||||
@@ -82,8 +84,10 @@ public class PushTokenService : IPushTokenService
|
||||
{
|
||||
var tokens = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => userIds.Contains(t.UserId) && t.IsActive)
|
||||
.Where(t => userIds.Contains(t.UserId) && t.IsActive && _context.UserSessions.Any(s =>
|
||||
s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now))
|
||||
.Select(t => t.Token)
|
||||
.Distinct()
|
||||
.ToListAsync();
|
||||
|
||||
return tokens;
|
||||
@@ -101,7 +105,8 @@ public class PushTokenService : IPushTokenService
|
||||
{
|
||||
var token = await _context.UserPushTokens
|
||||
.AsNoTracking()
|
||||
.Where(t => t.UserSessionId == sessionId && t.IsActive)
|
||||
.Where(t => t.UserSessionId == sessionId && t.IsActive && _context.UserSessions.Any(s =>
|
||||
s.Id == t.UserSessionId && s.UserId == t.UserId && !s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now))
|
||||
.Select(t => t.Token)
|
||||
.FirstOrDefaultAsync();
|
||||
|
||||
@@ -138,13 +143,22 @@ public class PushTokenService : IPushTokenService
|
||||
|
||||
public async Task<Result<Unit, Error>> AddOrUpdateTokenAsync(Guid userId, Guid sessionId, string token, string platform)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(token))
|
||||
if (string.IsNullOrWhiteSpace(token) || token.Length > 512 || string.IsNullOrWhiteSpace(platform) || platform.Length > 50)
|
||||
{
|
||||
return Result<Unit, Error>.Failure(Error.Failure("PushToken.Empty", "Push token cannot be empty."));
|
||||
}
|
||||
|
||||
var existingToken = await _context.UserPushTokens
|
||||
.FirstOrDefaultAsync(t => t.Platform == platform && t.UserId == userId && t.UserSessionId == sessionId);
|
||||
if (!await _context.UserSessions.AnyAsync(s => s.Id == sessionId && s.UserId == userId &&
|
||||
!s.IsRevoked && s.ExpiresAt > _nowDateTimeProvider.Now))
|
||||
return Result<Unit, Error>.Failure(Error.Forbidden("PushToken.Session", "An active own session is required."));
|
||||
|
||||
// Token and session both have unique indexes. Reassign the device row when an
|
||||
// account changes, instead of inserting a duplicate or retaining the old owner.
|
||||
var sessionToken = await _context.UserPushTokens.FirstOrDefaultAsync(t => t.UserSessionId == sessionId);
|
||||
var deviceToken = await _context.UserPushTokens.FirstOrDefaultAsync(t => t.Token == token);
|
||||
if (sessionToken is not null && deviceToken is not null && sessionToken.Id != deviceToken.Id)
|
||||
_context.UserPushTokens.Remove(sessionToken);
|
||||
var existingToken = deviceToken ?? sessionToken;
|
||||
|
||||
if (existingToken is null)
|
||||
{
|
||||
@@ -167,6 +181,8 @@ public class PushTokenService : IPushTokenService
|
||||
existingToken.Platform = platform;
|
||||
existingToken.Token = token;
|
||||
existingToken.UpdatedAt = _nowDateTimeProvider.Now;
|
||||
existingToken.IsActive = true;
|
||||
_context.Entry(existingToken).Property(t => t.IsActive).IsModified = true;
|
||||
}
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Reactions;
|
||||
|
||||
public record ReactionCount(Guid? ReactionId, string ReactionCode, int Count);
|
||||
public record MessageReactionState(Guid MessageId, Guid RecipientId, RecipientType RecipientType,
|
||||
long Version, Guid ActorId, MessageReaction? ActorReaction, IReadOnlyList<ReactionCount> Counts, bool Changed = false);
|
||||
public record ChannelReactionPolicy(Guid GroupId, ChannelReactionMode Mode, long Version, IReadOnlyList<Guid> ReactionIds);
|
||||
|
||||
public interface IMessageReactionService
|
||||
{
|
||||
Task<Result<MessageReactionState, Error>> GetAsync(Guid userId, Guid messageId);
|
||||
Task<Result<MessageReactionState, Error>> SetAsync(Guid userId, Guid messageId, Guid? reactionId);
|
||||
Task<Result<ChannelReactionPolicy, Error>> GetPolicyAsync(Guid userId, Guid groupId);
|
||||
Task<Result<ChannelReactionPolicy, Error>> SetPolicyAsync(Guid userId, Guid groupId, ChannelReactionMode mode, IReadOnlyCollection<Guid> reactionIds);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Reactions;
|
||||
|
||||
public interface IReactionPackService
|
||||
{
|
||||
Task<List<ReactionPack>> ListAsync(Guid userId, bool installedOnly = false, bool includeDisabled = false, int skip = 0, int take = 50);
|
||||
Task<Result<ReactionPack, Error>> GetAsync(Guid packId, bool includeDisabled = false);
|
||||
Task<Result<ReactionPack, Error>> GetSharedAsync(string shareCode);
|
||||
Task<Result<ReactionItem, Error>> GetReactionAsync(Guid reactionId);
|
||||
Task<Result<Unit, Error>> SubscribeAsync(Guid userId, Guid packId, bool subscribe);
|
||||
Task<Result<ReactionPack, Error>> CreateAsync(Guid actorId, string name, string description);
|
||||
Task<Result<ReactionPack, Error>> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled);
|
||||
Task<Result<Unit, Error>> DisableAsync(Guid actorId, Guid packId);
|
||||
Task<Result<ReactionItem, Error>> AddEmojiAsync(Guid actorId, Guid packId, string name, string emoji);
|
||||
Task<Result<ReactionItem, Error>> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data, CancellationToken cancellationToken = default);
|
||||
Task<Result<Unit, Error>> DisableReactionAsync(Guid actorId, Guid packId, Guid reactionId);
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Messages;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Reactions;
|
||||
|
||||
public class MessageReactionService(GovorDbContext context, INowDateTimeProvider clock) : IMessageReactionService
|
||||
{
|
||||
public async Task<Result<MessageReactionState, Error>> GetAsync(Guid userId, Guid messageId)
|
||||
{
|
||||
var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
if (message is null) return Result.Failure<MessageReactionState>(Missing());
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
// A repeatable snapshot keeps version, counts and actor reaction consistent.
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable);
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
var state = await StateAsync(messageId, userId);
|
||||
await transaction.CommitAsync();
|
||||
return state is null ? Result.Failure<MessageReactionState>(Missing()) : Result.Success(state);
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<Result<MessageReactionState, Error>> SetAsync(Guid userId, Guid messageId, Guid? reactionId)
|
||||
{
|
||||
if (reactionId == Guid.Empty)
|
||||
return Result.Failure<MessageReactionState>(Error.Validation("Reaction.InvalidId", "A reaction ID is required."));
|
||||
var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
if (message is null) return Result.Failure<MessageReactionState>(Missing());
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
if (message.RecipientType == RecipientType.Group)
|
||||
// Same lock order as channel policy changes; serialize reaction decisions with policy writes.
|
||||
await context.ChatGroups.Where(g => g.Id == message.RecipientId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.ReactionMode, g => g.ReactionMode));
|
||||
if (await context.Messages.Where(m => m.Id == messageId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion)) == 0)
|
||||
return Result.Failure<MessageReactionState>(Missing());
|
||||
if (!await context.HasChatAccessAsync(userId, message.RecipientId, message.RecipientType))
|
||||
return Result.Failure<MessageReactionState>(Denied());
|
||||
|
||||
ReactionItem? item = null;
|
||||
if (reactionId.HasValue)
|
||||
{
|
||||
item = await context.ReactionItems.AsNoTracking()
|
||||
.FirstOrDefaultAsync(r => r.Id == reactionId && r.IsEnabled && r.Pack.IsEnabled);
|
||||
if (item is null) return Result.Failure<MessageReactionState>(Error.NotFound("Reaction.NotAvailable", "Reaction is not available."));
|
||||
var channel = message.RecipientType == RecipientType.Group
|
||||
? await context.ChatGroups.AsNoTracking().FirstOrDefaultAsync(g => g.Id == message.RecipientId && g.IsChannel)
|
||||
: null;
|
||||
if (channel is not null && (channel.ReactionMode == ChannelReactionMode.None ||
|
||||
(channel.ReactionMode == ChannelReactionMode.Selected && !await context.ChannelAllowedReactions
|
||||
.AnyAsync(r => r.GroupId == channel.Id && r.ReactionId == item.Id))))
|
||||
return Result.Failure<MessageReactionState>(Error.Forbidden("Reaction.ChannelRestricted", "This reaction is not allowed in the channel."));
|
||||
}
|
||||
|
||||
var current = await context.MessageReactions.AsNoTracking().FirstOrDefaultAsync(r => r.MessageId == messageId && r.UserId == userId);
|
||||
var changed = reactionId.HasValue ? current?.ReactionId != reactionId : current is not null;
|
||||
if (changed)
|
||||
{
|
||||
if (item is null)
|
||||
await context.MessageReactions.Where(r => r.MessageId == messageId && r.UserId == userId).ExecuteDeleteAsync();
|
||||
else
|
||||
{
|
||||
var id = Guid.NewGuid();
|
||||
var now = clock.Now;
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"MessageReactions\" (\"Id\", \"MessageId\", \"UserId\", \"ReactionId\", \"ReactionCode\", \"ReactedAt\") VALUES ({id}, {messageId}, {userId}, {item.Id}, {item.Code}, {now}) ON CONFLICT (\"MessageId\", \"UserId\") DO UPDATE SET \"ReactionId\" = excluded.\"ReactionId\", \"ReactionCode\" = excluded.\"ReactionCode\", \"ReactedAt\" = excluded.\"ReactedAt\"");
|
||||
}
|
||||
await context.Messages.Where(m => m.Id == messageId)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(m => m.ReactionsVersion, m => m.ReactionsVersion + 1));
|
||||
}
|
||||
var state = (await StateAsync(messageId, userId))! with { Changed = changed };
|
||||
await transaction.CommitAsync();
|
||||
return Result.Success(state);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<MessageReactionState?> StateAsync(Guid messageId, Guid actorId)
|
||||
{
|
||||
var message = await context.Messages.AsNoTracking().FirstOrDefaultAsync(m => m.Id == messageId);
|
||||
if (message is null) return null;
|
||||
var counts = await context.MessageReactions.AsNoTracking().Where(r => r.MessageId == messageId)
|
||||
.GroupBy(r => new { r.ReactionId, r.ReactionCode })
|
||||
.OrderByDescending(g => g.Count()).ThenBy(g => g.Key.ReactionCode)
|
||||
.Select(g => new ReactionCount(g.Key.ReactionId, g.Key.ReactionCode, g.Count()))
|
||||
.ToListAsync();
|
||||
var actor = await context.MessageReactions.AsNoTracking().FirstOrDefaultAsync(r => r.MessageId == messageId && r.UserId == actorId);
|
||||
return new MessageReactionState(messageId, message.RecipientId, message.RecipientType,
|
||||
message.ReactionsVersion, actorId, actor, counts);
|
||||
}
|
||||
|
||||
public async Task<Result<ChannelReactionPolicy, Error>> GetPolicyAsync(Guid userId, Guid groupId)
|
||||
{
|
||||
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group))
|
||||
return Result.Failure<ChannelReactionPolicy>(Denied());
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync(System.Data.IsolationLevel.Serializable);
|
||||
var policy = await PolicyAsync(groupId);
|
||||
await transaction.CommitAsync();
|
||||
return Result.Success(policy);
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<Result<ChannelReactionPolicy, Error>> SetPolicyAsync(Guid userId, Guid groupId,
|
||||
ChannelReactionMode mode, IReadOnlyCollection<Guid> reactionIds)
|
||||
{
|
||||
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) ||
|
||||
!await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId))
|
||||
return Result.Failure<ChannelReactionPolicy>(Denied());
|
||||
if (!Enum.IsDefined(mode) || reactionIds is null || reactionIds.Count > 100 || reactionIds.Contains(Guid.Empty) ||
|
||||
(mode != ChannelReactionMode.Selected && reactionIds.Count > 0))
|
||||
return Result.Failure<ChannelReactionPolicy>(Error.Validation("Reaction.Policy.Invalid", "Provide a valid mode and at most 100 reaction IDs for Selected mode."));
|
||||
var ids = reactionIds.Distinct().ToArray();
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
var updated = await context.ChatGroups.Where(g => g.Id == groupId && g.IsChannel)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(g => g.ReactionMode, mode)
|
||||
.SetProperty(g => g.ReactionPolicyVersion, g => g.ReactionPolicyVersion + 1));
|
||||
if (updated == 0) return Result.Failure<ChannelReactionPolicy>(Error.Validation("Reaction.Policy.NotChannel", "Only channels support reaction restrictions."));
|
||||
if (!await context.HasChatAccessAsync(userId, groupId, RecipientType.Group) ||
|
||||
!await context.GroupAdmins.AnyAsync(a => a.GroupId == groupId && a.UserId == userId))
|
||||
return Result.Failure<ChannelReactionPolicy>(Denied());
|
||||
if (await context.ReactionItems.CountAsync(r => ids.Contains(r.Id) && r.IsEnabled && r.Pack.IsEnabled) != ids.Length)
|
||||
return Result.Failure<ChannelReactionPolicy>(Error.Validation("Reaction.Policy.InvalidSelection", "All reactions must be active and available."));
|
||||
await context.ChannelAllowedReactions.Where(r => r.GroupId == groupId).ExecuteDeleteAsync();
|
||||
foreach (var id in ids)
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"ChannelAllowedReactions\" (\"GroupId\", \"ReactionId\") VALUES ({groupId}, {id})");
|
||||
var policy = await PolicyAsync(groupId);
|
||||
await transaction.CommitAsync();
|
||||
return Result.Success(policy);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<ChannelReactionPolicy> PolicyAsync(Guid groupId)
|
||||
{
|
||||
var group = await context.ChatGroups.AsNoTracking().FirstAsync(g => g.Id == groupId);
|
||||
var ids = await context.ChannelAllowedReactions.Where(r => r.GroupId == groupId)
|
||||
.OrderBy(r => r.ReactionId).Select(r => r.ReactionId).ToListAsync();
|
||||
return new ChannelReactionPolicy(groupId, group.ReactionMode, group.ReactionPolicyVersion, ids);
|
||||
}
|
||||
|
||||
private static Error Missing() => Error.NotFound("Message.NotFound", "Message not found.");
|
||||
private static Error Denied() => Error.Forbidden("Reaction.AccessDenied", "You do not have access to this chat or operation.");
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using SixLabors.ImageSharp;
|
||||
using SixLabors.ImageSharp.Formats;
|
||||
using SixLabors.ImageSharp.Formats.Gif;
|
||||
using SixLabors.ImageSharp.Memory;
|
||||
using SixLabors.ImageSharp.PixelFormats;
|
||||
using SixLabors.ImageSharp.Processing;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Reactions;
|
||||
|
||||
public static class ReactionMediaLimits
|
||||
{
|
||||
public const int MaxDimension = 128;
|
||||
public const int MaxUploadBytes = 2 * 1024 * 1024;
|
||||
public const int MaxImageBytes = 256 * 1024;
|
||||
public const int MaxGifBytes = 512 * 1024;
|
||||
public const int MaxFrames = 60;
|
||||
public const int MaxDurationMilliseconds = 5000;
|
||||
}
|
||||
|
||||
public record ProcessedReactionMedia(byte[] Data, ReactionKind Kind, string MimeType,
|
||||
string Extension, int Width, int Height, int DurationMilliseconds);
|
||||
|
||||
public interface IReactionMediaProcessor
|
||||
{
|
||||
Task<Result<ProcessedReactionMedia, Error>> ProcessAsync(byte[] data, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public class ReactionMediaProcessor : IReactionMediaProcessor
|
||||
{
|
||||
public async Task<Result<ProcessedReactionMedia, Error>> ProcessAsync(byte[] data, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (data.Length == 0 || data.Length > ReactionMediaLimits.MaxUploadBytes)
|
||||
return Invalid("Upload must contain at most 2 MiB.");
|
||||
|
||||
try
|
||||
{
|
||||
var configuration = Configuration.Default.Clone();
|
||||
configuration.MaxDegreeOfParallelism = 2;
|
||||
configuration.MemoryAllocator = MemoryAllocator.Create(new MemoryAllocatorOptions
|
||||
{ MaximumPoolSizeMegabytes = 16, AllocationLimitMegabytes = 64 });
|
||||
var options = new DecoderOptions
|
||||
{
|
||||
Configuration = configuration, SkipMetadata = true,
|
||||
MaxFrames = ReactionMediaLimits.MaxFrames + 1,
|
||||
TargetSize = new Size(ReactionMediaLimits.MaxDimension, ReactionMediaLimits.MaxDimension)
|
||||
};
|
||||
using var input = new MemoryStream(data, writable: false);
|
||||
var format = await Image.DetectFormatAsync(input, cancellationToken);
|
||||
var isGif = format.Name == "GIF";
|
||||
if (!isGif && format.Name is not ("PNG" or "JPEG" or "WEBP"))
|
||||
return Invalid("Only PNG, JPEG, WebP and GIF are supported.");
|
||||
input.Position = 0;
|
||||
var info = await Image.IdentifyAsync(options, input, cancellationToken);
|
||||
if (info.Width > 2048 || info.Height > 2048 || info.FrameMetadataCollection.Count > ReactionMediaLimits.MaxFrames)
|
||||
return Invalid("Source dimensions must not exceed 2048 px and GIF must not exceed 60 frames.");
|
||||
input.Position = 0;
|
||||
using var image = await Image.LoadAsync<Rgba32>(options, input, cancellationToken);
|
||||
if (image.Frames.Count > ReactionMediaLimits.MaxFrames || (!isGif && image.Frames.Count > 1))
|
||||
return Invalid("Only GIF animations with at most 60 frames are supported.");
|
||||
|
||||
var duration = 0;
|
||||
if (isGif)
|
||||
{
|
||||
foreach (var frame in image.Frames)
|
||||
{
|
||||
var metadata = frame.Metadata.GetGifMetadata();
|
||||
metadata.FrameDelay = Math.Max(2, metadata.FrameDelay);
|
||||
duration += metadata.FrameDelay * 10;
|
||||
}
|
||||
if (duration > ReactionMediaLimits.MaxDurationMilliseconds)
|
||||
return Invalid("GIF duration must not exceed 5 seconds per loop.");
|
||||
}
|
||||
|
||||
// Re-encode pixels, never store the original upload or trust its MIME/extension.
|
||||
foreach (var dimension in new[] { 128, 96, 64, 48 })
|
||||
{
|
||||
image.Mutate(x => x.Resize(new ResizeOptions
|
||||
{ Size = new Size(dimension, dimension), Mode = ResizeMode.Max }));
|
||||
using var output = new MemoryStream();
|
||||
if (isGif)
|
||||
await image.SaveAsGifAsync(output, new GifEncoder { SkipMetadata = true }, cancellationToken);
|
||||
else
|
||||
await image.SaveAsPngAsync(output, cancellationToken);
|
||||
if (output.Length <= (isGif ? ReactionMediaLimits.MaxGifBytes : ReactionMediaLimits.MaxImageBytes))
|
||||
return new ProcessedReactionMedia(output.ToArray(), isGif ? ReactionKind.Gif : ReactionKind.Image,
|
||||
isGif ? "image/gif" : "image/png", isGif ? ".gif" : ".png", image.Width, image.Height, duration);
|
||||
}
|
||||
return Invalid("The processed file exceeds the reaction size limit.");
|
||||
}
|
||||
catch (Exception ex) when (ex is UnknownImageFormatException or InvalidImageContentException or InvalidMemoryOperationException or ArgumentException)
|
||||
{
|
||||
return Invalid("Invalid or excessively complex image.");
|
||||
}
|
||||
}
|
||||
|
||||
private static Result<ProcessedReactionMedia, Error> Invalid(string message) =>
|
||||
Result<ProcessedReactionMedia, Error>.Failure(Error.Validation("Reaction.Media.Invalid", message));
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
using System.Globalization;
|
||||
using Govor.Application.Infrastructure.Common;
|
||||
using Govor.Application.Storage;
|
||||
using Govor.Domain;
|
||||
using Govor.Domain.Common;
|
||||
using Govor.Domain.Models;
|
||||
using Govor.Domain.Models.Messages;
|
||||
using Govor.Domain.Models.Reactions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using SmartRes;
|
||||
|
||||
namespace Govor.Application.Reactions;
|
||||
|
||||
public class ReactionPackService(GovorDbContext context, INowDateTimeProvider clock,
|
||||
IReactionMediaProcessor processor, IStorageService storage, ILogger<ReactionPackService> logger) : IReactionPackService
|
||||
{
|
||||
public async Task<List<ReactionPack>> ListAsync(Guid userId, bool installedOnly = false,
|
||||
bool includeDisabled = false, int skip = 0, int take = 50)
|
||||
{
|
||||
var query = context.ReactionPacks.AsNoTracking();
|
||||
if (!includeDisabled) query = query.Where(p => p.IsEnabled);
|
||||
if (installedOnly) query = query.Where(p => p.IsDefault || context.UserReactionPacks
|
||||
.Any(s => s.UserId == userId && s.PackId == p.Id));
|
||||
return await query.OrderByDescending(p => p.IsDefault).ThenBy(p => p.CreatedAt).ThenBy(p => p.Id)
|
||||
.Skip(Math.Max(0, skip)).Take(Math.Clamp(take, 1, 100))
|
||||
.Include(p => p.Reactions.Where(r => includeDisabled || r.IsEnabled)).AsSplitQuery().ToListAsync();
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionPack, Error>> GetAsync(Guid packId, bool includeDisabled = false)
|
||||
{
|
||||
var pack = await context.ReactionPacks.AsNoTracking()
|
||||
.Include(p => p.Reactions.Where(r => includeDisabled || r.IsEnabled))
|
||||
.FirstOrDefaultAsync(p => p.Id == packId && (includeDisabled || p.IsEnabled));
|
||||
return pack is null ? Result.Failure<ReactionPack>(Missing()) : Result.Success(pack);
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionPack, Error>> GetSharedAsync(string shareCode)
|
||||
{
|
||||
var id = await context.ReactionPacks.Where(p => p.ShareCode == shareCode && p.IsEnabled)
|
||||
.Select(p => (Guid?)p.Id).FirstOrDefaultAsync();
|
||||
return id.HasValue ? await GetAsync(id.Value) : Result.Failure<ReactionPack>(Missing());
|
||||
}
|
||||
|
||||
// Definitions remain readable after disabling so historical reactions still render.
|
||||
public async Task<Result<ReactionItem, Error>> GetReactionAsync(Guid reactionId)
|
||||
{
|
||||
var item = await context.ReactionItems.AsNoTracking().FirstOrDefaultAsync(r => r.Id == reactionId);
|
||||
return item is null ? Result.Failure<ReactionItem>(Missing()) : Result.Success(item);
|
||||
}
|
||||
|
||||
public async Task<Result<Unit, Error>> SubscribeAsync(Guid userId, Guid packId, bool subscribe)
|
||||
{
|
||||
var pack = await context.ReactionPacks.AsNoTracking().FirstOrDefaultAsync(p => p.Id == packId && (!subscribe || p.IsEnabled));
|
||||
if (pack is null) return Result.Failure(Missing());
|
||||
if (pack.IsDefault)
|
||||
return subscribe ? Result.Success() : Result.Failure(Invalid("The default pack is always available."));
|
||||
if (subscribe)
|
||||
await context.Database.ExecuteSqlInterpolatedAsync($"INSERT INTO \"UserReactionPacks\" (\"UserId\", \"PackId\") VALUES ({userId}, {packId}) ON CONFLICT (\"UserId\", \"PackId\") DO NOTHING");
|
||||
else
|
||||
await context.UserReactionPacks.Where(p => p.UserId == userId && p.PackId == packId).ExecuteDeleteAsync();
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionPack, Error>> CreateAsync(Guid actorId, string name, string description)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionPack>(Denied());
|
||||
if (!ValidText(name, description)) return Result.Failure<ReactionPack>(Invalid("Invalid name or description."));
|
||||
var pack = new ReactionPack
|
||||
{
|
||||
Id = Guid.NewGuid(), Name = name.Trim(), Description = description.Trim(),
|
||||
ShareCode = Guid.NewGuid().ToString("N"), CreatedByUserId = actorId, CreatedAt = clock.Now
|
||||
};
|
||||
context.ReactionPacks.Add(pack);
|
||||
await context.SaveChangesAsync();
|
||||
return pack;
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionPack, Error>> UpdateAsync(Guid actorId, Guid packId, string name, string description, bool enabled)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionPack>(Denied());
|
||||
if (!ValidText(name, description)) return Result.Failure<ReactionPack>(Invalid("Invalid name or description."));
|
||||
var pack = await context.ReactionPacks.FirstOrDefaultAsync(p => p.Id == packId);
|
||||
if (pack is null) return Result.Failure<ReactionPack>(Missing());
|
||||
if (pack.IsDefault) return Result.Failure<ReactionPack>(Invalid("The default pack cannot be modified."));
|
||||
pack.Name = name.Trim(); pack.Description = description.Trim(); pack.IsEnabled = enabled;
|
||||
await context.SaveChangesAsync();
|
||||
return pack;
|
||||
}
|
||||
|
||||
public async Task<Result<Unit, Error>> DisableAsync(Guid actorId, Guid packId)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure(Denied());
|
||||
var pack = await context.ReactionPacks.FirstOrDefaultAsync(p => p.Id == packId);
|
||||
if (pack is null) return Result.Failure(Missing());
|
||||
if (pack.IsDefault) return Result.Failure(Invalid("The default pack cannot be disabled."));
|
||||
pack.IsEnabled = false;
|
||||
await context.SaveChangesAsync();
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionItem, Error>> AddEmojiAsync(Guid actorId, Guid packId, string name, string emoji)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(emoji) || emoji.Length > 64 || StringInfo.ParseCombiningCharacters(emoji).Length != 1 ||
|
||||
!emoji.EnumerateRunes().Any(r => System.Text.Rune.GetUnicodeCategory(r) == UnicodeCategory.OtherSymbol))
|
||||
return Result.Failure<ReactionItem>(Invalid("Provide a single emoji grapheme."));
|
||||
return await AddAsync(actorId, packId, name, emoji, null);
|
||||
}
|
||||
|
||||
public async Task<Result<ReactionItem, Error>> AddMediaAsync(Guid actorId, Guid packId, string name, byte[] data,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionItem>(Denied());
|
||||
if (!await context.ReactionPacks.AnyAsync(p => p.Id == packId && !p.IsDefault && p.IsEnabled))
|
||||
return Result.Failure<ReactionItem>(Invalid("An active custom pack is required."));
|
||||
var processed = await processor.ProcessAsync(data, cancellationToken);
|
||||
if (processed.IsFailure) return Result.Failure<ReactionItem>(processed.Error);
|
||||
return await AddAsync(actorId, packId, name, null, processed.Value);
|
||||
}
|
||||
|
||||
private async Task<Result<ReactionItem, Error>> AddAsync(Guid actorId, Guid packId, string name,
|
||||
string? emoji, ProcessedReactionMedia? media)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure<ReactionItem>(Denied());
|
||||
if (!ValidText(name, "")) return Result.Failure<ReactionItem>(Invalid("Invalid reaction name."));
|
||||
var operationId = Guid.NewGuid();
|
||||
return await context.Database.CreateExecutionStrategy().ExecuteAsync(async () =>
|
||||
{
|
||||
var completed = await context.ReactionItems.AsNoTracking().FirstOrDefaultAsync(r => r.Id == operationId);
|
||||
if (completed is not null) return Result.Success(completed);
|
||||
await using var transaction = await context.Database.BeginTransactionAsync();
|
||||
// Lock the pack to serialize the item limit and concurrent disabling.
|
||||
var locked = await context.ReactionPacks.Where(p => p.Id == packId && !p.IsDefault && p.IsEnabled)
|
||||
.ExecuteUpdateAsync(s => s.SetProperty(p => p.Name, p => p.Name));
|
||||
if (locked == 0) return Result.Failure<ReactionItem>(Invalid("An active custom pack is required."));
|
||||
if (await context.ReactionItems.CountAsync(r => r.PackId == packId) >= 100)
|
||||
return Result.Failure<ReactionItem>(Invalid("A pack can contain at most 100 reactions, including disabled entries."));
|
||||
|
||||
var item = new ReactionItem
|
||||
{
|
||||
Id = operationId, PackId = packId, Name = name.Trim(), Emoji = emoji,
|
||||
Kind = media?.Kind ?? ReactionKind.Emoji, CreatedAt = clock.Now
|
||||
};
|
||||
item.Code = $":reaction_{item.Id:N}:";
|
||||
string? path = null;
|
||||
try
|
||||
{
|
||||
if (media is not null)
|
||||
{
|
||||
path = await storage.SaveAsync(media.Data, item.Id.ToString("N") + media.Extension);
|
||||
var file = new MediaFile
|
||||
{
|
||||
Id = Guid.NewGuid(), UploaderId = actorId, Url = path, MineType = media.MimeType,
|
||||
DateCreated = clock.Now, OwnerType = MediaOwnerType.Reaction, OwnerId = item.Id,
|
||||
MediaType = MediaType.Image
|
||||
};
|
||||
context.MediaFiles.Add(file);
|
||||
item.MediaFileId = file.Id; item.Width = media.Width; item.Height = media.Height;
|
||||
item.SizeBytes = media.Data.Length; item.DurationMilliseconds = media.DurationMilliseconds;
|
||||
}
|
||||
context.ReactionItems.Add(item);
|
||||
await context.SaveChangesAsync();
|
||||
}
|
||||
catch
|
||||
{
|
||||
if (path is not null)
|
||||
{
|
||||
try { await storage.RemoveAsync(path); }
|
||||
catch (Exception ex) { logger.LogError(ex, "Cannot remove failed reaction upload {ReactionId}", item.Id); }
|
||||
}
|
||||
// Clear failed tracked additions before an execution-strategy retry.
|
||||
context.ChangeTracker.Clear();
|
||||
throw;
|
||||
}
|
||||
// Do not delete the file on an ambiguous Commit outcome. The stable operation ID
|
||||
// above detects an already committed item when the execution strategy retries.
|
||||
try { await transaction.CommitAsync(); }
|
||||
catch { context.ChangeTracker.Clear(); throw; }
|
||||
return Result.Success(item);
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<Result<Unit, Error>> DisableReactionAsync(Guid actorId, Guid packId, Guid reactionId)
|
||||
{
|
||||
if (!await IsAdminAsync(actorId)) return Result.Failure(Denied());
|
||||
var item = await context.ReactionItems.Include(r => r.Pack)
|
||||
.FirstOrDefaultAsync(r => r.Id == reactionId && r.PackId == packId);
|
||||
if (item is null) return Result.Failure(Missing());
|
||||
if (item.Pack.IsDefault) return Result.Failure(Invalid("Default reactions cannot be disabled."));
|
||||
item.IsEnabled = false;
|
||||
await context.SaveChangesAsync();
|
||||
return Result.Success();
|
||||
}
|
||||
|
||||
private Task<bool> IsAdminAsync(Guid actorId) => context.Users.AnyAsync(u => u.Id == actorId && u.Invite != null && u.Invite.IsAdmin);
|
||||
private static bool ValidText(string name, string description) => !string.IsNullOrWhiteSpace(name) &&
|
||||
name.Trim().Length <= 100 && description is not null && description.Length <= 500;
|
||||
private static Error Invalid(string message) => Error.Validation("ReactionPack.Invalid", message);
|
||||
private static Error Missing() => Error.NotFound("ReactionPack.NotFound", "Reaction pack or item not found.");
|
||||
private static Error Denied() => Error.Forbidden("ReactionPack.AdminRequired", "Administrator permission is required.");
|
||||
}
|
||||
@@ -30,7 +30,7 @@ public class SessionKeysReader : ISessionKeysReader
|
||||
return await _context.UserCryptoSessions
|
||||
.AsNoTracking()
|
||||
.Include(c => c.OneTimePreKeys)
|
||||
.Include(c => c.UserSession)
|
||||
.Include(c => c.SignedPreKey)
|
||||
.Where(c => c.UserSession.UserId == userId
|
||||
&& !c.UserSession.IsRevoked
|
||||
&& c.UserSession.ExpiresAt > now)
|
||||
@@ -44,7 +44,7 @@ public class SessionKeysReader : ISessionKeysReader
|
||||
return await _context.OneTimePreKeys
|
||||
.AsNoTracking()
|
||||
.Include(f => f.UserCryptoSession)
|
||||
.CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId);
|
||||
.CountAsync(f => f.UserCryptoSession.UserSessionId == sessionId && !f.IsUsed);
|
||||
}
|
||||
|
||||
public async Task<UserCryptoSession?> GetKeysBySessionIdAsync(Guid sessionId)
|
||||
@@ -57,4 +57,4 @@ public class SessionKeysReader : ISessionKeysReader
|
||||
.Include(c => c.UserSession)
|
||||
.FirstOrDefaultAsync(c => c.UserSessionId == sessionId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,21 +45,10 @@ public class UserSessionOpener : IUserSessionOpener
|
||||
return Result.Failure<RefreshResult>(result.Error);
|
||||
}
|
||||
|
||||
var sessions = result.Value;
|
||||
var existingSession = sessions.FirstOrDefault(s => s.DeviceInfo == deviceInfo);
|
||||
|
||||
try
|
||||
{
|
||||
RefreshResult refreshResult;
|
||||
|
||||
if (existingSession is not null)
|
||||
{
|
||||
refreshResult = await UpdateExistingSessionAsync(user, deviceInfo, existingSession);
|
||||
}
|
||||
else
|
||||
{
|
||||
refreshResult = await CreateNewSessionAsync(user, deviceInfo);
|
||||
}
|
||||
// DeviceInfo is a display label, not a device identity. Never reuse another sid.
|
||||
var refreshResult = await CreateNewSessionAsync(user, deviceInfo ?? string.Empty);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
@@ -120,4 +109,4 @@ public class UserSessionOpener : IUserSessionOpener
|
||||
var refreshToken = await _jwtService.GenerateRefreshTokenAsync(user);
|
||||
return (accessToken, refreshToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,11 +61,15 @@ public class UserSessionRefresher : IUserSessionRefresher
|
||||
var newRefreshToken = await _jwtService.GenerateRefreshTokenAsync(session.User);
|
||||
var newRefreshTokenHash = _jwtTokenHasher.HashToken(newRefreshToken);
|
||||
|
||||
session.RefreshTokenHash = newRefreshTokenHash;
|
||||
session.CreatedAt = DateTime.UtcNow;
|
||||
session.ExpiresAt = DateTime.UtcNow.AddDays(_options.RefreshTokenLifetimeDays);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
var now = DateTime.UtcNow;
|
||||
var updated = await _context.UserSessions.Where(s => s.Id == session.Id &&
|
||||
s.RefreshTokenHash == hashedToken && !s.IsRevoked && s.ExpiresAt > now)
|
||||
.ExecuteUpdateAsync(setters => setters
|
||||
.SetProperty(s => s.RefreshTokenHash, newRefreshTokenHash)
|
||||
.SetProperty(s => s.ExpiresAt, now.AddDays(_options.RefreshTokenLifetimeDays)));
|
||||
if (updated == 0)
|
||||
return Result.Failure<RefreshResult>(Error.Unauthorized("Auth.InvalidToken",
|
||||
"Refresh token was already used or the session was revoked."));
|
||||
|
||||
_logger.LogInformation("Successfully refreshed session {SessionId} for user {UserId}", session.Id, session.UserId);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user