collections.rb 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. module Sessions::Backend::Collections
  2. @@last_change = {}
  3. def self.worker( user, worker )
  4. worker.log 'notice', "---user - fetch push_collection data"
  5. # get available collections
  6. cache_key = 'user_' + user.id.to_s + '_push_collections'
  7. collections = Sessions::CacheIn.get( cache_key )
  8. if !collections
  9. collections = {}
  10. push_collection = SessionHelper::push_collections(user)
  11. push_collection.each { | key, value |
  12. collections[ key ] = true
  13. }
  14. Sessions::CacheIn.set( cache_key, collections, { :expires_in => 2.minutes } )
  15. end
  16. # check all collections to push
  17. push_collection = {}
  18. collections.each { | key, v |
  19. cache_key = 'user_' + user.id.to_s + '_push_collections_' + key.to_s
  20. if Sessions::CacheIn.expired(cache_key)
  21. if push_collection.empty?
  22. push_collection = SessionHelper::push_collections(user)
  23. end
  24. push_collection_cache = Sessions::CacheIn.get( cache_key, { :re_expire => true } )
  25. worker.log 'notice', "---user - fetch push_collection data " + cache_key
  26. if !push_collection[key] || !push_collection_cache || push_collection[key] != push_collection_cache || !push_collection[ key ].zip( push_collection_cache ).all? { |x, y| x.attributes == y.attributes }
  27. worker.log 'notify', 'fetch push_collection changed - ' + cache_key
  28. Sessions::CacheIn.set( cache_key, push_collection[key], { :expires_in => 1.minutes } )
  29. end
  30. end
  31. }
  32. end
  33. def self.push( user, client )
  34. cache_key = 'user_' + user.id.to_s + '_push_collections'
  35. if !client.last_change['push_collections']
  36. client.last_change['push_collections'] = {}
  37. end
  38. collections = Sessions::CacheIn.get( cache_key ) || {}
  39. collections.each { | key, v |
  40. collection_cache_key = 'user_' + user.id.to_s + '_push_collections_' + key.to_s
  41. collection_time = Sessions::CacheIn.get_time( collection_cache_key, { :ignore_expire => true } )
  42. if collection_time && client.last_change['push_collections'][ key ] != collection_time
  43. client.last_change['push_collections'][ key ] = collection_time
  44. push_collections = Sessions::CacheIn.get( collection_cache_key, { :ignore_expire => true } )
  45. client.log 'notify', "push push_collections #{key} for user #{user.id}"
  46. # send update to browser
  47. data = {}
  48. data['collections'] = {}
  49. data['collections'][key] = push_collections
  50. client.send({
  51. :event => 'resetCollection',
  52. :data => data,
  53. })
  54. end
  55. }
  56. end
  57. end