Example #1
0
        public async Task ChatMessage(GroupMessageDto payload, User user, Group group, IClientProxy clients)
        {
            if (!string.IsNullOrEmpty(user.ConnectionId))
            {
                await clients.SendAsync("IncomingMessage", payload);
            }

            if (string.IsNullOrEmpty(user.FcmToken))
            {
                return;
            }
            var serializedMessage = JsonConvert.SerializeObject(payload);

            var message = new Message()
            {
                Token = user.FcmToken,
                Data  = new Dictionary <string, string>()
                {
                    { "type", "IncomingMessage" },
                    { "data", serializedMessage }
                },
                Android = new AndroidConfig()
                {
                }
            };
            var response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
        }
Example #2
0
        public async Task PushNotify(string clientGroupName, Noftication noftication, Triple <string, string, ObjectNotificationType> notificationSetting, string customContent)
        {
            try
            {
                FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

                ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

                foreach (string receiver in clientGroup.UserIds)
                {
                    Noftication finalNotification = new Noftication()
                    {
                        AuthorId        = noftication.AuthorId,
                        OwnerId         = noftication.OwnerId,
                        ReceiverId      = receiver,
                        ObjectId        = noftication.ObjectId,
                        ObjectType      = notificationSetting.Item3,
                        ObjectThumbnail = noftication.ObjectThumbnail,
                        Content         = customContent
                    };

                    await nofticationRepository.AddAsync(finalNotification);

                    var notiViewModel = mapper.Map <NotificationViewModel>(finalNotification);

                    try
                    {
                        FilterDefinition <FcmInfo> user = Builders <FcmInfo> .Filter.Eq("user_id", receiver);

                        string token  = (await fcmInfoRepository.FindAsync(user)).DeviceToken;
                        User   sender = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotification.AuthorId));

                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,

                            Data = new Dictionary <string, string>()
                            {
                                { "notification", JsonConvert.SerializeObject(notiViewModel) }
                            },
                            Notification = new Notification()
                            {
                                Title    = "Quản trị viên CoStudy",
                                Body     = notiViewModel.Content,
                                ImageUrl = configuration["AdminAvatar"]
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                }
            }
            catch (Exception)
            {
                //Do nothing
            }
        }
Example #3
0
        private async Task btnPeticion_ClickAsync()
        {
            //INICIALIZACION DEL SDK CON LAS CREDENCIALES PROPORCIONADAS POR FIREBASE
            FirebaseApp.Create(new AppOptions()
            {
                Credential = GoogleCredential.FromFile("C:/Users/kokod/Downloads/fir-3aea1-firebase-adminsdk-1i19f-0b40e0855a.json")
            });

            //TOKEN DEL DISPOSITIVO PARA ENVIAR LA NOTIFICACION
            var registrationToken = "cJKqQVSsQiqsJNBlP3Aj13:APA91bGwB56RkH2C2dpvl9Iwf4G4pqa9Hw6PKIVc3RYwGY2dy4b2ez8ncrjJ72a2Rdy6Yyst3Kj_NE4hz_eXZfkBd7pqGqdasd0-uIFxHhcSVjjU2At9mS0d3Y0J03nx4sefxEaxEWEI";

            //DEFINICION DE UN MENSAJE, QUE INCLUYE UNA NOTIFICACION CON TITULO Y CUERPO, ASI COMO EL TOKEN
            var message = new FirebaseAdmin.Messaging.Message()
            {
                Notification = new Notification()
                {
                    Title = txtTitulo.Text,
                    Body  = txtCuerpo.Text,
                },
                Token = registrationToken,
            };

            //ENVIAR EL MENSAJE AL TOKEN INDICADO
            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);

            //RESPUESTA DE LA PETICION CON EL ID DEL MENSAJE ENVIADO
            MessageBox.Show("Successfully sent message: " + response);
        }
        public async Task <bool> PushNotification(PushNotificationInput input)
        {
            try
            {
                ApplicationUser userDeviceToken = _userManager.Users.FirstOrDefault(x => x.Id == input.UserId);
                if (userDeviceToken != null)
                {
                    if (!string.IsNullOrEmpty(userDeviceToken.RegId))
                    {
                        var message = new FirebaseAdmin.Messaging.Message()
                        {
                            Notification = new FirebaseAdmin.Messaging.Notification()
                            {
                                Title = input.title,
                                Body  = input.body,
                            },
                            Token = userDeviceToken.RegId,
                        };

                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
                    }
                }
                return(true);
            }
            catch (Exception exc)
            {
                return(false);
            }
        }
