Class: VoiceVault::Connection

Inherits:
Object
  • Object
show all
Includes:
REXML
Defined in:
lib/voice_vault/connection.rb

Constant Summary collapse

FORM_BOUNDARY =
"AaB03x"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server_url, credential_id, credential_password) ⇒ Connection

Instantiate the API helper



14
15
16
17
# File 'lib/voice_vault/connection.rb', line 14

def initialize server_url, credential_id, credential_password
  @server_url = server_url
  @default_params = {"username" => credential_id, "password" => credential_password}
end

Instance Attribute Details

#credsObject (readonly)

Returns the value of attribute creds.



11
12
13
# File 'lib/voice_vault/connection.rb', line 11

def creds
  @creds
end

#server_urlObject (readonly)

Returns the value of attribute server_url.



11
12
13
# File 'lib/voice_vault/connection.rb', line 11

def server_url
  @server_url
end

Instance Method Details

#post(page, params = {}) ⇒ Object

Takes care of the HTTP POST to the VoiceVault Fusion REST API Taken directly from VoiceVault example.



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/voice_vault/connection.rb', line 21

def post page, params = {}
  # Set up our HTTP request
  uri = URI::join(@server_url, page)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = Net::HTTP::Post.new(uri.request_uri)

  # Add our credentials to the parameters before we construct the form
  params.update @default_params

  # If we have audio, we need to construct the multipart form by hand.
  # Note: gems such as "multipart" or "rest_client" can greatly simplify this process
  if audio_file = params.delete(:audio_file)
    post_body = []

    params.each do |k, v|
      post_body << "--#{FORM_BOUNDARY}\r\n"
      post_body << "Content-Disposition: form-data; name=\"#{k}\"\r\n\r\n#{v}\r\n"
    end

    post_body << "--#{FORM_BOUNDARY}\r\n"
    post_body << "Content-Disposition: form-data; name=\"utterance\"; filename=\"audio.wav\"\r\n"
    post_body << "Content-Type: audio/wav\r\n\r\n"
    post_body << audio_file.read
    post_body << "\r\n--#{FORM_BOUNDARY}--\r\n"

    request.content_type = "multipart/form-data, boundary=#{FORM_BOUNDARY}"
    request.body = post_body.join
  else
    # Much simpler if we're not doing a multipart submission!
    request.set_form_data(params)
  end

  # Do the actual HTTP post
  begin
    response = http.request(request)

    # And parse the XML response into a hash
    response_xml = Document.new(response.body)
    hash = {}
    response_xml.elements.each("response_info/*") do |e|
      hash[e.name()] = e.text
    end

    # Return the populated hash
    hash
  rescue => e
    raise VoiceVault::Error.new(e.message)
  end
end