Exemple #1
0
 public void Broadcast(NotificationModel data)
 {
     foreach (var sub in _subscriptions)
     {
         Dictionary <string, object> options = new Dictionary <string, object>();
         options["vapidDetails"] = _vapid;
         try
         {
             _webpush.SendNotification(sub.Value.Subscription, JsonSerializer.Serialize(data), options);
         } catch (Exception ex)
         {
             _subscriptions.Remove(sub.Value.Subscription.Endpoint);
         }
     }
 }
        // https://github.com/web-push-libs/web-push-csharp
        // https://github.com/web-push-libs/web-push
        // https://glitch.com/edit/#!/web-push-codelab
        // https://web-push-codelab.glitch.me/
        public ActionResult Index()
        {
            var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/dhpapmn14tg:APA91bEFV6kKTb3KKaXoCv1AX6GlW9wVEnfkRTSTqP4mLr9nsJDE3lj_06TD5bNyl-JFVQf9A9xh2C9idXo3ATur-E1L7d10nCDdvanHKMOO--EnRl8P1Tlwu2xT-lBCubPd9XmSzRlU";
            var p256dh       = @"BE-ceh5xFFS_JP6Tho2hUOyYkDQMjgeW254khLbKILZphaUio5FlONgEoXSwZ3T_s1KeiIhc78YDoTS2v8ziI_g";
            var auth         = @"59NQn-N3yvkQOMASjECxiQ";

            var subject    = @"mailto:[email protected]";
            var publicKey  = @"BCJqUeH5liwbNa-a9SxbHdGIUhqxACWIPoOUQHoixXU4DZjmRgN_7dJYIVmGhRyzvSpKQCdKwmSVsft6gfxqhpE";
            var privateKey = @"8Nm10_AZI1TwJP1KKwa3gBYrLl2P0SXU-UUnoYPF538";

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "Hello~~~", vapidDetails);
                return(Content("{\"status\":\"success\"}", "application/json", System.Text.Encoding.UTF8));
            }
            catch (WebPushException exception)
            {
                Console.WriteLine("Http STATUS code" + exception.StatusCode);
                return(Content("{\"status\":\"error\"}", "application/json", System.Text.Encoding.UTF8));
            }
        }
        public bool Push(string message)
        {
            if (!_healthy)
            {
                _logger.LogError("Service worker not healthy");
                return(false);
            }
            if (_subscription == null)
            {
                _logger.LogWarning("No subscription");
                return(false);;
            }

            var subject = @"mailto:[email protected]";

            var subscription = new PushSubscription(_subscription.endpoint, _subscription.keys.p256dh, _subscription.keys.auth);
            var vapidDetails = new VapidDetails(subject, _publicKey, _privateKey);
            //var gcmAPIKey = @"[your key here]";

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, message, vapidDetails);
                //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
                return(true);
            }
            catch (WebPushException exception)
            {
                _logger.LogError("Http STATUS code" + exception.StatusCode);
                return(false);
            }
        }
Exemple #4
0
        private static async Task DoWebPush(ILogger log)
        {
            var subject       = @"mailto:[email protected]";
            var subscriptions = await GetSubscriptions();

            foreach (var subscription in subscriptions)
            {
                var      vapidDetails  = new VapidDetails(subject, PublicKey, PrivateKey);
                var      webPushClient = new WebPushClient();
                PushData pushData      = CreatePushMessage();

                try
                {
                    webPushClient.SendNotification(subscription, JsonConvert.SerializeObject(pushData), vapidDetails);
                }
                catch (AggregateException exception)
                {
                    log.LogError("Error when pushing: " + exception.StackTrace);

                    if (exception.InnerException is WebPushException)
                    {
                        await _documentClient.ExecuteStoredProcedureAsync <dynamic>(
                            UriFactory.CreateStoredProcedureUri(Database, Collection, SprocName), subscription.Endpoint);
                    }
                }
            }
        }
