Class: Vanity::Source::Backtweets

Inherits:
Object
  • Object
show all
Includes:
Vanity::Source
Defined in:
lib/vanity/sources/backtweets.rb

Overview

Track Twitter links using the Backtype API.

Instance Method Summary collapse

Methods included from Vanity::Source

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

Instance Method Details

#meta(context) ⇒ Object



54
55
56
# File 'lib/vanity/sources/backtweets.rb', line 54

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

#setup(context, params) ⇒ Object



7
8
9
10
11
12
13
# File 'lib/vanity/sources/backtweets.rb', line 7

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

#update(context, webhook, &block) ⇒ Object



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
# File 'lib/vanity/sources/backtweets.rb', line 19

def update(context, webhook, &block)
  Net::HTTP.start "backtweets.com" do |http|
    get = Net::HTTP::Get.new("/search.json?key=#{api_key}&q=#{Rack::Utils.escape context["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 = context["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
        context["last_tweet_id"] = recent["tweet_id"]
      end
    end

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

#validate(context) ⇒ Object



15
16
17
# File 'lib/vanity/sources/backtweets.rb', line 15

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