Esempio n. 1
0
        private void EnqueueAndroidNotification(Device device, PushNotification notification)
        {
            var config = PushServiceConfiguration.GetSection();

            string json = string.Format(@"{{""message"":""{0}"",""msgcnt"":""{1}"",""regid"":""{2}""", notification.Message, device.Badge, device.RegistrationID);

            if (notification.Module != PushModule.Unknown && notification.Item != null)
            {
                var itemType = notification.Item.Type;
                var itemId   = notification.Item.ID;

                if (notification.Item.Type == PushItemType.Subtask && notification.ParentItem != null)
                {
                    itemType = notification.ParentItem.Type;
                    itemId   = notification.ParentItem.ID;
                }

                json += string.Format(@",""itemid"":""{0}"",""itemtype"":""{1}""", itemId, itemType.ToString().ToLower());
            }

            json += "}";

            var gcmNotification = new GcmNotification()
                                  .ForDeviceRegistrationId(device.Token)
                                  .WithJson(json);

            if (config.IsDebug || !config.Gcm.ElementInformation.IsPresent)
            {
                _log.DebugFormat("notification ({0}) prevented from sending to device {1}", gcmNotification, device.ID);
                return;
            }

            PushBrokerProvider.Instance.QueueNotification(gcmNotification);
        }
        private static void RegisterApnsService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Apns.ElementInformation.IsPresent)
            {
                return;
            }

            try
            {
                Log.Debug("registering apns service");

                string certPath = config.Apns.CertificatePath;
                if (!Path.IsPathRooted(certPath))
                {
                    certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), certPath);
                }

                var appleCert = File.ReadAllBytes(certPath);
                pushBroker.RegisterAppleService(
                    new ApplePushChannelSettings(!config.Apns.IsDevelopmentMode, appleCert, config.Apns.CertificatePassword)
                {
                    FeedbackIntervalMinutes = config.Apns.FeedbackIntervalMinutes
                });
            }
            catch (Exception error)
            {
                Log.Error("couldn't register apns service", error);
            }
        }
        public void Start()
        {
            XmlConfigurator.Configure();

            _notificationCleaner = new NotificationCleaner(PushServiceConfiguration.GetSection().FeedLifetime);
            _notificationCleaner.Start();

            _serviceHost = new ServiceHost(typeof(PushService));
            _serviceHost.Open();
        }
        private static PushBroker CreateInstance()
        {
            Log.Info("initializing PushBroker instance");

            var config = PushServiceConfiguration.GetSection();

            var pushBroker = new PushBroker();

            SubscribeOnEvents(pushBroker, config);
            RegisterApnsService(pushBroker, config);
            RegisterGcmService(pushBroker, config);

            return(pushBroker);
        }
        private static void SubscribeOnEvents(PushBroker pushBroker, PushServiceConfiguration config)
        {
            pushBroker.OnChannelCreated += (sender, channel) => Log.DebugFormat("channel ({0}) created", channel);
            pushBroker.OnChannelDestroyed += sender => Log.Debug("channel destroyed");
            pushBroker.OnChannelException += (sender, channel, exception) => Log.ErrorFormat("channel ({0}) exception: {1}", channel, exception);
            pushBroker.OnServiceException += (sender, error) => Log.Error("service exception", error);
            pushBroker.OnNotificationRequeue += (sender, args) => Log.DebugFormat("notification ({0}) requeue: cancel = {1}", args.Notification, args.Cancel);
            pushBroker.OnNotificationSent += (sender, notification) => Log.DebugFormat("notification ({0}) sent", notification);

            pushBroker.OnNotificationFailed += (sender, notification, error) =>
                {
                    Log.ErrorFormat("notification ({0}) failed: {1}", notification, error);
                    if (error is MaxSendAttemptsReachedException)
                    {
                        if (Monitor.TryEnter(Lock))
                        {
                            try
                            {
                                if (_lastRestartTime + config.RestartInterval < DateTime.UtcNow)
                                {
                                    _instance.StopAllServices(false);
                                    _instance = null;
                                    _lastRestartTime = DateTime.UtcNow;
                                }
                            }
                            catch (Exception restartError)
                            {
                                Log.Error("can't restart service", restartError);
                            }
                            finally
                            {
                                Monitor.Exit(Lock);
                            }
                        }
                    }
                };

            pushBroker.OnDeviceSubscriptionChanged += (sender, id, subscriptionId, notification) =>
                {
                    Log.DebugFormat("device ({0}) subscription changed to {1}. notification is ({2})", id, subscriptionId, notification);
                    new DeviceDao().UpdateToken(id, subscriptionId);
                };

            pushBroker.OnDeviceSubscriptionExpired += (sender, id, utc, notification) =>
                {
                    Log.DebugFormat("device ({0}) subscription expired. notification is ({1}) and utc is ({2})", id, notification, utc);
                    new DeviceDao().Delete(id);
                };
        }
        private static void SubscribeOnEvents(PushBroker pushBroker, PushServiceConfiguration config)
        {
            pushBroker.OnChannelCreated      += (sender, channel) => Log.DebugFormat("channel ({0}) created", channel);
            pushBroker.OnChannelDestroyed    += sender => Log.Debug("channel destroyed");
            pushBroker.OnChannelException    += (sender, channel, exception) => Log.ErrorFormat("channel ({0}) exception: {1}", channel, exception);
            pushBroker.OnServiceException    += (sender, error) => Log.Error("service exception", error);
            pushBroker.OnNotificationRequeue += (sender, args) => Log.DebugFormat("notification ({0}) requeue: cancel = {1}", args.Notification, args.Cancel);
            pushBroker.OnNotificationSent    += (sender, notification) => Log.DebugFormat("notification ({0}) sent", notification);

            pushBroker.OnNotificationFailed += (sender, notification, error) =>
            {
                Log.ErrorFormat("notification ({0}) failed: {1}", notification, error);
                if (error is MaxSendAttemptsReachedException)
                {
                    if (Monitor.TryEnter(Lock))
                    {
                        try
                        {
                            if (_lastRestartTime + config.RestartInterval < DateTime.UtcNow)
                            {
                                _instance.StopAllServices(false);
                                _instance        = null;
                                _lastRestartTime = DateTime.UtcNow;
                            }
                        }
                        catch (Exception restartError)
                        {
                            Log.Error("can't restart service", restartError);
                        }
                        finally
                        {
                            Monitor.Exit(Lock);
                        }
                    }
                }
            };

            pushBroker.OnDeviceSubscriptionChanged += (sender, id, subscriptionId, notification) =>
            {
                Log.DebugFormat("device ({0}) subscription changed to {1}. notification is ({2})", id, subscriptionId, notification);
                new DeviceDao().UpdateToken(id, subscriptionId);
            };

            pushBroker.OnDeviceSubscriptionExpired += (sender, id, utc, notification) =>
            {
                Log.DebugFormat("device ({0}) subscription expired. notification is ({1}) and utc is ({2})", id, notification, utc);
                new DeviceDao().Delete(id);
            };
        }
