public SubscriptionInfo GetOrSubscribe(string topicArn)
{
SubscriptionInfo item;
lock (_ConfirmedSubscriptions) {
item = _ConfirmedSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
if (item is object)
{
return(item);
}
}
lock (_LocalPendingSubscriptions) {
item = _LocalPendingSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault();
if (item is object)
{
//orphaned - usually is takes only a few seconds until a subscription is confirmed!
if (item.Initiated.AddSeconds(30) < DateTime.Now)
{
//just remoce thie item, becasue a new one will be created below...
_LocalPendingSubscriptions.Remove(item);
}
return(item);
}
#if DEBUG
if (SuppressSubscriptionDevmode)
{
item = new SubscriptionInfo(this, topicArn, "<dummy>", false); //simulate already confirmed subscription
_LocalPendingSubscriptions.Add(item);
return(item);
}
#endif
try {
using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) {
Task <SubscribeResponse> t;
if (this.SubscriptionCallbackUrl.StartsWith("https:"))
{
t = client.SubscribeAsync(topicArn, "https", this.SubscriptionCallbackUrl);
}
else
{
t = client.SubscribeAsync(topicArn, "http", this.SubscriptionCallbackUrl);
}
t.Wait();
if (t.IsCompleted && t.Result is object)
{
item = new SubscriptionInfo(this, topicArn, t.Result.SubscriptionArn, true);
_LocalPendingSubscriptions.Add(item);
}
else
{
if (t.Exception != null)
{
throw t.Exception;
}
else if (t.Result is object)
{
throw new Exception($"Subscribe-Task failed with Http-Status-Code: {t.Result.HttpStatusCode}!");
}
else
{
throw new Exception($"Subscribe-Task failed!");
}
}
}
}
catch (AggregateException aex) {
foreach (var subex in aex.InnerExceptions)
{
_ExceptionHandler.Invoke(subex);
}
}
catch (Exception ex) {
_ExceptionHandler.Invoke(ex);
}
}
return(item);
}