public async Task <IActionResult> UserNotification([FromRoute] int id, [FromBody] UserNotificationRequest notif)
        {
            var loggedUser = User.GetUserIdFromToken();
            await _userService.SendUserNotificationAsync(loggedUser, id, notif);

            return(Ok());
        }
Exemple #2
0
        public async Task SendUserNotificationAsync(int loggedUser, int id, UserNotificationRequest notif)
        {
            var user = await _uow.UserRepository.GetAsync(loggedUser);

            if (user.Role == RoleEnum.NORMAL)
            {
                throw new NotAllowedException("User");
            }
            var userToUpdate = await _uow.UserRepository.GetAll()
                               .Include(u => u.Devices)
                               .Where(u => u.Id == id)
                               .FirstOrDefaultAsync();

            if (userToUpdate == null)
            {
                throw new NotFoundException("User");
            }
            var serverKey = _config["Firebase:ServerKey"];
            var senderId  = _config["Firebase:SenderId"];

            foreach (var dev in userToUpdate.Devices)
            {
                using (var fcm = new FcmSender(serverKey, senderId))
                {
                    Message message = new Message()
                    {
                        Notification = new Notification
                        {
                            Title = notif.Title,
                            Body  = notif.Body
                        },
                        Token = dev.Token
                    };
                    try
                    {
                        var response = await fcm.SendAsync(dev.Token, message);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
        }