Exemple #5
0
        public static void Main()
        {
            var pushEndpoint =
                @"https://fcm.googleapis.com/fcm/send/eRoxpie1SyE:APA91bEs-q3RvgOU44dKOqaQDrNAOPQc6BMpn_wdmL0kSWd-ZY6X72LwUDU_0syzcKnU2ymdwFwr0cBAwpTBPT0of9UUVkY3yS_fGrIlflc7x50lV_Ut1N1PjmVy0Vk0wQyZct5tefO9";
            var p256dh = @"BNst5NFg14qt20FjL-npIx-qwSuiLNyzLZQQUBNM2utwIV5cb7DA6zSpxq0-pwjCZK8R217VlwN2VIApmiOQpmY";
            var auth   = @"Bg72WKGBAIHf1-zJ54GzVA";

            var subject    = @"mailto:[email protected]";
            var publicKey  = @"BAINe9-vznpeHcvqae6Zg0i6edR96Whdh65Qp83FQnifTVTL2jP5oL7Q4Edvq9V1rdCFqnktRQ0vhwN-z-trfJ8";
            var privateKey = @"oVSUyM7AxK4bcCiSZpUg5Yqtb4zb5xJ5G9p3iX0C8_s";

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);


            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "{ \"data\":{\"title\": \"hello\", \"content\": \"Euristiq\"}}", vapidDetails);
                //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
            }
            catch (WebPushException exception)
            {
                Console.WriteLine("Http STATUS code" + exception.StatusCode);
            }
        }
Exemple #6
0
        private void NotifyUser(int topicId)
        {
            var vapidDetails = new VapidDetails(
                @"mailto:[email protected]",
                "BIzudo5gPnMUVAhQrTRDEuIMPOLwtIInO-KHrukWLkguSyCyKNrYnaHr36_zK4bfvJ5hMxu7HFWlAr0n579-tbE",
                "eCB1JO4enyxjbeXxzMbTDiYHVhJeeweq3hWMXkOHliU");

            var subscriptions = SubRepository.Items;
            var topic         = Repository.Get(topicId);

            var payload = JsonConvert.SerializeObject(
                new
            {
                topic = new { title = topic.Title, id = topic.Id }
            });

            var webPushClient = new WebPushClient();

            foreach (var subscription in subscriptions.Select(s => new PushSubscription(s.Endpoint, s.Keys.P256dh, s.Keys.Auth)))
            {
                try
                {
                    webPushClient.SendNotification(subscription, payload, vapidDetails);
                }
                catch (Exception)
                {
                }
            }
        }
