92 lines
3.8 KiB
C#
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();
|
|
}
|
|
}
|
|
} |