public async Task SendNotificationAsync(WP.PushSubscription subscription, PushMessage message, string target)
        {
            _logger.LogInformation($"Sending VAPID push: {message.Content}: Image {_options.ImageUrl}");
            var sub = new WebPush.PushSubscription(
                subscription.Endpoint,
                subscription.Keys["p256dh"],
                subscription.Keys["auth"]
                );

            var vapid   = new VapidDetails(_options.Subject, _options.PublicKey, _options.PrivateKey);
            var payload = JsonConvert.SerializeObject(new {
                notification = new {
                    title        = message.Topic,
                    body         = message.Content,
                    icon         = _options.ImageUrl,
                    click_action = string.IsNullOrEmpty(target) ? _options.ClickUrl : target
                }
            });

            var client = new WebPushClient();

            try {
                _logger.LogDebug($"VAPID: Push to {subscription.Endpoint}");
                await client.SendNotificationAsync(sub, payload, vapid);
            } catch (WebPushException ex) {
                _logger.LogError($"ERROR in VAPID: {ex.Message}");
                _logger.LogError($"{subscription.Endpoint}");
            } catch (Exception ex) {
                _logger.LogError($"ERROR in VAPID: {ex.Message}");
                _logger.LogError($"{subscription.Endpoint}");
            }
        }
Пример #2
0
 public PushSubscription(WebPush.PushSubscription subscription)
 {
     Id        = GetId(subscription.Endpoint);
     Partition = PARTITION_KEY_VALUE;
     Endpoint  = subscription.Endpoint;
     Keys      = subscription.Keys;
 }
Пример #3
0
 public PushSubscription(WebPush.PushSubscription subscription, int id, string clientip)
 {
     Endpoint = subscription.Endpoint;
     Keys     = subscription.Keys;
     MemberID = id;
     clientIP = clientip;
 }
Пример #4
0
        public void SendNotification(Facets.PushSubscription subscription, string message, string publicKey, string privateKey)
        {
            var webSubscription = new Lib.Net.Http.WebPush.PushSubscription();

            webSubscription.Endpoint = subscription.Endpoint;
            webSubscription.Keys     = subscription.Keys;

            //Need to make sure we're using right keys for subscription, maybe change to get for specific site.
            var vapidAuth = new Lib.Net.Http.WebPush.Authentication.VapidAuthentication(publicKey, privateKey);

            var pushMessage = new PushMessage(message);

            var task = webPushClient.RequestPushMessageDeliveryAsync(webSubscription, pushMessage, vapidAuth);

            try
            {
                task.Wait();
            }
            catch (AggregateException ae)
            {
                foreach (var e in ae.InnerExceptions)
                {
                    throw e;
                }
            }
        }
Пример #5
0
        public async Task <IActionResult> StoreSubscription([FromBody] WP.PushSubscription subscription)
        {
            var subscriptionId = await _subscriptionStore.StoreSubscriptionAsync(_applicationUser.Id, subscription);

            _logger.LogDebug($"Creating push registration for {_applicationUser.Id} with subscriptionId of {subscriptionId}");
            return(Ok(new {
                uid = subscriptionId,
                status = true
            }));
        }
        private async Task SendNotificationAsync(Lib.Net.Http.WebPush.PushSubscription subscription, PushMessage message, CancellationToken cancellationToken)
        {
            var _pushClient = new PushServiceClient();

            _pushClient.DefaultAuthentication = new VapidAuthentication("BP3KYW8aPpClaCjP2MUceUNTwqBSaK88kTnl6SWg0k134zAy_dNNub8LfGHo83bbkm-LUGAd_aLKM0z_4cpUlY8", "SSvrSz8WiLxNJB4SOZXiBs12n3VPLyftqHR05xpobGo");
            try
            {
                await _pushClient.RequestPushMessageDeliveryAsync(subscription, message, cancellationToken);
            }
            catch (Exception ex)
            {
                //_logger?.LogError(ex, "Failed requesting push message delivery to {0}.", subscription.Endpoint);
            }
        }
        private HttpRequestMessage PreparePushMessageDeliveryRequest(PushSubscription subscription, PushMessage message, VapidAuthentication authentication, VapidAuthenticationScheme authenticationScheme)
        {
            authentication = authentication ?? DefaultAuthentication;
            if (authentication == null)
            {
                throw new InvalidOperationException("The VAPID authentication information is not available");
            }

            HttpRequestMessage pushMessageDeliveryRequest = new HttpRequestMessage(HttpMethod.Post, subscription.Endpoint)
            {
                Headers =
                {
                    { TTL_HEADER_NAME, (message.TimeToLive ?? DefaultTimeToLive).ToString(CultureInfo.InvariantCulture) }
                }
            };

            pushMessageDeliveryRequest = SetAuthentication(pushMessageDeliveryRequest, subscription, authentication, authenticationScheme);
            pushMessageDeliveryRequest = SetUrgency(pushMessageDeliveryRequest, message);
            pushMessageDeliveryRequest = SetTopic(pushMessageDeliveryRequest, message);
            pushMessageDeliveryRequest = SetContent(pushMessageDeliveryRequest, subscription, message);

            return(pushMessageDeliveryRequest);
        }