Exemple #7
0
        public async Task TriggerPush(PushMessage pushMessage)
        {
            pushMessage.Message += $"-{DateTime.Now:dddd HH:mm:ss}";
            var subscriptions = await _subscriptionsRepository.GetSubscriptionsAsync();

            foreach (var sub in subscriptions)
            {
                var subscription = new PushSubscription(sub.Endpoint, sub.Key, sub.AuthSecret);

                var webPushClient = new WebPushClient();
                try
                {
                    webPushClient.SendNotification(subscription, JsonConvert.SerializeObject(pushMessage, new JsonSerializerSettings
                    {
                        ContractResolver = new CamelCasePropertyNamesContractResolver()
                    }), _vapidDetails);
                }
                catch (WebPushException exception)
                {
                    Console.WriteLine("Http STATUS code" + exception.StatusCode);
                }
                catch (Exception exception)
                {
                    await _subscriptionsRepository.RemoveSubscription(sub);

                    Console.WriteLine(exception);
                }
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            var pushEndpoint = @"https://updates.push.services.mozilla.com/wpush/v2/gAAAAABcPYyEx7EN4bI8suXnzcCB94xX6kd0_m4ggu1qdpGfdwkmMw5kWUq_Kacjy_R-j1iyp_OzuvILnizH5dbFJWsUVqH3uHYoz8c9Ya3wLIq39l9h_ke8gp-3gj6GKS5Se2yWQnxbxaiYes8s1c6TZzQFjiX9VlWz3Jou2pQ7N-alab1thcI";
            var p256dh       = @"BM-wGN-lWJWrZ_EinsQBjay_Os8flZTfhN4xaBqlw1aJ_usc9qJi7vMf5wHFZYqwatyt0BCRnfp6PdboE92m95o";
            var auth         = @"byXCU0iZ_d12HdE9f23WvA";

            var subject    = @"mailto:[email protected]";
            var publicKey  = @"BM19ABrxlF90WXluoBYTPuOf53JzbgXKVaiMJAVo6HELcb01UfG6h7_Y0GYhJzVcEYWLirOwvCuUTY0dGCEnOgU";
            var privateKey = @"rZjgAUeFmMVx9AhGZSFyM264QKEDLnKcbViCBeRUJpQ";

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
            //var gcmAPIKey = @"[your key here]";
            int i             = 0;
            var webPushClient = new WebPushClient();

            while (true)
            {
                Console.WriteLine("Push: " + i);
                try
                {
                    webPushClient.SendNotification(subscription, "Push: " + i, vapidDetails);
                }
                catch (WebPushException exception)
                {
                    Console.WriteLine("Http STATUS code" + exception.StatusCode);
                }
                i++;
                Task.Delay(5000).Wait();
            }
        }
Exemple #9
0
        static void Main(string[] args)
        {
            if (args.Length <= 0)
            {
                return;
            }
            var pushInformation = PushInformation.Load(AppDomain.CurrentDomain.BaseDirectory + "../../../info.xml");              // ASP.NETが保存しているファイルを見ます

            var webPushClient = new WebPushClient();
            var vapidDetails  = new VapidDetails("mailto:[email protected]", pushInformation.VapidPublic, pushInformation.VapipPrivate);
            var targetList    = pushInformation.Targets.ToArray();

            foreach (var target in targetList)
            {
                try
                {
                    var subscription = new PushSubscription(target.EndPoint, target.PublicKey, target.AuthSecret);
                    webPushClient.SendNotification(subscription, @"test application", vapidDetails);
                }
                catch (Exception exp)
                {
                    if (exp.Message == "Subscription no longer valid")                      // 購読者がいなくなるとこんな感じの例外を吐くので送信先から消しておこう
                    {
                        pushInformation.Targets.Remove(target);
                    }
                }
            }
            PushInformation.Save(pushInformation, AppDomain.CurrentDomain.BaseDirectory + "../../../info.xml");
            Console.ReadKey();
        }
Exemple #10
0
        public async Task SendMessage(string roomId, string msg)
        {
            var room = _rooms.GetRoom(roomId);

            room.Message = msg;
            await Clients.OthersInGroup(roomId).SendMessage(msg);

            room.Users.Where(w => w.Subscription != null).ToList().ForEach(user =>
            {
                try
                {
                    var device           = user.Subscription;
                    var pushSubscription = new PushSubscription(device.Endpoint, device.Keys.P256dh, device.Keys.Auth);
                    var vapidDetails     = new VapidDetails("http://fakvat.pl/", "BPbHlo7Z4-5Z_rr-ZKte830jOf6R4tnAS8J0IonjF269gRCdu8cdj9fsRKD9RkxprzgNO-UTFarud7QP94cHJEM", "GSMD4HwHOnybEmYeEQjylLPE3kpcA3WTKpJVd9bOOzA");

                    var webPushClient = new WebPushClient();
                    webPushClient.SendNotification(pushSubscription, msg, vapidDetails);
                }
                catch
                {
                    user.Subscription = null;
                    room.UpdateUser(user);
                }
            });
        }
        public void SendNotification()
        {
            var pushEndpoint = endpoint;
            var p256dh       = this.p256dh;
            var auth         = this.auth;

            var          subject    = @"mailto:[email protected]";
            const string publicKey  = @"BEu09qCcFIreSF2qnR2W8pAKcFAn6wpJVFaKKx0BICpxevmLyGnrxxZFNOV0rJOyZifkgdxIxjhtNsYWREPJBNg";
            const string privateKey = @"NbLMH1eHsktglOLgiBLsD2L1eklzY1vrtlHWliAV0SU";

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
            //var gcmAPIKey = @"[your key here]";

            var webPushClient = new WebPushClient();

            try
            {
                //webPushClient.SendNotification(subscription);
                //var payload = new { message = "Haww koi hila", image = await NetworkManager.SendImage() };
                webPushClient.SendNotification(subscription, " koi hila", vapidDetails);
                //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
            }
            catch (WebPushException exception)
            {
                Debug.WriteLine("Http STATUS code" + exception.StatusCode);
            }
            catch (Exception)
            {
                Debug.WriteLine("Notification failed");
            }
        }
        public async Task <IActionResult> Send(int id)
        {
            string userEmail = User.FindFirst("email")?.Value ?? "NoUser";

            // Todo: Replace with role based access
            if (userEmail.ToUpper() != Constants.AdminEmail.ToUpper())
            {
                return(RedirectToAction("Index", "Home"));
            }

            var payload = Request.Form["payload"];
            var device  = await _context.PushDevices.SingleOrDefaultAsync(m => m.Id == id);

            string vapidPublicKey  = _configuration["VapidPublicKey"];
            string vapidPrivateKey = _configuration["VapidPrivateKey"];

            var pushSubscription = new PushSubscription(device.PushEndpoint, device.PushP256DH, device.PushAuth);
            var vapidDetails     = new VapidDetails("mailto:" + Constants.SupportEmail, vapidPublicKey, vapidPrivateKey);

            var webPushClient = new WebPushClient();

            webPushClient.SendNotification(pushSubscription, payload, vapidDetails);

            return(View());
        }
Exemple #13
0
        public async Task <IActionResult> Send(int id)
        {
            var payload       = Request.Form["payload"];
            var subscriptions = await _context.PushSubscriptions.ToListAsync();

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

            foreach (var subscription in subscriptions)
            {
                if (subscription.PushAuth == null || subscription.PushEndpoint == null || subscription.PushP256DH == null)
                {
                }
                else
                {
                    var pushSubscription = new PushSubscription(subscription.PushEndpoint, subscription.PushP256DH, subscription.PushAuth);
                    var vapidDetails     = new VapidDetails("mailto:[email protected]", vapidPublicKey, vapidPrivateKey);

                    var webPushClient = new WebPushClient();
                    webPushClient.SendNotification(pushSubscription, payload, vapidDetails);
                }
            }


            return(View());
        }
        public IActionResult Notify(string message, string client)
        {
            if (client == null)
            {
                return(BadRequest("No Client Name parsed."));
            }
            PushSubscription subscription = PersistentStorage.GetSubscription(client);

            if (subscription == null)
            {
                return(BadRequest("Client was not found"));
            }

            var subject    = configuration["VAPID:subject"];
            var publicKey  = configuration["VAPID:publicKey"];
            var privateKey = configuration["VAPID:privateKey"];

            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, message, vapidDetails);
            }
            catch (Exception exception)
            {
            }

            return(View(PersistentStorage.GetClientNames()));
        }
