From 67992af5701dc08fdfb5d448a5cb066e26865567 Mon Sep 17 00:00:00 2001 From: "YUN-PC5\\user" Date: Fri, 20 Oct 2023 17:12:58 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=E5=88=A0=E9=99=A4=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E9=80=9A=E7=9F=A5=E5=90=8E=EF=BC=8C=E4=BC=9A=E5=90=91?= =?UTF-8?q?=E5=BD=93=E5=89=8D=E7=99=BB=E5=BD=95=E7=9A=84=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E7=BB=84=E5=8F=91=E9=80=81=E9=80=9A=E7=9F=A5=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E9=80=9A=E7=9F=A5=E5=90=8E=EF=BC=8C=E5=A6=82=E6=9E=9C?= =?UTF-8?q?=E8=AF=A5=E9=80=9A=E7=9F=A5=E4=B9=8B=E5=89=8D=E8=A2=AB=E7=94=A8?= =?UTF-8?q?=E6=88=B7=E5=B7=B2=E8=AF=BB=E8=BF=87=EF=BC=8C=E5=88=99=E5=B0=86?= =?UTF-8?q?=E5=85=B6=E9=87=8D=E6=96=B0=E7=BD=AE=E4=BA=8E=E6=9C=AA=E8=AF=BB?= =?UTF-8?q?=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Infrastructure/ZR.Infrastructure.csproj | 1 + .../Controllers/System/SysNoticeController.cs | 78 +++++-- .../System/monitor/SysUserOnlineController.cs | 4 +- ZR.ServiceCore/Model/SysNotice.cs | 33 ++- ZR.ServiceCore/Model/SysNoticeLog.cs | 11 + ZR.ServiceCore/Signalr/MessageHub.cs | 208 +++++++++++++----- 6 files changed, 265 insertions(+), 70 deletions(-) diff --git a/Infrastructure/ZR.Infrastructure.csproj b/Infrastructure/ZR.Infrastructure.csproj index 869ca58..af69019 100644 --- a/Infrastructure/ZR.Infrastructure.csproj +++ b/Infrastructure/ZR.Infrastructure.csproj @@ -14,6 +14,7 @@ + diff --git a/ZR.Admin.WebApi/Controllers/System/SysNoticeController.cs b/ZR.Admin.WebApi/Controllers/System/SysNoticeController.cs index fe71832..5e7961b 100644 --- a/ZR.Admin.WebApi/Controllers/System/SysNoticeController.cs +++ b/ZR.Admin.WebApi/Controllers/System/SysNoticeController.cs @@ -1,12 +1,14 @@ -using Microsoft.AspNetCore.Mvc; +using System.Net; +using System.Net.Sockets; using Microsoft.AspNetCore.SignalR; +using Microsoft.AspNetCore.SignalR.Client; using SqlSugar; using ZR.Admin.WebApi.Filters; using ZR.Model; -using ZR.Model.System; using ZR.Service.System.IService; using ZR.ServiceCore.Model; using ZR.ServiceCore.Model.Dto; +using ZR.ServiceCore.Services.IService; using ZR.ServiceCore.Signalr; namespace ZR.Admin.WebApi.Controllers.System @@ -24,11 +26,14 @@ namespace ZR.Admin.WebApi.Controllers.System /// private readonly ISysNoticeService _sysNoticeService; private readonly IHubContext _hubContext; - - public SysNoticeController(ISysNoticeService sysNoticeService, IHubContext hubContext) + private readonly ISysNoticeLogService _sysNoticeLogService; + private readonly IWebHostEnvironment _webHostEnvironment; + public SysNoticeController(ISysNoticeService sysNoticeService, IHubContext hubContext, ISysNoticeLogService sysNoticeLogService, IWebHostEnvironment webHostEnvironment) { _sysNoticeService = sysNoticeService; _hubContext = hubContext; + _sysNoticeLogService = sysNoticeLogService; + _webHostEnvironment = webHostEnvironment; } /// @@ -77,7 +82,7 @@ namespace ZR.Admin.WebApi.Controllers.System [HttpPost] [ActionPermissionFilter(Permission = "system:notice:add")] [Log(Title = "发布通告", BusinessType = BusinessType.INSERT)] - public IActionResult AddSysNotice([FromBody] SysNoticeDto parm) + public async Task AddSysNotice([FromBody] SysNoticeDto parm) { var modal = parm.Adapt().ToCreate(HttpContext); modal.Create_by = HttpContext.GetUId(); @@ -95,8 +100,23 @@ namespace ZR.Admin.WebApi.Controllers.System // it.Create_time // }); - var result = _sysNoticeService.Insertable(modal).ExecuteReturnSnowflakeId(); - + var result = await _sysNoticeService + .Insertable(modal) + .ExecuteReturnSnowflakeIdAsync(); + var scheme = HttpContext.Request.Scheme + "://"; + var serverIP = HttpContext.Request.Host.Value; + if (_webHostEnvironment.IsProduction()) + { + var host = await Dns.GetHostEntryAsync(Dns.GetHostName()); + var ip = host.AddressList + .FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork); + serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP + } + var url = scheme + serverIP; + var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build(); + await hubConnection.StartAsync(); + await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", result, true); + await hubConnection.StopAsync(); return SUCCESS(result); } @@ -107,13 +127,13 @@ namespace ZR.Admin.WebApi.Controllers.System [HttpPut] [ActionPermissionFilter(Permission = "system:notice:update")] [Log(Title = "修改公告", BusinessType = BusinessType.UPDATE)] - public IActionResult UpdateSysNotice([FromBody] SysNoticeDto parm) + public async Task UpdateSysNotice([FromBody] SysNoticeDto parm) { var config = new TypeAdapterConfig(); config.ForType() .Map(dest => dest.NoticeId, src => src.NoticeId.ParseToLong()); var model = parm.Adapt(config).ToUpdate(HttpContext); - + var nowDate = DateTime.Now; var response = _sysNoticeService.Update(w => w.NoticeId == model.NoticeId, it => new SysNotice() { NoticeTitle = model.NoticeTitle, @@ -123,9 +143,24 @@ namespace ZR.Admin.WebApi.Controllers.System Remark = model.Remark, Update_by = HttpContext.GetUId(), Update_name = HttpContext.GetNickName(), - Update_time = DateTime.Now + Update_time = nowDate, + Create_time = nowDate }); - + + var scheme = HttpContext.Request.Scheme + "://"; + var serverIP = HttpContext.Request.Host.Value; + if (_webHostEnvironment.IsProduction()) + { + var host = await Dns.GetHostEntryAsync(Dns.GetHostName()); + var ip = host.AddressList + .FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork); + serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP + } + var url = scheme + serverIP; + var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build(); + await hubConnection.StartAsync(); + await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", model.NoticeId, true); + await hubConnection.StopAsync(); return SUCCESS(response); } /// @@ -156,13 +191,30 @@ namespace ZR.Admin.WebApi.Controllers.System [HttpDelete("{ids}")] [ActionPermissionFilter(Permission = "system:notice:delete")] [Log(Title = "通知公告", BusinessType = BusinessType.DELETE)] - public IActionResult DeleteSysNotice(string ids) + public async Task DeleteSysNotice(string ids) { var idsArr = Tools.SpitLongArrary(ids); if (idsArr.Length <= 0) { return ToResponse(ApiResult.Error($"删除失败Id 不能为空")); } var response = _sysNoticeService.Delete(idsArr); - + await _sysNoticeLogService.Deleteable() + .Where(it => idsArr.Contains(it.NoticeId)) + .ExecuteCommandAsync(); + + var scheme = HttpContext.Request.Scheme + "://"; + var serverIP = HttpContext.Request.Host.Value; + if (_webHostEnvironment.IsProduction()) + { + var host = await Dns.GetHostEntryAsync(Dns.GetHostName()); + var ip = host.AddressList + .FirstOrDefault(it => it.AddressFamily == AddressFamily.InterNetwork); + serverIP = ip + ":" + Request.HttpContext.Connection.LocalPort;//获取服务器IP + } + var url = scheme + serverIP; + var hubConnection = new HubConnectionBuilder().WithUrl(url + "/msghub").Build(); + await hubConnection.StartAsync(); + await hubConnection.InvokeAsync("SendNoticeToOnlineUsers", null, false); + await hubConnection.StopAsync(); return SUCCESS(response); } } diff --git a/ZR.Admin.WebApi/Controllers/System/monitor/SysUserOnlineController.cs b/ZR.Admin.WebApi/Controllers/System/monitor/SysUserOnlineController.cs index e0d785d..5b7e310 100644 --- a/ZR.Admin.WebApi/Controllers/System/monitor/SysUserOnlineController.cs +++ b/ZR.Admin.WebApi/Controllers/System/monitor/SysUserOnlineController.cs @@ -30,11 +30,11 @@ namespace ZR.Admin.WebApi.Controllers.monitor [HttpGet("list")] public IActionResult Index([FromQuery] PagerInfo parm) { - var result = MessageHub.onlineClients + var result = MessageHub.OnlineClients .OrderByDescending(f => f.LoginTime) .Skip(parm.PageNum - 1).Take(parm.PageSize); - return SUCCESS(new { result, totalNum = MessageHub.onlineClients.Count }); + return SUCCESS(new { result, totalNum = MessageHub.OnlineClients.Count }); } /// diff --git a/ZR.ServiceCore/Model/SysNotice.cs b/ZR.ServiceCore/Model/SysNotice.cs index 08476b4..bb692bb 100644 --- a/ZR.ServiceCore/Model/SysNotice.cs +++ b/ZR.ServiceCore/Model/SysNotice.cs @@ -10,7 +10,7 @@ namespace ZR.ServiceCore.Model /// [SugarTable("sys_notice", "通知公告表")] [Tenant(0)] - public class SysNotice : SysBase + public class SysNotice { /// /// 公告ID @@ -38,5 +38,36 @@ namespace ZR.ServiceCore.Model /// [SugarColumn(DefaultValue = "0", ExtendedAttribute = ProteryConstant.NOTNULL)] public int Status { get; set; } + + /// + /// 备注 + /// + public string Remark { get; set; } + + [SugarColumn(IsOnlyIgnoreUpdate = true)] + [JsonProperty(propertyName: "CreateBy")] + public long Create_by { get; set; } + + [SugarColumn(IsOnlyIgnoreUpdate = true)] + [JsonProperty(propertyName: "CreateName")] + public string Create_name { get; set; } + + [JsonProperty(propertyName: "CreateTime")] + public DateTime Create_time { get; set; } = DateTime.Now; + + [JsonIgnore] + [JsonProperty(propertyName: "UpdateBy")] + [SugarColumn(IsOnlyIgnoreInsert = true)] + public long Update_by { get; set; } + + [JsonIgnore] + [JsonProperty(propertyName: "UpdateName")] + [SugarColumn(IsOnlyIgnoreInsert = true)] + public string Update_name { get; set; } + + //[JsonIgnore] + [SugarColumn(IsOnlyIgnoreInsert = true)] + [JsonProperty(propertyName: "UpdateTime")] + public DateTime? Update_time { get; set; } } } \ No newline at end of file diff --git a/ZR.ServiceCore/Model/SysNoticeLog.cs b/ZR.ServiceCore/Model/SysNoticeLog.cs index e4a1ea1..fc2a0e6 100644 --- a/ZR.ServiceCore/Model/SysNoticeLog.cs +++ b/ZR.ServiceCore/Model/SysNoticeLog.cs @@ -10,4 +10,15 @@ public class SysNoticeLog public long UserId { get; set; } public string Status { get; set; } + + public SysNoticeLog() + { + } + + public SysNoticeLog(long noticeId, long userId, string status) + { + NoticeId = noticeId; + UserId = userId; + Status = status; + } } \ No newline at end of file diff --git a/ZR.ServiceCore/Signalr/MessageHub.cs b/ZR.ServiceCore/Signalr/MessageHub.cs index a491aad..15b3de9 100644 --- a/ZR.ServiceCore/Signalr/MessageHub.cs +++ b/ZR.ServiceCore/Signalr/MessageHub.cs @@ -20,24 +20,29 @@ namespace ZR.ServiceCore.Signalr public class MessageHub : Hub { //创建用户集合,用于存储所有链接的用户数据 - public static readonly List onlineClients = new(); - public static List users = new(); + public static readonly List OnlineClients = new(); + public static List Users = new(); //private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); - private readonly ISysNoticeService SysNoticeService; + private readonly ISysNoticeService _sysNoticeService; private readonly ISysNoticeLogService _sysNoticeLogService; public MessageHub(ISysNoticeService noticeService, ISysNoticeLogService sysNoticeLogService) { - SysNoticeService = noticeService; + _sysNoticeService = noticeService; _sysNoticeLogService = sysNoticeLogService; } private ApiResult SendNotice() { - var result = SysNoticeService.GetSysNotices(); + var result = _sysNoticeService.GetSysNotices(); return new ApiResult(200, "success", result); } + + private ApiResult SendNotice(object notice) + { + return new ApiResult(200, "success", notice); + } #region 客户端连接 @@ -45,7 +50,7 @@ namespace ZR.ServiceCore.Signalr /// 客户端连接的时候调用 /// /// - public override Task OnConnectedAsync() + public override async Task OnConnectedAsync() { var context = App.HttpContext; var name = HttpContextExtension.GetName(context); @@ -60,8 +65,8 @@ namespace ZR.ServiceCore.Signalr long userid = HttpContextExtension.GetUId(context); string uuid = device + userid + ip; - var user = onlineClients.Any(u => u.ConnnectionId == Context.ConnectionId); - var user2 = onlineClients.Any(u => u.Uuid == uuid); + var user = OnlineClients.Any(u => u.ConnnectionId == Context.ConnectionId); + var user2 = OnlineClients.Any(u => u.Uuid == uuid); //判断用户是否存在,否则添加集合!user2 && !user && if (!user2 && !user && Context.User.Identity.IsAuthenticated) @@ -73,47 +78,43 @@ namespace ZR.ServiceCore.Signalr Platform = from, ClientId = clientId ?? Context.ConnectionId }; - onlineClients.Add(onlineUser); - Log.WriteLine(msg: $"{name},{Context.ConnectionId}连接服务端success,当前已连接{onlineClients.Count}个"); + OnlineClients.Add(onlineUser); + Log.WriteLine(msg: $"{name},{Context.ConnectionId}连接服务端success,当前已连接{OnlineClients.Count}个"); //Clients.All.SendAsync("welcome", $"欢迎您:{name},当前时间:{DateTime.Now}"); var noticeRes = (List) SendNotice()[ApiResult.DATA_TAG]; - var notifications = _sysNoticeLogService.Queryable() + // 获取当前在线用户的通知日志记录id + var unreadAndReadNoticeIds = await _sysNoticeLogService.Queryable() .Where(it => it.UserId == userid) - .ToList(); - var unreadNotificationIds = notifications - .Where(it => it.Status == SysNoticeLogStatus.Unread) .Select(it => it.NoticeId) - .ToList(); - var readNotificationIds = notifications - .Where(it => it.Status == SysNoticeLogStatus.Read) - .Select(it => it.NoticeId) - .ToList(); - var unreadAndReadNoticeIds = unreadNotificationIds - .Union(readNotificationIds).ToList(); + .ToListAsync(); + // 当前在线用户的日志通知记录里如果有不存在的通知记录则添加未读记录 foreach (var notice in noticeRes.Select(it => it.NoticeId).ToList().Except(unreadAndReadNoticeIds)) { - _sysNoticeLogService.Insertable(new SysNoticeLog + await _sysNoticeLogService.Insertable(new SysNoticeLog { NoticeId = notice, UserId = userid, Status = SysNoticeLogStatus.Unread - }).ExecuteCommand(); + }).ExecuteReturnSnowflakeIdAsync(); } - - foreach (var notice in unreadAndReadNoticeIds.Except(noticeRes.Select(it => it.NoticeId).ToList())) - { - _sysNoticeLogService.Deleteable() - .Where(it => it.UserId == userid && it.NoticeId == notice) - .ExecuteCommand(); - } - var newUnReadNotificationIds = _sysNoticeLogService - .Queryable().Where(it => it.Status == SysNoticeLogStatus.Unread && it.UserId == userid) + // 当前在线用户的日志通知记录里如果有冗余的通知记录则删除已读记录 + // foreach (var notice in unreadAndReadNoticeIds.Except(noticeRes.Select(it => it.NoticeId).ToList())) + // { + // _sysNoticeLogService.Deleteable() + // .Where(it => it.UserId == userid && it.NoticeId == notice) + // .ExecuteCommand(); + // } + var newUnReadNotificationIdsAndReadNotifications = await _sysNoticeLogService.Queryable() + .Where(it => it.UserId == userid) + .ToListAsync(); + var newUnReadNotificationIds = newUnReadNotificationIdsAndReadNotifications + .Where(it => it.Status == SysNoticeLogStatus.Unread) .Select(it => it.NoticeId) .ToList(); - var newReadNotificationIds = _sysNoticeLogService - .Queryable().Where(it => it.Status == SysNoticeLogStatus.Read && it.UserId == userid) + var newReadNotificationIds = newUnReadNotificationIdsAndReadNotifications + .Where(it => it.Status == SysNoticeLogStatus.Read) .Select(it => it.NoticeId) .ToList(); var config = new TypeAdapterConfig(); @@ -123,7 +124,11 @@ namespace ZR.ServiceCore.Signalr newUnReadNotificationIds.Contains(it.NoticeId)).ToList().Adapt>(config); var newReadNotifications = noticeRes.Where(it => newReadNotificationIds.Contains(it.NoticeId)).ToList().Adapt>(config); - Clients.Caller.SendAsync(HubsConstant.MoreNotice, newUnReadNotifications, newReadNotifications); + await Clients.Caller.SendAsync(HubsConstant.MoreNotice, SendNotice(new + { + unReadNotifications = newUnReadNotifications, + readNotifications = newReadNotifications + })); // Clients.Caller.SendAsync(HubsConstant.MoreNotice, SendNotice()); // Clients.Caller.SendAsync(HubsConstant.ConnId, onlineUser.ConnnectionId); } @@ -131,7 +136,7 @@ namespace ZR.ServiceCore.Signalr if (userInfo == null) { userInfo = new OnlineUsers() { Userid = userid, Name = name, LoginTime = DateTime.Now }; - users.Add(userInfo); + Users.Add(userInfo); } else { @@ -140,23 +145,22 @@ namespace ZR.ServiceCore.Signalr userInfo.LoginTime = DateTime.Now; userInfo.TodayOnlineTime = 0; } - var clientUser = onlineClients.Find(x => x.Userid == userid); + var clientUser = OnlineClients.Find(x => x.Userid == userid); userInfo.TodayOnlineTime += Math.Round(clientUser?.OnlineTime ?? 0, 2); } //给当前所有登录当前账号的用户下发登录时长 - var connIds = onlineClients.Where(f => f.Userid == userid).ToList(); + var connIds = OnlineClients.Where(f => f.Userid == userid).ToList(); userInfo.ClientNum = connIds.Count; // Clients.Clients(connIds.Select(f => f.ConnnectionId)).SendAsync("onlineInfo", userInfo); - Log.WriteLine(ConsoleColor.Blue, msg: $"用户{name}已连接,今日已在线{userInfo?.TodayOnlineTime}分钟,当前已连接{onlineClients.Count}个"); + Log.WriteLine(ConsoleColor.Blue, msg: $"用户{name}已连接,今日已在线{userInfo?.TodayOnlineTime}分钟,当前已连接{OnlineClients.Count}个"); //给所有用户更新在线人数 - Clients.All.SendAsync(HubsConstant.OnlineNum, new + await Clients.All.SendAsync(HubsConstant.OnlineNum, new { - num = onlineClients.Count, - onlineClients + num = OnlineClients.Count, onlineClients = OnlineClients }); - return base.OnConnectedAsync(); + await base.OnConnectedAsync(); } /// @@ -165,15 +169,15 @@ namespace ZR.ServiceCore.Signalr /// public override Task OnDisconnectedAsync(Exception exception) { - var user = onlineClients.Where(p => p.ConnnectionId == Context.ConnectionId).FirstOrDefault(); + var user = OnlineClients.Where(p => p.ConnnectionId == Context.ConnectionId).FirstOrDefault(); if (user != null) { - onlineClients.Remove(user); + OnlineClients.Remove(user); //给所有用户更新在线人数 Clients.All.SendAsync(HubsConstant.OnlineNum, new { - num = onlineClients.Count, - onlineClients, + num = OnlineClients.Count, + onlineClients = OnlineClients, leaveUser = user }); @@ -183,7 +187,7 @@ namespace ZR.ServiceCore.Signalr { userInfo.TodayOnlineTime += user?.OnlineTime ?? 0; } - Log.WriteLine(ConsoleColor.Red, msg: $"用户{user?.Name}离开了,已在线{userInfo?.TodayOnlineTime}分,当前已连接{onlineClients.Count}个"); + Log.WriteLine(ConsoleColor.Red, msg: $"用户{user?.Name}离开了,已在线{userInfo?.TodayOnlineTime}分,当前已连接{OnlineClients.Count}个"); } return base.OnDisconnectedAsync(exception); } @@ -202,7 +206,7 @@ namespace ZR.ServiceCore.Signalr { var userName = HttpContextExtension.GetName(App.HttpContext); long userid = HttpContextExtension.GetUId(App.HttpContext); - var toUserList = onlineClients.Where(p => p.Userid == toUserId); + var toUserList = OnlineClients.Where(p => p.Userid == toUserId); var toUserInfo = toUserList.FirstOrDefault(); IList sendToUser = toUserList.Select(x => x.ConnnectionId).ToList(); sendToUser.Add(GetConnectId()); @@ -230,6 +234,94 @@ namespace ZR.ServiceCore.Signalr Console.WriteLine($"用户{userName}对{toConnectId}-{toUserId}说:{message}"); } + /// + /// 对当前在线用户累加新通知公告 + /// + /// + /// + public async Task SendNoticeToOnlineUsers(long? noticeId, bool enableDelete = true) + { + if (enableDelete) + { + // 防止日志记录有冗余数据 + await _sysNoticeLogService.Deleteable() + .Where(it => it.NoticeId == noticeId) + .ExecuteCommandAsync(); + // 获取所有通知 + var noticeRes = (List) SendNotice()[ApiResult.DATA_TAG]; + + foreach (var onlineUser in OnlineClients) + { + var userid = onlineUser.Userid; + + var sysNoticeLogStore = await _sysNoticeLogService + .Storageable(new SysNoticeLog(noticeId!.Value, onlineUser.Userid, SysNoticeLogStatus.Unread)) + .WhereColumns(it => new { it.NoticeId, it.UserId }) + .ToStorageAsync(); + await sysNoticeLogStore + .AsInsertable + .ExecuteReturnSnowflakeIdAsync(); + await sysNoticeLogStore + .AsUpdateable + .ExecuteCommandAsync(); + // 获取当前在线用户的通知日志记录id + var unreadAndReadNotices = await _sysNoticeLogService.Queryable() + .Where(it => it.UserId == userid) + .ToListAsync(); + var config = new TypeAdapterConfig(); + config.ForType() + .Map(dest => dest.NoticeId, src => src.NoticeId.ToString()); + var unReadNotifications = noticeRes.Where(it => + unreadAndReadNotices.Where(o => o.Status == SysNoticeLogStatus.Unread) + .Select(o => o.NoticeId).Contains(it.NoticeId)).ToList() + .Adapt>(config); + var readNotifications = noticeRes.Where(it => + unreadAndReadNotices.Where(o => o.Status == SysNoticeLogStatus.Read) + .Select(o => o.NoticeId).Contains(it.NoticeId)).ToList() + .Adapt>(config); + + await Clients.Client(onlineUser.ConnnectionId).SendAsync(HubsConstant.MoreNotice, + SendNotice(new + { + unReadNotifications, + readNotifications + })); + } + } + else + { + // 获取所有通知 + var noticeRes = (List) SendNotice()[ApiResult.DATA_TAG]; + foreach (var onlineUser in OnlineClients) + { + var userid = onlineUser.Userid; + // 获取当前在线用户的通知日志记录id + var unreadAndReadNotices = await _sysNoticeLogService.Queryable() + .Where(it => it.UserId == userid) + .ToListAsync(); + var config = new TypeAdapterConfig(); + config.ForType() + .Map(dest => dest.NoticeId, src => src.NoticeId.ToString()); + var unReadNotifications = noticeRes.Where(it => + unreadAndReadNotices.Where(o => o.Status == SysNoticeLogStatus.Unread) + .Select(o => o.NoticeId).Contains(it.NoticeId)).ToList() + .Adapt>(config); + var readNotifications = noticeRes.Where(it => + unreadAndReadNotices.Where(o => o.Status == SysNoticeLogStatus.Read) + .Select(o => o.NoticeId).Contains(it.NoticeId)).ToList() + .Adapt>(config); + await Clients.Client(onlineUser.ConnnectionId).SendAsync(HubsConstant.MoreNotice, + SendNotice(new + { + unReadNotifications, + readNotifications + })); + } + } + + // var onlineUsers = ClientUsers.Where(it => it.ConnnectionId != Context.ConnectionId); + } + /// /// 全部标为已读 /// @@ -268,7 +360,11 @@ namespace ZR.ServiceCore.Signalr newUnReadNotificationIds.Contains(it.NoticeId)).ToList(); var newReadNotifications = noticeRes.Where(it => newReadNotificationIds.Contains(it.NoticeId)).ToList(); - await Clients.Caller.SendAsync(HubsConstant.MoreNotice, newUnReadNotifications, newReadNotifications); + await Clients.Caller.SendAsync(HubsConstant.MoreNotice, SendNotice(new + { + unReadNotifications = newUnReadNotifications, + readNotifications = newReadNotifications + })); } /// @@ -303,16 +399,20 @@ namespace ZR.ServiceCore.Signalr newUnReadNotificationIds.Contains(it.NoticeId)).ToList(); var newReadNotifications = noticeRes.Where(it => newReadNotificationIds.Contains(it.NoticeId)).ToList(); - await Clients.Caller.SendAsync(HubsConstant.MoreNotice, newUnReadNotifications, newReadNotifications); + await Clients.Caller.SendAsync(HubsConstant.MoreNotice, SendNotice(new + { + unReadNotifications = newUnReadNotifications, + readNotifications = newReadNotifications + })); } private OnlineUsers GetUserByConnId(string connId) { - return onlineClients.Where(p => p.ConnnectionId == connId).FirstOrDefault(); + return OnlineClients.Where(p => p.ConnnectionId == connId).FirstOrDefault(); } private static OnlineUsers GetUserById(long userid) { - return users.Where(f => f.Userid == userid).FirstOrDefault(); + return Users.Where(f => f.Userid == userid).FirstOrDefault(); } /// @@ -336,7 +436,7 @@ namespace ZR.ServiceCore.Signalr long userid = HttpContextExtension.GetUId(App.HttpContext); if (singleLogin) { - var onlineUsers = onlineClients.Where(p => p.ConnnectionId != Context.ConnectionId && p.Userid == userid); + var onlineUsers = OnlineClients.Where(p => p.ConnnectionId != Context.ConnectionId && p.Userid == userid); await Clients.Clients(onlineUsers.Select(x => x.ConnnectionId)) .SendAsync("logOut"); }