Example #5
0
        public async Task <string> SendNotification()
        {
            FirebaseAdmin.Messaging.Message message = new FirebaseAdmin.Messaging.Message()
            {
                Token =
                    "d2Yvrq1sT8iZyZvgKtaE2Z:APA91bGuJp5Cyt2J1WuPB-GhEA3sR1eG-CwnIFJn0E2BguDjenY4TDy9gyY0phVJ8VqCZL_3Z56gaG-tBoIXjPZGxmHRpcT_CsQbNi-OxJ-XCJDxQx9LFWGgvnVPxyNqPoTm50GzNmwz",

                Data = new Dictionary <string, string>()
                {
                    { "title", "Title test" },
                    { "body", "Body Test" },
                },
                Notification = new Notification()
                {
                    Title = "title test",
                    Body  = "body test"
                }
            };
            string response = await FirebaseMessaging.DefaultInstance.SendAsync(message).ConfigureAwait(true);

            return(response);
        }
Example #6
0
        public async Task CallStarted(User user, Group @group, IClientProxy clients)
        {
            var payload = new CallStartedDto(user, @group);

            if (!string.IsNullOrEmpty(user.ConnectionId))
            {
                await clients.SendAsync("CallStarted", payload);
            }
            if (string.IsNullOrEmpty(user.FcmToken))
            {
                return;
            }
            var serializedMessage = JsonConvert.SerializeObject(payload);
            var message           = new Message()
            {
                Token = user.FcmToken,
                Data  = new Dictionary <string, string>()
                {
                    { "type", "CallStarted" },
                    { "data", serializedMessage }
                }
            };
            var response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
        }
Example #7
0
        private async void Home_PanicButtonEventHandler(object sender, EventArgs e)
        {
            CrossCloudFirestore
            .Current
            .Instance
            .Collection("PEOPLE")
            .Document(FirebaseAuth.Instance.Uid)
            .AddSnapshotListener(async(value, error) =>
            {
                if (value.Exists)
                {
                    var users = value.ToObject <AppUsers>();

                    Dictionary <string, object> data = new Dictionary <string, object>();
                    data.Add("Uid", FirebaseAuth.Instance.CurrentUser.Uid);
                    data.Add("TimeDate", FieldValue.ServerTimestamp);
                    dbref = await CrossCloudFirestore
                            .Current
                            .Instance
                            .Collection("EMERGENCY")
                            .AddAsync(data);
                    var stream = Resources.Assets.Open("ServiceAccount.json");
                    var fcm    = FirebaseHelper.FirebaseAdminSDK.GetFirebaseMessaging(stream);
                    FirebaseAdmin.Messaging.Message message = new FirebaseAdmin.Messaging.Message()
                    {
                        Topic        = "alerts",
                        Notification = new Notification()
                        {
                            Title = "Emergency Alert",
                            Body  = $"${users.Username} may be in need of emergency assistance, please contact him on ${users.PhoneNumber} or contact the police and provide the address in the alert locator in the map.",
                        },
                    };
                    await fcm.SendAsync(message);
                }
            });
        }
