feat: decrement message counts on bulk message deletions

This commit is contained in:
rladenson 2024-11-25 02:09:40 -07:00
parent 71dd59b57d
commit 21a63a43cc
3 changed files with 30 additions and 6 deletions

View file

@ -63,6 +63,27 @@ public class MessageDeleted: IEventHandler<MessageDeleteEvent>, IEventHandler<Me
_logger.Information("Bulk deleting {Count} messages in channel {Channel}",
evt.Ids.Length, evt.ChannelId);
await _repo.DeleteMessagesBulk(evt.Ids);
// get all the messages from the database
var messages = await _repo.GetMessagesBulk(evt.Ids);
// make a dictionary of every member id associated with a message and how many messages it's associated with
var memberMessageCounts = new Dictionary<MemberId, int>();
foreach (PKMessage msg in messages)
{
if (!msg.Member.HasValue) continue;
if (memberMessageCounts.ContainsKey(msg.Member.Value))
memberMessageCounts[msg.Member.Value] = memberMessageCounts[msg.Member.Value] + 1;
else
memberMessageCounts[msg.Member.Value] = 1;
}
// go through each member id in dictionary and decrement that member's message count by appropriate amount
foreach (MemberId member in memberMessageCounts.Keys)
{
await _repo.UpdateMemberForDeletedMessage(member, (await _repo.GetMember(member)).MessageCount, memberMessageCounts[member]);
}
}
_lastMessage.HandleMessageDeletion(evt.ChannelId, evt.Ids.ToList());

View file

@ -111,21 +111,21 @@ public partial class ModelRepository
await _db.ExecuteQuery(query);
}
public async Task UpdateMemberForDeletedMessage(MemberId id, int msgCount)
public async Task UpdateMemberForDeletedMessage(MemberId id, int msgCount, int numberToDecrement = 1)
{
if (msgCount <= 0) return;
var query = new Query("members")
.When(msgCount > 1,
// when there are plenty of messages
.When(msgCount > numberToDecrement,
// when message count is higher than number we're removing
q => q.AsUpdate(new
{
message_count = new UnsafeLiteral("message_count - 1")
message_count = new UnsafeLiteral($"message_count - {numberToDecrement}")
}),
// when this is the only message (if the db for some reason thinks there are no messages we already returned)
// when this is the only/last message(s) (if the db for some reason thinks there are no messages we already returned)
q => q.AsUpdate(new
{
message_count = new UnsafeLiteral("message_count - 1"),
message_count = 0,
last_message_timestamp = new UnsafeLiteral("null")
})
)

View file

@ -26,6 +26,9 @@ public partial class ModelRepository
public Task<PKMessage?> GetMessage(ulong id)
=> _db.QueryFirst<PKMessage?>(new Query("messages").Where("mid", id), messages: true);
public Task<IEnumerable<PKMessage>> GetMessagesBulk(IReadOnlyCollection<ulong> ids)
=> _db.Query<PKMessage>(new Query("messages").WhereIn("mid", ids.Select(id => (long)id).ToArray()));
public async Task<FullMessage?> GetFullMessage(ulong id)
{
var rawMessage = await GetMessage(id);