Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
99 lines (87 sloc) 2.63 KB
%w(rubygems json open-uri cgi).each { |f| require f }
module AdultFriendFinder
extend self
def consumer
@consumer ||= OAuth::Consumer.new "ZaoX2axV5AvdgwT7UiglBQ",
"ZGHodV1SDY2p47Al044SwqDR7D32Jll7MleXo6jCao8", { :site => "http://twitter.com" }
end
def pull(url)
txt = []
page = -1
data = nil
@access_token = OAuth::AccessToken.new(consumer, @user.token, @user.secret)
while(data != "[]" && page != "0")
request = consumer.request(:get, "/statuses/friends/#{url}.json?cursor=#{page}", @access_token, { :scheme => :query_string })
case request
when Net::HTTPSuccess
data = request.body
else
raise "Auth fail? #{request.inspect}"
end
json = JSON.parse(data)
page = json['next_cursor_str']
data = json['users'].to_json
data.gsub!(/\]$/, "").gsub!(/^\[/, "") # strip out the array [ and ]
txt << data
end
"[" + txt.compact.join(",").gsub(/,+$/, "").to_s + "]" # put those [ and ] on either side
end
def check_api_load
return @api_load if @api_load
@access_token = OAuth::AccessToken.new(consumer, @user.token, @user.secret)
limit = consumer.request :get, '/account/rate_limit_status.json', @access_token, { :scheme => :query_string }
case limit
when Net::HTTPSuccess
@api_load = JSON.parse(limit.body)['remaining_hits']
else
raise "Auth failed?"
end
end
def cache(url)
filename = File.dirname(__FILE__) + "/cache/#{url}.js"
if !File.exists?(filename) or (Time.now - File.ctime(filename)) > 3600 or File.size(filename) == 0
return "[]" if check_api_load == 0
File.open(filename, "w+") do |f|
begin
html = pull(url)
raise if html.size == 0
f.write(@data = "friends['#{url}']=" + html)
rescue OpenURI::HTTPError
$stderr.puts "Limit exceeded?"
end
end
@data
else
File.open(filename, "r") { |f| f.read }
end
@api_load = nil
File.chmod 0644, filename rescue nil
end
def sanitize(item)
CGI::escape(item).gsub(/\W/, '').strip
end
def user=(user)
@user = user
end
def json(users)
return [] if users.nil? or users.empty?
raise "You must login" unless @user
result = users.inject([]) do |arr,user|
user = sanitize(user)
arr << "#{user}:#{cache(user)}"
arr
end
"{"+result.join(",")+"}"
end
def friends(user)
if str = json([user]) and str.any?
json = JSON::parse str
json.map { |friend|
Hash2[ :title, friend['name'],
:href, friend['screen_name'] ]
}
else
[]
end
end
end