Class: Mcjsonapi::API

Inherits:
Object
  • Object
show all
Defined in:
lib/mcjsonapi/api.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ API

Returns a new instance of API.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
11
12
13
# File 'lib/mcjsonapi/api.rb', line 5

def initialize(options = {})
  raise ArgumentError, "Username and password must be given." if options[:username].nil? || options[:password].nil?

  @host = options[:host] || "localhost"
  @port = options[:port] || 20059

  @username = options[:username]
  @password = options[:password]
end

Instance Attribute Details

#hostObject (readonly)

Returns the value of attribute host.



3
4
5
# File 'lib/mcjsonapi/api.rb', line 3

def host
  @host
end

#portObject (readonly)

Returns the value of attribute port.



3
4
5
# File 'lib/mcjsonapi/api.rb', line 3

def port
  @port
end

#usernameObject (readonly)

Returns the value of attribute username.



3
4
5
# File 'lib/mcjsonapi/api.rb', line 3

def username
  @username
end

Instance Method Details

#call(options = {}) ⇒ Object

Raises:



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
# File 'lib/mcjsonapi/api.rb', line 19

def call(options = {})

  if options.is_a? String
    if options.empty?
      raise ArgumentError, "A method must be given."
    else
      options = { name: options }
    end
  elsif options.is_a? Hash
    if options.empty? || options[:name].nil?
      raise ArgumentError, "A method must be given."
    end
  else
    raise ArgumentError, "A method must be given."
  end

  options[:username] = @username
  options[:key]      = generate_key(options[:name])

  data = URI::encode JSON.generate(options)
  
  response = Net::HTTP.get_response URI("http://#{@host}:#{@port}/api/2/call?json=#{data}")

  raise APIError, "The API responded with an HTTP error." unless response.is_a? Net::HTTPOK

  response_data = JSON.parse(response.body)[0]

  if response_data["is_success"]
    return response_data["success"]
  else
    raise APIError, "The API raised an error: #{response_data["error"]["message"]} (Code #{response_data["error"]["code"]})"
  end
end

#generate_key(method) ⇒ Object



15
16
17
# File 'lib/mcjsonapi/api.rb', line 15

def generate_key(method)
  Digest::SHA256.hexdigest @username+method+@password
end