Exemplo n.º 1
0
        public void UnmonitorEmail(string emailaddr)
        {
            if (monitors.ContainsKey(emailaddr))
            {
                var monitor = monitors[emailaddr];
                try
                {
                    var unsubresponse = snsclient.UnsubscribeAsync(new UnsubscribeRequest
                    {
                        SubscriptionArn = monitor.subscription_arn
                    });
                    var unsubresult = unsubresponse.Result;
                }
                catch (AmazonSimpleNotificationServiceException e)
                {
                    Console.WriteLine("Unable to unsubscripe topic for {0}: {1}", emailaddr, e.Message);
                }
                try
                {
                    var sqsresponse = sqsclient.DeleteQueueAsync(new DeleteQueueRequest
                    {
                        QueueUrl = monitor.sqsqueue_url
                    });

                    DeleteQueueResponse sqsresult = sqsresponse.Result;
                }
                catch (AmazonSQSException e)
                {
                    Console.WriteLine("Unable to delete queue for {0}: {1}", emailaddr, e.Message);
                }
            }
        }
Exemplo n.º 2
0
        public static async Task UnsubscribeQueue(string subscriptionArn)
        {
            using var sqs = new AmazonSQSClient(Credentials);
            using var sns = new AmazonSimpleNotificationServiceClient(Credentials);

            await sns.UnsubscribeAsync(subscriptionArn);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> Unsubscribe(string arn)
        {
            var clientSNS           = new AmazonSimpleNotificationServiceClient(_awsAccessKeySNS, _awsSecretKeySNS, Amazon.RegionEndpoint.USEast1);
            var unsubscribeResponse = await clientSNS.UnsubscribeAsync(new UnsubscribeRequest(arn));

            if (unsubscribeResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                throw new Exception("Topic unsubscription falied");
            }

            return(Ok());
        }
        public async System.Threading.Tasks.Task <UnsubscribeResponse> Unsubcribe(string subscriptionArn)
        {
            UnsubscribeResponse unsubscribeResponse = new UnsubscribeResponse();

            using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(credentials, Amazon.RegionEndpoint.USEast2))
            {
                UnsubscribeRequest unsubscribeRequest = new UnsubscribeRequest(subscriptionArn);
                unsubscribeResponse = await snsClient.UnsubscribeAsync(unsubscribeRequest);
            }

            return(unsubscribeResponse);
        }
Exemplo n.º 5
0
        private static async Task Cleanup(AmazonSQSClient sqsClient, AmazonSimpleNotificationServiceClient snsClient, List <Task <string> > subscribeTask, string topic1Arn, string topic2Arn, string queueUrl)
        {
            foreach (var task in subscribeTask)
            {
                await snsClient.UnsubscribeAsync(task.Result);
            }

            await snsClient.DeleteTopicAsync(topic1Arn);

            await snsClient.DeleteTopicAsync(topic2Arn);

            await sqsClient.DeleteQueueAsync(queueUrl);
        }
Exemplo n.º 6
0
        public async System.Threading.Tasks.Task UnsubscribeAsync()
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint.APSoutheast1);

            string topicArn = "";

            // Delete an Amazon SNS topic.
            UnsubscribeRequest  unsubscribeRequest  = new UnsubscribeRequest(topicArn);
            UnsubscribeResponse unsubscribeResponse = await snsClient.UnsubscribeAsync(unsubscribeRequest);

            // Print the request ID for the DeleteTopicRequest action.
            Console.WriteLine("UnsubscribeRequest: " + unsubscribeResponse.ResponseMetadata.RequestId);
        }
Exemplo n.º 7
0
        static async Task <Func <Task> > Subscribe(AmazonSimpleNotificationServiceClient snsClient,
                                                   string functionArn,
                                                   string topicArn,
                                                   CancellationToken cancellationToken)
        {
            var subscription = await snsClient.SubscribeAsync(new SubscribeRequest
            {
                Endpoint = functionArn,
                Protocol = "lambda",
                TopicArn = topicArn
            }, cancellationToken);

            return(async() => await snsClient.UnsubscribeAsync(subscription.SubscriptionArn));
        }
