64 lines
2.4 KiB
C#
64 lines
2.4 KiB
C#
using AutoMapper;
|
|
using IM_API.Application.Interfaces;
|
|
using IM_API.Domain.Events;
|
|
using IM_API.Dtos;
|
|
using IM_API.Exceptions;
|
|
using IM_API.Interface.Services;
|
|
using IM_API.Models;
|
|
using IM_API.Services;
|
|
using IM_API.Tools;
|
|
using MassTransit;
|
|
using Microsoft.EntityFrameworkCore;
|
|
using Newtonsoft.Json;
|
|
|
|
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
|
|
{
|
|
public class ConversationEventHandler : IConsumer<MessageCreatedEvent>
|
|
{
|
|
private readonly IConversationService _conversationService;
|
|
private readonly ILogger<ConversationEventHandler> _logger;
|
|
private readonly ImContext _context;
|
|
private readonly IMapper _mapper;
|
|
public ConversationEventHandler(
|
|
IConversationService conversationService,
|
|
ILogger<ConversationEventHandler> logger,
|
|
ImContext imContext,
|
|
IMapper mapper
|
|
)
|
|
{
|
|
_conversationService = conversationService;
|
|
_logger = logger;
|
|
_context = imContext;
|
|
_mapper = mapper;
|
|
}
|
|
|
|
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
|
|
{
|
|
var @event = context.Message;
|
|
|
|
if (@event.ChatType == ChatType.PRIVATE)
|
|
{
|
|
Conversation? userAConversation = await _context.Conversations.FirstOrDefaultAsync(
|
|
x => x.UserId == @event.MsgSenderId && x.TargetId == @event.MsgRecipientId
|
|
);
|
|
Conversation? userBConversation = await _context.Conversations.FirstOrDefaultAsync(
|
|
x => x.UserId == @event.MsgRecipientId && x.TargetId == @event.MsgSenderId
|
|
);
|
|
if (userAConversation is null || userBConversation is null)
|
|
{
|
|
_logger.LogError("消息事件更新会话信息失败:{@event}", @event);
|
|
}
|
|
userAConversation.LastMessage = @event.MessageContent;
|
|
userAConversation.LastReadMessageId = @event.MessageId;
|
|
userAConversation.LastMessageTime = @event.MessageCreated;
|
|
userBConversation.LastMessage = @event.MessageContent;
|
|
userBConversation.UnreadCount += 1;
|
|
userBConversation.LastMessageTime = @event.MessageCreated;
|
|
_context.UpdateRange(userAConversation, userBConversation);
|
|
await _context.SaveChangesAsync();
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|