Пример #8
0
        public async Task SendNotificationAsync(Lib.Net.Http.WebPush.PushSubscription subscription, PushMessage message, CancellationToken cancellationToken)
        {
            try
            {
                WebPush.PushSubscription sub = new WebPush.PushSubscription();

                foreach (KeyValuePair <string, string> en in subscription.Keys)
                {
                    Console.WriteLine("Keys and Values: ");

                    Console.WriteLine(en.Key + " :  " + en.Value);
                }
                sub.Auth     = subscription.Keys["auth"];
                sub.Endpoint = subscription.Endpoint;
                sub.P256DH   = subscription.Keys["p256dh"];

                await _webPushClient.SendNotificationAsync(sub, message.Content, vapidDetails);
            }
            catch (Exception ex)
            {
                await HandlePushMessageDeliveryExceptionAsync(ex, subscription);
            }
        }
Пример #9
0
 public Task AddAsync(WebPush.PushSubscription subscription)
 {
     return(Subscriptions.CreateItemAsync <PushSubscription>(new PushSubscription(subscription), _partitionKey));
 }
 /// <summary>
 /// Requests delivery of push message by push service as an asynchronous operation.
 /// </summary>
 /// <param name="subscription">The push service subscription.</param>
 /// <param name="message">The push message.</param>
 /// <param name="authentication">The authentication details.</param>
 /// <param name="authenticationScheme">The <see cref="VapidAuthenticationScheme"/> to use.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 public Task RequestPushMessageDeliveryAsync(PushSubscription subscription, PushMessage message, VapidAuthentication authentication, VapidAuthenticationScheme authenticationScheme)
 {
     return(RequestPushMessageDeliveryAsync(subscription, message, authentication, authenticationScheme, CancellationToken.None));
 }
 /// <summary>
 /// Requests delivery of push message by push service as an asynchronous operation.
 /// </summary>
 /// <param name="subscription">The push service subscription.</param>
 /// <param name="message">The push message.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 public Task RequestPushMessageDeliveryAsync(PushSubscription subscription, PushMessage message)
 {
     return(RequestPushMessageDeliveryAsync(subscription, message, null, DefaultAuthenticationScheme, CancellationToken.None));
 }
Пример #12
0
 /// <summary>
 /// Creates new instance of <see cref="PushServiceClientException"/> class.
 /// </summary>
 /// <param name="message">The message that describes the current exception.</param>
 /// <param name="statusCode">The status code of the push service response.</param>
 /// <param name="headers">The headers of the push service response.</param>
 /// <param name="body">The body of the push service response.</param>
 /// <param name="pushSubscription">The <see cref="WebPush.PushSubscription"/> that initiated the push service request.</param>
 public PushServiceClientException(string message, HttpStatusCode statusCode, HttpResponseHeaders headers, string body, PushSubscription pushSubscription)
     : base(message)
 {
     StatusCode       = statusCode;
     Headers          = headers;
     Body             = body;
     PushSubscription = pushSubscription;
 }
Пример #13
0
 public PushSubscription(Lib.Net.Http.WebPush.PushSubscription subscription)
 {
     Endpoint = subscription.Endpoint;
     Keys     = subscription.Keys;
 }
