获得当前用户以在ActiveJob Sidekiq中设置聊天室消息的样式

时间:2019-07-05 17:47:28

标签: ruby-on-rails ruby-on-rails-5 sidekiq actioncable rails-activejob

我已经创建了消息传递应用程序,但是我无法让它识别当前用户正在呈现消息还是“其他”用户。目标是在右边显示current_user消息,在左边显示其他消息。我不知道在ApplicationJob中创建消息是否是不好的做法,但我相信这是必要的,因为它也将在ReactNative App中使用,这是否重要? 任何帮助是极大的赞赏。

这是我的ActionCable:

class MoveRecordChatroomsChannel < ApplicationCable::Channel

  def subscribed
    stream_from "chatroom_#{params[:chatroom_id]}"
  end

  def receive(payload)
    # message = Message.create(body: payload["body"], user_id: payload["user_id"], chatroom_id: payload["chatroom_id"])
    ActionCable.server.broadcast("chatroom_#{payload["chatroom_id"]}", {body: payload["body"], chatroom_id: payload["chatroom_id"], user_id: payload["user_id"]})
  end

  def send_message(payload)
    # MessageNotificationBroadcastJob.perform_later(payload)
    MoveRecordChatroomBroadcastJob.perform_later(payload)
  end


end

ApplicationJob:

class MoveRecordChatroomBroadcastJob < ApplicationJob
  queue_as :default

  def perform(payload)
    message = Message.create!(body: payload["body"], user_id: payload["user_id"], chatroom_id: payload["chatroom_id"])
    if message.save
      ActionCable.server.broadcast("chatroom_#{message["chatroom_id"]}", {message: render_message(message), body: message.body, chatroom_id: message.chatroom_id, user_id: message.user_id})
      payload["chatroom_user_ids"].each do |user_id|
        # unless @current_user.id == user_id
          notification = MessageNotification.create!(user_id: user_id, message_id: message.id, checked: false)
          if notification.save
            ActionCable.server.broadcast("notifications_for_#{user_id}", {message_notification: render_notification(notification), message: message.body})
          end
        # end
      end
    end
  end

  private
    def render_message(message)
      renderer = ApplicationController.renderer.new
      renderer.render(partial: 'messages/message', locals: { message: message })
    end
    def render_notification(notification)
      renderer = ApplicationController.renderer.new
      renderer.render(partial: 'message_notificatons/notification', locals: { notification: notification })
    end
end

和频道js:

$( document ).ready(function() {
  jQuery('.chatroom').each(function() {
    var chatroomId = $(this).data("chatroom-id");
    var userId = $(this).data("user-id");
    var chatroomName = $(this).data("chatroom-name");
    var chatroomUserIds = $(this).data("notify-users");
    $('#messages_' + chatroomName).stop().animate({ scrollTop: $('#messages_' + chatroomName).scrollHeight}, 1000);
    App['chatroom_' + chatroomId] = App.cable.subscriptions.create({channel: "MoveRecordChatroomsChannel", chatroom_id: chatroomId}, {
      received(data) {
        console.log(data);
        $('#messages_' + chatroomName).removeClass('hidden');
        $('#messages_' + chatroomName).append(data["message"]);
        $('#messages_' + chatroomName).stop().animate({ scrollTop: $('#messages_' + chatroomName).scrollHeight}, 1000);
      },
      send_message(message) {
        return this.perform('send_message', ({body: message["message"], chatroom_id: message["chatroom_id"], user_id: message["user_id"], chatroom_user_ids: message["chatroom_user_ids"]}));
      },
      setChatroomId(id) {
        $(this).chatroomId = id
      }
    });

    sendNewMessage(chatroomId, userId, chatroomName, chatroomUserIds);
  });
});
function sendNewMessage(chatroomId, userId, chatroomName, chatroomUserIds){
  var mentionOn = false;
  var shiftDown = false
  $('#' + chatroomName).keydown(function(event) {
    if (event.keyCode == 13) {
      if ($(this).parent().children(':nth-child(4)')[0].style.display == 'block') {
        return mentionOn = true;
      } else {
        mentionOn = false
      }
      if($('#' + chatroomName).is(":focus") && !shiftDown && !mentionOn) {
        event.preventDefault()
        var arrMentions, dataArr
        var usersArr = []
        $(this).mentionsInput('getMentions', function(data) {
          arrMentions = JSON.stringify(data);
        });
        dataArr = JSON.parse(arrMentions);
        dataArr.forEach(function(user) {
          usersArr.push(user.id)
        });
        console.log(usersArr);
        App['chatroom_' + chatroomId].setChatroomId(chatroomId);
        App['chatroom_' + chatroomId].send_message({ message: event.target.value, chatroom_id: chatroomId, user_id: userId, chatroom_user_ids: usersArr });
        $('#' + chatroomName).val("");
        return false;
      }
    }
  });
  $(document).keydown(function (e) {
      if(e.keyCode == 16) shiftDown = true;
  });
  $(document).keyup(function (e) {
      if(e.keyCode == 16) shiftDown = false;
  });
}

0 个答案:

没有答案