Esempio n. 1
0
        public async Task <IHttpActionResult> Post([FromBody] Alert value)
        {
            var client = new FCMClient("AIzaSyChp172E9Q9oWg14_Ejy7H6Zr3x1SUCqwA");

            if (value.IsAndroid)
            {
                var info = new Dictionary <string, string>();
                info["Body"]  = JsonConvert.SerializeObject(value);
                info["Title"] = "Alert";
                var message = new Message()
                {
                    To = "GENERAL",

                    Data = info
                };

                var result = await client.SendMessageAsync(message);
            }
            else
            {
                var message = new Message()
                {
                    To           = "GENERAL",
                    Notification = new IOSNotification()
                    {
                        Body  = JsonConvert.SerializeObject(value),
                        Title = "Alert"
                    }
                };

                var result = await client.SendMessageAsync(message);
            }
            return(Ok());
        }
Esempio n. 2
0
        public async Task Send(string title, string body)
        {
            var messageToAndroid = AndroidMesasgeBuilder(title, body);
            var messageToIOS     = IOSMessageBuilder(title, body);
            await fcmClient.SendMessageAsync(messageToAndroid);

            await fcmClient.SendMessageAsync(messageToIOS);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_topic_message_with_data_AND_optional_fields_set_AND_notification_set_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To           = "/topics/android",
                CollapseKey  = "score_update",
                TimeToLive   = 108,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vss Denmark",
                    Icon  = "myIcon"
                },
                Data = new Dictionary <string, string>
                {
                    { "score", "5x1" },
                    { "time", "15:10" }
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <TopicMessageResponse>(result);
        }
        public async void SenderToFirebaseAsync(String msg)
        {
            var       registrationId = "dARiEevCnFo:APA91bFTev5UB_plXxXKmYTrkx79isGzjIeCSy0UST-KNaVQsnGICoF7qgbEYyFu-3n1y807iPNmFI5IbzIlNLpJQ6q-OMqAZmWZeEURmoO3TIlA2TmR9ZSL4Bq4INzHqPmtRsAIxg0Y";
            var       serverKey      = "AAAAkwlfmpI:APA91bElre6S3XNPQUzrLjhF5zPgUJFFWHrzblzNxcIpxAgzVEoay_RdS9wTbW-99Gq8KMvd9ecimKgBjJLh_Zjbrv4wQ-Hjl_gFEOYeGNzPUjxWljH7lIwVwyXvn3QCMFEvFF-Jh9_Q";
            FCMClient client         = new FCMClient(serverKey);
            var       message        = new Message
            {
                To           = registrationId,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                    Icon  = "myIcon"
                }
            };

            try{
                var result = await client.SendMessageAsync(message);

                Console.WriteLine("After FCMClient: SendMessageAsync");
            }catch (Exception error)
            {
                Console.WriteLine($"Text: '{error.Message}'");
            }
        }
        public async Task <bool> SenderToFirebaseAsync2(String dataJson)
        {
            bool bStatus  = true;
            var  ind      = dataJson.IndexOf("Index");
            var  indexVal = dataJson.Substring(ind, 10);

            Console.WriteLine("Processing Messsage " + indexVal);

            var       registrationId = "dARiEevCnFo:APA91bFTev5UB_plXxXKmYTrkx79isGzjIeCSy0UST-KNaVQsnGICoF7qgbEYyFu-3n1y807iPNmFI5IbzIlNLpJQ6q-OMqAZmWZeEURmoO3TIlA2TmR9ZSL4Bq4INzHqPmtRsAIxg0Y";
            var       serverKey      = "AAAAkwlfmpI:APA91bElre6S3XNPQUzrLjhF5zPgUJFFWHrzblzNxcIpxAgzVEoay_RdS9wTbW-99Gq8KMvd9ecimKgBjJLh_Zjbrv4wQ-Hjl_gFEOYeGNzPUjxWljH7lIwVwyXvn3QCMFEvFF-Jh9_Q";
            FCMClient client         = new FCMClient(serverKey);
            var       message        = new Message
            {
                To           = registrationId,
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                    Icon  = "myIcon"
                }
            };

            try{
                DownstreamMessageResponse result = (DownstreamMessageResponse)await client.SendMessageAsync(message);

                Console.WriteLine("After FCMClient: SendMessageAsync");
                Console.WriteLine($"Success: {result.Success} " + " Message" + indexVal);
            }catch (Exception error)
            {
                Console.WriteLine($"Text: '{error.Message}'");
            }
            return(bStatus);
        }
