Beispiel #1
0
        private async Task SendCoreAsync(WebPushJob job,
                                         CancellationToken ct)
        {
            try
            {
                var pushSubscription = new PushSubscription(
                    job.Subscription.Endpoint,
                    job.Subscription.Keys["p256dh"],
                    job.Subscription.Keys["auth"]);

                var json = job.Payload;

                await webPushClient.SendNotificationAsync(pushSubscription, json, cancellationToken : ct);
            }
            catch (WebPushException ex) when(ex.StatusCode == HttpStatusCode.Gone)
            {
                await logStore.LogAsync(job.AppId, Name, Texts.WebPush_TokenRemoved);

                var command = new RemoveUserWebPushSubscription
                {
                    Endpoint = job.Subscription.Endpoint
                };

                await userStore.UpsertAsync(job.AppId, job.UserId, command, ct);
            }
            catch (WebPushException ex)
            {
                throw new DomainException(ex.Message);
            }
        }
Beispiel #2
0
        public async Task PushAsync(string recieverId, string triggerEmail, string payload)
        {
            var devices = await _dbContext.Devices.Where(t => t.UserID == recieverId).ToListAsync();

            string vapidPublicKey  = _configuration.GetSection("VapidKeys")["PublicKey"];
            string vapidPrivateKey = _configuration.GetSection("VapidKeys")["PrivateKey"];

            foreach (var device in devices)
            {
                try
                {
                    var pushSubscription = new PushSubscription(device.PushEndpoint, device.PushP256DH, device.PushAuth);
                    var vapidDetails     = new VapidDetails("mailto:" + triggerEmail, vapidPublicKey, vapidPrivateKey);
                    _logger.LogInformation($"Trying to call WebPush API to push a new event to {recieverId}, Event content is '{payload}', Device ID is {device.Id}");
                    await _webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
                }
                catch (WebPushException e)
                {
                    _logger.LogCritical(e, "A WebPush error occoured while calling WebPush API: " + e.Message);
                }
                catch (Exception e)
                {
                    _logger.LogCritical(e, "An error occoured while calling WebPush API: " + e.Message);
                }
            }
        }
        public async Task SendNotificationsAsync(string title, string message, string clickUrl)
        {
            var payload = JsonConvert.SerializeObject(new { title, message, url = clickUrl });

            var vapidDetails  = new VapidDetails("mailto:[email protected]", vapidPublicKey, vapidPrivateKey);
            var webPushClient = new WebPushClient();

            foreach (var subscription in PushSubsciptions.GetSubscriptions())
            {
                var pushSubscription = new PushSubscription(subscription.PushEndpoint, subscription.PushP256DH, subscription.PushAuth);
                try
                {
                    await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
                }
                catch (WebPushException e)
                {
                    switch (e.StatusCode)
                    {
                    case HttpStatusCode.NotFound:
                    case HttpStatusCode.Gone:
                        PushSubsciptions.RemoveSubscription(subscription);
                        break;
                    }
                }
            }
        }
        public async Task SendNotificationAsync(PushSubscriptionUser subscription, WebPushNotificationMessages message, CancellationToken cancellationToken)
        {
            var vapidDetails = new VapidDetails(this._options.Subject, this._options.PublicKey, this._options.PrivateKey);
            PushSubscription pushSubscription = new WebPush.PushSubscription(subscription.Endpoint, subscription.P256DH, subscription.Auth);
            //var payload = System.Text.Json.JsonSerializer.Serialize(message);
            var settings = new JsonSerializerSettings();

            settings.ContractResolver = new DefaultContractResolver {
                NamingStrategy = new JsonLowerCaseNamingStrategy()
            };;
            var payload = JsonConvert.SerializeObject(message, settings);

            try
            {
                await _pushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
            }
            catch (WebPushException ex)
            {
                {
                    using (IStoreRepositoryAccessor pushstoreAccessor = _pushStoreAccessorProvider.GetStoreRepositoryAccessor())
                    {
                        subscription.DateEndTime = DateTime.Now;
                        await pushstoreAccessor.StoreRepository.UpdateSubscriptionAsync(subscription);
                    }
                    _logger?.LogInformation("Subscription has expired or is no longer valid and has been removed.");
                }

                Console.Error.WriteLine("(WebPush) Error sending push notification: " + ex.Message);
            }
        }
