最近在学习ruby的GUI工具Shoes,想用ruby做一个和JE Talker差不多的工具,所以就先写了个JavaEye的Client。
目前已完成认证,get_all(获取全站闲聊),get_list(获取自己订阅的闲聊),get_reply(获取@自己的闲聊)。
这是项目地址:http://javaeye-client-ruby.googlecode.com/svn/trunk/
code:
require'net/http'
require'json'
module JavaEye
AUTH_URL="http://api.iteye.com/api/auth/verify"
VIA="EyeShoes"
LIST_URL="http://api.iteye.com/api/twitters/list"
REPLY_URL='http://api.iteye.com/api/twitters/replies'
ALL_URL='http://api.iteye.com/api/twitters/all'
class User
%W[name domain id logo].each do |attr|
attr_accessor attr.to_sym
end
def initialize(hash)
hash.each do |key,value|
self.send("#{key}=",value)
end
end
end
class Twitter
%W[user id created_at body name logo domain receiver reply_to_id via].each do |attr|
attr_accessor attr.to_sym
end
def initialize(hash)
hash.each do |key,value|
if key=="user"
self.send("#{key}=",User.new(value))
else
self.send("#{key}=",value)
end
end
end
end
class Client
attr_accessor:user
attr_accessor:auth_code
def initialize(username,password)
@username=username
@password=password
end
def auth
@url=AUTH_URL
@url=URI.parse(@url)
Net::HTTP.start(@url.host) do |http|
req=Net::HTTP::Get.new(@url.path)
req.basic_auth @username,@password
resp=http.request(req)
case resp.code
when "200"
@auth_code="200"
@user=User.new(JSON.parse(resp.body))
when "400"
@auth_code="400"
when "401"
@auth_code="401"
end
end
end
def option2query(option)
query=''
option.each do |key,value|
query<<(key.to_s+'='+value.to_s+'&')
query.chomp
end
query.chop
end
def get_request_uri(path,option)
query=option2query(option)
if query.empty?
path
else
path+'?'+query
end
end
def basic_get_request(url,option={})
url=get_request_uri(url,option)
url=URI.parse(url)
Net::HTTP.start(url.host) do |http|
req=Net::HTTP::Get.new(url.request_uri)
req.basic_auth @username,@password
resp=http.request(req)
return resp
end
end
def basic_post_request(url,data,option={})
url=get_request_uri(url,option)
url=URI.parse(url)
Net::HTTP.start(url.host) do |http|
req=Net::HTTP::Post.new(url.request_uri,data)
req.basic_auth @username,@password
resp=http.request(req)
return resp
end
end
def get_twitters(url,option)
resp=basic_get_request(url,option)
case resp.code
when "200"
@auth_code="200"
twitters||=[]
JSON.parse(resp.body).each do |twitter|
twitters<<Twitter.new(twitter)
end
twitters
when "400"
@auth_code="400"
nil
when "401"
@auth_code="401"
nil
end
end
def get_list(option={})
get_twitters(LIST_URL,option)
end
def get_reply(option={})
get_twitters(REPLY_URL,option)
end
def get_all(option={})
get_twitters(ALL_URL,option)
end
def create
end
def delete
end
end
end