sessions.rb 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module Sessions
  3. @store = case Rails.application.config.websocket_session_store
  4. when :redis then Sessions::Store::Redis.new
  5. else Sessions::Store::File.new
  6. end
  7. =begin
  8. start new session
  9. Sessions.create(client_id, session_data, { type: 'websocket' })
  10. returns
  11. true|false
  12. =end
  13. def self.create(client_id, session, meta)
  14. # collect session data
  15. meta[:last_ping] = Time.now.utc.to_i
  16. data = {
  17. user: session,
  18. meta: meta,
  19. }
  20. content = data.to_json
  21. @store.create(client_id, content)
  22. # send update to browser
  23. return if !session || session['id'].blank?
  24. send(
  25. client_id,
  26. {
  27. event: 'ws:login',
  28. data: { success: true },
  29. }
  30. )
  31. end
  32. =begin
  33. list of all session
  34. client_ids = Sessions.sessions
  35. returns
  36. ['4711', '4712']
  37. =end
  38. def self.sessions
  39. @store.sessions
  40. end
  41. =begin
  42. list of all session
  43. Sessions.session_exists?(client_id)
  44. returns
  45. true|false
  46. =end
  47. def self.session_exists?(client_id)
  48. @store.session_exists?(client_id)
  49. end
  50. =begin
  51. list of all session with data
  52. client_ids_with_data = Sessions.list
  53. returns
  54. {
  55. '4711' => {
  56. user: {
  57. 'id' => 123,
  58. },
  59. meta: {
  60. type: 'websocket',
  61. last_ping: time_of_last_ping,
  62. }
  63. },
  64. '4712' => {
  65. user: {
  66. 'id' => 124,
  67. },
  68. meta: {
  69. type: 'ajax',
  70. last_ping: time_of_last_ping,
  71. }
  72. },
  73. }
  74. =end
  75. def self.list
  76. client_ids = sessions
  77. session_list = {}
  78. client_ids.each do |client_id|
  79. data = get(client_id)
  80. next if !data
  81. session_list[client_id] = data
  82. end
  83. session_list
  84. end
  85. =begin
  86. destroy session
  87. Sessions.destroy(client_id)
  88. returns
  89. true|false
  90. =end
  91. def self.destroy(client_id)
  92. @store.destroy(client_id)
  93. end
  94. =begin
  95. destroy idle session
  96. list_of_client_ids = Sessions.destroy_idle_sessions
  97. returns
  98. ['4711', '4712']
  99. =end
  100. def self.destroy_idle_sessions(idle_time_in_sec = 240)
  101. list_of_closed_sessions = []
  102. clients = Sessions.list
  103. clients.each do |client_id, client|
  104. if !client[:meta] || !client[:meta][:last_ping] || (client[:meta][:last_ping].to_i + idle_time_in_sec) < Time.now.utc.to_i
  105. list_of_closed_sessions.push client_id
  106. Sessions.destroy(client_id)
  107. end
  108. end
  109. list_of_closed_sessions
  110. end
  111. =begin
  112. touch session
  113. Sessions.touch(client_id)
  114. returns
  115. true|false
  116. =end
  117. def self.touch(client_id)
  118. data = get(client_id)
  119. return false if !data
  120. data[:meta][:last_ping] = Time.now.utc.to_i
  121. @store.set(client_id, data)
  122. true
  123. end
  124. =begin
  125. get session data
  126. data = Sessions.get(client_id)
  127. returns
  128. {
  129. user: {
  130. 'id' => 123,
  131. },
  132. meta: {
  133. type: 'websocket',
  134. last_ping: time_of_last_ping,
  135. }
  136. }
  137. =end
  138. def self.get(client_id)
  139. @store.get client_id
  140. end
  141. =begin
  142. send message to client
  143. Sessions.send(client_id_of_recipient, data)
  144. returns
  145. true|false
  146. =end
  147. def self.send(client_id, data) # rubocop:disable Zammad/ForbidDefSend
  148. @store.send_data(client_id, data)
  149. end
  150. =begin
  151. send message to recipient client
  152. Sessions.send_to(user_id, data)
  153. e. g.
  154. Sessions.send_to(user_id, {
  155. event: 'session_takeover',
  156. data: {
  157. taskbar_id: 12312
  158. },
  159. })
  160. returns
  161. true|false
  162. =end
  163. def self.send_to(user_id, data)
  164. # list all current clients
  165. client_list = sessions
  166. client_list.each do |client_id|
  167. session = Sessions.get(client_id)
  168. next if !session
  169. next if !session[:user]
  170. next if !session[:user]['id']
  171. next if session[:user]['id'].to_i != user_id.to_i
  172. Sessions.send(client_id, data)
  173. end
  174. true
  175. end
  176. =begin
  177. send message to all authenticated client
  178. Sessions.broadcast(data)
  179. returns
  180. [array_with_client_ids_of_recipients]
  181. broadcase also to not authenticated client
  182. Sessions.broadcast(data, 'public') # public|authenticated
  183. broadcase also not to sender
  184. Sessions.broadcast(data, 'public', sender_user_id)
  185. =end
  186. def self.broadcast(data, recipient = 'authenticated', sender_user_id = nil)
  187. # list all current clients
  188. recipients = []
  189. client_list = sessions
  190. client_list.each do |client_id|
  191. session = Sessions.get(client_id)
  192. next if !session
  193. if recipient != 'public'
  194. next if session[:user].blank?
  195. next if session[:user]['id'].blank?
  196. end
  197. next if sender_user_id && session[:user] && session[:user]['id'] && session[:user]['id'].to_i == sender_user_id.to_i
  198. Sessions.send(client_id, data)
  199. recipients.push client_id
  200. end
  201. recipients
  202. end
  203. =begin
  204. get messages for client
  205. messages = Sessions.queue(client_id_of_recipient)
  206. returns
  207. [
  208. {
  209. key1 => 'some data of message 1',
  210. key2 => 'some data of message 1',
  211. },
  212. {
  213. key1 => 'some data of message 2',
  214. key2 => 'some data of message 2',
  215. },
  216. ]
  217. =end
  218. def self.queue(client_id)
  219. @store.queue(client_id)
  220. end
  221. =begin
  222. remove all session and spool messages
  223. Sessions.cleanup
  224. =end
  225. def self.cleanup
  226. @store.cleanup
  227. end
  228. =begin
  229. Zammad previously used a spooling mechanism for session mechanism.
  230. The code to clean-up such data is still here, even though the mechanism
  231. itself was removed in the meantime.
  232. Sessions.spool_delete
  233. =end
  234. def self.spool_delete
  235. @store.clear_spool
  236. end
  237. =begin
  238. start client for browser
  239. Sessions.thread_client(client_id)
  240. returns
  241. thread
  242. =end
  243. def self.thread_client(client_id, try_count = 0, try_run_time = Time.now.utc, node_id)
  244. log('debug', "LOOP #{node_id}.#{client_id} - #{try_count}")
  245. begin
  246. Sessions::Client.new(client_id, node_id)
  247. rescue => e
  248. log('error', "thread_client #{client_id} exited with error #{e.inspect}")
  249. log('error', e.backtrace.join("\n "))
  250. sleep 10
  251. try_run_max = 10
  252. try_count += 1
  253. # reset error counter if to old
  254. if try_run_time + (60 * 5) < Time.now.utc
  255. try_count = 0
  256. end
  257. try_run_time = Time.now.utc
  258. # restart job again
  259. if try_run_max > try_count
  260. thread_client(client_id, try_count, try_run_time, node_id)
  261. end
  262. raise "STOP thread_client for client #{node_id}.#{client_id} after #{try_run_max} tries"
  263. end
  264. log('debug', "/LOOP #{node_id}.#{client_id} - #{try_count}")
  265. end
  266. def self.symbolize_keys(hash)
  267. hash.each_with_object({}) do |(key, value), result|
  268. new_key = case key
  269. when String then key.to_sym
  270. else key
  271. end
  272. new_value = case value
  273. when Hash then symbolize_keys(value)
  274. else value
  275. end
  276. result[new_key] = new_value
  277. end
  278. end
  279. # we use it in rails and non rails context
  280. def self.log(level, message)
  281. if defined?(Rails)
  282. case level
  283. when 'debug'
  284. Rails.logger.debug { message }
  285. when 'info'
  286. Rails.logger.info message
  287. else
  288. Rails.logger.error message
  289. end
  290. return
  291. end
  292. puts "#{Time.now.utc.iso8601}:#{level} #{message}" # rubocop:disable Rails/Output
  293. end
  294. # This is a shorthand to simulate the old Sessions.jobs behavior using the new BackgroundServices worker
  295. # This should be used for debugging only
  296. # For production, please run BackgroundServices
  297. def self.jobs
  298. BackgroundServices::Service::ProcessSessionsJobs
  299. .pre_run
  300. BackgroundServices::Service::ProcessSessionsJobs
  301. .new(manager: nil)
  302. .launch
  303. end
  304. end