tumblr_likes_agent.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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,
  17. 'expected_update_period_in_days is required') unless options['expected_update_period_in_days'].present?
  18. end
  19. def working?
  20. event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
  21. end
  22. def default_options
  23. {
  24. 'expected_update_period_in_days' => '10',
  25. 'blog_name' => 'someblog',
  26. }
  27. end
  28. def check
  29. memory[:ids] ||= []
  30. memory[:last_liked] ||= 0
  31. # Request Likes of blog_name after the last stored timestamp (or default of 0)
  32. liked = tumblr.blog_likes(options['blog_name'], after: memory[:last_liked])
  33. if liked['liked_posts']
  34. # Loop over all liked posts which came back from Tumblr, add to memory, and create events.
  35. liked['liked_posts'].each do |post|
  36. next if memory[:ids].include?(post['id'])
  37. memory[:ids].push(post['id'])
  38. memory[:last_liked] = post['liked_timestamp'] if post['liked_timestamp'] > memory[:last_liked]
  39. create_event(payload: post)
  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