IM/backend/IM_API/Services/ConversationService.cs

92 lines
3.8 KiB
C#

using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using Microsoft.EntityFrameworkCore;
namespace IM_API.Services
{
public class ConversationService : IConversationService
{
private readonly ImContext _context;
public ConversationService(ImContext context)
{
_context = context;
}
#region
public async Task<bool> ClearConversationsAsync(int userId)
{
await _context.Conversations.Where(x => x.UserId == userId).ExecuteDeleteAsync();
return true;
}
#endregion
#region
public async Task<List<ConversationDto>> GetConversationsAsync(int userId)
{
var privateQuery = from c in _context.Conversations
join f in _context.Friends on new { c.UserId, c.TargetId}
equals new { UserId = f.UserId, TargetId = f.FriendId}
where c.UserId == userId && c.ChatType == (int)ChatType.PRIVATE
select new ConversationDto
{
Id = c.Id,
UserId = c.UserId,
TargetId = c.TargetId,
LastReadMessageId = c.LastReadMessageId,
LastReadMessage = c.LastReadMessage,
UnreadCount = c.UnreadCount,
ChatType = c.ChatType,
LastMessage = c.LastMessage,
TargetAvatar = f.Avatar,
TargetName = f.RemarkName,
DateTime = c.LastMessageTime
};
var groupQuery = from c in _context.Conversations
join g in _context.Groups on c.TargetId equals g.Id
where c.UserId == userId && c.ChatType == (int)ChatType.GROUP
select new ConversationDto
{
Id = c.Id,
UserId = c.UserId,
TargetId = c.TargetId,
LastReadMessageId = c.LastReadMessageId,
LastReadMessage = c.LastReadMessage,
UnreadCount = c.UnreadCount,
ChatType = c.ChatType,
LastMessage = c.LastMessage,
TargetAvatar = g.Avatar,
TargetName = g.Name,
DateTime = c.LastMessageTime
};
return await privateQuery
.Concat(groupQuery)
.OrderByDescending(x => x.DateTime)
.ToListAsync();
}
#endregion
#region
public async Task<bool> DeleteConversationAsync(int conversationId)
{
var conversation = await _context.Conversations.FirstOrDefaultAsync(x => x.Id == conversationId);
if (conversation == null) throw new BaseException(CodeDefine.CONVERSATION_NOT_FOUND);
_context.Conversations.Remove(conversation);
await _context.SaveChangesAsync();
return true;
}
#endregion
public async Task<List<string>> GetUserAllStreamKeyAsync(int userId)
{
return await _context.Conversations.Where(x => x.UserId == userId)
.Select(x => x.StreamKey)
.Distinct()
.ToListAsync();
}
}
}