Beispiel #5
0
        public async Task <IActionResult> PushTest([FromBody] string testMessage)
        {
            var webPushClient = new WebPushClient();

            webPushClient.SetVapidDetails(_vapidDetails);

            // send test notification
            var payload = new PushNotificationPayload
            {
                Msg  = "Aurelia har falt. Vaktsentralen, ta kontakt å sjekk ut situasjon og meld neste aksjon",
                Icon = "[URL to an image to display in the notification]"
            };

            try
            {
                await webPushClient.SendNotificationAsync(_pushSubscription, JsonConvert.SerializeObject(payload), _vapidDetails);
            }
            catch (WebPushException exception)
            {
                var statusCode = exception.StatusCode;
                return(new StatusCodeResult((int)statusCode));
            }

            return(new OkResult());
        }
Beispiel #6
0
        public async Task <IActionResult> Create([FromBody] PushNotificationSubscription subscription)
        {
            var pushSubscription = new PushSubscription(subscription.Endpoint, subscription.Key, subscription.AuthSecret);
            var vapidDetails     = new VapidDetails(_vapidSettings.Subject, _vapidSettings.PublicKey, _vapidSettings.PrivateKey);

            var webPushClient = new WebPushClient();

            webPushClient.SetVapidDetails(vapidDetails);

            //TODO; store pushsubscription for later use
            _pushSubscription = pushSubscription;
            _vapidDetails     = vapidDetails;

            // send notification
            var payload = new PushNotificationPayload
            {
                Msg  = "Thank you for subscribing",
                Icon = "[URL to an image to display in the notification]"
            };

            try
            {
                await webPushClient.SendNotificationAsync(pushSubscription, JsonConvert.SerializeObject(payload), vapidDetails);
            }
            catch (WebPushException exception)
            {
                var statusCode = exception.StatusCode;
                return(new StatusCodeResult((int)statusCode));
            }

            return(new OkResult());
        }
        private static async Task SendNotificationAsync(Order order,
                                                        NotificationSubscription subscription, string message)
        {
            // En una aplicación real puedes generar tus propias llaves en
            // https://tools.reactpwa.com/vapid
            var PublicKey =
                "BLC8GOevpcpjQiLkO7JmVClQjycvTCYWm6Cq_a7wJZlstGTVZvwGFFHMYfXt6Njyvgx_GlXJeo5cSiZ1y4JOx1o";
            var PrivateKey =
                "OrubzSz3yWACscZXjFQrrtDwCKg-TGFuWhluQ2wLXDo";
            var PushSubscription =
                new PushSubscription(
                    subscription.Url, subscription.P256dh, subscription.Auth);
            // Aquí puedes colocar tu propio correo en <*****@*****.**>
            var VapidDetails =
                new VapidDetails("mailto:[email protected]",
                                 PublicKey, PrivateKey);
            var WebPushClient = new WebPushClient();

            try
            {
                var Payload = JsonSerializer.Serialize(new
                {
                    message,
                    url = $"myorders/{order.OrderId}",
                });
                await WebPushClient.SendNotificationAsync(
                    PushSubscription, Payload, VapidDetails);
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(
                    $"Error al enviar la notificación push: {ex.Message}");
            }
        }
