session.rb 2.1 KB

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