示例#1
0
        public async Task <ServiceResult <object> > Notify(int userId, string message, NotificationTypeEnum notificationType)
        {
            var user = Context.Users.FirstOrDefault(u => u.Id == userId);

            if (user == null)
            {
                return(NotFound("用户不存在"));
            }
            if (ConnectionService.IsOnline(userId))
            {
                await HubContext.Clients.Client(ConnectionService.GetConnectionId(userId)).SendAsync("OnNotify", (int)notificationType, message);

                return(Success("在线通知成功"));
            }
            else
            {
                var notification = new Notification
                {
                    Content          = message,
                    UserId           = userId,
                    NotificationType = notificationType
                };
                Context.Notifications.Add(notification);
                await Context.SaveChangesAsync();

                return(Success("离线通知保存成功"));
            }
        }
        public async Task <string> JoinAsUser(int userId)
        {
            if (!XueLeMeContext.Users.Where(u => u.Id == userId).Any())
            {
                return("账号不存在");
            }
            var groups = XueLeMeContext.GroupMemberships.Where(m => m.UserId == userId).Select(m => m.ChatGroupId).ToList();

            if (ConnectionService.IsOnline(userId))
            {
                string connectionId = ConnectionService.GetConnectionId(userId);
                if (connectionId != Context.ConnectionId)
                {
                    Logger.LogInformation("Force Out connection {0}, uid = {1}", Context.ConnectionId, userId);
                    await Clients.Client(connectionId).SendAsync("OnNotify", (int)NotificationTypeEnum.ForceOut, "您的账号在别的设备被登录,可能是密码泄露,请重新登陆!");

                    ConnectionService.Detach(connectionId);
                }
            }
            ConnectionService.Attach(Context.ConnectionId, userId);
            foreach (var group in groups)
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, group.ToString());
            }
            return("成功与服务器建立连接");
        }