Class: Joggle::Twitter::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/joggle/twitter/fetcher.rb

Overview

Handler for Twitter HTTP requests.

Constant Summary collapse

DEFAULTS =
{
  'twitter.fetcher.url.timeline' => 'https://twitter.com/statuses/friends_timeline.json',
  'twitter.fetcher.url.tweet'    => 'https://twitter.com/statuses/update.json',
}

Instance Method Summary collapse

Constructor Details

#initialize(message_store, cache, opt = {}) ⇒ Fetcher

Create a new Twitter::Fetcher object.



21
22
23
24
25
# File 'lib/joggle/twitter/fetcher.rb', line 21

def initialize(message_store, cache, opt = {})
  @opt = DEFAULTS.merge(opt || {})
  @store = message_store
  @cache = cache
end

Instance Method Details

#get(user, show_all = false, &block) ⇒ Object

Get Twitter updates for given user and pass them to the specified block.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/joggle/twitter/fetcher.rb', line 31

def get(user, show_all = false, &block)
  url, opt = url_for(user, 'timeline'), opt_for(user)

  if data = @cache.get(url, opt)
    JSON.parse(data).reverse.each do |row|
      cached = @store.has_message?(row['id'])

      if show_all || !cached
        # cache message
        @store.add_message(row['id'], row)

        # send to parent
        block.call(
          row['id'], 
          Time.parse(row['created_at']), 
          row['user']['screen_name'], 
          row['text']
        )
      end
    end
  end
end

#tweet(user, msg) ⇒ Object

Send a tweet. Use Joggle::Engine#tweet instead.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
101
# File 'lib/joggle/twitter/fetcher.rb', line 57

def tweet(user, msg)
  # build URI and headers (opt)
  url, opt = url_for(user, 'tweet'), opt_for(user)
  uri = URI.parse(url)
  ret = nil

  # build post data
  data = {
    'status' => msg,
  }.map { |a| 
    a.map { |v| CGI.escape(v) }.join('=') 
  }.join('&')

  # FIXME: add user-agent to headers
  req = Net::HTTP.new(uri.host, uri.port)
  req.use_ssl = (uri.scheme == 'https')

  # start http request
  req.start do |http|
    # post request
    r = http.post(uri.path, data, opt)

    # check response
    case r
    when Net::HTTPSuccess
      ret = JSON.parse(r.body)

      # File.open('/tmp/foo.log', 'a') do |fh|
      #   fh.puts "r.body = #{r.body}"
      # end

      # check result
      if ret && ret.key?('id')
        @store.add_message(ret['id'], ret)
      else
        throw "got weird response from twitter"
      end
    else
      throw r
    end
  end

  # return result
  ret
end