Class: Rmpd::Connection

Inherits:
Object
  • Object
show all
Includes:
Commands, Socket::Constants
Defined in:
lib/rmpd/connection.rb

Constant Summary collapse

MAX_RETRIES =
5

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Commands

#kill, #volume

Constructor Details

#initialize(config_file = nil) ⇒ Connection

Returns a new instance of Connection.



16
17
18
19
# File 'lib/rmpd/connection.rb', line 16

def initialize(config_file=nil)
  @config = Rmpd::Config.new(config_file)
  @socket = nil
end

Instance Attribute Details

#socketObject (readonly)

Returns the value of attribute socket.



13
14
15
# File 'lib/rmpd/connection.rb', line 13

def socket
  @socket
end

Instance Method Details

#closeObject



21
22
23
# File 'lib/rmpd/connection.rb', line 21

def close
  @socket.close
end

#connectObject



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rmpd/connection.rb', line 25

def connect
  return unless @socket.nil? || @socket.closed?

  if %r{^/} === @config.hostname
    connect_unix_socket
  else
    connect_inet_socket
  end

  read_response # protocol version, ignore for now
  password(@config.password) if @config.password
end

#connect_inet_socketObject



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rmpd/connection.rb', line 45

def connect_inet_socket
  Socket::getaddrinfo(@config.hostname, @config.port, nil, SOCK_STREAM).each do |info|
    begin
      sockaddr = Socket.pack_sockaddr_in(info[1], info[3])
      @socket = Socket.new(info[4], info[5], 0)
      @socket.connect(sockaddr)
    rescue StandardError => error
      @socket = nil
      raise MpdConnRefusedError.new(error)
    else
      break
    end
  end
end

#connect_unix_socketObject



38
39
40
41
42
43
# File 'lib/rmpd/connection.rb', line 38

def connect_unix_socket
  @socket = UNIXSocket.new(@config.hostname)
rescue StandardError => error
  @socket = nil
  raise MpdConnRefusedError.new(error)
end

#mpdObject



86
87
88
# File 'lib/rmpd/connection.rb', line 86

def mpd
  self
end

#quote(args) ⇒ Object



90
91
92
# File 'lib/rmpd/connection.rb', line 90

def quote(args)
  args.collect {|arg| "\"#{arg.to_s.gsub(/"/, "\\\"").gsub(/\\/, "\\\\\\\\")}\""}
end

#read_responseObject



76
77
78
79
80
81
82
83
84
# File 'lib/rmpd/connection.rb', line 76

def read_response
  response = []

  while (line = @socket.readline.force_encoding("UTF-8"))
    response << line.strip
    break if END_RE === line
  end
  response
end

#send_command(command, *args) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rmpd/connection.rb', line 60

def send_command(command, *args)
  tries = 0

  begin
    connect
    @socket.puts("#{command} #{quote(args).join(" ")}".strip)
  rescue Errno::EPIPE, EOFError
    @socket.close
    if (tries += 1) < MAX_RETRIES
      retry
    else
      raise MpdError.new("Retry count exceeded")
    end
  end
end