-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstarchatapiclient.rb
100 lines (86 loc) · 2.62 KB
/
starchatapiclient.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
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
# encoding: utf-8
require 'rubygems'
require 'net/http'
require 'uri'
require 'json'
class StarChatApiClient
def initialize(url, username, password)
@url = url
@username = username
@password = password
end
def enc(str)
URI.encode_www_form_component(str)
end
def get_user()
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Get.new('/users/' + enc(@username));
req.basic_auth(@username, @password)
JSON.parse(http.request(req).read_body)
end
end
def get_channels()
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Get.new('/users/' + enc(@username) + '/channels');
req.basic_auth(@username, @password)
JSON.parse(http.request(req).read_body)
end
end
def get_channel(channel)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Get.new('/channels/' + enc(channel));
req.basic_auth(@username, @password)
JSON.parse(http.request(req).read_body)
end
end
def get_users(channel)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Get.new('/channels/' + enc(channel) + '/users');
req.basic_auth(@username, @password)
JSON.parse(http.request(req).read_body)
end
end
def subscribe_channel(channel)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Put.new("/subscribings?user_name=" + enc(@username) + ";channel_name=" + enc(channel));
req.basic_auth(@username, @password)
res = http.request(req, "")
end
end
def unsubscribe_channel(channel)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Delete.new("/subscribings?user_name=" + enc(@username) + ";channel_name=" + enc(channel));
req.basic_auth(@username, @password)
res = http.request(req)
end
end
def post_comment(channel, comment)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Post.new('/channels/' + enc(channel) + '/messages');
req.basic_auth(@username, @password)
s = "body=" + enc(comment) + ";notice=true";
res = http.request(req, s)
end
end
def get_stream(&block)
Net::HTTP.start(@url) do |http|
req = Net::HTTP::Get.new('/users/' + enc(@username) + '/stream');
req.basic_auth(@username, @password)
http.request(req) do |res|
txt = ""
res.read_body do |body|
body.each_line {|line|
next if line == "\n" # bypass return code
line = txt + line if txt != ""
begin
block.call(JSON.parse(line))
txt = ""
rescue JSON::ParserError
txt += line
end
}
end
end
end
end
end