client.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Sessions::Client
  3. def initialize(client_id, node_id)
  4. @client_id = client_id
  5. @node_id = node_id
  6. log '---client start ws connection---'
  7. fetch
  8. log '---client exiting ws connection---'
  9. end
  10. def fetch
  11. backends = [
  12. 'Sessions::Backend::TicketOverviewList',
  13. 'Sessions::Backend::ActivityStream',
  14. ]
  15. asset_lookup = {}
  16. backend_pool = []
  17. user_id_last_run = nil
  18. user_updated_at_last_run = nil
  19. loop_count = 0
  20. loop do
  21. return if BackgroundServices.shutdown_requested
  22. ActiveRecord::Base.clear_query_caches_for_current_thread
  23. ActiveSupport::CurrentAttributes.clear_all
  24. # check if session still exists
  25. return if !Sessions.session_exists?(@client_id)
  26. # get connection user
  27. session_data = Sessions.get(@client_id)
  28. return if !session_data
  29. return if !session_data[:user]
  30. return if !session_data[:user]['id']
  31. user = User.lookup(id: session_data[:user]['id'])
  32. return if !user
  33. UserInfo.current_user_id = user.id
  34. # init new backends
  35. if user_id_last_run != user.id
  36. user_id_last_run = user.id
  37. asset_lookup = {}
  38. # release old objects
  39. backend_pool.collect! do
  40. nil
  41. end
  42. # create new pool
  43. backend_pool = []
  44. backends.each do |backend|
  45. item = backend.constantize.new(user, asset_lookup, self, @client_id)
  46. backend_pool.push item
  47. end
  48. # update user if required
  49. elsif user_updated_at_last_run != user.updated_at
  50. user_updated_at_last_run = user.updated_at
  51. log "---client - updating user #{user.id} - #{user_updated_at_last_run}"
  52. backend_pool.each do |backend|
  53. backend.user = user
  54. end
  55. end
  56. loop_count += 1
  57. log "---client - looking for data of user #{user.id}"
  58. # push messages from backends
  59. backend_pool.each(&:push)
  60. log '---/client-'
  61. # start faster in the beginnig
  62. if loop_count < 20
  63. sleep 1
  64. else
  65. sleep 2.2
  66. end
  67. end
  68. end
  69. # send update to browser
  70. def send(data) # rubocop:disable Zammad/ForbidDefSend
  71. Sessions.send(@client_id, data)
  72. end
  73. def log(msg)
  74. Rails.logger.debug { "client(#{@node_id}.#{@client_id}) #{msg}" }
  75. end
  76. end