コード例 #1
0
 public ChatroomsController(
     IChatroomsManager chatroomManagerService,
     INotificationsService notificationsService,
     ILogger <ChatroomsController> logger)
 {
     _chatroomManagerService = chatroomManagerService ?? throw new ArgumentNullException(nameof(chatroomManagerService));
     _notificationsService   = notificationsService ?? throw new ArgumentNullException(nameof(notificationsService));
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
コード例 #2
0
        public async Task <ActionResult> CreateAsync(
            [FromBody] CreateMessageRequest request,
            [FromServices] IUsersManager usersManager,
            [FromServices] IChatroomsManager chatroomsManager)
        {
            try
            {
                var sender = await usersManager.GetUserAsync(request.AuthorId);

                if (sender is null)
                {
                    return(BadRequest($"User with ID '{request.AuthorId}' does not exist."));
                }

                var senderChatrooms = await chatroomsManager.GetUserChatroomsAsync(sender);

                if (senderChatrooms is null || !senderChatrooms.Any(x => x.Id == request.ChatroomId))
                {
                    return(Unauthorized(
                               $"User with ID '{request.AuthorId}' is not a member of chatroom with ID " +
                               $"'${request.ChatroomId}'."));
                }

                var message = await _messagesManager.CreateMessageAsync(
                    new CreateMessageModel
                {
                    AuthorId    = request.AuthorId,
                    Body        = request.Body,
                    ChatroomId  = request.ChatroomId,
                    TimeSentUtc = request.TimeSentUtc,
                });

                _notificationsService.EnqueueNotification(new ChatroomMessageNotification(message));

                return(new JsonResult(new MessageResponse
                {
                    AuthorId = message.AuthorId,
                    Body = message.Body,
                    ChatroomId = message.ChatroomId,
                    Id = message.Id,
                    TimeSentUtc = message.TimeSentUtc,
                }));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(
                    ex,
                    $"Could add message from user with id ({request.AuthorId}) to chatroom with " +
                    $"id ({request.ChatroomId}).");
                return(BadRequest());
            }
        }
コード例 #3
0
ファイル: UsersController.cs プロジェクト: ful-stackz/nvisibl
        public async Task <IActionResult> GetChatroomsAsync(
            int id,
            [FromServices] IChatroomsManager chatroomsManager)
        {
            try
            {
                var user = await _userManager.GetUserAsync(id);

                if (user is null)
                {
                    return(NotFound());
                }

                var chatrooms = await chatroomsManager.GetUserChatroomsAsync(user);

                var responseChatrooms = new List <ChatroomResponse>();
                foreach (var chatroom in chatrooms)
                {
                    var chatroomUsers = (await chatroomsManager.GetChatroomUsersAsync(chatroom.Id))
                                        .Select(user => new BasicUserResponse {
                        Id = user.Id, Username = user.Username
                    })
                                        .ToList();
                    responseChatrooms.Add(new ChatroomResponse
                    {
                        Id    = chatroom.Id,
                        Name  = chatroom.Name,
                        Users = chatroomUsers,
                    });
                }

                return(new JsonResult(new UserChatroomsResponse {
                    Chatrooms = responseChatrooms
                }));
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"Could not retrieve the chatrooms of user with id ({id}).");
                return(BadRequest());
            }
        }
