session.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. class Chat::Session < ApplicationModel
  2. include HasSearchIndexBackend
  3. include HasTags
  4. include Chat::Session::Search
  5. include Chat::Session::SearchIndex
  6. include Chat::Session::Assets
  7. # rubocop:disable Rails/InverseOf
  8. has_many :messages, class_name: 'Chat::Message', foreign_key: 'chat_session_id'
  9. # rubocop:enable Rails/InverseOf
  10. before_create :generate_session_id
  11. store :preferences
  12. def generate_session_id
  13. self.session_id = Digest::MD5.hexdigest(Time.zone.now.to_s + rand(99_999_999_999_999).to_s)
  14. end
  15. def add_recipient(client_id, store = false)
  16. if !preferences[:participants]
  17. preferences[:participants] = []
  18. end
  19. return preferences[:participants] if preferences[:participants].include?(client_id)
  20. preferences[:participants].push client_id
  21. if store
  22. save
  23. end
  24. preferences[:participants]
  25. end
  26. def recipients_active?
  27. return true if !preferences
  28. return true if !preferences[:participants]
  29. count = 0
  30. preferences[:participants].each do |client_id|
  31. next if !Sessions.session_exists?(client_id)
  32. count += 1
  33. end
  34. return true if count >= 2
  35. false
  36. end
  37. def send_to_recipients(message, ignore_client_id = nil)
  38. preferences[:participants].each do |local_client_id|
  39. next if local_client_id == ignore_client_id
  40. Sessions.send(local_client_id, message)
  41. end
  42. true
  43. end
  44. def position
  45. return if state != 'waiting'
  46. position = 0
  47. Chat::Session.where(state: 'waiting').order(created_at: :asc).each do |chat_session|
  48. position += 1
  49. break if chat_session.id == id
  50. end
  51. position
  52. end
  53. def self.messages_by_session_id(session_id)
  54. chat_session = Chat::Session.find_by(session_id: session_id)
  55. return if !chat_session
  56. session_attributes = []
  57. Chat::Message.where(chat_session_id: chat_session.id).order(created_at: :asc).each do |message|
  58. session_attributes.push message.attributes
  59. end
  60. session_attributes
  61. end
  62. def self.active_chats_by_user_id(user_id)
  63. actice_sessions = []
  64. Chat::Session.where(state: 'running', user_id: user_id).order(created_at: :asc).each do |session|
  65. session_attributes = session.attributes
  66. session_attributes['messages'] = []
  67. Chat::Message.where(chat_session_id: session.id).order(created_at: :asc).each do |message|
  68. session_attributes['messages'].push message.attributes
  69. end
  70. actice_sessions.push session_attributes
  71. end
  72. actice_sessions
  73. end
  74. end