public static ResponseEntity FCMSend(DbEntity record) { const string fcm = "[FCM ]"; string GoogleAppID; string SENDER_ID; FcmConfiguration config; ResponseEntity pushResult = new ResponseEntity(); #if DEBUG Console.WriteLine($"Вошли в метод FCMSend"); #endif try { GoogleAppID = "************"; SENDER_ID = "**********"; //Configuration config = new FcmConfiguration(SENDER_ID, GoogleAppID, null); config.FcmUrl = "https://fcm.googleapis.com/fcm/send"; //Create a new broker var fcmBroker = new FcmServiceBroker(config); //Wire up events fcmBroker.OnNotificationFailed += (notification, aggregateEx) => { aggregateEx.Handle(ex => { //See what kind of exception it was to further diagnose if (ex is FcmNotificationException) { var notificationException = (FcmNotificationException)ex; //Deal with the failed notifications var fcmNotification = notificationException.Notification; var description = notificationException.Description; string desc = $"{fcm} Notification Failed: ID = [{fcmNotification.MessageId}], Desc = [{description}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, notificationException); } else if (ex is FcmMulticastResultException) { var multicastException = (FcmMulticastResultException)ex; foreach (var succeededNotification in multicastException.Succeeded) { string desc = $"{fcm} Notification Succeeded: ID = [{succeededNotification.MessageId}]"; Console.WriteLine(desc); } foreach (var failedKvp in multicastException.Failed) { var n = failedKvp.Key; var e = failedKvp.Value; string desc = $"{fcm} Notification Failed: ID = [{n.MessageId}], Desc = [{e.Message}]"; Console.WriteLine(desc); } pushResult = BasePush.GetResponseEntity(record, multicastException); } else if (ex is DeviceSubscriptionExpiredException) { var expiredException = (DeviceSubscriptionExpiredException)ex; var oldId = expiredException.OldSubscriptionId; var newId = expiredException.NewSubscriptionId; string desc = $"{fcm} Device RegistrationId Expired: [{oldId}], \nMessage Id = [{record.Message_id}]"; Console.WriteLine(desc); if (!string.IsNullOrWhiteSpace(newId)) { string desc2 = $"{fcm} Device RegistrationId Changes To: [{newId}]"; Console.WriteLine(desc2); //If this value isn`t null, our subscription changed and we should update our databse } pushResult = BasePush.GetResponseEntity(record, expiredException); } else if (ex is RetryAfterException) { var retryException = (RetryAfterException)ex; //If you get rate limited, you should stop sending messages until after the RetryAfterUtc date string desc = $"{fcm} Rate Limited, don`t send more until after [{retryException.RetryAfterUtc}], \nMessage Id = [{record.Message_id}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, retryException); } else { var otherException = ex; string desc = $"{fcm} Notification failed for some unknown reason. Message: [{otherException.Message}], \nMessage Id = [{record.Message_id}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, otherException); } //Mark it as handled return(true); // обязательное условие такой конструкции (выдать bool) }); }; fcmBroker.OnNotificationSucceeded += (notification) => { #if DEBUG string desc = "Success"; Console.WriteLine(desc); #endif Console.WriteLine($"{fcm} Сообщение [{record.Message_id}] успешно отправлено"); pushResult = BasePush.GetResponseEntity(record); }; //Start the Broker fcmBroker.Start(); //Queue a notification to send fcmBroker.QueueNotification(new FcmNotification { To = record.Push_id, Data = MakeFcmData(record.Message_text, "info"), TimeToLive = record.Msg_Ttl }); //Stop the Broker, wait for it to finish //This isn`t done after every message, but after you`re //done with the Broker fcmBroker.Stop(); return(pushResult); // выдаём наружу результат отправки пуша } catch (Exception ex) { Console.WriteLine("{fcm} ERROR: " + ex.Message); return(BasePush.GetResponseEntity(record, ex)); } }
public static ResponseEntity ApnsSend(DbEntity record) { const string apns = "[APNS]"; #if DEBUG Console.WriteLine($"Вошли в метод ApnsSend"); #endif ApnsConfiguration config = null; ApnsServiceBroker apnsBroker = null; try { config = ApnsConfigBuilder.Config(ApnsConfiguration.ApnsServerEnvironment.Production); } catch (Exception ex) { Console.WriteLine($"{apns} Возникла критическая ошибка. " + $"Отправка сообщений на сервер {apns} отменена " + Environment.NewLine + $"{ex.Message}"); return(null); } // Create a new broker ResponseEntity pushResult = new ResponseEntity(); apnsBroker = new ApnsServiceBroker(config); var apnsNotification = new ApnsNotification(); try { // Wire up events apnsBroker.OnNotificationFailed += (notification, aggregateEx) => { #if DEBUG Console.WriteLine($"Сервер APNS ответил ошибкой. Попытка определить тип ошибки"); #endif aggregateEx.Handle(ex => { // See what kind of exception it was to further diagnose if (ex is ApnsNotificationException) { var notificationException = (ApnsNotificationException)ex; // Deal with the failed notification var apnsNotificationWithException = notificationException.Notification; var statusCode = notificationException.ErrorStatusCode; string desc = $"{apns} Notification Failed: Message ID = [{record.Message_id}], Code = [{statusCode}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, notificationException); } else if (ex is ApnsConnectionException) { var connectionException = (ApnsConnectionException)ex; var innerException = connectionException.InnerException; var message = connectionException.Message; string desc = $"{apns} Notification Failed. Connection failure: \nMessage = [{message}], \nInnerException = [{innerException}], \nMessage Id = [{record.Message_id}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, connectionException); } else { var otherException = ex; // Inner exception might hold more useful information like an ApnsConnectionException string desc = $"{apns} Notification Failed for some unknown reason : \nMessage = [{otherException.Message}], \nInnerException = [{otherException.InnerException}], \nMessage Id = [{record.Message_id}]"; Console.WriteLine(desc); pushResult = BasePush.GetResponseEntity(record, otherException); } // Mark it as handled return(true); // обязательное условие такой конструкции (выдать bool) }); }; apnsBroker.OnNotificationSucceeded += (notification) => { #if DEBUG var desc = "Сообщение отправлено на сервер APNS"; //responseMessage = desc; Console.WriteLine(desc); #endif Console.WriteLine($"{apns} Сообщение [{record.Message_id}] успешно отправлено"); pushResult = BasePush.GetResponseEntity(record); }; // Start the broker apnsBroker.Start(); #if DEBUG Console.WriteLine($"Брокер отправки сообщений запущен"); #endif var jsonString = $"{{\"aps\":{{\"alert\":\"{record.Message_text}\"}}}}"; var apns_expiration = DateTime.UtcNow.AddSeconds(record.Msg_Ttl); apnsNotification = new ApnsNotification { DeviceToken = record.Push_id, Payload = JObject.Parse(jsonString), Expiration = apns_expiration }; apnsBroker.QueueNotification(apnsNotification); // Stop the broker, wait for it to finish // This isn't done after every message, but after you're // done with the broker #if DEBUG Console.WriteLine($"Останавливаем брокер - это действие выполнит отправку сообщения"); #endif apnsBroker.Stop(); return(pushResult); // выдаём наружу результат отправки пуша } catch (Exception ex) { Console.WriteLine("{apns} ERROR: " + ex.Message); return(BasePush.GetResponseEntity(record, ex)); } }