Exemple #15
0
        public IActionResult Send(SendRequestModel model)
        {
            Application application = _dbContext.Application.SingleOrDefault(m => m.id == model.id);

            List <Device> devices = _dbContext.Device.Where(m => m.appId == application.id).ToList();

            string vapidPublicKey  = application.publicKey;
            string vapidPrivateKey = application.privateKey;

            PushModel payload = new PushModel
            {
                title   = model.title,
                message = model.message
            };

            foreach (Device device in devices)
            {
                var pushSubscription = new PushSubscription(device.pushEndpoint, device.pushP256DH, device.pushAuth);
                var vapidDetails     = new VapidDetails("mailto:[email protected]", vapidPublicKey, vapidPrivateKey);

                var webPushClient = new WebPushClient();
                webPushClient.SendNotification(pushSubscription, JsonConvert.SerializeObject(payload), vapidDetails);
            }

            return(RedirectToAction(nameof(Index)));
        }
Exemple #16
0
        /// <summary>
        /// Send push notification to subscribers.
        /// </summary>
        /// <param name="userId">
        /// User id for sending the push notification.
        /// </param>
        /// <param name="data">
        /// Data dictionary containing push notification elements.
        /// </param>
        public static void Send(int userId, Dictionary <string, string> data)
        {
            using (var db = new LibiadaWebEntities())
            {
                var subscribers = db.AspNetPushNotificationSubscribers.Where(s => s.UserId == userId);

                if (subscribers.Count() != 0)
                {
                    foreach (var subscriber in subscribers)
                    {
                        var endpoint = subscriber.Endpoint;
                        var p256dh   = subscriber.P256dh;
                        var auth     = subscriber.Auth;
                        var payload  = JsonConvert.SerializeObject(data);

                        var subscription = new PushSubscription(endpoint, p256dh, auth);
                        var options      = new Dictionary <string, object>();
                        options["TTL"] = 3600;

                        var publicKey  = ConfigurationManager.AppSettings["PublicVapidKey"];
                        var privateKey = ConfigurationManager.AppSettings["PrivateVapidKey"];
                        options["vapidDetails"] = new VapidDetails(subject, publicKey, privateKey);
                        var webPushClient = new WebPushClient();
                        try
                        {
                            webPushClient.SendNotification(subscription, payload, options);
                        }
                        catch (WebPushException exception)
                        {
                            Debug.WriteLine("Http STATUS code: {0}", exception.StatusCode);
                        }
                    }
                }
            }
        }
        public ActionResult <string> enviar(string pushEndpoint, string p256dh, string auth)
        {
            var keys = VapidHelper.GenerateVapidKeys();

            // "eC8kA5lfrjc:APA91bHHHh3ikNWPa-614pz7FbWdPvCTn01OvkNuas6m-ilwP-U_VPHLd5QPsjL8W5G8gLquoTJd-jUVRDOziyXvxXoeY8ua2sRvt6GnG8WLpFdOkk7SI8_AxFZnlug4t9FOU7S-XjzH"
            pushEndpoint = @"https://fcm.googleapis.com/fcm/send/" + pushEndpoint;
            //p256dh = @"BAGGIn3MC7LZRCFKuRRSjA28bwQRP7mO_9AEr2l7ety-dtSn7Fcw11-aZu5UCOE0C2gVXVEaWkFLu7PWCR1ufGI";
            //auth = @"VKMl5N1lJomQreFUjKlzeQ";

            var subject    = @"mailto:[email protected]";
            var publicKey  = keys.PublicKey;
            var privateKey = keys.PrivateKey;

            var subscription = new PushSubscription(pushEndpoint, p256dh, auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, "payload", vapidDetails);
            }
            catch (WebPushException exception)
            {
                return(exception.StatusCode.ToString());
            }

            return("OK");
        }
        public void action(PushExample.Models.Entities.ClientInformation e, string message)
        {
            //var pushEndpoint = @"https://fcm.googleapis.com/fcm/send/elpgb-hTYfE:APA91bEbOObMfgrR2nc-kjfhm1iQscT6hcqGFDXn_IGYFMs5n5KCGIclzMAC_WZDbA34om0Ub9sqyhR1i_3Y0BQPhiZp1CnDWjTr74exx8wJp8KBFbMWhlzNWQJ3zA3LkM8rm2ZkQCjS";
            //var p256dh = @"BASOQRL625ssxHi4QiPRy-Tu9dih25IcVECTGfWqIIROwpq3xsWuwN3bpX3zWF_rv-jSCG08rkv4M2uAhYUnJSQ=";
            //var auth = @"Y6tPjfsSmb8aUPdNaJzBXA==";

            var subject    = @"mailto:[email protected]";
            var publicKey  = @"BD8r6N3kP4649YLBtRfaLn4rMPxSyMVUsE7sbE3acIlgk51SximXV2SlT8_TWpU5DYKBuFD8ZeZQyi0yS85Q4FY";
            var privateKey = @"z4wKrFkzEj-XQPpqPCZwaYsLQwctAzJHkbi2UykduLg";

            var subscription = new PushSubscription(e.pushEndpoint, e.p256dh, e.auth);
            var vapidDetails = new VapidDetails(subject, publicKey, privateKey);
            //var gcmAPIKey = @"[your key here]";

            var webPushClient = new WebPushClient();

            try
            {
                webPushClient.SendNotification(subscription, message, vapidDetails);
                //webPushClient.SendNotification(subscription, "payload", gcmAPIKey);
            }
            catch (WebPushException exception)
            {
                Console.WriteLine("Http STATUS code" + exception.StatusCode);
            }
        }
        public void FireNotification(NotificationContent notificationContent)
        {
            if (SubscriptionBrowsers.Subscriptions.Any())
            {
                if (SubscriptionBrowsers.Subscriptions.ContainsKey(notificationContent.Browser))
                {
                    var pushSubscription = SubscriptionBrowsers.Subscriptions[notificationContent.Browser].ToPushSubscription();

                    var vapidDetails = new VapidDetails(this.ApplicationMailTo, this.ApplicationPublicKey, this.ApplicationPrivateKey);

                    var data = Newtonsoft.Json.JsonConvert.SerializeObject(notificationContent);

                    var webPushClient = new WebPushClient();
                    webPushClient.SendNotification(pushSubscription, data, vapidDetails);
                }
                else
                {
                    throw new Exception("There is no subscription for this browser.");
                }
            }
            else
            {
                throw new Exception("There isn't any subscriptions");
            }
        }
