Exemplo n.º 1
0
        public async Task <bool> SubscribeEmail(string topicArn, string email)
        {
            //subscribe to an SNS topic
            SubscribeRequest  subscribeRequest  = new SubscribeRequest(topicArn, "email", email);
            SubscribeResponse subscribeResponse = await _sns.SubscribeAsync(subscribeRequest);

            Console.WriteLine("Subscribe RequestId: {0}", subscribeResponse.ResponseMetadata.RequestId);
            Console.WriteLine("Check your email and confirm subscription.");
            return(true);
        }
        private async void HandleRegistration(Intent intent)
        {
            string registrationId = intent.GetStringExtra("registration_id");
            string error          = intent.GetStringExtra("error");
            string unregistration = intent.GetStringExtra("unregistered");


            CognitoAWSCredentials credentials = new Authenticator().getCredentials();

            snsClient = new AmazonSimpleNotificationServiceClient(credentials, RegionEndpoint.USEast1);


            if (string.IsNullOrEmpty(error))
            {
                var response = await snsClient.CreatePlatformEndpointAsync(new CreatePlatformEndpointRequest
                {
                    Token = registrationId,
                    PlatformApplicationArn = Keys.GCMEndpointARN                     /* insert your platform application ARN here */
                });

                var endpoint = response.EndpointArn;

                var subscribeResponse = await snsClient.SubscribeAsync(new SubscribeRequest
                {
                    TopicArn = Keys.AppTopicARN,
                    Endpoint = endpoint,
                    Protocol = "application"
                });
            }
        }
        // Notify through sms (or email)
        private static void snsPublish(string contact, string message)
        {
            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient(RegionEndpoint.USEast1);
            string arn = "arn:aws:sns:xxxxxxxx:TrafficTicket";

            // subscribe user to the ticketing policy
            SubscribeRequest request = new SubscribeRequest(arn, "sms", contact); // ("sms" can be replaced by "email)
            var task = client.SubscribeAsync(request, new System.Threading.CancellationToken());

            task.Wait();

            // Publish the message
            PublishRequest p = new PublishRequest
                               (
                message: message,
                topicArn: arn
                               );
            var task2 = client.PublishAsync(p, new System.Threading.CancellationToken());

            task2.Wait();
            PublishResponse r = task2.Result;

            Console.WriteLine("PublishRequest: " + r.ResponseMetadata.RequestId);
            Console.WriteLine("Message sent succesfully.");
        }
        public override async void RegisteredForRemoteNotifications(UIApplication application, NSData token)
        {
            var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", "");

            if (!string.IsNullOrEmpty(deviceToken))
            {
                //register with SNS to create an endpoint ARN
                var response = await snsClient.CreatePlatformEndpointAsync(
                    new CreatePlatformEndpointRequest
                {
                    Token = deviceToken,
                    PlatformApplicationArn = Keys.APNSEndpointARN                     /* insert your platform application ARN here */
                });

                var endpoint = response.EndpointArn;


                var subscribeResponse = await snsClient.SubscribeAsync(new SubscribeRequest
                {
                    TopicArn = Keys.AppTopicARN,
                    Endpoint = endpoint,
                    Protocol = "application"
                });
            }
        }
Exemplo n.º 5
0
        public static async Task CreateEmailSubscription(string topicArn, string emailAddress)
        {
            using (var client = new AmazonSimpleNotificationServiceClient(ConfigManager.ConfigSettings.AccessKey, ConfigManager.ConfigSettings.Secret, Amazon.RegionEndpoint.USWest2))
            {
                var request = new SubscribeRequest(topicArn, "email", emailAddress);

                await client.SubscribeAsync(request);
            }
        }
        public async System.Threading.Tasks.Task <SubscribeResponse> SubscribeToTopic(string topicArn, string emailAddress)
        {
            SubscribeResponse subscribeResponse = new SubscribeResponse();

            using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(credentials, Amazon.RegionEndpoint.USEast2))
            {
                SubscribeRequest subscribeRequest = new SubscribeRequest(topicArn, "email", emailAddress);
                subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest);
            }

            return(subscribeResponse);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Subscribe(string email)
        {
            var clientSNS         = new AmazonSimpleNotificationServiceClient(_awsAccessKeySNS, _awsSecretKeySNS, Amazon.RegionEndpoint.USEast1);
            var subscribeResponse = await clientSNS.SubscribeAsync(new SubscribeRequest(_topic, "email", email));

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

            return(Ok());
        }