Esempio n. 7
0
        private void EnqueueApnsNotification(Device device, PushNotification notification)
        {
            var config = PushServiceConfiguration.GetSection();

            string message = notification.Message;

            if (message != null && message.Length > config.Apns.MaxMessageLength)
            {
                message = notification.ShortMessage ?? notification.Message;
            }

            if (message != null && message.Length > config.Apns.MaxMessageLength)
            {
                _log.WarnFormat("message is larger than maximum allowed length of {0}", config.Apns.MaxMessageLength);
                return;
            }

            var apnsNotification = new AppleNotification()
                                   .ForDeviceToken(device.Token)
                                   .WithAlert(message)
                                   .WithBadge(device.Badge)
                                   .WithCustomItem("regid", device.RegistrationID);

            if (notification.Module != PushModule.Unknown && notification.Item != null)
            {
                var itemType = notification.Item.Type;
                var itemId   = notification.Item.ID;

                if (notification.Item.Type == PushItemType.Subtask && notification.ParentItem != null)
                {
                    itemType = notification.ParentItem.Type;
                    itemId   = notification.ParentItem.ID;
                }

                apnsNotification.WithCustomItem("itemid", itemId);
                apnsNotification.WithCustomItem("itemtype", itemType.ToString().ToLower());
            }

            if (config.IsDebug || !config.Apns.ElementInformation.IsPresent)
            {
                _log.DebugFormat("notification ({0}) prevented from sending to device {1}", apnsNotification, device.ID);
                return;
            }

            PushBrokerProvider.Instance.QueueNotification(apnsNotification);
        }
        private static void RegisterGcmService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Gcm.ElementInformation.IsPresent)
            {
                return;
            }

            try
            {
                Log.Debug("registering gcm service");
                pushBroker.RegisterGcmService(new GcmPushChannelSettings(config.Gcm.AuthorizationKey));
            }
            catch (Exception error)
            {
                Log.Error("couldn't register gcm service", error);
            }
        }
        private static void RegisterGcmService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Gcm.ElementInformation.IsPresent)
                return;

            try
            {
                Log.Debug("registering gcm service");
                pushBroker.RegisterGcmService(new GcmPushChannelSettings(config.Gcm.AuthorizationKey));
            }
            catch (Exception error)
            {
                Log.Error("couldn't register gcm service", error);
            }
        }
        private static void RegisterApnsService(PushBroker pushBroker, PushServiceConfiguration config)
        {
            if (!config.Apns.ElementInformation.IsPresent)
                return;

            try
            {
                Log.Debug("registering apns service");

                string certPath = config.Apns.CertificatePath;
                if (!Path.IsPathRooted(certPath))
                    certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), certPath);

                var appleCert = File.ReadAllBytes(certPath);
                pushBroker.RegisterAppleService(
                    new ApplePushChannelSettings(!config.Apns.IsDevelopmentMode, appleCert, config.Apns.CertificatePassword)
                        {
                            FeedbackIntervalMinutes = config.Apns.FeedbackIntervalMinutes
                        });
            }
            catch (Exception error)
            {
                Log.Error("couldn't register apns service", error);
            }
        }