protected virtual async Task <long[]> GetUserIds(NotificationScheme notificationScheme)
        {
            List <long> userIds;

            if (!notificationScheme.UserIds.IsNullOrEmpty())
            {
                //Directly get from UserIds and filter out not receive notification users
                userIds = notificationScheme
                          .UserIds
                          .Split(",")
                          .Select(long.Parse)
                          .Where(uid =>
                                 AsyncHelper.RunSync(() => _settingService.GetSettingValueForUserAsync(uid, SettingDefinitions.Names.ReceiveNotifications)).ToUpper() == "TRUE")
                          .ToList();
            }
            else
            {
                //Get all subscribed users
                var subscriptions = await _notificationRepository.GetSubscriptionsAsync(
                    notificationScheme.NotificationName,
                    notificationScheme.EntityTypeName,
                    notificationScheme.EntityId
                    );

                //Remove invalid subscriptions
                var invalidSubscriptions = new Dictionary <long, NotificationSubscription>();
                foreach (var subscription in subscriptions)
                {
                    if (!await _notificationDefinitionManager.IsAvailableAsync(notificationScheme.NotificationName, subscription.UserId) ||
                        AsyncHelper.RunSync(() => _settingService.GetSettingValueForUserAsync(subscription.UserId, SettingDefinitions.Names.ReceiveNotifications)).ToUpper() != "TRUE")
                    {
                        invalidSubscriptions[subscription.Id] = subscription;
                    }
                }

                subscriptions.RemoveAll(s => invalidSubscriptions.ContainsKey(s.Id));

                //Get user ids
                userIds = subscriptions.Select(s => s.UserId).ToList();
            }

            if (!notificationScheme.ExcludedUserIds.IsNullOrEmpty())
            {
                //Exclude specified userIds.
                var excludedUserIds = notificationScheme
                                      .ExcludedUserIds
                                      .Split(",")
                                      .Select(long.Parse)
                                      .ToList();

                userIds.RemoveAll(uid => excludedUserIds.Any(euid => euid.Equals(uid)));
            }

            return(userIds.ToArray());
        }
Esempio n. 2
0
        public async Task <ActionResult <Item> > AddItem([FromBody] Item item)
        {
            if (item == null)
            {
                return(BadRequest());
            }

            var _item = _context.Items.Where(i => i.TaesaId == item.TaesaId).FirstOrDefault();

            if (_item != null)
            {
                return(BadRequest(new { message = "Item já cadastrado." }));
            }

            item.FilterAttribute();

            var user = _context.Users.Include("Notifications").Where(u => u.Email.Equals(item.Email)).FirstOrDefault();

            if (user == null)
            {
                user = new User {
                    Email = item.Email
                };
                _context.Users.Add(user);
                _context.SaveChanges();
            }

            item.UserId = user.Id;
            _context.Add(item);
            _context.SaveChanges();

            // Enviar Notificação
            if (user.Notifications != null && user.Notifications.Count > 0)
            {
                var NotificationScheme = new NotificationScheme
                {
                    Title         = "Aprovador Taesa",
                    Body          = "Novo item cadastrado: " + item.Title,
                    Data          = item.GetItem(),
                    Notifications = user.Notifications
                };

                await _pushNotification.Send(NotificationScheme);
            }

            return(CreatedAtAction("GetItem", new { id = item.Id }, item));
        }
