Created
February 11, 2010 22:30
-
-
Save barbuza/302045 to your computer and use it in GitHub Desktop.
mailru api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'net/http' | |
require 'cgi' | |
require 'uri' | |
require 'md5' | |
require 'json' | |
module Mailru | |
API_METHODS = ['friends.get', 'friends.getAppUsers', 'users.getInfo', | |
'users.isAppUser', 'users.hasAppPermission', 'payments.openDialog', | |
'stream.publish', 'notifications.send', 'widget.set', | |
'photos.getAlbums', 'photos.get', 'audios.get', 'audios.linkAudio'] | |
class RpcError < Exception | |
end | |
class RpcNamespace | |
def initialize(name) | |
@name = name | |
end | |
def method_missing(name, *args) | |
method = "#{@name}.#{name}" | |
raise unless API_METHODS.index method | |
@params = args.shift.merge :method => method | |
make_request | |
end | |
def sign_params | |
@params.merge! :app_id => APP_CONFIG['app_id'], :secure => 1 | |
# convert all keys and values to strings | |
@params = Hash[@params.map { |k,v| [k.to_s, v.to_s] }] | |
sign_str = @params.keys.sort.map{ |key| "#{key}=#{@params[key]}" }.join('') + APP_CONFIG['secret'] | |
@params[:sig] = MD5.new(sign_str).hexdigest | |
end | |
def make_request | |
sign_params | |
uri = URI.parse(APP_CONFIG['api_url']) | |
query = @params.map{ |key, value| | |
CGI::escape(key.to_s) + '=' + CGI::escape(value.to_s) | |
}.join '&' | |
req = Net::HTTP::Get.new("#{uri.path}?#{query}") | |
http_resp = Net::HTTP.start(uri.host, uri.port) do |http| | |
http.request req | |
end | |
return JSON.parse http_resp.body | |
rescue JSON::ParserError => e | |
raise RpcError, 'json parse error' | |
end | |
end | |
class Rpc | |
def self.method_missing(name) | |
RpcNamespace.new name | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment