twitter_concern.rb 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. module TwitterConcern
  2. extend ActiveSupport::Concern
  3. included do
  4. include Oauthable
  5. validate :validate_twitter_options
  6. valid_oauth_providers :twitter
  7. gem_dependency_check { defined?(Twitter) && Devise.omniauth_providers.include?(:twitter) && ENV['TWITTER_OAUTH_KEY'].present? && ENV['TWITTER_OAUTH_SECRET'].present? }
  8. end
  9. def validate_twitter_options
  10. unless twitter_consumer_key.present? &&
  11. twitter_consumer_secret.present? &&
  12. twitter_oauth_token.present? &&
  13. twitter_oauth_token_secret.present?
  14. errors.add(:base, "Twitter consumer_key, consumer_secret, oauth_token, and oauth_token_secret are required to authenticate with the Twitter API. You can provide these as options to this Agent, or as Credentials with the same names, but starting with 'twitter_'.")
  15. end
  16. end
  17. def twitter_consumer_key
  18. (config = Devise.omniauth_configs[:twitter]) && config.strategy.consumer_key
  19. end
  20. def twitter_consumer_secret
  21. (config = Devise.omniauth_configs[:twitter]) && config.strategy.consumer_secret
  22. end
  23. def twitter_oauth_token
  24. service && service.token
  25. end
  26. def twitter_oauth_token_secret
  27. service && service.secret
  28. end
  29. def twitter
  30. @twitter ||= Twitter::REST::Client.new do |config|
  31. config.consumer_key = twitter_consumer_key
  32. config.consumer_secret = twitter_consumer_secret
  33. config.access_token = twitter_oauth_token
  34. config.access_token_secret = twitter_oauth_token_secret
  35. end
  36. end
  37. module ClassMethods
  38. def twitter_dependencies_missing
  39. if ENV['TWITTER_OAUTH_KEY'].blank? || ENV['TWITTER_OAUTH_SECRET'].blank?
  40. "## Set TWITTER_OAUTH_KEY and TWITTER_OAUTH_SECRET in your environment to use Twitter Agents."
  41. elsif !defined?(Twitter) || !Devise.omniauth_providers.include?(:twitter)
  42. "## Include the `twitter`, `omniauth-twitter`, and `cantino-twitter-stream` gems in your Gemfile to use Twitter Agents."
  43. end
  44. end
  45. end
  46. end
  47. class Twitter::Error
  48. remove_const :FORBIDDEN_MESSAGES
  49. FORBIDDEN_MESSAGES = proc do |message|
  50. case message
  51. when /(?=.*status).*duplicate/i
  52. # - "Status is a duplicate."
  53. Twitter::Error::DuplicateStatus
  54. when /already favorited/i
  55. # - "You have already favorited this status."
  56. Twitter::Error::AlreadyFavorited
  57. when /already retweeted|Share validations failed/i
  58. # - "You have already retweeted this Tweet." (Nov 2017-)
  59. # - "You have already retweeted this tweet." (?-Nov 2017)
  60. # - "sharing is not permissible for this status (Share validations failed)" (-? 2017)
  61. Twitter::Error::AlreadyRetweeted
  62. end
  63. end
  64. end