Class: DashFu::Mario::Backtweets

Inherits:
Object
  • Object
show all
Includes:
DashFu::Mario
Defined in:
lib/dash-fu/marios/backtweets.rb

Overview

Track Twitter links using the Backtype API.

Instance Method Summary collapse

Methods included from DashFu::Mario

all, #description, #display, find, included, load_marios, #name, #register, #unregister

Instance Method Details

#meta(source) ⇒ Object



53
54
55
# File 'lib/dash-fu/marios/backtweets.rb', line 53

def meta(source)
  [ { :text=>"Search yourself", :url=>"http://backtweets.com/search?q=#{URI.escape source["url"]}" } ]
end

#setup(source, params) ⇒ Object



6
7
8
9
10
11
12
# File 'lib/dash-fu/marios/backtweets.rb', line 6

def setup(source, params)
  url = params["url"].strip.downcase.sub(/^http(s?):\/\//, "")
  source["source.name"] = "Tweets for #{url}"
  source["metric.columns"] = [{ :id=>"tweets", :label=>"Tweets" }]
  source["metric.totals"] = true
  source["url"] = url
end

#update(source, request, &block) ⇒ Object



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
# File 'lib/dash-fu/marios/backtweets.rb', line 18

def update(source, request, &block)
  Net::HTTP.start "backtweets.com" do |http|
    get = Net::HTTP::Get.new("/search.json?key=#{api_key}&q=#{Rack::Utils.escape source["url"]}")
    response = http.request(get)
    json = JSON.parse(response.body) rescue nil if Net::HTTPOK === response
    unless json
      logger.error "Backtweets: #{response.code} #{response.message}"
      raise "Last request didn't go as expected, trying again later"
    end
   
    if tweets = json["tweets"]
      last_tweet_id = source["last_tweet_id"]
      if last_tweet_id
        new_ones = tweets.take_while { |tweet| tweet["tweet_id"] != last_tweet_id }.reverse
        new_ones.each do |tweet|
          handle, id = tweet["tweet_from_user"], tweet["tweet_id"]
          url = "http://twitter.com/#{handle}/#{id}"
          html = <<-HTML
<a href="#{url}">tweeted</a>:
<blockquote>#{tweet["tweet_text"]}</blockquote>
          HTML
          person = { :fullname=>handle, :identities=>%W{twitter.com:#{handle}}, :photo_url=>tweet["tweet_profile_image_url"] }
          block.call :activity=>{ :uid=>id, :url=>url, :html=>html, :tags=>%w{twitter mention},
                                  :timestamp=>Time.parse(tweet["tweet_created_at"]).utc, :person=>person }
        end
      end
      if recent = tweets.first
        source["last_tweet_id"] = recent["tweet_id"]
      end
    end

    block.call :set=>{ :tweets=>json["totalresults"].to_i }
  end
end

#validate(source) ⇒ Object



14
15
16
# File 'lib/dash-fu/marios/backtweets.rb', line 14

def validate(source)
  raise "Missing URL" if source["url"].blank?
end