/
stream.rb
68 lines (57 loc) · 1.52 KB
/
stream.rb
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
# -*- mode:ruby; coding:utf-8 -*-
require 'rubygems'
require 'json'
require 'uri'
require 'logger'
require 'atig/twitter_struct'
require 'atig/util'
require 'atig/url_escape'
module Atig
class Stream
include Util
attr_reader :channel
class APIFailed < StandardError; end
def initialize(context, channel, access)
@log = context.log
@opts = context.opts
@channel = channel
@access = access
end
def watch(path, query={}, &f)
path.sub!(%r{\A/+}, "")
uri = api_base
uri.path += path
uri.path += ".json"
uri.query = query.to_query_str unless query.empty?
@log.debug [uri.to_s]
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request.oauth!(http, @access.consumer, @access)
http.request(request) do |response|
unless response.code == '200' then
raise APIFailed,"#{response.code} #{response.message}"
end
begin
buffer = ''
response.read_body do |chunk|
next if chunk.chomp.empty?
buffer << chunk.to_s
if buffer =~ /\A(.*)\n/ then
text = $1
unless text.strip.empty?
f.call TwitterStruct.make(JSON.parse(text))
end
buffer = ''
end
end
rescue => e
raise APIFailed,e.to_s
end
end
end
def api_base
URI(@opts.stream_api_base)
end
end
end