Beispiel #8
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> Send(string sampleParam)
        {
            //TODO endpoint, auth - retrieve from UI, save to db
            var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/fcQY8aBpBUQ:APA91bHQxER48x97XDAk5P_Ahdjuka7kqRmUGI33gfqP2xLYWoN8Fhc6YYxHxINa02A77kOt-MT7WXkre2cdLpl4Cb7Rc_p7n4SKvPL-enwFVcL2ke7fEPtiB_0gOEi29H_p5_WAsJBt";
            var p256dh       = @"BJLeaEQRpqNvCcxK-qoQhmTb_02zIwWY5gTal-124sE89aqE5-gM7c4xlqi-vctsY7tlbr8K9lisw9aKfUfdp_s";
            var auth         = @"Vz2aZFiZ7-K6KknndrxSng";
            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);

            var options    = new Dictionary <string, object>();
            var subject    = @"mailto:[email protected]";
            var publicKey  = @"BFVE8GeDN3tHNJJc50Zufq3KkEFRU4vmuxOIVyjw5VxXiQ7KpnZ7vqfvn67hMSLxv6Cbe_308e_V9xffPH5ncjc";
            var privateKey = @"E3utukZxBbaIIH295QqQcxDjAg6GNswsPDhj6Z9HJ2Y";

            options["vapidDetails"] = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                await webPushClient.SendNotificationAsync(subscription, sampleParam, options);

                return(Ok(sampleParam));
            }
            catch (WebPushException ex)
            {
                return(Ok(ex.Message));
            }
        }
        /// <summary>
        /// Sends a message to multiple devices.
        /// </summary>
        /// <param name="p_message">Message to send.</param>
        /// <param name="p_targetDevices">Target devices.</param>
        public Task SendMessage(MessageViewModel p_message, IEnumerable <Device> p_targetDevices)
        {
            WebPushClient v_webPushClient = new WebPushClient();

            if (this.HasVapidPublicKey())
            {
                v_webPushClient.SetVapidDetails(VapidDetails);
            }

            if (!String.IsNullOrWhiteSpace(GcmAPIKey))
            {
                v_webPushClient.SetGcmApiKey(GcmAPIKey);
            }


            List <Task> v_pending = new List <Task>();

            foreach (Device v_targetDevice in p_targetDevices)
            {
                string v_message = JsonConvert.SerializeObject(p_message);
                v_pending.Add(v_webPushClient.SendNotificationAsync(v_targetDevice, v_message));
            }

            return(Task.WhenAll(v_pending));
        }
        public async Task SendNotification(BrowserSubscription subscription, Notification notification)
        {
            if (_vapid.PrivateKey == null)
            {
                _logger.Error("WebPush config is missing keys for accountId " + subscription.AccountId);
                return;
            }

            var json = JsonConvert.SerializeObject(notification);
            var dto  = new PushSubscription(subscription.Endpoint, subscription.PublicKey,
                                            subscription.AuthenticationSecret);

            try
            {
                await _client.SendNotificationAsync(dto, json, _vapid);
            }
            catch (WebPushException ex)
            {
                if (ex.Message == "Subscription no longer valid")
                {
                    throw new InvalidSubscriptionException(
                              $"Subscription for {subscription.Endpoint} is no longer valid.", ex);
                }

                throw;
            }
        }
        public async Task EnviarNotificacionPeliculaEnCartelera(Pelicula pelicula)
        {
            var notificaciones = await context.Notificaciones.ToListAsync();

            var llavePublica = configuration.GetValue <string>("notificaciones:llave_publica");
            var llavePrivada = configuration.GetValue <string>("notificaciones:llave_privada");
            var email        = configuration.GetValue <string>("notificaciones:email");

            var vapidDetails = new VapidDetails(email, llavePublica, llavePrivada);

            foreach (var notificacion in notificaciones)
            {
                var pushSubscription = new PushSubscription(notificacion.URL,
                                                            notificacion.P256dh, notificacion.Auth);

                var webPushClient = new WebPushClient();

                try
                {
                    var payload = JsonSerializer.Serialize(new
                    {
                        titulo = pelicula.Titulo,
                        imagen = pelicula.Poster,
                        url    = $"pelicula/{pelicula.Id}"
                    });

                    await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    // ...
                }
            }
        }
