tumblr_likes_agent.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. module Agents
  2. class TumblrLikesAgent < Agent
  3. include TumblrConcern
  4. gem_dependency_check { defined?(Tumblr::Client) }
  5. description <<-MD
  6. The Tumblr Likes Agent checks for liked Tumblr posts from a specific blog.
  7. #{'## Include `tumblr_client` and `omniauth-tumblr` in your Gemfile to use this Agent!' if dependencies_missing?}
  8. To be able to use this Agent you need to authenticate with Tumblr in the [Services](/services) section first.
  9. **Required fields:**
  10. `blog_name` The Tumblr URL you're querying (e.g. "staff.tumblr.com")
  11. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent.
  12. MD
  13. default_schedule 'every_1h'
  14. def validate_options
  15. errors.add(:base, 'blog_name is required') unless options['blog_name'].present?
  16. errors.add(:base, 'expected_update_period_in_days is required') unless options['expected_update_period_in_days'].present?
  17. end
  18. def working?
  19. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  20. end
  21. def default_options
  22. {
  23. 'expected_update_period_in_days' => '10',
  24. 'blog_name' => 'someblog',
  25. }
  26. end
  27. def check
  28. memory[:ids] ||= []
  29. memory[:last_liked] ||= 0
  30. # Request Likes of blog_name after the last stored timestamp (or default of 0)
  31. liked = tumblr.blog_likes(options['blog_name'], after: memory[:last_liked])
  32. if liked['liked_posts']
  33. # Loop over all liked posts which came back from Tumblr, add to memory, and create events.
  34. liked['liked_posts'].each do |post|
  35. unless memory[:ids].include?(post['id'])
  36. memory[:ids].push(post['id'])
  37. memory[:last_liked] = post['liked_timestamp'] if post['liked_timestamp'] > memory[:last_liked]
  38. create_event(payload: post)
  39. end
  40. end
  41. elsif liked['status'] && liked['msg']
  42. # If there was a problem fetching likes (like 403 Forbidden or 404 Not Found) create an error message.
  43. error "Error finding liked posts for #{options['blog_name']}: #{liked['status']} #{liked['msg']}"
  44. end
  45. # Store only the last 50 (maximum the API will return) IDs in memory to prevent performance issues.
  46. memory[:ids] = memory[:ids].last(50) if memory[:ids].length > 50
  47. end
  48. end
  49. end