Class: XBMC_JSONRPC::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/xbmc-jsonrpc.rb

Overview

Class to create and store connection information for xbmc server also handles actual json back and forth.

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Connection

Returns a new instance of Connection.



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/xbmc-jsonrpc.rb', line 84

def initialize(options)

  connection_info = {
    :server => '127.0.0.1',
    :port => '8080',
    :user => 'xbmc',
    :pass => ''
  }

  @connection_info = connection_info.merge(options)

  @url = URI.parse("http://#{@connection_info[:server]}:#{@connection_info[:port]}/jsonrpc")
end

Instance Method Details

#command(method, params = {}) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/xbmc-jsonrpc.rb', line 98

def command(method, params = {})
  req = Net::HTTP::Post.new(@url.path)
  req.basic_auth @connection_info[:user], @connection_info[:pass]
  req.add_field 'Content-Type', 'application/json'
  req.body = {
    "id" => 1,
    "jsonrpc" => "2.0",
    "method" => method,
    "params" => params
  }.to_json

  res = Net::HTTP.new(@url.host, @url.port).start {|http| http.request(req) }

  if res.kind_of? Net::HTTPSuccess
    return JSON.parse(res.body)
  else
    return res.error!
  end
rescue StandardError
  print "Unable to connect to server specified\n", $!
  return false
end