Пример #14
0
        private async Task HandlePushMessageDeliveryExceptionAsync(Exception exception, Lib.Net.Http.WebPush.PushSubscription subscription)
        {
            PushServiceClientException pushServiceClientException = exception as PushServiceClientException;

            if (pushServiceClientException is null)
            {
                _logger?.LogError(exception, "Failed requesting push message delivery to {0}.", subscription.Endpoint);
            }
            else
            {
                if ((pushServiceClientException.StatusCode == HttpStatusCode.NotFound) || (pushServiceClientException.StatusCode == HttpStatusCode.Gone))
                {
                    using (IPushSubscriptionStoreAccessor subscriptionStoreAccessor = _subscriptionStoreAccessorProvider.GetPushSubscriptionStoreAccessor())
                    {
                        await subscriptionStoreAccessor.PushSubscriptionStore.DiscardSubscriptionAsync(subscription.Endpoint);
                    }
                    _logger?.LogInformation("Subscription has expired or is no longer valid and has been removed.");
                }
            }
        }
 /// <summary>
 /// Requests delivery of push message by push service as an asynchronous operation.
 /// </summary>
 /// <param name="subscription">The push service subscription.</param>
 /// <param name="message">The push message.</param>
 /// <param name="authentication">The authentication details.</param>
 /// <param name="cancellationToken">The cancellation token to cancel operation.</param>
 /// <returns>The task object representing the asynchronous operation.</returns>
 public Task RequestPushMessageDeliveryAsync(PushSubscription subscription, PushMessage message, VapidAuthentication authentication, CancellationToken cancellationToken)
 {
     return(RequestPushMessageDeliveryAsync(subscription, message, authentication, DefaultAuthenticationScheme, cancellationToken));
 }
        private static HttpRequestMessage SetAuthentication(HttpRequestMessage pushMessageDeliveryRequest, PushSubscription subscription, VapidAuthentication authentication, VapidAuthenticationScheme authenticationScheme)
        {
            Uri    endpointUri = new Uri(subscription.Endpoint);
            string audience    = endpointUri.Scheme + @"://" + endpointUri.Host;

            if (authenticationScheme == VapidAuthenticationScheme.WebPush)
            {
                VapidAuthentication.WebPushSchemeHeadersValues webPushSchemeHeadersValues = authentication.GetWebPushSchemeHeadersValues(audience);

                pushMessageDeliveryRequest.Headers.Authorization = new AuthenticationHeaderValue(WEBPUSH_AUTHENTICATION_SCHEME, webPushSchemeHeadersValues.AuthenticationHeaderValueParameter);
                pushMessageDeliveryRequest.Headers.Add(CRYPTO_KEY_HEADER_NAME, webPushSchemeHeadersValues.CryptoKeyHeaderValue);
            }
            else
            {
                pushMessageDeliveryRequest.Headers.Authorization = new AuthenticationHeaderValue(VAPID_AUTHENTICATION_SCHEME, authentication.GetVapidSchemeAuthenticationHeaderValueParameter(audience));
            }

            return(pushMessageDeliveryRequest);
        }
        private static HttpRequestMessage SetContent(HttpRequestMessage pushMessageDeliveryRequest, PushSubscription subscription, PushMessage message)
        {
            HttpContent httpContent = message.HttpContent;

            if (httpContent is null)
            {
                pushMessageDeliveryRequest.Content = null;
            }
            else
            {
                AsymmetricCipherKeyPair applicationServerKeys = ECKeyHelper.GenerateAsymmetricCipherKeyPair();
                byte[] applicationServerPublicKey             = ((ECPublicKeyParameters)applicationServerKeys.Public).Q.GetEncoded(false);

                pushMessageDeliveryRequest.Content = new Aes128GcmEncodedContent(
                    httpContent,
                    GetKeyingMaterial(subscription, applicationServerKeys.Private, applicationServerPublicKey),
                    applicationServerPublicKey,
                    CONTENT_RECORD_SIZE
                    );
            }

            return(pushMessageDeliveryRequest);
        }
        private static async Task HandlePushMessageDeliveryRequestResponse(HttpResponseMessage pushMessageDeliveryRequestResponse, PushSubscription subscription)
        {
            if (pushMessageDeliveryRequestResponse.StatusCode == HttpStatusCode.Created)
            {
                return;
            }

            string reason = String.IsNullOrWhiteSpace(pushMessageDeliveryRequestResponse.ReasonPhrase) ?
                            $"Received unexpected response code: {pushMessageDeliveryRequestResponse.StatusCode}"
                                : pushMessageDeliveryRequestResponse.ReasonPhrase;

            string content = await pushMessageDeliveryRequestResponse.Content.ReadAsStringAsync();

            throw new PushServiceClientException(reason, pushMessageDeliveryRequestResponse.StatusCode, pushMessageDeliveryRequestResponse.Headers, content, subscription);
        }
Пример #19
0
 public void Add(WebPush.PushSubscription subscription)
 {
     _subscriptions.Insert(new PushSubscription(subscription));
 }
Пример #20
0
 public Task SendNotificationAsync(Lib.Net.Http.WebPush.PushSubscription subscription, PushMessage message)
 {
     return(SendNotificationAsync(subscription, message, CancellationToken.None));
 }
Пример #21
0
 public PushSubscription(WebPush.PushSubscription subscription)
 {
     Endpoint = subscription.Endpoint;
     Keys     = subscription.Keys;
 }
 public PushSubscription(string id, WP.PushSubscription subscription)
 {
     Id       = id;
     Endpoint = subscription.Endpoint;
     Keys     = subscription.Keys;
 }