Beispiel #12
0
        public async Task <IActionResult> SendNotificationAsync([FromBody] SendNotification model)
        {
            var vapidDetails = new VapidDetails(_settings.Subject, _settings.PublicKey, _settings.PrivateKey);

            var webPushClient = new WebPushClient();

            webPushClient.SetVapidDetails(vapidDetails);

            // send notification
            var payload = new PushNotificationPayload
            {
                Title   = "Push Demo Title",
                Body    = "Put some message in the body of the notification.",
                Icon    = "assets/cazton-c.png",
                Vibrate = new List <int> {
                    100, 50, 100
                }
            };

            try
            {
                var subscription = _pushSusbscriptions.GetAll().FirstOrDefault(x => x.Endpoint == model.Endpoint);

                if (subscription != null)
                {
                    await webPushClient.SendNotificationAsync(subscription, JsonConvert.SerializeObject(new { notification = payload }), vapidDetails);
                }
            }
            catch (WebPushException exception)
            {
                var statusCode = exception.StatusCode;
            }

            return(Ok());
        }
Beispiel #13
0
        public void SendNotification(IContactNotificationSubscription subscription, INotification notification)
        {
            IPushKeySetProvider keyProvider = Factory.KeySetProvider();

            var pushSubscription = new PushSubscription(subscription.Endpoint, subscription.P256dh, subscription.AuthorizationToken);

            var vapidDetails = new VapidDetails(notification.Subject, keyProvider.PublicKey, keyProvider.PrivateKey);

            var webPushClient = new WebPushClient();

            try
            {
                string message = string.Format("{{ \"body\":\"{0}\", \"title\":\"{1}\", \"icon\":\"{2}\", \"badge\":\"{3}\" }}",
                                               notification.Body,
                                               notification.Title,
                                               notification.Icon,
                                               notification.Badge
                                               );
                webPushClient.SendNotificationAsync(pushSubscription, message, vapidDetails);
                //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
            }
            catch (WebPushException exception)
            {
                Console.WriteLine("Http STATUS code" + exception.StatusCode);
            }
        }
Beispiel #14
0
        public async Task EnviarNotificacionNuevoPedido(Pedido pedido)
        {
            var notificaciones = await _context.Notificaciones.ToListAsync();

            var llavePublica = _configuration.GetValue <string>("Notificaciones:publicKey");
            var llavePrivada = _configuration.GetValue <string>("Notificaciones:privateKey");
            var email        = _configuration.GetValue <string>("Notificaciones:email");
            var vapidDetails = new VapidDetails(email, llavePublica, llavePrivada);

            foreach (var notificacion in notificaciones)
            {
                var pushSubscription = new PushSubscription(notificacion.URL, notificacion.P256dh,
                                                            notificacion.Auth);
                var webPushClient = new WebPushClient();

                try
                {
                    var payload = JsonSerializer.Serialize(new
                    {
                    });
                    await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
                }
                catch (Exception exception)
                {
                    Console.Write(exception.Message);
                }
            }
        }
        private static async Task SendNotificationAsync(Order order, NotificationSubscription subscription, string message)
        {
            // For a real application, generate your own
            var publicKey  = "BLC8GOevpcpjQiLkO7JmVClQjycvTCYWm6Cq_a7wJZlstGTVZvwGFFHMYfXt6Njyvgx_GlXJeo5cSiZ1y4JOx1o";
            var privateKey = "OrubzSz3yWACscZXjFQrrtDwCKg-TGFuWhluQ2wLXDo";

            var pushSubscription = new PushSubscription(subscription.Url, subscription.P256dh, subscription.Auth);
            var vapidDetails     = new VapidDetails("mailto:<*****@*****.**>", publicKey, privateKey);
            var webPushClient    = new WebPushClient();

            try
            {
                var payload = JsonSerializer.Serialize(new
                {
                    message,
                    url = $"myorders/{order.OrderId}"
                });

                await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
            }
            catch (Exception e)
            {
                Console.Error.WriteLine("Error sending push notification: " + e.Message);
            }
        }
        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}");
            }
        }
