public async Task <IActionResult> SendToGroup(int id, string message)
        {
            try
            {
                var user = await _userService.GetAsync(id);

                var groups = await _groupService.GetUserGroupsIdAsync(id);

                if (groups.Count() == 1)
                {
                    await _chatHubContext.Clients.Group(groups.First().ToString())
                    .SendMessage(id, user.FirstName, message, DateTime.Now.ToString("h:mm:ss tt"));

                    await _groupChatService.AddGroupChatMessageAsync(user.Id, groups.First(), message, DateTime.Now);

                    string           notificationText = "You have new messages from your group";
                    NotificationType notificationType = NotificationType.NewMessage;
                    var users = await _groupService.GetUsersAsync(groups.FirstOrDefault());

                    foreach (var userReciever in users)
                    {
                        if (userReciever.Id != user.Id && !NotificationController.ConnectedUsers.ContainsKey(userReciever.Id.ToString()))
                        {
                            await _notificationService.AddNotificationAsync(notificationText, notificationType, DateTime.Now, userReciever.Id);
                        }
                    }
                }

                return(Ok());
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Пример #2
0
        public async Task <ActionResult <NotificationDto> > AddNotification(string userId, [FromBody] NotificationToAddDto notificationToAdd)
        {
            if (Guid.TryParse(userId, out Guid gUserId))
            {
                try
                {
                    if (await _userService.CheckIfUserExists(gUserId))
                    {
                        var addedNotification = _notificationService.AddNotificationAsync(gUserId, notificationToAdd);

                        return(CreatedAtRoute("GetNotification",
                                              new
                        {
                            userId,
                            notificationId = addedNotification.Id
                        }));
                    }
                    else
                    {
                        return(NotFound($"User: {userId} not found."));
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error occured during adding the notification. User id: {userId}", userId);
                    return(StatusCode(StatusCodes.Status500InternalServerError));
                }
            }
            else
            {
                return(BadRequest($"{userId} is not valid guid."));
            }
        }
Пример #3
0
        public async Task SendNotificationToUser(string toWhoId, string type, string when, string eventId)
        {
            try
            {
                var notificationType = type switch
                {
                    "comment" => NotificationType.Comment,
                    "friendRequiest" => NotificationType.FriendRequiest,
                    "reaction" => NotificationType.Reaction,
                    "friendRequiestAccepted" => NotificationType.FriendRequiestAccepted,
                    _ => throw new ArgumentNullException(nameof(NotificationType)),
                };

                var fromWhoUser = GetLoggedUser().Id;
                if (!string.IsNullOrWhiteSpace(toWhoId) && Guid.TryParse(toWhoId, out Guid gToWhoId) && Guid.TryParse(eventId, out Guid gEventId))
                {
                    if (_onlineUsersService.IsUserOnline(toWhoId))
                    {
                        string toWhoConnectionId = _onlineUsersService.GetOnlineUser(toWhoId).ConnectionId;
                        await Clients.Client(toWhoConnectionId).SendAsync("ReceiveNotification");
                    }
                    await _notificationService.AddNotificationAsync(gToWhoId, new NotificationToAddDto
                    {
                        FromWho          = Guid.Parse(fromWhoUser),
                        WhenAdded        = Convert.ToDateTime(when),
                        EventId          = gEventId,
                        HasSeen          = false,
                        NotificationType = notificationType
                    });
                }
                else
                {
                    throw new ArgumentNullException(nameof(toWhoId));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Something went wrong during sending notification to the user: {userId}", toWhoId);
                _logger.LogError("{0}", ex);
            }
            return;
        }
Пример #4
0
        public async Task <ActionResult> PutNewUserTaskStatusAsync(int userTaskId, string newStatus)
        {
            try
            {
                if (!Regex.IsMatch(newStatus, ValidationRules.USERTASK_STATE))
                {
                    return(BadRequest());
                }

                var success = await taskService.UpdateUserTaskStatusAsync(userTaskId, newStatus);

                if (success)
                {
                    var message = $"Succesfully updated user task with id = {userTaskId} on status {newStatus}";
                    logger.LogInformation(message);

                    UserDTO userReciever = null;

                    bool   isSenderMentor = contextAccessor.HttpContext.User.IsInRole("Mentor");
                    bool   isSenderAdmin  = contextAccessor.HttpContext.User.IsInRole("Admin");
                    string senderName     = contextAccessor.HttpContext.User.Identity.Name;

                    if (isSenderMentor || isSenderAdmin)
                    {
                        userReciever = await taskService.GetUserByUserTaskId(userTaskId);
                    }
                    else
                    {
                        userReciever = await taskService.GetMentorByUserTaskId(userTaskId);
                    }

                    string           notificationText = "";
                    NotificationType notificationType = NotificationType.TaskReset;

                    switch (newStatus)
                    {
                    case "D" when(isSenderMentor || isSenderAdmin):
                        notificationText = "Your task has been reset to done by " + senderName;
                        notificationType = NotificationType.TaskReset;
                        break;

                    case "D":
                        notificationText = "Student " + senderName + " has comleted the task";
                        notificationType = NotificationType.TaskCompleted;
                        break;

                    case "A":
                        notificationText = "Your task has been approved by " + senderName;
                        notificationType = NotificationType.TaskApproved;
                        break;

                    case "R":
                        notificationText = "Your task has been rejected by " + senderName;
                        notificationType = NotificationType.TaskRejected;
                        break;

                    case "RE":
                        notificationText = "Your task has been reset by " + senderName;
                        notificationType = NotificationType.TaskReset;
                        break;

                    default:
                        break;
                    }

                    await notificationService.AddNotificationAsync(notificationText, notificationType, DateTime.Now, userReciever.Id);

                    string recieverKey = userReciever.Id.ToString();

                    if (NotificationController.ConnectedUsers.ContainsKey(recieverKey))
                    {
                        string recieverConnectionId = NotificationController.ConnectedUsers[recieverKey];
                        await hubContext.Clients.Client(recieverConnectionId).Notify();
                    }

                    return(Ok(message));
                }

                var errorMessage = "Incorrect request syntax or usertask does not exist.";
                logger.LogInformation("Error :  {0}", errorMessage);
                return(BadRequest(errorMessage));
            }
            catch (Exception e)
            {
                logger.LogInformation("Error :  {0}", e.Message);
                return(BadRequest(e));
            }
        }