Class: Transmission::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/transmission-client/em-connection.rb

Class Method Summary collapse

Class Method Details

.build_json(method, attributes = {}) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/transmission-client/em-connection.rb', line 47

def build_json(method,attributes = {})
  if attributes.length == 0
    {'method' => method}.to_json
  else
   {'method' => method, 'arguments' => attributes }.to_json
  end
end

.init(host, port, username = nil, password = nil) ⇒ Object



4
5
6
7
8
9
10
# File 'lib/transmission-client/em-connection.rb', line 4

def init(host, port, username = nil, password = nil)
  @host = host
  @port = port
  @header = username.nil? ? {} : {'authorization' => [username, password]}
  uri = URI.parse("http://#{@host}:#{@port}/transmission/rpc")
  @conn = EventMachine::HttpRequest.new(uri)
end

.request(method, attributes = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/transmission-client/em-connection.rb', line 12

def request(method, attributes={})
  req = @conn.post(:body => build_json(method,attributes), :head => @header )
  req.callback {
    case req.response_header.status
      when 401
        raise SecurityError, 'The client was not able to authenticate, is your username or password wrong?'
      when 409 #&& @header['x-transmission-session-id'].nil?
        @header['x-transmission-session-id'] = req.response_header['X_TRANSMISSION_SESSION_ID']
        request(method,attributes) do |resp|
          yield resp
        end
      when 200
        resp = JSON.parse(req.response)
        if resp["result"] == 'success'
          yield resp['arguments']
        else
          yield resp
        end
    end
  }
  req.errback {
    STDERR.puts "Response Start ->"
    STDERR.puts req.response
    STDERR.puts "<- Response End"
    
    raise "Unknown response."
  }
end

.send(method, attributes = {}) ⇒ Object



41
42
43
44
45
# File 'lib/transmission-client/em-connection.rb', line 41

def send(method, attributes={})
  request(method, attributes) do |resp|
    yield resp
  end
end