예제 #1
0
 public MessagePushHandler(
     RequestDelegate next,
     IApplicationLifetime appLifetime,
     IConversationDataSource conversationDataSource,
     JwtAuthenticationService jwtAuthentioncationService,
     string url)
 {
     _next = next;
     _applicationStoppingCancellationToken = appLifetime.ApplicationStopping;
     _conversationDataSource     = conversationDataSource;
     _jwtAuthentioncationService = jwtAuthentioncationService;
     _url = url;
 }
예제 #2
0
        static async Task PushMessages(IConversationDataSource conversationDataSource, Guid userId, WebSocket socket, CancellationToken cancellationToken)
        {
            var messagesQueue = new ConcurrentQueue <Message>();

            conversationDataSource.OnMessage += enqueueMessage;
            try
            {
                while (!cancellationToken.IsCancellationRequested)
                {
                    if (!messagesQueue.TryDequeue(out var message))
                    {
                        await Task.Delay(PushMessagePollingInterval, cancellationToken);

                        continue;
                    }

                    try
                    {
                        var json   = JsonConvert.SerializeObject(message);
                        var buffer = Encoding.UTF8.GetBytes(json);
                        await socket.SendAsync(buffer, WebSocketMessageType.Text, true, cancellationToken);
                    }
                    catch (OperationCanceledException)
                    {
                        // Исключение OperationCanceledException обрабатывать не нужно.
                        // Выходим из метода при следующей итерации цикла.
                    }
                }
            }
            finally
            {
                conversationDataSource.OnMessage -= enqueueMessage;
            }

            void enqueueMessage(object sender, MessageEventArgs messageEventArgs)
            {
                var message        = messageEventArgs.Message;
                var conversationId = message.ConversationId;

                // TODO: переписать
                if (conversationId == "public" ||
                    conversationId.Contains($"{userId}", StringComparison.OrdinalIgnoreCase))
                {
                    messagesQueue.Enqueue(message);
                }
            }
        }
 public ConversationsController(IConversationDataSource dataSource)
 {
     _dataSource = dataSource ?? throw new ArgumentNullException(nameof(dataSource));
 }