Example #8
0
        public async Task PushNotifyPostMatch(string userId, NotificationDetail notificationDetail)
        {
            var currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

            await AddToGroup(
                new AddUserToGroupRequest
            {
                GroupName = userId,
                Type      = Feature.GetTypeName(currentUser),
                UserIds   = new List <string> {
                    userId
                }
            }
                );

            var finder = Builders <ClientGroup> .Filter.Eq("name", userId);

            var clientGroup = await clientGroupRepository.FindAsync(finder);

            foreach (string id in clientGroup.UserIds)
            {
                NotificationDetail finalNotificationDetail = new NotificationDetail()
                {
                    CreatorId            = notificationDetail.CreatorId,
                    ReceiverId           = userId,
                    NotificationObjectId = notificationDetail.NotificationObjectId
                };
                await notificationDetailRepository.AddAsync(finalNotificationDetail);

                NotificationObject notificationObject =
                    await notificationObjectRepository.GetByIdAsync(
                        ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                FilterDefinition <NotificationType> notificationTypeFilter =
                    Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                NotificationType notificationType = await notificationTypeRepository.FindAsync(notificationTypeFilter);

                User creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                PushedNotificationViewModel notificationToPush = new PushedNotificationViewModel()
                {
                    AuthorName   = $"{creator.FirstName} {creator.LastName}",
                    AuthorAvatar = creator.AvatarHash,
                    AuthorId     = creator.OId,
                    Content      = $"{notificationType.ContentTemplate}.",
                    CreatedDate  = DateTime.Now,
                    IsRead       = false,
                    ModifiedDate = DateTime.Now,
                    ObjectId     = notificationObject.ObjectId,
                    OId          = notificationObject.OId,
                    OwnerId      = userId,
                    Status       = ItemStatus.Active
                };
                //Push notification
                try
                {
                    FilterDefinition <FcmInfo> userFilter = Builders <FcmInfo> .Filter.Eq("user_id", userId);

                    string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                    FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                    {
                        Token = token,
                        Data  = new Dictionary <string, string>()
                        {
                            { "notification", JsonConvert.SerializeObject(notificationToPush) }
                        },
                        Notification = new Notification()
                        {
                            Title    = creator.LastName,
                            Body     = notificationToPush.Content,
                            ImageUrl = creator.AvatarHash
                        }
                    };
                    string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
        }
Example #9
0
        public async Task PushNotifyDetail(string clientGroupName, NotificationDetail notificationDetail)
        {
            FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

            User currentUser = Feature.CurrentUser(httpContextAccessor, userRepository);

            foreach (string receiverId in clientGroup.UserIds)
            {
                var existNotificationDetailBuilder = Builders <NotificationDetail> .Filter;
                var existNotificationDetailFilter  =
                    existNotificationDetailBuilder.Eq("creator_id", notificationDetail.CreatorId)
                    & existNotificationDetailBuilder.Eq("receiver_id", receiverId)
                    & existNotificationDetailBuilder.Eq("notification_object_id",
                                                        notificationDetail.NotificationObjectId);

                var existNotificationDetail =
                    await notificationDetailRepository.FindAsync(existNotificationDetailFilter);

                var finalNotificationDetail = new NotificationDetail();

                if (existNotificationDetail != null)
                {
                    finalNotificationDetail = existNotificationDetail;
                    finalNotificationDetail.ModifiedDate = DateTime.Now;
                    finalNotificationDetail.IsDeleted    = false;
                    await notificationDetailRepository.UpdateAsync(finalNotificationDetail, finalNotificationDetail.Id);
                }
                else
                {
                    finalNotificationDetail.CreatorId            = notificationDetail.CreatorId;
                    finalNotificationDetail.ReceiverId           = receiverId;
                    finalNotificationDetail.NotificationObjectId = notificationDetail.NotificationObjectId;
                    await notificationDetailRepository.AddAsync(finalNotificationDetail);
                }

                ;

                var notificationObject =
                    await notificationObjectRepository.GetByIdAsync(
                        ObjectId.Parse(finalNotificationDetail.NotificationObjectId));

                var owner = await userRepository.GetByIdAsync(ObjectId.Parse(notificationObject.OwnerId));

                var receiver = await userRepository.GetByIdAsync(ObjectId.Parse(receiverId));

                var creator = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotificationDetail.CreatorId));

                var notificationTypeFilter =
                    Builders <NotificationType> .Filter.Eq("code", notificationObject.NotificationType);

                var notificationType = await notificationTypeRepository.FindAsync(notificationTypeFilter);

                string notifyContent = string.Empty;

                if (owner.OId == creator.OId)
                {
                    if (receiver.OId == owner.OId)
                    {
                        notifyContent = $"Bạn {notificationType.ContentTemplate} chính mình";
                    }
                    else if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} họ";
                    }
                }
                else if (owner.OId != creator.OId)
                {
                    if (receiver.OId != owner.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} {owner.LastName}";
                    }
                    else if (receiver.OId != creator.OId)
                    {
                        notifyContent = $"{creator.LastName} {notificationType.ContentTemplate} bạn";
                    }
                }


                var notificationToPush = new PushedNotificationViewModel()
                {
                    AuthorName   = $"{creator.FirstName} {creator.LastName}",
                    AuthorAvatar = creator.AvatarHash,
                    AuthorId     = creator.OId,
                    Content      = notifyContent,
                    CreatedDate  = DateTime.Now,
                    IsRead       = false,
                    ModifiedDate = DateTime.Now,
                    ObjectId     = notificationObject.ObjectId,
                    OId          = notificationObject.OId,
                    OwnerId      = owner.OId,
                    Status       = ItemStatus.Active
                };

                switch (notificationType.Code)
                {
                case "ADD_POST_NOTIFY":
                case "UPVOTE_POST_NOTIFY":
                case "DOWNVOTE_POST_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Post;
                    break;

                case "UPVOTE_COMMENT_NOTIFY":
                case "DOWNVOTE_COMMENT_NOTIFY":
                case "COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Comment;
                    break;

                case "UPVOTE_REPLY_NOTIFY":
                case "DOWNVOTE_REPLY_NOTIFY":
                case "REPLY_COMMENT_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.Reply;
                    break;

                case "FOLLOW_NOTIFY":
                    notificationToPush.NotificationType = PushedNotificationType.User;
                    break;

                default:
                    notificationToPush.NotificationType = PushedNotificationType.Other;
                    break;
                }

                try
                {
                    if (!(owner.OId == creator.OId && receiver.OId == owner.OId))
                    {
                        var userFilter = Builders <FcmInfo> .Filter.Eq("user_id", receiverId);

                        string token = (await fcmInfoRepository.FindAsync(userFilter)).DeviceToken;

                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "notification", JsonConvert.SerializeObject(notificationToPush) }
                            },
                            Notification = new Notification()
                            {
                                Title    = creator.LastName,
                                Body     = notifyContent,
                                ImageUrl = creator.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                }
                catch (Exception)
                {
                    // do nothing
                }
            }
        }