Exemplo n.º 8
0
        public async System.Threading.Tasks.Task SubscribeAsync()
        {
            AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(RegionEndpoint.APSoutheast1);

            string topicArn = "";

            // Subscribe an email endpoint to an Amazon SNS topic.
            SubscribeRequest  subscribeRequest  = new SubscribeRequest(topicArn, "email", "*****@*****.**");
            SubscribeResponse subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest);

            // Print the request ID for the SubscribeRequest action.
            Console.WriteLine("SubscribeRequest: " + subscribeResponse.ResponseMetadata.RequestId);
            Console.WriteLine("To confirm the subscription, check your email.");
        }
Exemplo n.º 9
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.º 10
0
        private static async Task SetupAws()
        {
            try
            {
                Environment.SetEnvironmentVariable("AWS_ACCESS_KEY_ID", "XXX", EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("AWS_SECRET_ACCESS_KEY", "XXX", EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("AWS_SESSION_TOKEN", "XXX", EnvironmentVariableTarget.Process);
                Environment.SetEnvironmentVariable("AWS_DEFAULT_REGION", "us-east-1", EnvironmentVariableTarget.Process);

                var snsClient = new AmazonSimpleNotificationServiceClient(new AmazonSimpleNotificationServiceConfig
                {
                    ServiceURL = "http://localhost:4575"
                });

                var sqsClient = new AmazonSQSClient(new AmazonSQSConfig
                {
                    ServiceURL = "http://localhost:4576"
                });

                var topicName = topic.Replace(".", "_");

                var topicRequest  = new CreateTopicRequest(topicName);
                var topicResponse = await snsClient.CreateTopicAsync(topicRequest);

                var queueRequest  = new CreateQueueRequest($"{topicName}.queue");
                var queueResponse = await sqsClient.CreateQueueAsync(queueRequest);

                var subscribeRequest = new SubscribeRequest
                {
                    Endpoint = queueResponse.QueueUrl,
                    TopicArn = topicResponse.TopicArn,
                    Protocol = "sqs",
                    ReturnSubscriptionArn = true,
                    Attributes            = new Dictionary <string, string>
                    {
                        ["RawMessageDelivery"] = "true"
                    }
                };
                var subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest);

                (await snsClient.ListTopicsAsync()).Topics.ForEach(x => Console.WriteLine($"[AWS] Topic: {x.TopicArn}"));
                (await sqsClient.ListQueuesAsync(new ListQueuesRequest())).QueueUrls.ForEach(x => Console.WriteLine($"[AWS] Queue: {x}"));
                (await snsClient.ListSubscriptionsAsync(new ListSubscriptionsRequest())).Subscriptions.ForEach(x => Console.WriteLine($"[AWS] Subscription: {x.TopicArn} -> {x.Endpoint}"));
            }
            catch (Exception e)
            {
                Console.WriteLine($"[AWS] {e.Message}");
            }
        }
        public async System.Threading.Tasks.Task <SubscribeResponse> SubscribeToSQS(string topicARN, string sqsArn, string queueUrl)
        {
            // subcriber SNS to a SQS
            SubscribeResponse subscriptionResponse = new SubscribeResponse();

            using (AmazonSimpleNotificationServiceClient snsClient = new AmazonSimpleNotificationServiceClient(credentials, Amazon.RegionEndpoint.USEast2))
            {
                SubscribeRequest request = new SubscribeRequest()
                {
                    TopicArn = topicARN,
                    Endpoint = sqsArn,
                    Protocol = "sqs"
                };

                subscriptionResponse = await snsClient.SubscribeAsync(request);
            }

            return(subscriptionResponse);
        }
Exemplo n.º 12
0
        private void CreateTopicsAndQueues()
        {
            var topicAndQueueName = $"toll-amount-threshold-breached-{Guid.NewGuid().ToString().Substring(0,8)}";

            var createTopicResponse = _snsClient.CreateTopicAsync(new CreateTopicRequest {
                Name = topicAndQueueName
            }).Result;
            var createQueueResponse = _sqsClient.CreateQueueAsync(new CreateQueueRequest {
                QueueName = topicAndQueueName
            }).Result;

            TopicArn = createTopicResponse.TopicArn;
            QueueUrl = createQueueResponse.QueueUrl;

            var subscriptionArn = _snsClient.SubscribeAsync(new SubscribeRequest {
                TopicArn = createTopicResponse.TopicArn, Endpoint = createQueueResponse.QueueUrl, Protocol = "sqs"
            }).Result;
            var r = _snsClient.SetSubscriptionAttributesAsync(subscriptionArn.SubscriptionArn, "RawMessageDelivery", "true").Result;
        }
Exemplo n.º 13
0
        public async Task <ISubscription> SubscribeAsync(String topic)
        {
            var amazonTopic = await amazonSnsClient.CreateTopicAsync(new CreateTopicRequest()
            {
                Name = topic
            });

            var queue = await amazonSqsClient.CreateQueueAsync(new CreateQueueRequest()
            {
                QueueName = Guid.NewGuid().ToString()
            });

            var queueAttributes = await amazonSqsClient.GetQueueAttributesAsync(new GetQueueAttributesRequest()
            {
                AttributeNames = new List <String>(new String[] { "QueueArn" }),
                QueueUrl       = queue.QueueUrl
            });

            var policy = new Policy()
                         .WithStatements(
                new Statement(Statement.StatementEffect.Allow)
                .WithPrincipals(Principal.AllUsers)
                .WithConditions(ConditionFactory.NewSourceArnCondition(amazonTopic.TopicArn))
                .WithResources(new Resource(queueAttributes.QueueARN))
                .WithActionIdentifiers(SQSActionIdentifiers.SendMessage));

            await amazonSqsClient.SetQueueAttributesAsync(queue.QueueUrl, new Dictionary <String, String>()
            {
                ["Policy"] = policy.ToJson()
            });

            await amazonSnsClient.SubscribeAsync(new SubscribeRequest()
            {
                Endpoint = queueAttributes.QueueARN,
                Protocol = "sqs",
                TopicArn = amazonTopic.TopicArn
            });

            var subscription = amazonSubscriptionFactory.Create(queue.QueueUrl);

            return(subscription);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> AddUserByEmail([FromBody] AddUserDto model)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(NotFound());
            }
            _dbContext.UserClass.Add(new UserClass()
            {
                ApplicationUserId = user.Id, ClassRoomId = model.ClassRoomId
            });
            _dbContext.SaveChanges();

            AmazonSimpleNotificationServiceClient client = new AmazonSimpleNotificationServiceClient("AKIAJLAJIOHNR4Q2EQSQ", "+5t2ISSTpRYQnZomhd+C4S9LqQ8YiRqKjV1YRHLM", Amazon.RegionEndpoint.USWest2);
            var topicArn = await client.CreateTopicAsync(new CreateTopicRequest(model.ClassRoomId.ToString()));

            await client.SubscribeAsync(new SubscribeRequest(topicArn.TopicArn, "email", model.Email));

            return(Json("All good bro!"));
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Subscribe(RegisterViewModel registerViewModel)
        {
            var emailAddress = registerViewModel.Email;
            var sns          = new AmazonSimpleNotificationServiceClient();

            if (!string.IsNullOrEmpty(emailAddress))
            {
                var listTopicsRequest = new ListTopicsRequest();
                ListTopicsResponse listTopicsResponse;

                listTopicsResponse = await sns.ListTopicsAsync(listTopicsRequest);

                var selectedTopic = listTopicsResponse.Topics.FirstOrDefault();


                await sns.SubscribeAsync(new SubscribeRequest
                {
                    TopicArn = selectedTopic.TopicArn,
                    Protocol = "email",
                    Endpoint = emailAddress
                });
            }
            return(View("Index"));
        }
Exemplo n.º 16
0
 private async Task SubscribeQueueToTopic()
 {
     var subscribeRequest = new SubscribeRequest(topicArn, "sqs", queueUrl);
     await snsClient.SubscribeAsync(subscribeRequest);
 }
Exemplo n.º 17
0
 private async Task SubscribeMessage()
 {
     var subscribeRequest  = new SubscribeRequest(topicArn, "email", "*****@*****.**");
     var subscribeResponse = await snsClient.SubscribeAsync(subscribeRequest);
 }
Exemplo n.º 18
0
        public static async Task SetupAsync(IWebApi webApi, string topicArn, string endPoint, string bucketName, Func <string, string, string[], Task <string> > handler)
        {
            if (!string.IsNullOrEmpty(endPoint))
            {
                Uri endPointUri = new Uri(endPoint);
                //logger.Debug($"SetupWebApi():endPointUri.PathAndQuery={endPointUri.PathAndQuery}");

                using (AmazonSimpleNotificationServiceClient amazonSimpleNotificationServiceClient = new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.USEast1)) {
                    SubscribeResponse subscribeResponse = await amazonSimpleNotificationServiceClient.SubscribeAsync(new SubscribeRequest {
                        TopicArn = topicArn,
                        Protocol = endPointUri.Scheme,
                        Endpoint = endPoint
                    });
                }

                AmazonS3Client amazonS3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1);

                webApi.OnPost(
                    endPointUri.PathAndQuery,
                    async(req, res) => {
                    logger.Debug($"{endPointUri.PathAndQuery}");
                    Dict evt = await req.ParseAsJsonAsync <Dict>();
                    logger.Debug($"{endPointUri.PathAndQuery},evt=" + JsonUtil.Serialize(evt));
                    string type = evt.GetAs("Type", (string)null);
                    if (type == "SubscriptionConfirmation")
                    {
                        string subscribeUrl = evt.GetAs("SubscribeURL", (string)null);
                        using (WebClient webClient = new WebClient()) {
                            string result = await webClient.DownloadStringTaskAsync(new Uri(subscribeUrl));
                            logger.Debug($"{endPointUri.PathAndQuery},result=" + result);
                        }
                    }
                    else if (type == "Notification")
                    {
                        //string messageId = evt.GetAs("MessageId", (string)null);
                        string messageJson = evt.GetAs("Message", (string)null);
                        logger.Debug($"{endPointUri.PathAndQuery},messageJson={messageJson}");

                        Dict message = JsonUtil.Deserialize <Dict>(messageJson);
                        Dict mail    = message.GetAs("mail", (Dict)null);

                        Dict[] headers       = mail.GetAs("headers", (Dict[])null);
                        Dict inReplyToHeader = Array.Find(headers, x => x.GetAs("name", "") == "In-Reply-To");
                        string inReplyTo     = inReplyToHeader.GetAs("value", "");
                        logger.Debug($"{endPointUri.PathAndQuery},inReplyTo={inReplyTo}");
                        Match match = IN_REPLY_TO_REGEX.Match(inReplyTo);
                        if (match.Success)
                        {
                            string sentMessageId = match.Groups[1].Value;
                            string bucketKey     = mail.GetAs("messageId", (string)null);
                            logger.Debug($"{endPointUri.PathAndQuery},sentMessageId={sentMessageId},bucketKey={bucketKey}");
                            if (!string.IsNullOrEmpty(bucketKey))
                            {
                                GetObjectResponse getObjectResponse = await amazonS3Client.GetObjectAsync(new GetObjectRequest {
                                    BucketName = bucketName,
                                    Key        = bucketKey
                                });
                                logger.Debug($"{endPointUri.PathAndQuery},getObjectResponse={getObjectResponse}");

                                MimeMessage mimeMessage = await MimeMessage.LoadAsync(getObjectResponse.ResponseStream);
                                logger.Debug($"{endPointUri.PathAndQuery},mimeMessage={mimeMessage}");

                                await handler(sentMessageId, mimeMessage.TextBody, new string[] { });
                            }
                        }
                    }
                }
                    );
            }
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        public void MonitorEmail(string emailaddr)
        {
            if (Exists(emailaddr) && !monitors.ContainsKey(emailaddr))
            {
                FastEmailMailbox mbx     = Mailboxes[emailaddr];
                FastEmailMonitor monitor = new FastEmailMonitor();
                monitor.mbx           = mbx;
                monitor.sqsqueue_name = mbx.S3Bucket + "-" + Process.GetCurrentProcess().Id + "-" + System.Environment.MachineName;
                create_sqsclient();
                try
                {
                    // create the queue
                    var sqscreateresponse = sqsclient.CreateQueueAsync(new CreateQueueRequest
                    {
                        QueueName = monitor.sqsqueue_name
                    });

                    CreateQueueResponse sqsresult = sqscreateresponse.Result;
                    monitor.sqsqueue_url = sqsresult.QueueUrl;
                }
                catch (AmazonSQSException e)
                {
                    Console.WriteLine("Exception while creating SQS Queue for {0}: {1}", emailaddr, e.Message);
                }

                // get the queue arn
                try
                {
                    List <string> attr = new List <string>()
                    {
                        "QueueArn"
                    };
                    var sqsattrresponse = sqsclient.GetQueueAttributesAsync(new GetQueueAttributesRequest
                    {
                        QueueUrl       = monitor.sqsqueue_url,
                        AttributeNames = attr
                    });
                    GetQueueAttributesResponse sqsresponse = sqsattrresponse.Result;
                    monitor.sqsqueue_arn = sqsresponse.QueueARN;
                }
                catch (AmazonSQSException e)
                {
                    Console.WriteLine("Exception while getting QueueARN SQS Queue for {0}: {1}", emailaddr, e.Message);
                }

                // add permission
                string perm = @"{
                ""Version"":""2012-10-17"",
                ""Statement"":[
                {
                    ""Sid"":""Policy-"
                              + monitor.mbx.TopicArn;
                perm += @""", 
                ""Effect"":""Allow"", 
                ""Principal"":""*"",
                ""Action"":""sqs:SendMessage"",
                ""Resource"":"""
                        + monitor.sqsqueue_arn;
                perm += @""", 
                ""Condition"":{ 
                    ""ArnEquals"":{
                        ""aws:SourceArn"":"""
                        + monitor.mbx.TopicArn;
                perm += @""" 
                                }
                            }
                        }
                    ]
                }";
                var policy = new Dictionary <string, string>();
                policy.Add("Policy", perm);
                try
                {
                    var qsattrrequest = sqsclient.SetQueueAttributesAsync(new SetQueueAttributesRequest
                    {
                        QueueUrl   = monitor.sqsqueue_url,
                        Attributes = policy
                    });
                    var qsattrresponse = qsattrrequest.Result;
                }
                catch (AmazonSQSException e)
                {
                    Console.WriteLine("Exception while adding permission policy to queue for {0}: {1}", emailaddr, e.Message);
                }
                create_snsclient();
                try
                {
                    var snsresponse = snsclient.SubscribeAsync(new SubscribeRequest
                    {
                        Protocol = "sqs",
                        Endpoint = monitor.sqsqueue_arn,
                        TopicArn = monitor.mbx.TopicArn
                    });
                    var subresult = snsresponse.Result;
                    monitor.subscription_arn = subresult.SubscriptionArn;
                }
                catch (AmazonSimpleNotificationServiceException e)
                {
                    Console.WriteLine("Exception while subscribing to queue for {0}: {1}", emailaddr, e.Message);
                }

                monitors.Add(emailaddr, monitor);
            }
        }
Exemplo n.º 21
0
        private static async Task <Topic> SetupTopicAndSubscriptionsAsync(string topicFileName, string outputDirectory, string regionSystemName, string archiveId = null, string filename = null)
        {
            var topic = new Topic
            {
                TopicFileName   = topicFileName,
                OutputDirectory = outputDirectory,
                ArchiveId       = archiveId,
                FileName        = filename,
                DateRequested   = DateTime.Now
            };
            long ticks    = DateTime.Now.Ticks;
            var  settings = GetSettingsAsync().Result;

            #region Setup SNS topic
            var snsClient = new AmazonSimpleNotificationServiceClient(
                settings.AWSAccessKeyID,
                settings.AWSSecretAccessKey,
                RegionEndpoint.GetBySystemName(regionSystemName));

            var sqsClient = new AmazonSQSClient(
                settings.AWSAccessKeyID,
                settings.AWSSecretAccessKey,
                RegionEndpoint.GetBySystemName(regionSystemName));

            var topicArn = snsClient.CreateTopicAsync(new CreateTopicRequest {
                Name = "GlacierDownload-" + ticks
            }).Result.TopicArn;
            //Debug.WriteLine($"topicArn: {topicArn}");
            topic.TopicARN = topicArn;
            #endregion

            #region Setup SQS queue
            var createQueueRequest = new CreateQueueRequest {
                QueueName = "GlacierDownload-" + ticks
            };
            var createQueueResponse = sqsClient.CreateQueueAsync(createQueueRequest).Result;
            var queueUrl            = createQueueResponse.QueueUrl;
            //Debug.WriteLine($"QueueURL: {queueUrl}");
            topic.QueueUrl = queueUrl;

            var getQueueAttributesRequest = new GetQueueAttributesRequest
            {
                AttributeNames = new List <string> {
                    "QueueArn"
                },
                QueueUrl = queueUrl
            };
            var response = await sqsClient.GetQueueAttributesAsync(getQueueAttributesRequest);

            var queueArn = response.QueueARN;
            Debug.WriteLine($"QueueArn: {queueArn}");
            topic.QueueARN = queueArn;
            #endregion

            // Setup the Amazon SNS topic to publish to the SQS queue.
            // TODO SMS subscription
            await snsClient.SubscribeAsync(new SubscribeRequest()
            {
                Protocol = "sqs",
                Endpoint = queueArn,
                TopicArn = topicArn
            });

            // Add the policy to the queue so SNS can send messages to the queue.
            var policy = SQS_POLICY.Replace("{TopicArn}", topicArn).Replace("{QuernArn}", queueArn);

            await sqsClient.SetQueueAttributesAsync(new SetQueueAttributesRequest
            {
                QueueUrl   = queueUrl,
                Attributes = new Dictionary <string, string>
                {
                    { QueueAttributeName.Policy, policy }
                }
            });

            return(topic);
        }