Exemplo n.º 8
0
        private void UnsubscribeFromTopic(AmazonSimpleNotificationServiceClient snsClient)
        {
            ListSubscriptionsByTopicResponse response;

            do
            {
                response = snsClient.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest {
                    TopicArn = _channelTopicArn
                }).GetAwaiter().GetResult();
                foreach (var sub in response.Subscriptions)
                {
                    var unsubscribe = snsClient.UnsubscribeAsync(new UnsubscribeRequest {
                        SubscriptionArn = sub.SubscriptionArn
                    }).GetAwaiter().GetResult();
                    if (unsubscribe.HttpStatusCode != HttpStatusCode.OK)
                    {
                        s_logger.LogError("Error unsubscribing from {TopicResourceName} for sub {ChannelResourceName}", _channelTopicArn, sub.SubscriptionArn);
                    }
                }
            } while (response.NextToken != null);
        }
Exemplo n.º 9
0
        public void DeleteTopic()
        {
            if (_connection == null)
            {
                return;
            }

            using (var snsClient = new AmazonSimpleNotificationServiceClient(_awsConnection.Credentials, _awsConnection.Region))
            {
                //TODO: could be a seperate method
                var exists = snsClient.ListTopicsAsync().Result.Topics.SingleOrDefault(topic => topic.TopicArn == _channelTopicARN);
                if (exists != null)
                {
                    try
                    {
                        var response = snsClient.ListSubscriptionsByTopicAsync(new ListSubscriptionsByTopicRequest {
                            TopicArn = _channelTopicARN
                        }).Result;
                        foreach (var sub in response.Subscriptions)
                        {
                            var unsubscribe = snsClient.UnsubscribeAsync(new UnsubscribeRequest {
                                SubscriptionArn = sub.SubscriptionArn
                            }).Result;
                            if (unsubscribe.HttpStatusCode != HttpStatusCode.OK)
                            {
                                _logger.Value.Error($"Error unsubscribing from {_channelTopicARN} for sub {sub.SubscriptionArn}");
                            }
                        }

                        snsClient.DeleteTopicAsync(_channelTopicARN).Wait();
                    }
                    catch (Exception)
                    {
                        //don't break on an exception here, if we can't delete, just exit
                        _logger.Value.Error($"Could not delete topic {_channelTopicARN}");
                    }
                }
            }
        }
        public void DeleteAllTopics()
        {
            AmazonSimpleNotificationServiceClient clientSNS = AwsFactory.CreateClient <AmazonSimpleNotificationServiceClient>();
            AmazonSQSClient    clientSQS    = AwsFactory.CreateClient <AmazonSQSClient>();
            AmazonLambdaClient lambdaClient = AwsFactory.CreateClient <AmazonLambdaClient>();


            var topics = clientSNS.ListTopicsAsync();
            // var subs = clientSNS.ListSubscriptionsAsync(new ListSubscriptionsRequest());
            var filas = clientSQS.ListQueuesAsync("subs");

            filas.Result.QueueUrls.ForEach(i =>
            {
                var deleted = clientSQS.DeleteQueueAsync(i);
                if (deleted.Result.HttpStatusCode != HttpStatusCode.OK)
                {
                    int x = 0;
                }
            });

            string nextToken = "";

            do
            {
                var subs = clientSNS.ListSubscriptionsAsync(new ListSubscriptionsRequest(nextToken));

                subs.Result.Subscriptions.ForEach(i =>
                {
                    var deleted = clientSNS.UnsubscribeAsync(i.SubscriptionArn);
                });

                nextToken = subs.Result.NextToken;
            } while (!String.IsNullOrEmpty(nextToken));



            var mapper = lambdaClient.ListEventSourceMappingsAsync(new Amazon.Lambda.Model.ListEventSourceMappingsRequest
            {
                FunctionName = "WebhookDispatcher"
            });

            mapper.Result.EventSourceMappings.ToList().ForEach(i =>
            {
                var result = lambdaClient.DeleteEventSourceMappingAsync(new Amazon.Lambda.Model.DeleteEventSourceMappingRequest()
                {
                    UUID = i.UUID
                });
                if (result.Result.HttpStatusCode != HttpStatusCode.OK)
                {
                    int x = 0;
                }
            });


            topics.Result.Topics.ForEach(i =>
            {
                var deleted = clientSNS.DeleteTopicAsync(new DeleteTopicRequest()
                {
                    TopicArn = i.TopicArn
                });
            });
        }