Esempio n. 6
0
        /// <summary>
        /// Send Push Android.
        /// </summary>
        /// <param name="registerationId"></param>
        /// <param name="body"></param>
        /// <param name="title"></param>
        /// <param name="icon"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <param name="firebaseServerKey"></param>
        /// <returns></returns>
        public async Task <bool> AndroidPushNotification(string registerationId, string body, string title, string icon, string data, string type, string firebaseServerKey)
        {
            if (!string.IsNullOrEmpty(firebaseServerKey))
            {
                FCMClient client  = new FCMClient(firebaseServerKey);
                var       message = new Message()
                {
                    To           = registerationId,
                    Notification = new AndroidNotification()
                    {
                        Body = body, Title = title, Icon = data, ClickAction = ".ClientDashboardActivity"
                    },
                    Data = new Dictionary <string, string> {
                        { "data", data }, { "NotificationType", type }, { "AccountType", "2" }
                    }
                };
                try
                {
                    await client.SendMessageAsync(message);

                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
Esempio n. 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="registerationId"></param>
        /// <param name="body"></param>
        /// <param name="title"></param>
        /// <param name="icon"></param>
        /// <param name="data"></param>
        /// <param name="type"></param>
        /// <param name="firebaseServerKey"></param>
        /// <param name="isRedirect"></param>
        /// <param name="notificationSubType"></param>
        /// <param name="customReferenceId"></param>
        /// <returns></returns>
        public async Task <bool> AndroidPushNotificationBulk(List <string> registerationId, string body, string title, string icon, string data, string type, string firebaseServerKey, bool isRedirect, string notificationSubType, int customReferenceId)
        {
            if (!string.IsNullOrEmpty(firebaseServerKey))
            {
                FCMClient client  = new FCMClient(firebaseServerKey);
                var       message = new Message()
                {
                    RegistrationIds = registerationId,
                    Notification    = new AndroidNotification()
                    {
                        Body = body, Title = title, Icon = data, ClickAction = ".ClientDashboardActivity"
                    },
                    Data = new Dictionary <string, string> {
                        { "data", data }, { "notificationType", type }, { "accountType", "2" }, { "IsRedirect", isRedirect.ToString() }, { "NotificationSubType", notificationSubType }, { "CustomReferenceId", customReferenceId.ToString() }
                    }
                };
                try
                {
                    await client.SendMessageAsync(message);

                    return(true);
                }
                catch (Exception)
                {
                    return(false);
                }
            }
            return(false);
        }
        public async Task <IActionResult> SaveMatch([FromBody] Match model)
        {
            try
            {
                if (_db.Matches.Where(x => x.OpportunityId == model.OpportunityId && x.UserId == model.UserId).Count() == 0)
                {
                    model.CreationDate = DateTime.Now;
                    model.LastUpdate   = DateTime.Now;

                    var Sender = await _db.Users.FirstOrDefaultAsync(x => x.Id == model.UserId);

                    var opp = await _db.Opportunities.Include(x => x.KPIs).Include(u => u.User).FirstOrDefaultAsync(x => x.Id == model.OpportunityId);

                    var Receiver = await _db.Users.FindAsync(opp.User.Id);

                    var AmIBlocked = await _db.BlockedUsers.FirstOrDefaultAsync(x => !x.IsDeleted && x.UserId == Receiver.Id && x.BlockedUserId == Sender.Id);

                    if (AmIBlocked != null)
                    {
                        return(BadRequest("You cant send a match to " + Receiver.Name + " since you are blocked."));
                    }

                    if (Sender != null && opp != null)
                    {
                        _db.Matches.Add(model);
                        Sender.Naos              += 100;
                        Receiver.Naos            += 100;
                        _db.Entry(Sender).State   = EntityState.Modified;
                        _db.Entry(Receiver).State = EntityState.Modified;
                        await _db.SaveChangesAsync();

                        await Task.Run(async() => {
                            FCMClient client = new FCMClient(ServerApiKey); //as derived from https://console.firebase.google.com/project/
                            var message      = new FirebaseNet.Messaging.Message()
                            {
                                To           = Receiver.FireBaseToken, //topic example /topics/all
                                Notification = new IOSNotification()
                                {
                                    Body  = "The user " + Sender.Name + " sent you a match.",
                                    Title = opp.Title + " Match!!",
                                },
                            };
                            var result = await client.SendMessageAsync(message);
                        });

                        return(StatusCode(StatusCodes.Status200OK));
                    }
                    return(BadRequest(ModelState));
                }
                else
                {
                    return(BadRequest("You’ve already sent a match to this opportunity and user."));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
        }
        public async Task <IActionResult> MatchBack([FromBody] Match model)
        {
            try
            {
                if (_db.Matches.Where(x => x.OpportunityId == model.OpportunityId && x.UserId == model.UserId).Count() == 1)
                {
                    var Receiver = await _db.Users.FirstOrDefaultAsync(x => x.Id == model.UserId);

                    var opp = await _db.Opportunities.Include(x => x.KPIs).Include(u => u.User).FirstOrDefaultAsync(x => x.Id == model.OpportunityId);

                    var Sender = await _db.Users.FindAsync(opp.User.Id);

                    var Match = await _db.Matches.FindAsync(model.Id);

                    if (Sender != null && opp != null && Receiver != null)
                    {
                        Match.LastUpdate = DateTime.Now;
                        Match.Status     = Status.Matched;
                        _db.Matches.Update(Match);


                        Sender.Naos   += 150;
                        Receiver.Naos += 150;

                        _db.Entry(Sender).State   = EntityState.Modified;
                        _db.Entry(Receiver).State = EntityState.Modified;


                        await _db.SaveChangesAsync();

                        await Task.Run(async() => {
                            FCMClient client = new FCMClient(ServerApiKey); //as derived from https://console.firebase.google.com/project/
                            var message      = new FirebaseNet.Messaging.Message()
                            {
                                To           = Receiver.FireBaseToken, //topic example /topics/all
                                Notification = new IOSNotification()
                                {
                                    Body  = "The user " + Sender.Name + " matched you back.",
                                    Title = opp.Title + " Matched back!",
                                },
                            };
                            var result = await client.SendMessageAsync(message);
                        });

                        return(StatusCode(StatusCodes.Status200OK));
                    }
                    return(BadRequest(ModelState));
                }
                else
                {
                    return(BadRequest("You already matched back this opportunity and user."));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
        }
 public static Task <IFCMResponse> SendMessage(List <string> toIds, string operationName, object contents)
 {
     return(_client.SendMessageAsync(new FirebaseNet.Messaging.Message()
     {
         RegistrationIds = toIds,
         Data = new Dictionary <string, string> {
             { "operation", operationName },
             { "contents", JsonSerializer.Serialize(contents) }
         }
     }));
 }
        public static async Task SendMessage(User recipient, IDictionary <string, string> data = null)
        {
            var client = new FCMClient(FcmServerKey);

            var message = new Message()
            {
                To   = recipient.FirebaseToken,
                Data = data
            };

            await client.SendMessageAsync(message);
        }
Esempio n. 12
0
        public async Task <IActionResult> SendMessage([FromBody] Entities.Message sentMessage)
        {
            try
            {
                var Receiver = await _db.Users.FindAsync(sentMessage.ReceiverId);

                var Sender = await _db.Users.FindAsync(sentMessage.SenderId);

                var AmIBlocked = await _db.BlockedUsers.FirstOrDefaultAsync(x => !x.IsDeleted && x.UserId == Receiver.Id && x.BlockedUserId == Sender.Id);

                if (AmIBlocked != null)
                {
                    return(BadRequest("You cant send a message to " + Receiver.Name + " since you are blocked."));
                }

                if (sentMessage != null)
                {
                    _db.Message.Add(sentMessage);
                    await _db.SaveChangesAsync();

                    await Task.Run(async() => {
                        FCMClient client = new FCMClient(ServerApiKey); //as derived from https://console.firebase.google.com/project/

                        var message = new FirebaseNet.Messaging.Message()
                        {
                            To           = Receiver.FireBaseToken, //topic example /topics/all
                            Notification = new IOSNotification()
                            {
                                Body  = sentMessage.Text,
                                Title = Sender.Name,
                            },
                            Data = new Dictionary <string, string>
                            {
                                { "Body", sentMessage.Text },
                                { "Title", "New Message" },
                                { "SenderId", sentMessage.SenderId },
                                { "SenderPicture", Sender?.ProfilePicUrl }
                            }
                        };
                        var result = await client.SendMessageAsync(message);
                    });

                    return(Ok());
                }

                return(BadRequest());
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
        }
Esempio n. 13
0
        public async Task <IHttpActionResult> Post([FromBody] Alert value)
        {
            var client = new FCMClient("AAAAJk2sCkg:APA91bGEr-eF3mxVqfr_-bo9JFiStCDVTVaKCIbvJGEDmEEgqXQL59-JbcpCStyG2mkUlt4KchuT0_85U0Vo1-yOTgwFv6sObO_YCzmyZI7ct8wh19YCExsO1SokTc11lE4BLgqsh_Jv");

            //await NotifyAsync("/topics/general", value.Title, JsonConvert.SerializeObject(value));
            if (value.IsAndroid)
            {
                var info = new Dictionary <string, string>();
                info["Body"]  = JsonConvert.SerializeObject(value);
                info["Title"] = value.Title;
                var message = new Message()
                {
                    /* Notification = new AndroidNotification()
                     * {
                     *   Body = JsonConvert.SerializeObject(value),
                     *   Title = value.Title
                     * },*/
                    To   = "/topics/general",
                    Data = info
                };

                var result = await client.SendMessageAsync(message);
            }
            else
            {
                var message = new Message()
                {
                    To           = "/topics/general",// "/topics/all",
                    Notification = new IOSNotification()
                    {
                        Body  = JsonConvert.SerializeObject(value),
                        Title = "Alert"
                    }
                };

                var result = await client.SendMessageAsync(message);
            }//*/
            return(Ok());
        }
Esempio n. 14
0
        /// <summary>
        /// Pass in the message object and call this method in a 'var' variable. It would work asynchronously.
        /// </summary>
        /// <param name="message">FCM message object</param>
        /// <returns></returns>
        async public Task sendNotification(Message message)
        {
            try
            {
                var result = await client.SendMessageAsync(message);

                Console.WriteLine(result);
            }
            catch (Exception)
            {
                Console.WriteLine("Notification failure.");
            }
        }
Esempio n. 15
0
        public async Task SendToAllRoomMembersAsync(string[] ids, string message)
        {
            var info = new Message()
            {
                RegistrationIds = ids,
                Data            = new Dictionary <string, string>
                {
                    { "Message", $"{message}" }
                }
            };

            var result = await fcmClient.SendMessageAsync(info);
        }
Esempio n. 16
0
        public async Task SendMessage(PushNotificationMessageType messageType,
                                      Station station, string topic, DateTime date)
        {
            var client  = new FCMClient(_ApiKey);
            var context = GetTitleAndBodyPlaceHolder(messageType);
            var payload = GetPayload(date, station, context.title, context.body);

            //var topic = stationKey;// "news";
            var message = new Message()
            {
                To           = $"/topics/{topic}_iOS",
                Data         = payload,
                Notification = new IOSNotificationExtented()
                {
                    Body           = context.body,
                    Title          = context.title,
                    MutableContent = "true"
                                     //Icon = "myIcon"
                }
            };

            var result = await client.SendMessageAsync(message);

            message = new Message()
            {
                To   = $"/topics/{topic}_Android",
                Data = payload
                       //Notification = new IOSNotificationExtented()
                       //{
                       //    Body = context.body,
                       //    Title = context.title,
                       //    MutableContent = "true"
                       //    //Icon = "myIcon"
                       //}
            };

            result = await client.SendMessageAsync(message);
        }
Esempio n. 17
0
        public Task NotificacionTerminarPedido(string token)
        {
            var client  = new FCMClient(FirebaseToken);
            var message = new Message()
            {
                To           = token,
                Notification = new AndroidNotification()
                {
                    Title = "Su pedido está listo",
                    Body  = "El mozo le estará trayendo su pedido en unos momentos"
                }
            };

            return(client.SendMessageAsync(message));
        }
Esempio n. 18
0
        public Task NotificacionGenerarBoleta(string token)
        {
            var client  = new FCMClient(FirebaseToken);
            var message = new Message()
            {
                To           = token,
                Notification = new AndroidNotification()
                {
                    Title = "Su boleta está lista",
                    Body  = "El mozo le estará trayendo su boleta en unos momentos o puede acercarse a caja"
                }
            };

            return(client.SendMessageAsync(message));
        }
Esempio n. 19
0
        public static async Task <IFCMResponse> foo()
        {
            FCMClient client  = new FCMClient("YOUR_APP_SERVER_KEY"); //as derived from https://console.firebase.google.com/project/
            var       message = new Message()
            {
                To           = "DEVICE_ID_OR_ANY_PARTICULAR_TOPIC", //topic example /topics/all
                Notification = new AndroidNotification()
                {
                    Body  = "great match!",
                    Title = "Portugal vs. Denmark",
                }
            };
            var result = await client.SendMessageAsync(message);

            return(result);
        }
Esempio n. 20
0
        public async Task <IFCMResponse> sendFireBaseNotification(string androidKey, string notificationTitle, string notificationBody)
        {
            var message = new Message()
            {
                To           = androidKey,
                Notification = new AndroidNotification()
                {
                    Body  = notificationBody,
                    Title = notificationTitle,
                    Sound = "default",
                    Color = "#df8001"
                }
            };
            var result = await _client.SendMessageAsync(message);

            return(result);
        }
        public static async Task Send(string topic, string title, string body)
        {
            HttpClient _client = new HttpClient();

            FCMClient client = new FCMClient(App.FCMServerKey);

            var message = new Message()
            {
                To           = "/topics/" + topic,
                Notification = new AndroidNotification()
                {
                    Title = title,
                    Body  = body
                }
            };

            var result = await client.SendMessageAsync(message);
        }
        public async Task Given_an_invalid_server_key_THEN_I_must_get_an_FCM_exception()
        {
            FCMClient client = new FCMClient("foo");

            var message = new Message()
            {
                DryRun       = true,
                To           = "1213",
                Notification = new AndroidNotification()
                {
                    Title = "Title",
                    Body  = "body",
                }
            };

            var result = await Assert.ThrowsAsync <FCMUnauthorizedException>(() => client.SendMessageAsync(message));

            Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
        }
Esempio n. 23
0
        public void SendPushNotification(string title, string body)
        {
            var notifications = new INotification[]
            {
                GetIosNotification(title, body)
            };

            var messages = notifications.Select(GetMessage).ToList();

            foreach (var message in messages)
            {
                dynamic resposne = fcmClient.SendMessageAsync(message).Result;
                var     error    = resposne?.Error;
                if (error != null)
                {
                    throw new Exception($"FCM Error: {error}");
                }
            }
        }
        public async Task Given_a_valid_server_key_AND_a_valid_downstream_message_with_data_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To   = "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
                Data = new Dictionary <string, string>
                {
                    { "score", "5x1" },
                    { "time", "15:10" }
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <DownstreamMessageResponse>(result);
        }
Esempio n. 25
0
 private static async Task SendFcmMessage(string pushName, string body, NotificationUser user, string token)
 {
     FCMClient client  = new FCMClient(GetServerKey());
     var       message = new FirebaseNet.Messaging.Message()
     {
         To   = token,
         Data = new Dictionary <string, string>
         {
             { "badge", (user.UnreadNotificationCount + 1).ToString() },
             { "app-action", @"new-message" },
             { "message", body }
         }
     };
     var response = client.SendMessageAsync(message);
     await response.ContinueWith(t =>
     {
         var results = t.Result as DownstreamMessageResponse;
         _logQueue.Enqueue(@" ------------" + DateTime.Now + "--------------------" + '\n' + "sent to  " + user.AppUserId + " is success : " + results.Success + '\n' + "errors : " + String.Join(" , ", results.Results.Select(x => x.Error)));
     });
 }
        public async Task Given_a_valid_server_key_AND_a_valid_downstream_message_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                To           = "deviceid",
                Notification = new AndroidNotification()
                {
                    Title = "Message title",
                    Body  = "Notification body",
                    Color = "#000000"
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <DownstreamMessageResponse>(result);
        }
        public async Task Given_a_valid_server_key_AND_a_valid_topic_message_THEN_I_must_get_a_valid_response()
        {
            FCMClient client = new FCMClient(ServerApiKey);

            var message = new Message()
            {
                DryRun       = true,
                To           = "/topics/android",
                Notification = new AndroidNotification()
                {
                    Title = "Title",
                    Body  = "body",
                }
            };

            var result = await client.SendMessageAsync(message);

            Assert.NotNull(result);
            Assert.IsType <TopicMessageResponse>(result);
        }
Esempio n. 28
0
        static void SendIOS()
        {
            Task.Run(async() =>
            {
                FCMClient client = new FCMClient(YOUR_APP_SERVER_KEY); //as derived from https://console.firebase.google.com/project/

                var message = new Message()
                {
                    To           = "DEVICE_ID_OR_ANY_PARTICULAR_TOPIC", //topic example /topics/all
                    Notification = new iOSNotification()
                    {
                        Body  = "Hello World",
                        Title = "MyApp",
                    }
                };

                var result = await client.SendMessageAsync(message);
                return(result);
            });
        }
Esempio n. 29
0
        private static int SendFcmBatchMessages(string body, List <NotificationUser> users) // restricted to 1000
        {
            FCMClient client  = new FCMClient(GetServerKey());
            var       message = new FirebaseNet.Messaging.Message()
            {
                RegistrationIds = users.Select(x => x.FcmToken).ToList(),
                Data            = new Dictionary <string, string>
                {
                    { "app-action", @"new-message" },
                    { "message", body }
                }
            };
            var res         = new List <DownstreamMessageResponse>();
            var response    = client.SendMessageAsync(message);
            var contiuation = response.ContinueWith(t => res.Add((DownstreamMessageResponse)t.Result));

            Notification.UpdateUnreadNotificationCountOfUsers(users.Select(x => x.AppUserId).ToList());
            contiuation.Wait();
            return((int)res.Sum(x => x.Success));
        }
        public static async Task SendMessage(User recipient, string title, string body,
                                             IDictionary <string, string> data = null, string clickAction = null, string sound = "default",
                                             string icon = "default")
        {
            var client = new FCMClient(FcmServerKey);

            var message = new Message()
            {
                To           = recipient.FirebaseToken,
                Notification = new AndroidNotification()
                {
                    Body        = body,
                    Title       = title,
                    Icon        = icon,
                    ClickAction = clickAction,
                    Sound       = sound,
                },
                Data = data
            };

            await client.SendMessageAsync(message);
        }