base.rb 2.1 KB

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