Beispiel #17
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            _context.Items.Add(Item);

            await _context.SaveChangesAsync();

            //use your own private and public key:
            //generator here: https://web-push-codelab.glitch.me/
            var vapidDetails = new VapidDetails(@"<youremail>",
                                                "<publickey>",
                                                "<privatekey>");

            var pushSubscriptions = await _context.PushSubscriptions.ToListAsync();

            var webPushClient = new WebPushClient();

            var tasks = new List <Task>();

            foreach (var pushSubscription in pushSubscriptions)
            {
                var webPushSubscription = new WebPush.PushSubscription(pushSubscription.EndPoint, pushSubscription.P256dh, pushSubscription.Auth);

                tasks.Add(webPushClient.SendNotificationAsync(webPushSubscription, "test", vapidDetails));
            }

            await Task.WhenAll(tasks);

            return(RedirectToPage("./Index"));
        }
Beispiel #18
0
        public async Task <IActionResult> CallShooter(CallShooterRequest request)
        {
            // For a real application, generate your own
            var currentUserId = PlatformUtils.GetIdentityUserId(User);
            var existingUser  = AuthorizationLayer.GetUserById(currentUserId);

            if (existingUser == null)
            {
                return(NotFound());
            }

            var subscriptions = BasicLayer.FetchNotificationSubscriptionsByUserId(request.ShooterId);

            var vapidDetails = new VapidDetails($"mailto:{_vapidUser}", _publicKey, _privateKey);


            var pushSubscriptions = subscriptions.Select(x => new PushSubscription(x.Url, x.P256dh, x.Auth)).ToList();
            var webPushClient     = new WebPushClient();

            try
            {
                var message = string.Empty;
                switch ((int)request.Context)
                {
                case (int)CallShooterContextEnum.MatchDirector:
                    var userStage = BasicLayer.GetSOStage(request.MatchId, existingUser.Id);
                    message = $"{existingUser.FirstName} {existingUser.LastName} ti sta cercando allo stage {userStage.Index}:{userStage.Name}!";
                    break;

                default:
                    message = $"{existingUser.FirstName} {existingUser.LastName} ti sta cercando!";
                    break;
                }
                var payload = JsonSerializer.Serialize(new
                {
                    message,
                    url = string.Empty,
                });
                if (pushSubscriptions.Count == 0)
                {
                    return(Ok(new OkResponse {
                        Status = false, Errors = new List <string> {
                            "NoSubscriptions"
                        }
                    }));
                }
                var tasks = pushSubscriptions.Select(pushSubscription => webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails)).ToList();
                await Task.WhenAll(tasks);

                return(Ok(new OkResponse()
                {
                    Status = true
                }));
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Error sending push notification: " + ex.Message);
                return(Ok(ex));
            }
        }
