ソースを参照

Merge branch 'develop' of http://132.232.92.186:3000/XinXiBu/OA2023 into develop

yuanrf 1 ヶ月 前
コミット
47feb19bd8

+ 3 - 2
OASystem/OASystem.Api/Controllers/FinancialController.cs

@@ -30,6 +30,7 @@ using Org.BouncyCastle.Asn1.X509.Qualified;
 using MathNet.Numerics;
 using static OASystem.API.OAMethodLib.JWTHelper;
 using Org.BouncyCastle.Asn1.Ocsp;
+using OASystem.API.OAMethodLib.APNs;
 
 namespace OASystem.API.Controllers
 {
@@ -199,7 +200,7 @@ namespace OASystem.API.Controllers
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
 
-                await GeneralMethod.iOS_PushNotifications("051", $"日付费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"日付费用审核", "", content);
             }
             catch (Exception ex)
             {
@@ -242,7 +243,7 @@ namespace OASystem.API.Controllers
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.DailyPayment, title, content, userIds, 0);
 
-                await GeneralMethod.iOS_PushNotifications("051", $"日付费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"日付费用审核", "", content);
             }
             catch (Exception ex)
             {

+ 12 - 10
OASystem/OASystem.Api/Controllers/GroupsController.cs

@@ -14,6 +14,7 @@ using NPOI.SS.UserModel;
 using NPOI.SS.Util;
 using NPOI.XSSF.UserModel;
 using OASystem.API.OAMethodLib;
+using OASystem.API.OAMethodLib.APNs;
 using OASystem.API.OAMethodLib.File;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.Hubs;
@@ -2767,7 +2768,7 @@ FROM
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
 
-                await GeneralMethod.iOS_PushNotifications("051", $"机票费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"机票费用审核", "", content);
 
             }
             catch (Exception ex)
@@ -3659,7 +3660,7 @@ FROM
 
             await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
 
-            await GeneralMethod.iOS_PushNotifications("051", $"其他款项费用审核", "", content);
+            await APNsTools.iOS_PushNotifications("051", $"其他款项费用审核", "", content);
 
 
 
@@ -4264,7 +4265,7 @@ FROM
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
 
-                await GeneralMethod.iOS_PushNotifications("051", $"商邀费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"商邀费用审核", "", content);
             }
             catch (Exception ex)
             {
@@ -7143,7 +7144,7 @@ FROM
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId); 
                 
-                await GeneralMethod.iOS_PushNotifications("051", $"签证费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"签证费用审核", "", content);
             }
             catch (Exception ex)
             {
@@ -7516,7 +7517,7 @@ FROM
                     string content = $"[更新-OP费用录入填写详情({groupInfo?.TeamName ?? "-"})]一项费用:{(((ccpInfo.PayMoney * ccpInfo.DayRate) / 100) * ccpInfo.PayPercentage).ToString("#0.00")} CNY;";
 
                     await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
-                    await GeneralMethod.iOS_PushNotifications("051", "OP费用审核", "", content);
+                    await APNsTools.iOS_PushNotifications("051", "OP费用审核", "", content);
                 }
                 catch (Exception ex)
                 {
@@ -11056,17 +11057,18 @@ ORDER by  gctggrc.id DESC
                 if (_dto.Id == 0) content = $"[新增-酒店费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
                 else if (_dto.Id > 0) content = $"[更新-酒店费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
 
-                Logs($"【iOS推送通知Exceptio1】Start");
+               
 
                 try
                 {
-                    var iosRes = await GeneralMethod.iOS_PushNotifications("051", title, "", content);
-                    Logs($"【iOS推送通知Exception2】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
+                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】Start");
+                    var iosRes = await APNsTools.iOS_PushNotifications("051", title, "", content);
+                    Logs($"【iOS推送通知PostHotelReservationsAddOrEdit】End Response:[{JsonConvert.SerializeObject(iosRes)}]");
                 }
                 catch (Exception ex )
                 {
 
-                    Logs($"【iOS推送通知Exception2-1】[{ex.Message}]");
+                    Logs($"【iOS推送通知-PostHotelReservationsAddOrEdit-Exception】[{ex.Message}]");
                 }
 
             }
@@ -13195,7 +13197,7 @@ ORDER by  gctggrc.id DESC
                 else if (dto.Status == 2) content = $"[更新-保险费用录入({groupInfo?.TeamName ?? "-"})]一项费用:{(ccpInfo.PayMoney * ccpInfo.DayRate).ToString("#0.00")} CNY;";
 
                 await GeneralMethod.MessageIssueAndNotification(MessageTypeEnum.GroupBusinessOperations, title, content, userIds, diId);
-                await GeneralMethod.iOS_PushNotifications("051", $"保险费用审核", "", content);
+                await APNsTools.iOS_PushNotifications("051", $"保险费用审核", "", content);
             }
             catch (Exception ex)
             {

+ 0 - 3
OASystem/OASystem.Api/Controllers/PersonnelModuleController.cs

@@ -2,7 +2,6 @@
 using FluentValidation;
 using Microsoft.AspNetCore.SignalR;
 using OASystem.API.OAMethodLib;
-using OASystem.API.OAMethodLib.APNsLib;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.QiYeWeChatAPI;
@@ -2344,8 +2343,6 @@ OPTION (MAXRECURSION 0); -- 允许无限递归      ";
             var jw = JsonView(false);
 
 
-            APNsLib.pushMsg("com.panamerican.oa2024", "9a624f38602a8d2cc12b8c44c3cb37633e246963ec2bfd7bca2094b59dc9f09c", NotificationType.Alert, "Ver.Production测试", "测试字标题", "测试内容");
-
             return Ok(jw);
         }
 

+ 111 - 65
OASystem/OASystem.Api/OAMethodLib/APNs/APNsService.cs

@@ -6,9 +6,12 @@ using static System.Net.Mime.MediaTypeNames;
 using Microsoft.Net.Http.Headers;
 using Microsoft.Extensions.Configuration;
 using NPOI.SS.Formula.Functions;
-using Serilog;
+using System.Net.Http;
+using Flurl.Http.Configuration;
+using System.Net;
+using QuzrtzJob.Factory;
 
-namespace OASystem.API.OAMethodLib.APNsLib
+namespace OASystem.API.OAMethodLib.APNs
 {
     public enum NotificationType : int
     {
@@ -26,17 +29,19 @@ namespace OASystem.API.OAMethodLib.APNsLib
         static string token = null;
         static string baseUrl = null;
 
+        private readonly ILogger<APNsService> _logger;
+        //private static readonly HttpClient _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
         private readonly IConfiguration _configuration;
-        private readonly IHttpClientFactory _httpClientFactory;
-        private readonly Serilog.ILogger _logger;
-        public APNsService(IConfiguration configuration, Serilog.ILogger logger, IHttpClientFactory httpClientFactory)
+        //private readonly IHttpClientFactory _httpClientFactory;
+        public APNsService(ILogger<APNsService> logger,IConfiguration configuration)
         {
             this._configuration = configuration;
-            this._httpClientFactory = httpClientFactory;
-            this._logger = logger;
-
+            //this._httpClientFactory = httpClientFactory;
             //APNsService.baseUrl = this._configuration["apple:pushNotificationServer"];
-            APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
+            //APNsService.baseUrl = this._configuration["apple:pushNotificationServer_Production"];
+            //
+            //APNsService.baseUrl = string.Format("https://api.push.apple.com:443/3/device/");
+            _logger = logger;
         }
 
         /// <summary>
@@ -78,29 +83,35 @@ namespace OASystem.API.OAMethodLib.APNsLib
             var kid = _configuration["apple:kid"];
             var securityKey = _configuration["apple:securityKey"].Replace("\n", "");
             var iss = _configuration["apple:iss"];
-
             var claims = new Claim[]
             {
-            new Claim("iss", iss),
-            new Claim("iat", iat.ToString())
+                new Claim("iss", iss),
+                new Claim("iat", iat.ToString())
             };
 
-            var eCDsa = ECDsa.Create();
-
-            eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
+            try
+            {
+                var eCDsa = ECDsa.Create();
 
-            var key = new ECDsaSecurityKey(eCDsa);
+                eCDsa.ImportPkcs8PrivateKey(Convert.FromBase64String(securityKey), out _);
 
-            key.KeyId = kid;
+                var key = new ECDsaSecurityKey(eCDsa);
 
-            var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
-            var jwtHeader = new JwtHeader(signingCredentials);
-            var jwtPayload = new JwtPayload(claims);
+                key.KeyId = kid;
 
-            var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
+                var signingCredentials = new SigningCredentials(key, SecurityAlgorithms.EcdsaSha256);
+                var jwtHeader = new JwtHeader(signingCredentials);
+                var jwtPayload = new JwtPayload(claims);
 
-            APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
+                var jwtSecurityToken = new JwtSecurityToken(jwtHeader, jwtPayload);
 
+                APNsService.token = tokenHandler.WriteToken(jwtSecurityToken);
+            }
+            catch (Exception ex)
+            {
+                return $"[ECDsa] ExMsg:[{ex.Message}]";
+            }
+            
             return APNsService.token;
         }
 
@@ -116,69 +127,104 @@ namespace OASystem.API.OAMethodLib.APNsLib
         /// <returns></returns>
         public async Task<Result> PushNotification(string apnsTopic, string deviceToken, NotificationType type, string title, string subtitle, string body)
         {
-            Result result = new Result() { Code = -1, Msg = "未知错误" };
+            Result result = new Result() { Code = -1, Msg = "[PushNotification] Start" };
+
+            result.Msg += "\r\n[PushNotification] Start";
+            _logger.LogInformation($"[PushNotification] Start");
             var responseData = FailedAPNsReponseData();
             var token = this.GetnerateAPNsJWTToken();
-            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
-            {
-                Headers =
-            {
-                { HeaderNames.Authorization, "bearer " +  token },
-                { "apns-topic", apnsTopic },
-                { "apns-expiration", "0" }
-            },
-                Version = new Version(2, 0)
-            };
 
-            var notContent = new
+            try
             {
-                aps = new
+                var _httpClientFactory = new HttpClient { BaseAddress = new Uri("https://api.push.apple.com:443/3/device/") };
+                result.Msg += $"\r\n[PushNotification] --> [HttpClient] --> Init --> jsonStr:{JsonConvert.SerializeObject(_httpClientFactory)}";
+
+                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, APNsService.baseUrl + deviceToken)
                 {
-                    alert = new
+                    Headers =
                     {
-                        title = title,
-                        subtitle = subtitle,
-                        body = body
+                        { HeaderNames.Authorization, "bearer " +  token },
+                        { "apns-topic", apnsTopic },
+                        { "apns-expiration", "0" }
+                    },
+                    Version = new Version(2, 0)
+                };
+                result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Init --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
+                var notContent = new
+                {
+                    aps = new
+                    {
+                        alert = new
+                        {
+                            title = title,
+                            subtitle = subtitle,
+                            body = body
+                        }
                     }
-                }
-            };
-            //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
+                };
+                //var content = new StringContent(JsonSerializerTool.SerializeDefault(notContent), System.Text.Encoding.UTF8, Application.Json);
 
-            var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent));
+                var content = new StringContent(System.Text.Json.JsonSerializer.Serialize(notContent), System.Text.Encoding.UTF8, Application.Json);
 
-            httpRequestMessage.Content = content;
+                httpRequestMessage.Content = content;
 
-            var httpClient = _httpClientFactory.CreateClient();
-            try
-            {
-                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
-
-                if (httpResponseMessage.IsSuccessStatusCode)
+                result.Msg += $"\r\n[PushNotification] --> [httpRequestMessage] --> Content --> jsonStr:{JsonConvert.SerializeObject(httpRequestMessage)}";
+                try
                 {
-                    responseData.Code = 200;
-                    result.Code = 0;
-                    result.Msg = "";
-                    result.Data = responseData;
-                    return result;
+                    //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls13;
+
+                    //HttpClientHandler handler = new HttpClientHandler()
+                    //{
+                    //    Proxy = new WebProxy("https://api.push.apple.com:443/3/device/"),
+                    //    SslProtocols = System.Security.Authentication.SslProtocols.Tls12, // Enforce TLS 1.2
+                    //    UseProxy = true
+                    //};
+                    //HttpClient client = new HttpClient(handler);
+
+                    //var httpResponseMessage = await client.SendAsync(httpRequestMessage);
+                    var httpResponseMessage = await _httpClientFactory.SendAsync(httpRequestMessage);
+
+                    if (httpResponseMessage.IsSuccessStatusCode)
+                    {
+                        responseData.Code = 200;
+                        result.Code = 0;
+                        result.Msg = "";
+                        result.Data = responseData;
+                        result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
+                        return result;
+                    }
+                    else
+                    {
+                        responseData.Data = httpResponseMessage.StatusCode;
+                        result.Code = -2;
+                        result.Msg = "";
+                        result.Data = responseData;
+                        result.Msg += $"\r\n[PushNotification] End jsonStr[{JsonConvert.SerializeObject(result)}]";
+
+                        return result;
+                    }
                 }
-                else
+                catch (Exception e)
                 {
-                    responseData.Data = httpResponseMessage.StatusCode;
-                    result.Code = -2;
+                    responseData.Data = e.Message;
+                    result.Code = -3;
                     result.Msg = "";
                     result.Data = responseData;
+
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] ExceptionMsg:{e.Message}";
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionData:{e.InnerException}";
+                    result.Msg += $"\r\n[PushNotification] --> [httpClientFactory] InnerExceptionMsg:{e.InnerException.Message}";
                     return result;
                 }
             }
-            catch (Exception e)
+            catch (Exception ex)
             {
-                responseData.Data = e.Message;
-                result.Code = -3;
-                result.Msg = "";
-                result.Data = responseData;
-                _logger.Information(string.Format(@" APNs : {0}", e.Message));
-                return result;
+                result.Msg += $"\r\n[PushNotification] InnerExceptionData:{JsonConvert.SerializeObject(ex.InnerException)}";
+                result.Msg += $"\r\n[PushNotification] InnerExceptionMsg:{ex.InnerException.Message}";
             }
+
+
+            return result;
         }
 
         public APNsReponseData FailedAPNsReponseData()

+ 40 - 0
OASystem/OASystem.Api/OAMethodLib/APNs/APNsTools.cs

@@ -0,0 +1,40 @@
+using EyeSoft.Runtime.InteropServices;
+using OASystem.API.Controllers;
+using OASystem.API.OAMethodLib.Hub.Hubs;
+using OASystem.Domain.Entities.Groups;
+using OASystem.Infrastructure.Repositories.Login;
+
+namespace OASystem.API.OAMethodLib.APNs
+{
+    public static class APNsTools
+    {
+        private static readonly DeviceTokenRepository _deviceTokenRep = AutofacIocManager.Instance.GetService<DeviceTokenRepository>();
+        
+        //private static readonly IAPNsService _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
+
+        public static async Task<Result> iOS_PushNotifications(string Numbers, string title, string subtitle, string body)
+        {
+            
+            Result rst2 = new Result() { Code = -1, Msg = "" };
+            try
+            {
+
+
+                var _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
+            var rst = await _deviceTokenRep.Query(s => s.Number == Numbers).FirstAsync();
+            //var rst = new Sys_DeviceToken() { DeviceToken = "08be7ba1ee42ecf36f695fd6b795b5e203295eaed0ba3857276141dbeee025ff" }
+            if (rst != null)
+            {
+                rst2 = await _APNsService.PushNotification("com.panamerican.oa2024", rst.DeviceToken, NotificationType.Alert, title, subtitle, body);
+            }
+
+            }
+            catch (Exception ex)
+            {
+
+
+            }
+            return rst2;
+        }
+    }
+}

+ 1 - 1
OASystem/OASystem.Api/OAMethodLib/APNs/IAPNsService.cs

@@ -1,4 +1,4 @@
-namespace OASystem.API.OAMethodLib.APNsLib
+namespace OASystem.API.OAMethodLib.APNs
 {
     public interface IAPNsService
     {

+ 3 - 12
OASystem/OASystem.Api/OAMethodLib/GeneralMethod.cs

@@ -5,7 +5,7 @@ using Aspose.Words.Layout;
 using Aspose.Words.Saving;
 using Microsoft.AspNetCore.SignalR;
 using Microsoft.International.Converters.PinYinConverter;
-using OASystem.API.OAMethodLib.APNsLib;
+using OASystem.API.OAMethodLib.APNs;
 using OASystem.API.OAMethodLib.File;
 using OASystem.API.OAMethodLib.Hub.HubClients;
 using OASystem.API.OAMethodLib.Hub.Hubs;
@@ -38,8 +38,7 @@ namespace OASystem.API.OAMethodLib
         private static readonly SetDataRepository _setDataRep = AutofacIocManager.Instance.GetService<SetDataRepository>();
         private static readonly TableOperationRecordRepository _tableOperationRecordRep = AutofacIocManager.Instance.GetService<TableOperationRecordRepository>();
         private static readonly MessageRepository _messageRep = AutofacIocManager.Instance.GetService<MessageRepository>();
-        private static readonly DeviceTokenRepository _deviceTokenRep = AutofacIocManager.Instance.GetService<DeviceTokenRepository>();
-        private static readonly IAPNsService _APNsService = AutofacIocManager.Instance.GetService<IAPNsService>();
+        
         private static readonly IHubContext<ChatHub, IChatClient> _hubContext = AutofacIocManager.Instance.GetService<IHubContext<ChatHub, IChatClient>>();
 
         private readonly static string[] weekdays = new string[] { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
@@ -4446,15 +4445,7 @@ namespace OASystem.API.OAMethodLib
 
         #region iOS推送通知
 
-        public static async Task<Result> iOS_PushNotifications(string Numbers, string title, string subtitle, string body)
-        {
-            var rst = await _deviceTokenRep.Query(s => s.Number == Numbers).SingleAsync();
-            Result rst2 = new Result() { Code = -1, Msg = "" };
-            if (rst != null) {
-                rst2 = await _APNsService.PushNotification("com.panamerican.oa2024", rst.DeviceToken, NotificationType.Alert, title, subtitle, body);
-            }
-            return rst2;
-        }
+        
 
 
         #endregion

+ 5 - 2
OASystem/OASystem.Api/Program.cs

@@ -4,7 +4,7 @@ using Microsoft.AspNetCore.Server.Kestrel.Core;
 using Microsoft.Extensions.DependencyInjection.Extensions;
 using OASystem.API.Middlewares;
 using OASystem.API.OAMethodLib;
-using OASystem.API.OAMethodLib.APNsLib;
+using OASystem.API.OAMethodLib.APNs;
 using OASystem.API.OAMethodLib.Hub.Hubs;
 using OASystem.API.OAMethodLib.JuHeAPI;
 using OASystem.API.OAMethodLib.QiYeWeChatAPI;
@@ -336,11 +336,14 @@ builder.Services.AddSingleton<ALiYunPostMessageJob>();
 builder.Services.AddSingleton<TaskJob>();
 builder.Services.AddSingleton<TaskNewsFeedJob>();
 //# new business
+builder.Services.AddControllersWithViews();
+builder.Services.AddSingleton<IAPNsService, APNsService>();
+
 builder.Services.AddSingleton<IJobFactory, IOCJobFactory>();
 
 #endregion
 
-builder.Services.AddSingleton<IAPNsService,APNsService>();
+
 
 #region SignalR
 builder.Services.AddSignalR()