Module: CortexReaver::Plugins::Twitter

Defined in:
lib/cortex_reaver/plugins/twitter.rb

Overview

Twitter plugin for Cortex Reaver.

Constant Summary collapse

Config =
CortexReaver.config.plugins.twitter ||= Construct.new

Class Method Summary collapse

Class Method Details

.parse_tweet(tweet) ⇒ Object

Parses tweet text and converts it into HTML. Explicit URLs and @username or #hashtag references will be turned into links.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/cortex_reaver/plugins/twitter.rb', line 71

def parse_tweet(tweet)
  index     = 0
  html      = tweet.dup
  protocols = ['ftp', 'ftps', 'git', 'http', 'https', 'mailto', 'scp',
               'sftp', 'ssh', 'telnet']
  urls      = []

  # Extract URLs and replace them with placeholders for later.
  URI.extract(html.dup, protocols) do |url|
    html.sub!(url, "__URL#{index}__")
    urls << url
    index += 1
  end

  # Replace URL placeholders with links.
  urls.each_with_index do |url, index|
    html.sub!("__URL#{index}__", "<a href=\"#{url}\">" <<
        "#{url.length > 26 ? url[0..26] + '...' : url}</a>")
  end

  # Turn @username into a link to the specified user's Twitter profile.
  html.gsub!(/@([a-zA-Z0-9_]{1,16})([^a-zA-Z0-9_])?/,
      '@<a href="http://twitter.com/\1">\1</a>\2')

  # Turn #hashtags into links.
  html.gsub!(/#([a-zA-Z0-9_]{1,32})([^a-zA-Z0-9_])?/,
      '<a href="http://search.twitter.com/search?q=%23\1">#\1</a>\2')

  return html
end

.recent_tweets(user = Config.username, options = {:count => 1}) ⇒ Object

Gets a Hash containing recent tweets for the specified user. The only valid option currently is :count, which specifies the maximum number of tweets that should be returned.



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/cortex_reaver/plugins/twitter.rb', line 105

def recent_tweets(user = Config.username, options = {:count => 1})
  if @skip_until
    return [] if @skip_until > Time.now
    @skip_until = nil
  end

  cache   = Ramaze::Cache.plugin
  options = {:count => 5}.merge(options)
  count   = options[:count].to_i

  count += 10 unless Config.include_replies
  count = 200 if count > 200

  url = "http://twitter.com/statuses/user_timeline/#{user}.json?count=" <<
      count.to_s

  if value = cache[url]
    return value
  end

  tweets = []

  Timeout.timeout(Config.request_timeout, StandardError) do
    failed = 0
    begin
      tweets = JSON.parse(open(url).read)
    rescue JSON::ParserError => e
      # Twitter likes to hand out weird HTML responses sometimes. :/
      failed += 1
      retry unless failed > 3

      # Admit defeat
      raise RuntimeError.new("Failed to parse Twitter response 4 times: #{e}")
    end
  end

  # Weed out replies if necessary.
  unless Config.include_replies
    tweets.delete_if do |tweet|
      !tweet['in_reply_to_status_id'].nil? ||
          !tweet['in_reply_to_user_id'].nil?
    end

    tweets = tweets.slice(0, options[:count].to_i)
  end

  # Parse the tweets into an easier-to-use format.
  tweets.map! do |tweet|
    {
      :created_at => Time.parse(tweet['created_at']),
      :html       => parse_tweet(tweet['text']),
      :id         => tweet['id'],
      :source     => tweet['source'],
      :text       => tweet['text'],
      :truncated  => tweet['truncated'],
      :url        => "http://twitter.com/#{user}/statuses/#{tweet['id']}"
    }
  end

  @failures = 0

  return cache.store(url, tweets, :ttl => Config.cache_ttl)

rescue => e
  Ramaze::Log.error "CortexReaver::Plugins::Twitter: #{e.message}"

  @failures ||= 0
  @failures += 1

  if @failures >= Config.failure_threshold
    @skip_until = Time.now + Config.failure_timeout
    Ramaze::Log.error "CortexReaver::Plugins::Twitter: Twitter failed to respond #{@failures} times. Will retry after #{@skip_until}."
  end

  return []
end