Skip to content

Instantly share code, notes, and snippets.

Created December 29, 2013 04:30
Show Gist options
  • Save anonymous/869a4c9ddf9155df52df to your computer and use it in GitHub Desktop.
Save anonymous/869a4c9ddf9155df52df to your computer and use it in GitHub Desktop.
$LOAD_PATH.unshift(File.realpath(File.dirname(__FILE__)))
require "multicraft_api"
api = MulticraftApi.new('address','user','key')
api.findConnections :id, 1
require 'json'
require 'net/http'
require 'uri'
require 'digest/md5'
class MulticraftApi
attr_accessor :last_response
@@methods = {
:listUsers => [],
:listConnections => [],
:findConnections => [{:name => :field, :type => :array}, {:name => :value, :type => :array}],
}
def initialize(url, user, key)
@url = url
@user = user
@key = key
end
def method_missing(method, *arguments)
if (!@@methods.has_key? method)
return {:success => false, :errors => ["Unknown API method \"#{method.to_s}\""], :data => {}}
end
callargs = {}
argnames = @@methods[method]
argnames.each_index do |item, index|
if item.kind_of?(Hash)
name = item[:name]
else
name = item.to_s
end
if index < arguments.count
value = arguments[index]
elsif item.kind_of?(Hash) && item.has_key?(:default)
if index >= arguments.count
value = arg[:default]
else
value = arguments[index]
end
else
return {:success => false, :errors => ["\"#{method.to_s}()\": Not enough arguments (#{arguments.count})"], :data => {}}
end
if item.kind_of?(Hash) && item.has_key?(:type)
if arg[:type] == :array
value = JSON.generate(value)
end
callargs[name] = value;
end
call(method.to_s, callargs)
end
end
def call(method, params = {})
if @url.empty?
return {:success => false, :errors => ['Invalid target URL']}
end
if @key.empty?
return {:success => false, :errors => ['Invalid API key']}
end
if !params.kind_of?(Hash)
params = {params => params}
end
params[:'_MulticraftAPIMethod'] = method;
params[:'_MulticraftAPIUser'] = @user;
str = ''
params.each_value { |param|
str << param
}
params[:'_MulticraftAPIKey'] = Digest::MD5.digest(@key+str)
send_request(@url, params)
end
def send_request(url, query)
uri = URI.parse(url)
response = Net::HTTP.post_form(uri, query)
if (!response.kind_of?(Net::HTTPSuccess))
error = 'Empty response (wrong API URL or connection problem)'
return {:success => false, :errors => [error], :data => ''}
end
@last_response = response
ret = JSON.parse(response.body, :symbolize_names => true)
if !ret.kind_of?(Hash)
return {:success => false, :errors => [ret], :data => {}}
end
ret
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment