/// <summary> /// 软删除连接信息 /// </summary> /// <param name="roomId">房间ID</param> /// <param name="userId">用户ID</param> /// <returns>表示软删除连接的任务</returns> public async Task <string> PerformSoftDeleteOfConnectionAsync(int roomId, int userId) { var connection = await _dbContext.Connection.FindAsync(roomId, userId); // 如果用户打开了两个窗口,这里会出问题 if (connection == null) { return(string.Empty); } connection.IsDeleted = true; _dbContext.Update(connection); await _dbContext.SaveChangesAsync(); // 返回空字符串避免前台出错 return(string.Empty); }
/// <summary> /// 加入房间 /// </summary> /// <param name="roomHashid">房间哈希ID</param> /// <returns>表示加入房间的任务,返回房间名和加入该房间的时间</returns> public async Task <ChatRoomInitialDisplayDto> JoinRoomAsync(string roomHashid) { var roomId = HashidsHelper.Decode(roomHashid); var userId = HashidsHelper.Decode(Context.User.FindFirst("uid").Value); var username = HttpUtility.UrlDecode(Context.User.Identity.Name); // 因为用户可能会尝试用一个账号同时登陆两个房间 // 这里查询条件不加上房间ID,前一个房间内的用户会被提示在别处登录 var connection = await _dbContext.Connection .FirstOrDefaultAsync(x => x.UserId == userId); string msgId = null; string connIdToBeRemoved = null; if (connection == null) { // 第一次进入该房间 msgId = "I001"; _dbContext.Add(new Connection { RoomId = roomId, UserId = userId, Username = username, ConnectionId = Context.ConnectionId }); } else { // 如果用户同时打开两个窗口 if (connection.IsOnline.Value) { connIdToBeRemoved = connection.ConnectionId; } // 重连的情况下 msgId = "I003"; connection.IsOnline = true; connection.ConnectionId = Context.ConnectionId; // 只保留一条记录 _dbContext.Update(connection); } await _dbContext.SaveChangesAsync(); // 将用户添加到分组 await Groups.AddAsync(Context.ConnectionId, roomHashid); // 只加载加入房间前的消息,避免消息重复显示 long unixTimeMilliseconds = new DateTimeOffset(DateTime.Now).ToUnixTimeMilliseconds(); // 显示欢迎用户加入房间的消息 await Clients.Group(roomHashid).InvokeAsync( "receiveSystemMessage", _msg.GetMessage(msgId, username)); if (!string.IsNullOrEmpty(connIdToBeRemoved)) { // 前一个窗口显示消息,告知账号已经在其他地方登陆 await Clients.Client(connIdToBeRemoved).InvokeAsync("onDuplicateLogin"); await Groups.RemoveAsync(connIdToBeRemoved, roomHashid); } // 显示用户列表 await RefreshMemberListAsync(roomHashid, roomId); var room = await _dbContext.ChatRoom .Where(r => r.Id == roomId) .Select(r => new { r.Name, r.OwnerId }) .FirstOrDefaultAsync(); return(new ChatRoomInitialDisplayDto { OwnerId = HashidsHelper.Encode(room.OwnerId), RoomName = room.Name, EntryTime = unixTimeMilliseconds }); }