Example #10
0
        public async Task PushNotify(string clientGroupName, Noftication noftication, Triple <string, string, ObjectNotificationType> notificationSetting)
        {
            try
            {
                FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

                ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

                foreach (string receiver in clientGroup.UserIds)
                {
                    var receiverUser = await userRepository.GetByIdAsync(ObjectId.Parse(receiver));

                    if (receiverUser.TurnOfNotification != null)
                    {
                        if (receiverUser.TurnOfNotification.Any(x => x == noftication.ObjectId))
                        {
                            return;
                        }
                    }

                    Noftication finalNotification = new Noftication()
                    {
                        AuthorId        = noftication.AuthorId,
                        OwnerId         = noftication.OwnerId,
                        ReceiverId      = receiver,
                        ObjectId        = noftication.ObjectId,
                        ObjectType      = notificationSetting.Item3,
                        ObjectThumbnail = noftication.ObjectThumbnail,
                    };

                    //Người tạo ra thông báo.
                    string creator     = noftication.AuthorId;
                    User   userCreator = await userRepository.GetByIdAsync(ObjectId.Parse(creator));

                    //Chủ sở hữu post
                    string owner     = noftication.OwnerId;
                    User   userOwner = await userRepository.GetByIdAsync(ObjectId.Parse(owner));


                    if (owner == creator)
                    {
                        if (receiver == owner)
                        {
                            finalNotification.Content = $"Bạn {notificationSetting.Item2} chính mình";
                        }
                        else if (receiver != owner)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} họ. ";
                        }
                    }
                    else if (owner != creator)
                    {
                        //owner: Trung
                        //receiver: trung
                        //Creator: Thắng
                        if (receiver != owner)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} {userOwner.FirstName} {userOwner.LastName}. ";
                        }
                        else if (receiver != creator)
                        {
                            finalNotification.Content = $"{userCreator.FirstName} {userCreator.LastName} {notificationSetting.Item2} bạn. ";
                        }
                    }

                    await nofticationRepository.AddAsync(finalNotification);

                    var notiViewModel = mapper.Map <NotificationViewModel>(finalNotification);
                    if (!(owner == creator && receiver == owner && creator == receiver))
                    {
                        try
                        {
                            FilterDefinition <FcmInfo> user = Builders <FcmInfo> .Filter.Eq("user_id", receiver);

                            string token  = (await fcmInfoRepository.FindAsync(user)).DeviceToken;
                            User   sender = await userRepository.GetByIdAsync(ObjectId.Parse(finalNotification.AuthorId));

                            FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                            {
                                Token = token,

                                Data = new Dictionary <string, string>()
                                {
                                    { "notification", JsonConvert.SerializeObject(notiViewModel) }
                                },
                                Notification = new Notification()
                                {
                                    Title    = $"{sender.FirstName} {sender.LastName}",
                                    Body     = notiViewModel.Content,
                                    ImageUrl = sender.AvatarHash
                                }
                            };
                            string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
            catch (Exception)
            {
                //Do nothing
            }
        }
Example #11
0
        public async Task SendMessage(string clientGroupName, MessageViewModel message)
        {
            FilterDefinition <ClientGroup> finder = Builders <ClientGroup> .Filter.Eq("name", clientGroupName);

            ClientGroup clientGroup = await clientGroupRepository.FindAsync(finder);

            foreach (string item in clientGroup.UserIds)
            {
                try
                {
                    FilterDefinition <FcmInfo> user = Builders <FcmInfo> .Filter.Eq("user_id", item);

                    string token  = (await fcmInfoRepository.FindAsync(user))?.DeviceToken;
                    User   sender = await userRepository.GetByIdAsync(ObjectId.Parse(message.SenderId));

                    var notifyBody = string.Empty;
                    switch (message.MessageType.Value)
                    {
                    case MessageBaseType.Text:
                        notifyBody = (message.Content as List <string>)[0];
                        break;

                    case MessageBaseType.Image:
                        notifyBody = "Đã gửi một ảnh. ";
                        break;

                    case MessageBaseType.MultiMedia:
                        notifyBody = "Đã gửi một phương tiện. ";
                        break;

                    case MessageBaseType.PostThumbnail:
                        notifyBody = "Đã gửi một liên kết. ";
                        break;

                    case MessageBaseType.ConversationActivity:
                        notifyBody = "Đã có hoạt động mới. ";
                        break;

                    case MessageBaseType.Other:
                        notifyBody = "Đã có thông báo mới. ";
                        break;

                    default:
                        break;
                    }

                    try
                    {
                        FirebaseAdmin.Messaging.Message mes = new FirebaseAdmin.Messaging.Message()
                        {
                            Token = token,
                            Data  = new Dictionary <string, string>()
                            {
                                { "message", JsonConvert.SerializeObject(message) }
                            },
                            Notification = new Notification()
                            {
                                Title    = sender.LastName,
                                Body     = notifyBody,
                                ImageUrl = sender.AvatarHash
                            }
                        };
                        string response = await FirebaseMessaging.DefaultInstance.SendAsync(mes).ConfigureAwait(true);
                    }
                    catch (Exception)
                    {
                        //Do nothing
                    }
                }
                catch (Exception)
                {
                    continue;
                }
            }
        }