Esempio n. 3
0
        //Create EntityIdentifier includes entityType and entityId.
        /// <inheritdoc />
        public virtual async Task PublishAsync(
            string notificationName,
            NotificationData data             = null,
            EntityIdentifier entityIdentifier = null,
            NotificationSeverity severity     = NotificationSeverity.Info,
            long[] userIds         = null,
            long[] excludedUserIds = null)
        {
            if (notificationName.IsNullOrEmpty())
            {
                throw new ArgumentException("NotificationName can not be null or whitespace!", nameof(notificationName));
            }

            var notificationScheme = new NotificationScheme()
            {
                NotificationName = notificationName,
                EntityTypeName   = entityIdentifier?.Type.FullName,
                EntityTypeAssemblyQualifiedName = entityIdentifier?.Type.AssemblyQualifiedName,
                EntityId        = entityIdentifier?.Id.ToJsonString(),
                Severity        = severity,
                UserIds         = (userIds == null || userIds.Length <= 0) ? null : string.Join(",", userIds),
                ExcludedUserIds = (excludedUserIds == null || excludedUserIds.Length <= 0) ? null : string.Join(",", excludedUserIds),
                Data            = data?.ToJsonString(),
                DataTypeName    = data?.GetType().AssemblyQualifiedName
            };

            await _notificationRepository.InsertNotificationSchemeAsync(notificationScheme);

            await _notificationRepository.SaveChangesAsync(); //To get Id of the notification

            if (userIds != null && userIds.Length <= MaxUserCountToDirectlyDistributeANotification)
            {
                //We can directly distribute the notification since there are not much receivers
                await _notificationDistributer.DistributeAsync(notificationScheme.Id);
            }
            else
            {
                //We enqueue a background job since distributing may get a long time
                await _backgroundJobManager.EnqueueAsync(new NotificationDistributionJobArgs(notificationScheme.Id));
            }
        }
Esempio n. 4
0
        public async Task <bool> Send(NotificationScheme NotificationScheme)
        {
            bool status = false;

            try{
                var tokensFcm = new List <string>();

                foreach (Notification Notification in NotificationScheme.Notifications)
                {
                    tokensFcm.Add(Notification.TokenFcm);
                }

                var notification = new {
                    registration_ids = tokensFcm,
                    notification     = new {
                        title        = NotificationScheme.Title,
                        body         = NotificationScheme.Body,
                        color        = "#042769",
                        sound        = "default",
                        some         = "payload",
                        icon         = "notification",
                        click_action = "FCM_PLUGIN_ACTIVITY",
                    },
                    data = new {
                        item = NotificationScheme.Data
                    }
                };

                string notificationJson = JsonConvert.SerializeObject(notification);
                var    httpContent      = new StringContent(notificationJson, Encoding.UTF8, "application/json");

                var client = _clientFactory.CreateClient("fcm");
                var result = await client.PostAsync("https://fcm.googleapis.com/fcm/send", httpContent);

                string resultContent = await result.Content.ReadAsStringAsync();

                NotificationResponse NotificationResponse = JsonConvert.DeserializeObject <NotificationResponse>(resultContent);

                if (NotificationResponse.success > 0)
                {
                    status = true;
                }

                if (NotificationResponse.failure > 0)
                {
                    int count = 0;
                    foreach (NotificationResult Result in NotificationResponse.results)
                    {
                        if (Result.message_id == null)
                        {
                            _context.Notifications.Remove(NotificationScheme.Notifications.ElementAt(count));
                        }
                        count++;
                    }
                    _context.SaveChanges();
                }
            } catch (HttpRequestException) {
                // Gravar erro no LOG
            }
            return(status);
        }
 public virtual Task InsertNotificationSchemeAsync(NotificationScheme notification)
 {
     _notificationSchemeRepository.Add(notification);
     return(Task.CompletedTask);
 }
 public virtual Task DeleteNotificationAsync(NotificationScheme notification)
 {
     notification.IsDeleted = true;
     //_notificationSchemeRepository.Remove(notification);
     return(Task.CompletedTask);
 }
        protected virtual async Task <List <UserNotificationDto> > SaveUserNotifications(long[] userIds, NotificationScheme notificationScheme)
        {
            var userNotificationDtos = new List <UserNotificationDto>();
            var notificationDetail   = new NotificationDetail(notificationScheme);
            await _notificationRepository.InsertNotificationDetailAsync(notificationDetail);

            await _notificationRepository.SaveChangesAsync(); //To get notificationDetail.Id.

            var notificationDetailDto = notificationDetail.ToNotificationDetailDto();

            foreach (var userId in userIds)
            {
                var userNotification = new UserNotification()
                {
                    UserId = userId,
                    NotificationDetailId = notificationDetail.Id
                };

                await _notificationRepository.InsertUserNotificationAsync(userNotification);

                userNotificationDtos.Add(userNotification.ToUserNotificationDto(notificationDetailDto));
            }
            await _notificationRepository.SaveChangesAsync();

            return(userNotificationDtos);
        }