base.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. class Sessions::Backend::Collections::Base < Sessions::Backend::Base
  2. class << self; attr_accessor :model, :permissions end
  3. attr_writer :user
  4. attr_writer :time_now
  5. def initialize(user, asset_lookup, client, client_id, ttl)
  6. @user = user
  7. @client = client
  8. @client_id = client_id
  9. @ttl = ttl
  10. @asset_lookup = asset_lookup
  11. @last_change = nil
  12. end
  13. def to_run?
  14. return true if !@time_now
  15. return true if Time.zone.now.to_i > (@time_now + @ttl)
  16. false
  17. end
  18. def load
  19. # get whole collection
  20. self.class.model.constantize.all.order(id: :asc)
  21. end
  22. def push
  23. return if !to_run?
  24. @time_now = Time.zone.now.to_i
  25. # check permission based access
  26. if self.class.permissions
  27. return if !@user.permissions?(self.class.permissions)
  28. end
  29. # check if update has been done
  30. last_change = self.class.model.constantize.latest_change
  31. return if last_change.to_s == @last_change
  32. @last_change = last_change.to_s
  33. # load current data
  34. items = load
  35. return if items.blank?
  36. # get relations of data
  37. all = []
  38. items.each do |item|
  39. all.push item.attributes_with_association_ids
  40. end
  41. # collect assets
  42. @time_now = Time.zone.now.to_i
  43. assets = {}
  44. items.each do |item|
  45. next if !asset_needed?(item)
  46. assets = asset_push(item, assets)
  47. end
  48. if !@client
  49. return {
  50. collection: {
  51. items.first.class.to_app_model => all,
  52. },
  53. assets: assets,
  54. }
  55. end
  56. @client.log "push assets for push_collection #{items.first.class} for user #{@user.id}"
  57. @client.send(
  58. data: assets,
  59. event: 'loadAssets',
  60. )
  61. @client.log "push push_collection #{items.first.class} for user #{@user.id}"
  62. @client.send(
  63. event: 'resetCollection',
  64. data: {
  65. items.first.class.to_app_model => all,
  66. },
  67. )
  68. end
  69. def self.model_set(model)
  70. @model = model
  71. end
  72. def self.add_if_permission(key)
  73. if !@permissions
  74. @permissions = []
  75. end
  76. @permissions.push key
  77. end
  78. end