Example #1
0
        /// <param name="results"></param>
        private async Task HandleResults(ProcessResult <DeliveryModel>[] results)
        {
            List <ProcessResult <DeliveryModel> > failures = results.Failures().ToList();
            List <DeliveryModel> successes = results.Successes().ToList();
            List <int>           invalidSubscriptionCodes = new List <int> {
                404, 410
            };

            using (IServiceScope scope = _services.CreateScope())
            {
                IServiceProvider        services               = scope.ServiceProvider;
                IDeliveryRepository     deliveryRepository     = services.GetRequiredService <IDeliveryRepository>();
                ISubscriptionRepository subscriptionRepository = services.GetRequiredService <ISubscriptionRepository>();

                List <Delivery> deliveries = await deliveryRepository.GetByKeysAsync(results.Select(x => x.ReturnValue.DeliveryKey), false);

                // handling the results
                failures.ForEach(async x =>
                {
                    if (invalidSubscriptionCodes.Contains(x.ErrorCode))
                    {
                        await subscriptionRepository.DeleteAsync(new PushSubscription()
                        {
                            SubscriptionKey = x.ReturnValue.Subscription.SubscriptionKey
                        });
                        _logger.LogDebug($"[DeliveryService] Invalid subscription {x.ReturnValue.Subscription.SubscriptionKey}. Deleted.");
                    }
                    else
                    {
                        string errMsg = $"[DeliveryService] Can't send notification [DeliveryKey: {x.ReturnValue.DeliveryKey}]";
                        errMsg       += $" for subscription {x.ReturnValue.Subscription.SubscriptionKey}. Response code: {x.ErrorCode}, Message: {x.ErrorMsg}";
                        _logger.LogError(errMsg);

                        Delivery delivery = deliveries.FirstOrDefault(e => e.DeliveryKey == x.ReturnValue.DeliveryKey);
                        if (delivery != null)
                        {
                            delivery.SetUnknownErrorStatus();
                        }
                    }
                });

                successes.ForEach(x =>
                {
                    Delivery delivery = deliveries.FirstOrDefault(e => e.DeliveryKey == x.DeliveryKey);
                    if (delivery != null)
                    {
                        delivery.SetHasBeenSentStatus();
                    }
                });

                await subscriptionRepository.UnitOfWork.SaveEntitiesAsync();

                await deliveryRepository.UnitOfWork.SaveEntitiesAsync();
            }
        }