Exemplo n.º 11
0
        public async Task RegisterUserNotifications()
        {
            string deviceToken = GetDeviceToken();

            var notificationsSubscriptions = GetNotificationsSubscriptions();

            if (string.IsNullOrEmpty(deviceToken))
            {
                return;
            }

            var credentials = new BasicAWSCredentials(
                AppSettings.Instance.AwsKey,
                AppSettings.Instance.AwsSecret
                );

            var client = new AmazonSimpleNotificationServiceClient(
                credentials,
                Amazon.RegionEndpoint.EUWest1
                );

            if (string.IsNullOrEmpty(notificationsSubscriptions.ApplicationEndPoint) ||
                notificationsSubscriptions.DeviceToken != deviceToken)
            {
                // **********************************************
                // de-register old endpoint and all subscriptions
                if (!string.IsNullOrEmpty(notificationsSubscriptions.ApplicationEndPoint))
                {
                    try
                    {
                        var response = await client.DeleteEndpointAsync(new DeleteEndpointRequest { EndpointArn = notificationsSubscriptions.ApplicationEndPoint });

                        if (response.HttpStatusCode != System.Net.HttpStatusCode.OK)
                        {
                            ShowAlert("Debug", $"Error eliminando endpoint: {response.HttpStatusCode}");
                        }
                    }
                    catch { /*Silent error in case endpoint doesn´t exist */ }

                    notificationsSubscriptions.ApplicationEndPoint = null;

                    foreach (var sub in notificationsSubscriptions.Subscriptions)
                    {
                        try
                        {
                            await client.UnsubscribeAsync(sub.Value);
                        }
                        catch { /*Silent error in case endpoint doesn´t exist */ }
                    }

                    notificationsSubscriptions.Subscriptions.Clear();
                }

                // register with SNS to create a new endpoint
                var endPointResponse = await client.CreatePlatformEndpointAsync(
                    new CreatePlatformEndpointRequest
                {
                    Token = deviceToken,
                    PlatformApplicationArn = Device.RuntimePlatform == Device.iOS ?
                                             AppSettings.Instance.AwsPlatformApplicationArnIOS :
                                             AppSettings.Instance.AwsPlatformApplicationArnAndroid
                }
                    );

                if (endPointResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                {
                    ShowAlert("Debug", $"Error registrando endpoint: {endPointResponse.HttpStatusCode}, {endPointResponse.ResponseMetadata}");
                }

                // Save device token and application endpoint created
                notificationsSubscriptions.DeviceToken         = deviceToken;
                notificationsSubscriptions.ApplicationEndPoint = endPointResponse.EndpointArn;
            }

            // Retrieve subscriptions
            var subscriptions = await AudioLibrary.Instance.GetUserSubscriptions(false);

            if (subscriptions == null)
            {
                subscriptions = new UserSubscriptions {
                    Subscriptions = new List <Models.Api.Subscription>()
                }
            }
            ;

            // Register non existings subscriptions
            var subscriptionsCodes = subscriptions.Subscriptions.Select(s => s.Code).ToList();

            foreach (var code in subscriptionsCodes)
            {
                if (!notificationsSubscriptions.Subscriptions.ContainsKey(code))
                {
                    var topicArn = AppSettings.Instance.AwsTopicArn;
                    topicArn += string.IsNullOrEmpty(code) ? "" : $"-{code}";

                    if (!await TopicExists(topicArn, client))
                    {
                        var topicResponse = await client.CreateTopicAsync(new CreateTopicRequest { Name = $"{AppSettings.Instance.AwsTopicName}-{code}" });

                        if (topicResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                        {
                            ShowAlert("Debug", $"Error creando topic: {topicResponse.HttpStatusCode}, {topicResponse.ResponseMetadata}");
                        }

                        topicArn = topicResponse.TopicArn;
                    }


                    // Subscribe
                    var subscribeResponse = await client.SubscribeAsync(new SubscribeRequest
                    {
                        Protocol = "application",
                        Endpoint = notificationsSubscriptions.ApplicationEndPoint,
                        TopicArn = topicArn
                    });

                    if (subscribeResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
                    {
                        ShowAlert("Debug", $"Error creando suscripción: {subscribeResponse.HttpStatusCode}, {subscribeResponse.ResponseMetadata}");
                    }

                    // Add to the list
                    notificationsSubscriptions.Subscriptions.Add(code, subscribeResponse.SubscriptionArn);
                }
            }

            // Remove subscriptions not in user list
            var currentSubscriptions = notificationsSubscriptions.Subscriptions.ToList();

            foreach (var subs in currentSubscriptions)
            {
                if (!subscriptionsCodes.Contains(subs.Key))
                {
                    try
                    {
                        await client.UnsubscribeAsync(subs.Value);
                    }
                    catch { /*Silent error in case endpoint doesn´t exist */ }

                    notificationsSubscriptions.Subscriptions.Remove(subs.Key);
                }
            }

            // Save notifications subscriptions
            await SaveNotificationsSubscriptions(notificationsSubscriptions);
        }
        public string Remove(Notification input, ILambdaContext context)
        {
            var region = RegionEndpoint.APSoutheast1;

            var topicId = input.TopicId;

            //Get item from DynamoDB
            var key = new Dictionary <string, AttributeValue>();

            key.Add("id", new AttributeValue()
            {
                S = topicId
            });

            var dynamoDBClient  = new AmazonDynamoDBClient(region);
            var getItemResponse = dynamoDBClient.GetItemAsync("Topics", key).Result;

            if (getItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't find item");
            }

            var item = getItemResponse.Item;

            var topicArn = item.GetValueOrDefault("arn").S;

            //Remove permission to accept CloudWatch Events trigger for Lambda
            var lambdaClient = new AmazonLambdaClient(region);

            var removePermissionRequest = new Amazon.Lambda.Model.RemovePermissionRequest();

            removePermissionRequest.FunctionName = "TestDonkeyLambda";
            removePermissionRequest.StatementId  = $"testdonkey-lambda-{ topicId }";

            var removePermissionResponse = lambdaClient.RemovePermissionAsync(removePermissionRequest).Result;

            if (removePermissionResponse.HttpStatusCode != HttpStatusCode.NoContent)
            {
                throw new TestDonkeyException("Can't remove permission");
            }

            //Remove target for CloudWatch Events
            var cloudWatchEventClient = new AmazonCloudWatchEventsClient(region);

            var removeTargetsRequest = new RemoveTargetsRequest();

            removeTargetsRequest.Ids = new List <string> {
                $"testdonkey-target-{ topicId }"
            };
            removeTargetsRequest.Rule = $"testdonkey-rule-{ topicId }";

            var removeTargetsResponse = cloudWatchEventClient.RemoveTargetsAsync(removeTargetsRequest).Result;

            if (removeTargetsResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't remove target");
            }

            //Delete rule in CloudWatch Events
            var deleteRuleRequest = new DeleteRuleRequest();

            deleteRuleRequest.Name = removeTargetsRequest.Rule;

            var deleteRuleResponse = cloudWatchEventClient.DeleteRuleAsync(deleteRuleRequest).Result;

            if (deleteRuleResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete rule");
            }

            //Remove subscribers from SNS
            var snsClient = new AmazonSimpleNotificationServiceClient(region);

            var listSubscriptionsByTopicRequest = new ListSubscriptionsByTopicRequest();

            listSubscriptionsByTopicRequest.TopicArn = topicArn;

            ListSubscriptionsByTopicResponse listSubscriptionsByTopicResponse = null;

            do
            {
                listSubscriptionsByTopicResponse = snsClient.ListSubscriptionsByTopicAsync(listSubscriptionsByTopicRequest).Result;
                if (listSubscriptionsByTopicResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    throw new TestDonkeyException("Can't list subscriptions");
                }

                if (listSubscriptionsByTopicResponse.Subscriptions != null && listSubscriptionsByTopicResponse.Subscriptions.Count > 0)
                {
                    foreach (var subscription in listSubscriptionsByTopicResponse.Subscriptions)
                    {
                        if (!subscription.SubscriptionArn.Equals("pendingconfirmation", StringComparison.OrdinalIgnoreCase))
                        {
                            snsClient.UnsubscribeAsync(subscription.SubscriptionArn).GetAwaiter().GetResult();
                        }
                    }
                }

                listSubscriptionsByTopicRequest.NextToken = listSubscriptionsByTopicResponse.NextToken;

                Thread.Sleep(1_000); //Wait for 1 second. Throttle: 100 transactions per second (TPS)
            } while (!string.IsNullOrWhiteSpace(listSubscriptionsByTopicResponse.NextToken));

            //Delete topic from SNS
            var deleteTopicResponse = snsClient.DeleteTopicAsync(topicArn).Result;

            if (deleteTopicResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete topic");
            }

            //Delete item from DynamoDB
            var dynamoDBDeleteItemResponse = dynamoDBClient.DeleteItemAsync("Topics", key).Result;

            if (dynamoDBDeleteItemResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                throw new TestDonkeyException("Can't delete item");
            }

            return("success");
        }