summaryrefslogtreecommitdiff
path: root/app/helpers/twitter_helper.rb
blob: cf75a73411bb5b233d940d64e57eec2ad525a0d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
module TwitterHelper
  def twitter_enabled
    if Rails.application.secrets.twitter
      Rails.application.secrets.twitter['enabled'] == true
    end
  end

  def twitter_client
    Twitter::REST::Client.new do |config|
      config.bearer_token = Rails.application.secrets.twitter['bearer_token']
    end
  end

  def twitter_handle
    Rails.application.secrets.twitter['twitter_handle']
  end

  def twitter_user_info
      $twitter_user_info ||= []
  end

  def update_twitter_info
    twitter_user_info[0] = Time.now
    twitter_user_info[1] = twitter_client.user(twitter_handle).name
    twitter_user_info[2] = twitter_client.user_timeline(twitter_handle).select{ |tweet| tweet.text.start_with?('RT','@')==false}.take(3)
    if twitter_user_info[2] == nil
      error_handling
      twitter_user_info[3] = "The twitter handle does not exist or the account's tweets are protected. Please change the privacy settings accordingly."
    end
  rescue Twitter::Error::BadRequest
    error_handling
    twitter_user_info[3] = "The request to display tweets is invalid or cannot be otherwise served."
  rescue Twitter::Error::Unauthorized
    error_handling
    twitter_user_info[3] = "The account's tweets are protected and cannot be displayed. Please change the privacy settings of the corresponding account."
  rescue Twitter::Error::Forbidden
    error_handling
    twitter_user_info[3] = "The request to display tweets is understood, but it has been refused or access is not allowed."
  rescue Twitter::Error::NotAcceptable
    error_handling
    twitter_user_info[3] = "An invalid format is specified in the request to display tweets."
  rescue Twitter::Error::TooManyRequests
    error_handling
    twitter_user_info[3] = "The rate-limit for accessing the tweets is reached. You should be able to display tweets in a couple of minutes."
  end

  def error_handling
    twitter_user_info[2] = []
    return twitter_user_info
  end

  def cached_info
    if twitter_user_info[0] == nil
      update_twitter_info
    else
      if Time.now > twitter_user_info[0] + 15.minutes
        update_twitter_info
      end
    end
    twitter_user_info
  end

  def twitter_name
    cached_info[1]
  end

  def tweets
    cached_info[2]
  end

  def error_message
    cached_info[3]
  end
end