Beispiel #19
0
        public async Task <bool> Post([FromBody] PushNotificationModel subscription)
        {
            try
            {
                var pushSubscription = new PushSubscription(subscription.Endpoint, subscription.Key, subscription.AuthSecret);
                var vapidDetails     = new VapidDetails("http://localhost:50973/forum", "BAdnuHOxwOFm_GV_NYG1CZOjddlrVfDbKobDFTTxQvgcGBhPI47gkxfEUdtgX2iO_x4PwUkyj-xS7Uke_UmIaqQ",
                                                        "vrRVfvxyx4kIEYSfansI_eOI4a-HdTCJpa0EVmjLYnE");

                ForumPostSubscriptions.AddSubscription(pushSubscription);

                var webPushClient = new WebPushClient();
                webPushClient.SetVapidDetails(vapidDetails);

                var payload = new PushNotificationPayload
                {
                    Msg  = "Thank you for subscribing",
                    Icon = "C:/Temp/icon192x192.png",
                };
                string temp = JsonConvert.SerializeObject(payload);

                //await webPushClient.SendNotificationAsync(pushSubscription, temp, );
                await webPushClient.SendNotificationAsync(pushSubscription, temp, vapidDetails);

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Beispiel #20
0
        public async Task SendNotificationAsync(string userID, string gameID, string comment)
        {
            _log.NotificationsHandlerSendingNotifications(userID);
            var maxLength = 25;

            if (comment.Length > maxLength)
            {
                var index = comment.IndexOf(' ', maxLength);
                if (index < 0 || index > maxLength + 5)
                {
                    index = maxLength;
                }
                comment  = comment.Substring(0, index);
                comment += "...";
            }

            var uri           = $"/play/{gameID}";
            var vapidDetails  = new VapidDetails($"{_options.PublicServerUri}{uri}", _options.PublicKey, _options.PrivateKey);
            var webPushClient = new WebPushClient();
            var json          = JsonSerializer.Serialize(new NotificationMessage()
            {
                Text = comment,
                Uri  = uri
            });

            var success = 0;
            var failed  = 0;

            await foreach (var notificationEntity in _context.GetAllAsync <UserNotificationEntity>(TableNames.UserNotifications, userID))
            {
                if (notificationEntity.Enabled)
                {
                    var endpoint = notificationEntity.Endpoint;
                    var p256dh   = notificationEntity.P256dh;
                    var auth     = notificationEntity.Auth;

                    var subscription = new PushSubscription(endpoint, p256dh, auth);

                    try
                    {
                        await webPushClient.SendNotificationAsync(subscription, json, vapidDetails);

                        success++;
                    }
                    catch (Exception ex)
                    {
                        failed++;
                        _log.NotificationsHandlerSendFailed(userID, ex);

                        notificationEntity.Enabled = false;

                        // Disable sending notifications to this endpoint
                        await _context.UpsertAsync(TableNames.UserNotifications, notificationEntity);
                    }
                }
            }

            _log.NotificationsHandlerSendStatistics(success, failed);
        }
Beispiel #21
0
        private static async Task SendAsync(string subscriptionJson, string payload, string publicKey, string privateKey)
        {
            var subscription = JsonConvert.DeserializeObject <Subscription>(subscriptionJson);

            var pushSubscription = new PushSubscription(subscription.ChannelUri, subscription.Keys.P256Dh, subscription.Keys.Auth);
            var vapidDetails     = new VapidDetails("mailto:[email protected]", publicKey, privateKey);
            await WebPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
        }
        public async Task SendNotificationAsync(PushSubscriptionNotification subscription, string payload)
        {
            var webPushSubscription = new PushSubscription(
                subscription.Endpoint,
                subscription.Keys["p256dh"],
                subscription.Keys["auth"]);

            await _pushClient.SendNotificationAsync(webPushSubscription, payload);
        }
Beispiel #23
0
        public async Task NotifyParticipants(ExtendedCalendarItem calendarItem, string firstName, string lastName, string message)
        {
            IEnumerable <NotificationSubscription> subscriptions;
            var publicKey  = "BJkgu1ZbFHQm1gQCkYBvsHgZn8-f_v9f9HzIi9UQlCYq2DfUzv4OEx1Dfg9gD0s88fSQ8Ya8kdE4Ib422JHk_E0";
            var privateKey = _notificationPrivateKey;

            var vapidDetails  = new VapidDetails("mailto:[email protected]", publicKey, privateKey);
            var webPushClient = new WebPushClient();

            _logger.LogInformation($"NotifiyParticpants(<{calendarItem.Title}>, <{firstName}>, <{lastName}>, <{message}>)");
            // Add host as participant to avoid extra handling
            if (!calendarItem.WithoutHost)
            {
                Participant hostAsParticipant = new Participant()
                {
                    ParticipantFirstName = calendarItem.HostFirstName, ParticipantLastName = calendarItem.HostLastName
                };
                calendarItem.ParticipantsList = calendarItem.ParticipantsList.Append(hostAsParticipant);
            }
            foreach (Participant p in calendarItem.ParticipantsList)
            {
                _logger.LogInformation($"NotifiyParticpants: Participant {p.ParticipantFirstName} {p.ParticipantLastName} ");
                if (!p.ParticipantFirstName.Equals(firstName) || !p.ParticipantLastName.Equals(lastName))
                {
                    if (null == calendarItem.Tenant)
                    {
                        subscriptions = await _cosmosDbRepository.GetItems(d => d.UserFirstName.Equals(p.ParticipantFirstName) && d.UserLastName.Equals(p.ParticipantLastName) && (d.Tenant ?? String.Empty) == String.Empty);
                    }
                    else
                    {
                        subscriptions = await _cosmosDbRepository.GetItems(d => d.UserFirstName.Equals(p.ParticipantFirstName) && d.UserLastName.Equals(p.ParticipantLastName) && d.Tenant.Equals(calendarItem.Tenant));
                    }
                    _logger.LogInformation($"NotifiyParticpants: {subscriptions.Count()} subscriptions for {p.ParticipantFirstName} {p.ParticipantLastName} ");
                    foreach (NotificationSubscription subscription in subscriptions)
                    {
                        try
                        {
                            var pushSubscription = new PushSubscription(subscription.Url, subscription.P256dh, subscription.Auth);
                            var payload          = JsonSerializer.Serialize(new
                            {
                                title = calendarItem.Title,
                                message,
                                url = subscription.PlannerUrl,
                            });;
                            _logger.LogInformation($"NotifiyParticpants.SendNotificationAsync({pushSubscription.Endpoint})");
                            await webPushClient.SendNotificationAsync(pushSubscription, payload, vapidDetails);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError("Error sending push notification: " + ex.Message);
                            await _cosmosDbRepository.DeleteItemAsync(subscription.Id);
                        }
                    }
                }
            }
        }
Beispiel #24
0
        public async Task <bool> SendToSubscription(Notification notification, Subscription subscription)
        {
            var pushSubscription = new PushSubscription(subscription.PushEndpoint, subscription.PushP256Dh, subscription.PushAuth);

            try
            {
                await _webPushClient.SendNotificationAsync(pushSubscription,
                                                           Serializer.ToJsonString(notification), _vapidDetails);

                return(true);
            }
            catch (Exception exception)
            {
                _logger.LogError(
                    $"Error sending web notification to Device: {subscription.DeviceId} with Error: ${exception.Message}");

                return(false);
            }
        }
        private async Task NotifySubscriber(Message message, Subscription subscription)
        {
            var sub     = new PushSubscription(subscription.Endpoint, subscription.Keys.P256Dh, subscription.Keys.Auth);
            var payload = JsonConvert.SerializeObject(message);

            try
            {
                await _pushClient.SendNotificationAsync(sub, payload, _vapid);
            }
            catch (Exception e)
            {
                Debug.WriteLine($"Push error: {e.Message}");
            }
        }
        private void NofityUser(string endpoint, string p256dh, string auth, string payload)
        {
            var vapidDetails = new VapidDetails(@"mailto:[email protected]"
                                                , "BCbYNxjxYPOcv3Hn8xZH1bB2kJLFLeO9Fx68U0C2FOZ7wFmG_yxGdiiNIWrFRHY6X1NL6egRgzZGAC_A_6fcigA"
                                                , "r2HJzuoJiFD0uMDoQcKMQCGo8M80wag8kCoTMFf3S34"
                                                );
            var client = new WebPushClient();
            var subs   = new PushSubscription(endpoint, p256dh, auth);

            var task = client.SendNotificationAsync(subs, payload, vapidDetails);

            task.Wait();
            var status = task.Status;
        }
Beispiel #27
0
        public async Task <IActionResult> Send([FromBody] PushRegisterModel model)
        {
            var subscription = new PushSubscription(model.Endpoint, model.Key, model.Secret);

            try
            {
                await _client.SendNotificationAsync(subscription, model.Payload, vapidKeys);
            }
            catch (WebPushException e)
            {
                return(StatusCode((int)e.StatusCode));
            }

            return(Created("Created", null));
        }
        public async Task SendNotificationToSubscribers(string message, string baseUrl)
        {
            var notificationPayload = new PushNotificationPayload
            {
                Msg  = message,
                Icon = GetIconUrl(baseUrl)
            };

            var payloadJson = JsonConvert.SerializeObject(notificationPayload);

            var subscribers = GetSubscribers();

            foreach (var subscriber in subscribers)
            {
                try
                {
                    await _pushClient.SendNotificationAsync(subscriber, payloadJson);
                }
                catch (WebPushException wpe)
                {
                    //add logging
                }
            }
        }
Beispiel #29
0
        public async Task RunAsync(CancellationToken cancellationToken = default)
        {
            var subscriptions = await _dbContext.PushSubscriptions
                                .ToArrayAsync(cancellationToken)
                                .ConfigureAwait(false);

            var teams = await _dbContext.Teams
                        .ToArrayAsync(cancellationToken)
                        .ConfigureAwait(false);

            var webPushClient = new WebPushClient();

            foreach (var sub in subscriptions)
            {
                if (string.IsNullOrWhiteSpace(sub.Data))
                {
                    continue;
                }

                dynamic jsonObj      = JsonConvert.DeserializeObject(sub.Data);
                string  pushEndpoint = (string)jsonObj.endpoint;
                string  p256Dh       = (string)jsonObj.keys?.p256dh;
                string  auth         = (string)jsonObj.keys?.auth;

                if (string.IsNullOrWhiteSpace(auth))
                {
                    continue;
                }

                string payload = CreatePayload(teams);
                try
                {
                    var subscription = new WebPush.PushSubscription(pushEndpoint, p256Dh, auth);
                    await webPushClient.SendNotificationAsync(subscription, payload, _vapidDetails);
                }
                catch (WebPushException e)
                    when(e.Message.Contains("no longer valid", StringComparison.OrdinalIgnoreCase))
                    {
                        _logger.LogWarning(e, "Remvoing invalid subscription.");
                        await RemoveSubscription(sub, cancellationToken)
                        .ConfigureAwait(false);
                    }
                catch (WebPushException e)
                {
                    _logger.LogError(e, "Unable to push notfications");
                }
            }
        }
Beispiel #30
0
        private async Task <bool> SendNotification(int userId, Models.Services.PushNotificationMessage message)
        {
            using (var db = _dbService.GetConnection())
            {
                var endpointsToRemove = new List <string>();
                var success           = false;

                var currentSubscriptions = await GetCurrentSubscriptions(userId, db);

                var options = new Dictionary <string, object> {
                    ["vapidDetails"] = _vapidDetails
                };
                if (message.Topic.HasValue())
                {
                    options["headers"] = new Dictionary <string, object>
                    {
                        ["topic"] = message.Topic
                    };
                }

                foreach (var subscriptionData in currentSubscriptions)
                {
                    var subscription = new PushSubscription(subscriptionData.Endpoint, subscriptionData.P256dh, subscriptionData.Auth);
                    try
                    {
                        await _webPushClient.SendNotificationAsync(subscription, Jil.JSON.Serialize(message, Jil.Options.CamelCase), options);

                        success = true;
                    }
                    catch (WebPushException exception)
                    {
                        if (exception.StatusCode == HttpStatusCode.NotFound || exception.StatusCode == HttpStatusCode.Gone)
                        {
                            endpointsToRemove.Add(subscriptionData.Endpoint);
                        }
                    }
                }

                if (endpointsToRemove.Count > 0)
                {
                    await SetCurrentSubscriptions(userId, currentSubscriptions.Where(s => !endpointsToRemove.Contains(s.Endpoint)), db);
                }

                return(success);
            }
        }