コード例 #4
0
        public async Task Invoke(
            HttpContext httpContext,
            IChatroomsManager chatroomsManager,
            ILogger <WebSocketSession> logger)
        {
            if (httpContext is null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }

            if (chatroomsManager is null)
            {
                throw new ArgumentNullException(nameof(chatroomsManager));
            }

            if (!httpContext.WebSockets.IsWebSocketRequest || httpContext.Request.Path != ChatClientEndpoint)
            {
                await _next(httpContext);

                return;
            }

            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            var webSocket = await httpContext.WebSockets.AcceptWebSocketAsync();

            using var webSocketSession = new WebSocketSession(webSocket, _messageParser, logger);

            var connectionRequest = webSocketSession.ReceivedMessages
                                    .Where(msg => msg is ConnectionRequestMessage)
                                    .Timeout(_connectionTimeout, Observable.Return(ClientMessageBase.Empty))
                                    .Take(1)
                                    .Wait() as ConnectionRequestMessage;

            if (connectionRequest is null)
            {
                httpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                await httpContext.Response.CompleteAsync();

                return;
            }

            httpContext.Request.Headers.Add(GetAuthorizationHeader(connectionRequest));
            var authResults = await Task.WhenAll(
                httpContext.AuthenticateAsync(JwtSchemes.Admin),
                httpContext.AuthenticateAsync(JwtSchemes.User));

            if (authResults.All(result => !result.Succeeded))
            {
                await httpContext.Response.CompleteAsync();

                return;
            }

            var sessionId = Guid.NewGuid();

            using var chatClient = new NotificationClient(
                      connectionRequest.UserId,
                      sessionId,
                      webSocketSession,
                      chatroomsManager,
                      _notificationsService);

            webSocketSession.EnqueueMessage(new ConnectedMessage {
                SessionId = sessionId,
            });

            await webSocketSession.Lifetime.Task;
        }
コード例 #5
0
        public NotificationClient(
            int userId,
            Guid sessionId,
            WebSocketSession webSocketSession,
            IChatroomsManager chatroomsManager,
            INotificationsService notificationsService)
        {
            if (webSocketSession is null)
            {
                throw new ArgumentNullException(nameof(webSocketSession));
            }

            if (chatroomsManager is null)
            {
                throw new ArgumentNullException(nameof(chatroomsManager));
            }

            if (notificationsService is null)
            {
                throw new ArgumentNullException(nameof(notificationsService));
            }

            UserId    = userId;
            SessionId = sessionId;

            var chatrooms = chatroomsManager.GetUserChatroomsAsync(new Business.Models.Users.UserModel {
                Id = userId
            })
                            .GetAwaiter()
                            .GetResult()
                            .Select(chatroom => chatroom.Id)
                            .ToList();

            _subscriptions.Add(
                notificationsService.Notifications
                .Where(notification => notification is ChatroomMessageNotification)
                .OfType <ChatroomMessageNotification>()
                .Select(notification => notification.Message)
                .Where(msg => chatrooms.Contains(msg.ChatroomId))
                .Subscribe(msg => webSocketSession.EnqueueMessage(new ChatroomMessageMessage
            {
                AuthorId    = msg.AuthorId,
                Body        = msg.Body,
                ChatroomId  = msg.ChatroomId,
                MessageId   = msg.Id,
                TimeSentUtc = msg.TimeSentUtc.ToString("o"),
            })));

            _subscriptions.Add(
                notificationsService.Notifications
                .Where(notification => notification is ChatroomChangedNotification)
                .OfType <ChatroomChangedNotification>()
                .Where(notification =>
                       notification.Participants.Contains(userId) && !chatrooms.Contains(notification.ChatroomId))
                .Subscribe(notification =>
            {
                chatrooms.Add(notification.ChatroomId);
                webSocketSession.EnqueueMessage(new ChatroomInvitationMessage
                {
                    ChatroomId   = notification.ChatroomId,
                    ChatroomName = notification.ChatroomName,
                    Users        = notification.Participants,
                });
            }));

            _subscriptions.Add(
                notificationsService.Notifications
                .Where(notification => notification is FriendRequestNotification)
                .OfType <FriendRequestNotification>()
                .Where(notification => notification.Sender.Id == userId || notification.Receiver.Id == userId)
                .Subscribe(notification => webSocketSession.EnqueueMessage(
                               new FriendRequestMessage
            {
                Accepted         = notification.Accepted,
                Id               = notification.FriendRequestId,
                ReceiverId       = notification.Receiver.Id,
                ReceiverUsername = notification.Receiver.Username,
                SenderId         = notification.Sender.Id,
                SenderUsername   = notification.Sender.Username,
            })));
        }