class XiamiRadio::Client

There is a client as you saw

Constants

HEADERS
HOST
LOGIN_HOST

Attributes

headers[RW]
http[RW]
user[RW]

Public Class Methods

new(headers: {}, user: nil, host: HOST) click to toggle source
# File lib/xiami_radio/client.rb, line 21
def initialize(headers: {}, user: nil, host: HOST)
  @user = user || User.new
  @headers = HEADERS.merge headers
  @uri = URI.parse host
  init_http
end

Public Instance Methods

get(uri, format: :json, headers: {}) click to toggle source
# File lib/xiami_radio/client.rb, line 32
def get(uri, format: :json, headers: {})
  request uri, format, headers do |_headers|
    @http.start { |http| http.request(Net::HTTP::Get.new uri, _headers) }
  end
end
init_http() click to toggle source
# File lib/xiami_radio/client.rb, line 46
def init_http
  @http = Net::HTTP.new @uri.host, @uri.port
  # -- OR --
  # @http = Net::HTTP.new(@uri.host, @uri.port, '127.0.0.1', '8888')
  # @http.verify_mode = ::OpenSSL::SSL::VERIFY_NONE
  @http.use_ssl = @uri.scheme == 'https'
end
post(uri, form_data, format: :json, headers: {}) click to toggle source
# File lib/xiami_radio/client.rb, line 38
def post(uri, form_data, format: :json, headers: {})
  request uri, format, headers do |_headers|
    req = Net::HTTP::Post.new uri, _headers
    req.set_form_data form_data
    @http.start { |http| http.request req }
  end
end
uri(**args) click to toggle source
# File lib/xiami_radio/client.rb, line 28
def uri(**args)
  @uri.class.build scheme: @uri.scheme, host: @uri.host, **args
end

Private Instance Methods

nori() click to toggle source
# File lib/xiami_radio/client.rb, line 71
def nori
  @nori ||= Nori.new(:convert_tags_to => -> (tag) { tag.snakecase.to_sym })
end
request(uri, format, headers, &block) click to toggle source
# File lib/xiami_radio/client.rb, line 56
def request(uri, format, headers, &block)
  _headers = @headers.merge headers
  _headers.merge! 'Cookie' => HTTP::Cookie.cookie_value(user.cookie_jar.cookies uri)
  _headers.merge! 'X-Requested-With' => 'XMLHttpRequest' if %i(json xml xhtml).include? format

  res = block.call _headers

  res.get_fields('set-cookie')&.each { |value| user.cookie_jar.parse value, uri }
  case format
    when :json then JSON.parse(res.body, symbolize_names: true)
    when :xml then nori.parse res.body
    else res
  end
end