Exemple #20
0
        private void OnExecute()
        {
            var pushSubscription = new PushSubscription(PushEndpoint, PushP256DH, PushAuth);
            var vapidDetails     = new VapidDetails("mailto:[email protected]", PublicKey, PrivateKey);

            var webPushClient = new WebPushClient();

            webPushClient.SendNotification(pushSubscription, Message, vapidDetails);
        }
Exemple #21
0
        public void SendNotification(Subscription subscription, Notification payload)
        {
            var webPushSubscription = new WebPush.PushSubscription(
                subscription.EndPoint,
                subscription.Code,
                subscription.Auth);

            _pushClient.SendNotification(webPushSubscription, Newtonsoft.Json.JsonConvert.SerializeObject((WebPushAdapter)payload));
        }
Exemple #22
0
        public void ReNotify(List <ReNotify> reNotify)
        {
            Api    API = new Api();
            string url = "Notification/SendNotification";

            foreach (var notify in reNotify)
            {
                Dictionary <string, string> arg = new Dictionary <string, string>()
                {
                    { "personId", notify.PersonId },
                    { "notificationId", notify.NotifyId },
                };
                var notifications = API.Get <List <SendNotificationBE> >(url, arg);

                foreach (var item in notifications)
                {
                    var objNotification = JsonConvert.DeserializeObject <KeyNotification>(item.Subs);

                    var pushEndpoint = objNotification.endpoint;
                    var p256dh       = objNotification.Keys.p256dh;
                    var auth         = objNotification.Keys.auth;

                    var oMessage = new Message();
                    oMessage.title   = item.Title;
                    oMessage.message = item.Message;

                    //var payload = "{'title':" +item.Title + "','message':" + item.Body + "}";
                    var payload = JsonConvert.SerializeObject(oMessage);
                    var options = new Dictionary <string, object>();
                    options["vapidDetails"] = new VapidDetails("mailto:[email protected]", "BKtlRblOBWPha7rSZ8pKA6NRsFz6PzKu1aQ0_nk4e5P_bANWknvjg0ViRmYVLTHDbeQurDv7YKt9J9luQm_EnYM", "h__qPKs38j65-UgxnRnfcVrDMEzriFvSVqL8EkugvXw");
                    options["gcmAPIKey"]    = @"[your key here]";

                    var webPushClient = new WebPushClient();

                    Thread t = new Thread((a) => {
                        try
                        {
                            webPushClient.SendNotification((PushSubscription)a,
                                                           payload, options);
                        }
                        catch (WebPushException exception)
                        {
                            Console.WriteLine("Http STATUS code" + exception.StatusCode);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    });
                    var s = new PushSubscription(pushEndpoint, p256dh, auth);
                    t.Start(s);
                }
            }


            //return new JsonResult { Data = notifications, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
        public static void SendNotification(PushSubscriptionInformation subscription, string message)
        {
            var pushClient   = new WebPushClient();
            var vapidDetails = new VapidDetails(VAPIDConfiguration.Subject, VAPIDConfiguration.PublicKey, VAPIDConfiguration.PrivateKey);

            pushClient.SetVapidDetails(vapidDetails);
            var pushSubscription = new PushSubscription(subscription.EndPoint, subscription.Keys.p256dh, subscription.Keys.Authentication);

            pushClient.SendNotification(pushSubscription, JsonConvert.SerializeObject(new RootNotification(message)));
        }
Exemple #24
0
        public void Broadcast([FromBody] NotificationModelDto message, [FromServices] VapidDetails vapidDetails)
        {
            var client            = new WebPushClient();
            var serializedMessage = JsonConvert.SerializeObject(message);

            foreach (var pushSubscription in Subscriptions)
            {
                client.SendNotification(pushSubscription, serializedMessage, vapidDetails);
            }
        }
        private void TestSendNotification(HttpStatusCode status)
        {
            var subscription = new PushSubscription(TestFcmEndpoint, TestPublicKey, TestPrivateKey);;

            httpMessageHandlerMock.When(TestFcmEndpoint).Respond(status);

            client.SetVapidDetails(TestSubject, TestPublicKey, TestPrivateKey);

            client.SendNotification(subscription, "123");
        }
        public void TestSendFCMMessage()
        {
            string           p256dh       = @"BPez73CdNHyBIFW";
            string           auth         = @"r_36Ti2Z";
            WebPushClient    client       = new WebPushClient();
            PushSubscription subscription = new PushSubscription(TEST_FCM_ENDPOINT, p256dh, auth);
            var vapidDetails = new VapidDetails("mailto:[email protected]", TEST_PUBLIC_KEY, TEST_PRIVATE_KEY);

            client.SendNotification(subscription, "Insert here a payload", vapidDetails);
        }
        private void TestSendNotification(HttpStatusCode status, string response = null)
        {
            var subscription = new PushSubscription(TestFcmEndpoint, TestPublicKey, TestPrivateKey);
            var httpContent  = response == null ? null : new StringContent(response);

            httpMessageHandlerMock.When(TestFcmEndpoint).Respond(new HttpResponseMessage {
                StatusCode = status, Content = httpContent
            });
            client.SetVapidDetails(TestSubject, TestPublicKey, TestPrivateKey);
            client.SendNotification(subscription, "123");
        }
        public static void Broadcast(NotificationModel message, List <User> Users)
        {
            var client            = new WebPushClient();
            var serializedMessage = JsonConvert.SerializeObject(message);
            List <Suscription> UserSuscriptions = Users.Where(a => a.UserDates.Suscribed == true).Select(a => a.Suscription).ToList();

            foreach (Suscription pushSubscription in UserSuscriptions)
            {
                client.SendNotification(pushSubscription, serializedMessage, _vapidDetails);
            }
        }
Exemple #29
0
        // POST api/values
        public void Post([FromBody] PushNotification pushNotification)
        {
            var vapidPublicKey  = ConfigurationManager.AppSettings["VapidPublicKey"];
            var vapidPrivateKey = ConfigurationManager.AppSettings["VapidPrivateKey"];

            var pushSubscription = new PushSubscription(pushNotification.PushEndpoint, pushNotification.PushP256DH, pushNotification.PushAuth);
            var vapidDetails     = new VapidDetails("mailto:[email protected]", vapidPublicKey, vapidPrivateKey);

            var webPushClient = new WebPushClient();

            webPushClient.SendNotification(pushSubscription, JsonConvert.SerializeObject(pushNotification), vapidDetails);
        }
 public void SendNotification(SubscriptionDTO subscription, string message)
 {
     try
     {
         PushSubscription pushSubscription = new(subscription.Endpoint,
                                                 subscription.Keys.P256dh, subscription.Keys.Auth);
         webPushClient.SendNotification(pushSubscription, message, vapidDetails);
     }
     catch (WebPushException)
     {
         // Subscription has expired or is no longer valid and should be removed.
     }
 }