base.rb 2.2 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. @time_now = Time.zone.now.to_i
  13. end
  14. def load
  15. # get whole collection
  16. self.class.model.constantize.all.order(id: :asc)
  17. end
  18. def client_key
  19. "collections::load::#{self.class}::#{@user.id}::#{@client_id}"
  20. end
  21. def push
  22. # check timeout
  23. timeout = Sessions::CacheIn.get(client_key)
  24. return if timeout
  25. # set new timeout
  26. Sessions::CacheIn.set(client_key, true, { expires_in: @ttl.seconds })
  27. # check permission based access
  28. if self.class.permissions
  29. return if !@user.permissions?(self.class.permissions)
  30. end
  31. # check if update has been done
  32. last_change = self.class.model.constantize.latest_change
  33. return if last_change.to_s == @last_change
  34. @last_change = last_change.to_s
  35. # load current data
  36. items = load
  37. return if items.blank?
  38. # get relations of data
  39. all = []
  40. items.each do |item|
  41. all.push item.attributes_with_association_ids
  42. end
  43. # collect assets
  44. @time_now = Time.zone.now.to_i
  45. assets = {}
  46. items.each do |item|
  47. next if !asset_needed?(item)
  48. assets = asset_push(item, assets)
  49. end
  50. if !@client
  51. return {
  52. collection: {
  53. items.first.class.to_app_model => all,
  54. },
  55. assets: assets,
  56. }
  57. end
  58. @client.log "push assets for push_collection #{items.first.class} for user #{@user.id}"
  59. @client.send(
  60. data: assets,
  61. event: 'loadAssets',
  62. )
  63. @client.log "push push_collection #{items.first.class} for user #{@user.id}"
  64. @client.send(
  65. event: 'resetCollection',
  66. data: {
  67. items.first.class.to_app_model => all,
  68. },
  69. )
  70. end
  71. def self.model_set(model)
  72. @model = model
  73. end
  74. def self.add_if_permission(key)
  75. if !@permissions
  76. @permissions = []
  77. end
  78. @permissions.push key
  79. end
  80. end