public override void Send(List <NeeoUser> receiverList, NotificationModel notificationModel) { if (receiverList == null || receiverList.Count == 0) { LogManager.CurrentInstance.ErrorLogger.LogError( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "receiverList is either null or empty."); return; } Parallel.ForEach(receiverList, (item) => { var payload = new GcmPayload().Create(item, notificationModel); if (item.PnSource == PushNotificationSource.Pushy) { var pushyRequest = new PushyPushRequest(payload, new string[] { item.DeviceToken }); PushyClient.SendPush(pushyRequest); return; } var notification = new GcmNotification() { RegistrationIds = new List <string> { item.DeviceToken }, Priority = GcmNotificationPriority.High, Data = JObject.FromObject(payload) }; _gcmServiceBroker.QueueNotification(notification); }); }
public static void SendPush(PushyPushRequest push) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(GetApiUrl()); request.ContentType = "application/json"; request.Method = "POST"; string postData = JsonConvert.SerializeObject(push); byte[] byteArray = Encoding.UTF8.GetBytes(postData); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); WebResponse response; try { response = request.GetResponse(); } catch (WebException exc) { string errorJSON = new StreamReader(exc.Response.GetResponseStream()).ReadToEnd(); PushyAPIError error = JsonConvert.DeserializeObject <PushyAPIError>(errorJSON); throw new Exception(error.error); } StreamReader reader = new StreamReader(response.GetResponseStream()); string responseData = reader.ReadToEnd(); LogManager.CurrentInstance.InfoLogger.LogInfo( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Request : " + JsonConvert.SerializeObject(push) + ", Status :" + responseData, System.Reflection.MethodBase.GetCurrentMethod().Name); reader.Close(); response.Close(); dataStream.Close(); }
/// <summary> /// Sends notifications to the specified device token and device platform . /// </summary> /// <param name="notification">An enum specifying the notification type.</param> public void SendNotification(Models.Notification notification) { int badgeCount = 0; ulong tempNumber; const string delimeter = ","; DevicePlatform devicePlatform; string deviceToken = null; switch (notification.NType) { case NotificationType.Im: #region IM notfication if (_notificationMsgLength == 0) { _notificationMsgLength = Convert.ToUInt16(ConfigurationManager.AppSettings[NotificationConstants.NotificationMsgLength]); } if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null && !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.SenderID) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) && notification.Badge != 0) { NeeoUser receiver = new NeeoUser(notification.ReceiverID) { DeviceToken = notification.DToken.Trim(), ImTone = notification.IMTone.GetValueOrDefault(), OfflineMsgCount = notification.Badge, DevicePlatform = notification.Dp.GetValueOrDefault(), PnSource = notification.PnSource.HasValue ? notification.PnSource.Value : PushNotificationSource.Default }; if (notification.Alert.Length > _notificationMsgLength) { notification.Alert = notification.Alert.Substring(0, _notificationMsgLength) + "..."; } if (receiver.DevicePlatform == DevicePlatform.iOS) { _push.QueueNotification(new AppleNotification(receiver.DeviceToken) .WithAlert(notification.Alert) .WithBadge(receiver.OfflineMsgCount) .WithSound(receiver.ImTone.GetDescription()) .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Im.ToString("D")) .WithCustomItem(NotificationConstants.SenderID, notification.SenderID)); } else if (receiver.DevicePlatform == DevicePlatform.Android) { Dictionary <string, string> payload = new Dictionary <string, string>() { { "alert", notification.Alert }, { NotificationConstants.NotificationID, NotificationType.Im.ToString("D") }, { NotificationConstants.SenderID, notification.SenderID } }; switch (receiver.PnSource) { case PushNotificationSource.Default: _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken) .WithJson(JsonConvert.SerializeObject(payload))); break; case PushNotificationSource.Pushy: var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken }); PushyClient.SendPush(pushyRequest); break; } } else if (receiver.DevicePlatform == DevicePlatform.WindowsMobile) { var alertParts = notification.Alert.Split(new[] { ':' }, 2); string notificationMeta = string.Format("/NeeoPivot.xaml?PhoneNumber={0}&PushNotificationType={1}", notification.SenderID, NotificationType.Im.ToString("D")); var winToastNotification = new WindowsToastNotification() .WithLaunch(notificationMeta) .AsToastText02(alertParts[0].Trim(), alertParts[1].Trim()) .ForChannelUri(receiver.DeviceToken); var customAudio = new CustomToastAudio() { CustomSource = "ms-appx:///Assets/Sounds/beep.wav" }; winToastNotification.Audio = customAudio; _push.QueueNotification(winToastNotification); _push.QueueNotification(new WindowsBadgeNumericNotification().WithBadgeNumber(receiver.OfflineMsgCount).ForChannelUri(receiver.DeviceToken)); } else { //do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; #endregion case NotificationType.Call: #region Incoming sip call notification if (_incomingCallingMsgText == null) { _incomingCallingMsgText = ConfigurationManager.AppSettings[NotificationConstants.IncomingCallingMsgText]; } if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber)) { // Get the name of the user from data base. DbManager dbManager = new DbManager(); var userInfo = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, false); NeeoUser receiver = new NeeoUser(notification.ReceiverID) { CallingTone = (CallingTone)Convert.ToInt16(userInfo[NeeoConstants.ReceiverCallingTone]), DevicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]), }; if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken]) && !NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.CallerName])) { receiver.DeviceToken = userInfo[NeeoConstants.ReceiverDeviceToken].Trim(); receiver.PnSource = (PushNotificationSource)Convert.ToInt32(userInfo[NeeoConstants.PushNotificationSource]); } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } if (receiver.DevicePlatform == DevicePlatform.iOS) { if (_actionKeyText == null) { _actionKeyText = ConfigurationManager.AppSettings[NotificationConstants.ActionKeyText]; } if (_iosIncomingCallingTone == null) { _iosIncomingCallingTone = ConfigurationManager.AppSettings[NotificationConstants.IosIncomingCallingTone]; } _push.QueueNotification(new AppleNotification(receiver.DeviceToken) .WithAlert(_incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]), "", _actionKeyText, new List <object>() { }) .WithSound(receiver.CallingTone.GetDescription()) .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Call.ToString("D")) .WithCustomItem(NotificationConstants.Timestamp, DateTime.UtcNow.ToString(NeeoConstants.TimestampFormat))); } else if (receiver.DevicePlatform == DevicePlatform.Android) { Dictionary <string, string> payload = new Dictionary <string, string>() { { "alert", _incomingCallingMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) }, { NotificationConstants.NotificationID, NotificationType.Call.ToString("D") }, { NotificationConstants.Timestamp, DateTime.UtcNow.ToString(NeeoConstants.TimestampFormat) }, { NotificationConstants.CallerID, notification.CallerID } }; switch (receiver.PnSource) { case PushNotificationSource.Default: _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken) .WithJson(JsonConvert.SerializeObject(payload))); break; case PushNotificationSource.Pushy: var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken }); PushyClient.SendPush(pushyRequest); break; } } else { // do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; #endregion case NotificationType.Mcr: #region Mcr notification if (_mcrMsgText == null) { _mcrMsgText = ConfigurationManager.AppSettings[NotificationConstants.McrMsgText]; } if (!NeeoUtility.IsNullOrEmpty(notification.CallerID) && ulong.TryParse(notification.CallerID, out tempNumber) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber) && notification.McrCount != 0) { DbManager dbManager = new DbManager(); var userInfo = dbManager.GetUserInforForNotification(notification.ReceiverID, notification.CallerID, true, notification.McrCount); NeeoUser receiver = new NeeoUser(notification.ReceiverID) { DevicePlatform = (DevicePlatform)Convert.ToInt16(userInfo[NeeoConstants.ReceiverUserDeviceplatform]), }; if (!NeeoUtility.IsNullOrEmpty(userInfo[NeeoConstants.ReceiverDeviceToken])) { receiver.DeviceToken = userInfo[NeeoConstants.ReceiverDeviceToken].Trim(); receiver.PnSource = (PushNotificationSource)Convert.ToInt32(userInfo[NeeoConstants.PushNotificationSource]); } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } badgeCount = Convert.ToInt32(userInfo[NeeoConstants.OfflineMessageCount]); if (receiver.DevicePlatform == DevicePlatform.iOS) { if (_iosApplicationMcrTone == null) { _iosApplicationMcrTone = ConfigurationManager.AppSettings[NotificationConstants.IosApplicationMcrTone]; } _push.QueueNotification(new AppleNotification(receiver.DeviceToken) .WithAlert(_mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName])) .WithBadge(badgeCount) .WithSound(_iosApplicationMcrTone) .WithCustomItem(NotificationConstants.NotificationID, NotificationType.Mcr.ToString("D")) .WithCustomItem(NotificationConstants.CallerID, notification.CallerID)); } else if (receiver.DevicePlatform == DevicePlatform.Android) { Dictionary <string, string> payload = new Dictionary <string, string>() { { "alert", _mcrMsgText.Replace("[" + NeeoConstants.CallerName + "]", userInfo[NeeoConstants.CallerName]) }, { NotificationConstants.NotificationID, NotificationType.Mcr.ToString("D") }, { NotificationConstants.CallerID, notification.CallerID } }; switch (receiver.PnSource) { case PushNotificationSource.Default: _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken) .WithJson(JsonConvert.SerializeObject(payload))); break; case PushNotificationSource.Pushy: var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken }); PushyClient.SendPush(pushyRequest); break; } } else { //do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; #endregion case NotificationType.GroupIm: #region Group notification if (!NeeoUtility.IsNullOrEmpty(notification.SenderID) && notification.RID != 0 && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.Alert) && notification.MessageType != null) { List <NeeoUser> lstgroupParticipant = NeeoGroup.GetGroupParticipants(notification.RID, notification.SenderID, (int)notification.MessageType); if (lstgroupParticipant.Count > 0) { var taskUpdateOfflineCount = Task.Factory.StartNew(() => { LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Group participants - " + JsonConvert.SerializeObject(lstgroupParticipant), System.Reflection.MethodBase.GetCurrentMethod().Name); IEnumerable <string> userList = from item in lstgroupParticipant where item.PresenceStatus == Presence.Offline select item.UserID; string userString = string.Join(delimeter, userList); //lstgroupParticipant.Where(i => i.PresenceStatus == Presence.Offline).Select(a => a.UserID) // .Aggregate((current, next) => current + delimeter + next); LogManager.CurrentInstance.InfoLogger.LogInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "User list - " + userString, System.Reflection.MethodBase.GetCurrentMethod().Name); if (!NeeoUtility.IsNullOrEmpty(userString)) { DbManager dbManager = new DbManager(); dbManager.UpdateUserOfflineCount(userString, delimeter); } }); var taskScheduleNotifications = Task.Factory.StartNew(() => { Parallel.ForEach(lstgroupParticipant, item => //foreach (var item in lstgroupParticipant) { if (!NeeoUtility.IsNullOrEmpty(item.DeviceToken) && item.DeviceToken != "-1" && item.PresenceStatus == Presence.Offline) { if (item.DevicePlatform == DevicePlatform.iOS) { _push.QueueNotification(new AppleNotification( item.DeviceToken.Trim()) .WithAlert(notification.Alert) .WithBadge(item.OfflineMsgCount + 1) .WithSound(item.ImTone.GetDescription()) .WithCustomItem(NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D")) .WithCustomItem(NotificationConstants.RoomID, notification.RName)); } else if (item.DevicePlatform == DevicePlatform.Android) { Dictionary <string, string> payload = new Dictionary <string, string>() { { "alert", notification.Alert }, { NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D") }, { NotificationConstants.RoomID, notification.RName } }; switch (item.PnSource) { case PushNotificationSource.Default: _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(item.DeviceToken) .WithJson(JsonConvert.SerializeObject(payload))); break; case PushNotificationSource.Pushy: var pushyRequest = new PushyPushRequest(payload, new string[] { item.DeviceToken }); PushyClient.SendPush(pushyRequest); break; } } else { //do nothing } } }); }); taskUpdateOfflineCount.Wait(); taskScheduleNotifications.Wait(); } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; #endregion case NotificationType.GroupInvite: #region Group invitation notification if (!NeeoUtility.IsNullOrEmpty(notification.DToken) && notification.Dp != null && notification.IMTone != null && !NeeoUtility.IsNullOrEmpty(notification.Alert) && !NeeoUtility.IsNullOrEmpty(notification.RName) && !NeeoUtility.IsNullOrEmpty(notification.ReceiverID) && ulong.TryParse(notification.ReceiverID, out tempNumber)) { NeeoUser receiver = new NeeoUser(notification.ReceiverID) { DeviceToken = notification.DToken.Trim(), ImTone = notification.IMTone.GetValueOrDefault(), OfflineMsgCount = notification.Badge, DevicePlatform = notification.Dp.GetValueOrDefault(), PnSource = notification.PnSource.HasValue ? notification.PnSource.Value : PushNotificationSource.Default }; if (receiver.DevicePlatform == DevicePlatform.iOS) { _push.QueueNotification(new AppleNotification(receiver.DeviceToken) .WithAlert(notification.Alert) .WithBadge(receiver.OfflineMsgCount) .WithSound(receiver.ImTone.GetDescription()) .WithCustomItem(NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D")) .WithCustomItem(NotificationConstants.RoomID, notification.RName)); } else if (receiver.DevicePlatform == DevicePlatform.Android) { Dictionary <string, string> payload = new Dictionary <string, string>() { { "alert", notification.Alert }, { NotificationConstants.NotificationID, NotificationType.GroupIm.ToString("D") }, { NotificationConstants.RoomID, notification.RName } }; switch (receiver.PnSource) { case PushNotificationSource.Default: _push.QueueNotification(new GcmNotification().ForDeviceRegistrationId(receiver.DeviceToken) .WithJson(JsonConvert.SerializeObject(payload))); break; case PushNotificationSource.Pushy: var pushyRequest = new PushyPushRequest(payload, new string[] { receiver.DeviceToken }); PushyClient.SendPush(pushyRequest); break; } } else { //do nothing } } else { throw new ApplicationException(CustomHttpStatusCode.InvalidArguments.ToString("D")); } break; #endregion } }