activity_stream.rb 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. class Sessions::Backend::ActivityStream
  2. attr_writer :user
  3. def initialize(user, asset_lookup, client = nil, client_id = nil, ttl = 25)
  4. @user = user
  5. @client = client
  6. @client_id = client_id
  7. @ttl = ttl
  8. @asset_lookup = asset_lookup
  9. @last_change = nil
  10. end
  11. def load
  12. # get whole collection
  13. activity_stream = @user.activity_stream(25)
  14. if activity_stream && !activity_stream.first
  15. return
  16. end
  17. if activity_stream&.first && activity_stream.first['created_at'] == @last_change
  18. return
  19. end
  20. # update last changed
  21. if activity_stream&.first
  22. @last_change = activity_stream.first['created_at']
  23. end
  24. assets = {}
  25. item_ids = []
  26. activity_stream.each do |item|
  27. begin
  28. assets = item.assets(assets)
  29. rescue ActiveRecord::RecordNotFound
  30. next
  31. end
  32. item_ids.push item.id
  33. end
  34. {
  35. record_ids: item_ids,
  36. assets: assets,
  37. }
  38. end
  39. def client_key
  40. "as::load::#{self.class}::#{@user.id}::#{@client_id}"
  41. end
  42. def push
  43. # check timeout
  44. timeout = Sessions::CacheIn.get(client_key)
  45. return if timeout
  46. # set new timeout
  47. Sessions::CacheIn.set(client_key, true, { expires_in: @ttl.seconds })
  48. data = load
  49. return if data.blank?
  50. if !@client
  51. return {
  52. event: 'activity_stream_rebuild',
  53. collection: 'activity_stream',
  54. data: data,
  55. }
  56. end
  57. @client.log "push activity_stream #{data.first.class} for user #{@user.id}"
  58. @client.send(
  59. event: 'activity_stream_rebuild',
  60. collection: 'activity_stream',
  61. data: data,
  62. )
  63. end
  64. end