Ruby Rails - сообщения, использующие канал websocket, не отображаются в реальном времени - PullRequest
0 голосов
/ 25 января 2019

У меня небольшой проект по обмену сообщениями, и сообщения от одного пользователя другому не отображаются в чате в режиме реального времени. Я имею в виду: user1 (вошел в систему) - отправить сообщение пользователю user2 (вошел в систему). Теперь сообщение становится видимым для user2 только после того, как я обновлю страницу. НО это должно быть видно, как только я отправлю сообщение без обновления страницы.

Приложение работает на

Rails version             5.2.2;
Ruby version              2.5.3-p105 (x86_64-linux);
RubyGems version          2.7.6;
Rack version              2.0.6

В журнале разработки вижу следующее:

Private::ConversationChannel#send_message({"message"=>[{"name"=>"conversation_id", "value"=>"3"}, {"name"=>"user_id", "value"=>"2"}, {"name"=>"body", "value"=>"hai sa mai vedem"}]})
  [1m[35m (0.6ms)[0m  [1m[35mBEGIN[0m
  ↳ app/channels/private/conversation_channel.rb:14
  [1m[36mUser Load (0.9ms)[0m  [1m[34mSELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1[0m
  ↳ app/channels/private/conversation_channel.rb:14
  [1m[36mPrivate::Conversation Load (0.8ms)[0m  [1m[34mSELECT  `private_conversations`.* FROM `private_conversations` WHERE `private_conversations`.`id` = 3 LIMIT 1[0m
  ↳ app/channels/private/conversation_channel.rb:14
  [1m[36mPrivate::Message Create (0.8ms)[0m  [1m[32mINSERT INTO `private_messages` (`body`, `user_id`, `conversation_id`, `created_at`, `updated_at`) VALUES ('hai sa mai vedem', 2, 3, '2019-01-24 15:36:13', '2019-01-24 15:36:13')[0m
  ↳ app/channels/private/conversation_channel.rb:14
  [1m[35m (1.4ms)[0m  [1m[35mCOMMIT[0m
  ↳ app/channels/private/conversation_channel.rb:14
  [1m[36mPrivate::Message Load (0.9ms)[0m  [1m[34mSELECT `private_messages`.* FROM `private_messages` WHERE `private_messages`.`conversation_id` = 3[0m
  ↳ app/models/private/message.rb:14
[ActiveJob] Enqueued Private::MessageBroadcastJob (Job ID: a1613129-5ebb-4649-8cbe-6e31732f9a93) to Async(default) with arguments: #<GlobalID:0x00007f92305b8528 @uri=#<URI::GID gid://appror/Private::Message/73>>, #<GlobalID:0x00007f92305bff80 @uri=#<URI::GID gid://appror/Private::Message/72>>
  [1m[36mPrivate::Message Load (0.9ms)[0m  [1m[34mSELECT  `private_messages`.* FROM `private_messages` WHERE `private_messages`.`id` = 73 LIMIT 1[0m
  ↳ /home/work/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
  [1m[36mPrivate::Message Load (0.6ms)[0m  [1m[34mSELECT  `private_messages`.* FROM `private_messages` WHERE `private_messages`.`id` = 72 LIMIT 1[0m
  ↳ /home/work/.rbenv/versions/2.5.3/lib/ruby/gems/2.5.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93] Performing Private::MessageBroadcastJob (Job ID: a1613129-5ebb-4649-8cbe-6e31732f9a93) from Async(default) with arguments: #<GlobalID:0x00007f92205c73d0 @uri=#<URI::GID gid://appror/Private::Message/73>>, #<GlobalID:0x00007f92205c6bd8 @uri=#<URI::GID gid://appror/Private::Message/72>>
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   [1m[36mUser Load (0.4ms)[0m  [1m[34mSELECT  `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1[0m
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   ↳ app/jobs/private/message_broadcast_job.rb:5
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   [1m[36mPrivate::Conversation Load (0.4ms)[0m  [1m[34mSELECT  `private_conversations`.* FROM `private_conversations` WHERE `private_conversations`.`id` = 3 LIMIT 1[0m
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   ↳ app/jobs/private/message_broadcast_job.rb:6
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   [1m[36mUser Load (0.4ms)[0m  [1m[34mSELECT  `users`.* FROM `users` WHERE `users`.`id` = 4 LIMIT 1[0m
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   ↳ app/models/private/conversation.rb:17
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   Rendered shared/_empty_partial.html.erb (0.2ms)
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   Rendered private/messages/_message.html.erb (5.5ms)
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93] [ActionCable] Broadcasting to private_conversations_2: {:message=>"\n<li title=\"15:36\">\n  <div class=\"row\">   \n    <div class=\"message-sent unseen\">\n      hai sa mai vedem\n    </div>\n  </div>\n</li>", :conversation_id=>3, :recipient_info=>#<User id: 4, email: "test3@test.com", name: "test3", created_at: "2019-01-18 14:17:58", updated_at: "2019-01-18 14:17:58">}
Private::ConversationChannel transmitting {"message"=>"\n<li title=\"15:36\">\n  <div class=\"row\">   \n    <div class=\"message-sent unseen\">\n      hai sa mai vedem\n    </div>\n  </div>\n</li>", "conversation_id"=>3, "recipient_info"=>{"id"=>4, "email"=>"test3@test.com", "name"=>"test3", "created_at"=>"2019-01-18T14:17:58.000Z", "up... (via streamed from private_conversations_2)
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   Rendered shared/_empty_partial.html.erb (0.0ms)
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93]   Rendered private/messages/_message.html.erb (3.6ms)
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93] [ActionCable] Broadcasting to private_conversations_4: {:recipient=>true, :sender_info=>#<User id: 2, email: "test1@test.com", name: "test1 - edit2", created_at: "2019-01-18 14:17:57", updated_at: "2019-01-24 12:51:24">, :message=>"\n<li title=\"15:36\">\n  <div class=\"row\">   \n    <div class=\"message-received unseen\">\n      hai sa mai vedem\n    </div>\n  </div>\n</li>", :conversation_id=>3}
[ActiveJob] [Private::MessageBroadcastJob] [a1613129-5ebb-4649-8cbe-6e31732f9a93] Performed Private::MessageBroadcastJob (Job ID: a1613129-5ebb-4649-8cbe-6e31732f9a93) from Async(default) in 26.52ms

в /app/jobs/private/message_broadcast_job.rb

class Private::MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message, previous_message)
    sender = message.user
    recipient = message.conversation.opposed_user(sender)

    broadcast_to_sender(sender, recipient, message, previous_message)
    broadcast_to_recipient(sender, recipient, message, previous_message)
  end

  private

  def broadcast_to_sender(sender, recipient, message, previous_message)
    ActionCable.server.broadcast(
      "private_conversations_#{sender.id}",
      message: render_message(message, previous_message, sender),
      conversation_id: message.conversation_id,
      recipient_info: recipient
    )
  end

  def broadcast_to_recipient(sender, recipient, message, previous_message)
    ActionCable.server.broadcast(
      "private_conversations_#{recipient.id}",
      recipient: true,
      sender_info: sender,
      message: render_message(message, previous_message, recipient),
      conversation_id: message.conversation_id
    )
  end

  def render_message(message, previous_message, user)
    ApplicationController.render(
      partial: 'private/messages/message',
      locals: { message: message, 
                previous_message: previous_message, 
                user: user }
    )
  end
end

и /app/assets/javascripts/channels/private/conversation.js

App.private_conversation = App.cable.subscriptions.create("Private::ConversationChannel", {
    connected: function() {},
    disconnected: function() {},

    received: function(data) {
        // if a link to the conversation in the conversations menu list exists
        // move the link to the top of the conversations menu list
        var conversation_menu_link = $('#conversations-menu ul')
                                         .find('#menu-pc' + data['conversation_id']);
        if (conversation_menu_link.length) {
            conversation_menu_link.prependTo('#conversations-menu ul');
        }

        // set variables
        var conversation = findConv(data['conversation_id'], 'p');
        var conversation_rendered = ConvRendered(data['conversation_id'], 'p');
        var messages_visible = ConvMessagesVisiblity(conversation);

        if (data['recipient'] == true) {
            // mark conversation as unseen, after new message is received
            $('#menu-pc' + data['conversation_id']).addClass('unseen-conv');
            // if conversation window exists
            if (conversation_rendered) {
                if (!messages_visible) {
                // change style of conv window when there are unseen messages
                // add an additional class to the conversation's window or something
                }
                conversation.find('.messages-list').find('ul').append(data['message']);
            }
            calculateUnseenConversations();
        }
        else {
            conversation.find('ul').append(data['message']);
        }

        if (conversation.length) {
            // after a new message was appended, scroll to the bottom of the conversation window
            var messages_list = conversation.find('.messages-list');
            var height = messages_list[0].scrollHeight;
            messages_list.scrollTop(height);
        }
    },

    send_message: function(message) {
        return this.perform('send_message', {
            message: message
        });
    },
    set_as_seen: function(conv_id) {
        return this.perform('set_as_seen', { conv_id: conv_id });
    }
});



$(document).on('submit', '.send-private-message', function(e) {
    e.preventDefault();
    var values = $(this).serializeArray();
    App.private_conversation.send_message(values);
    $(this).trigger('reset');
});

Есть идеи?

Спасибо !!!

EDIT:

Я запускаю это приложение под ngnix. Возможно ли быть связано с некоторыми настройками, которые мне нужно добавить / изменить на сервере?

EDIT:

проблема действительно была в ngnix. Я нашел исправление здесь: https://www.phusionpassenger.com/library/config/nginx/action_cable_integration/

...