Module: FitnessparkApi::HttpClient
- Defined in:
- lib/fitnesspark_api/http_client.rb
Class Method Summary collapse
- .api_key ⇒ Object
- .ensure_successful_response(response) ⇒ Object
- .get(uri, headers: {}, max_redirect_count: 10) ⇒ Object
- .get_center_volume_id(url) ⇒ Object
- .get_html(uri, headers: {}) ⇒ Object
- .get_json(uri, headers: {}) ⇒ Object
- .user_agent ⇒ Object
Class Method Details
.api_key ⇒ Object
69 70 71 72 73 74 75 |
# File 'lib/fitnesspark_api/http_client.rb', line 69 def api_key return @api_key if @api_key html = get_html('https://www.migros-fitness.ch/karte') json = Oj.load(html.css('html').first.attribute('data-setup').value.gsub("'", '"')) @api_key = json['sessionKey'] end |
.ensure_successful_response(response) ⇒ Object
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/fitnesspark_api/http_client.rb', line 51 def ensure_successful_response(response) return if response.code == '200' if response.body.to_s.strip.start_with?('{') error_json = Oj.load(response.body) if error_json.key?('error') msg = error_json['error'] msg << ": #{error_json['message']}" if error_json.key?('message') else msg = error_json.to_s end else msg = "Unsuccessful response #{response.code}" end raise ResponseError, msg end |
.get(uri, headers: {}, max_redirect_count: 10) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/fitnesspark_api/http_client.rb', line 28 def get(uri, headers: {}, max_redirect_count: 10) uri = URI(uri) if uri.is_a?(String) request = Net::HTTP::Get.new(uri) headers.merge!('User-Agent' => user_agent, 'Origin' => 'https://www.migros-fitness.ch') headers.each { |name, value| request[name] = value } http = Net::HTTP.new(uri.hostname, uri.port) http.use_ssl = uri.scheme == 'https' http.verify_mode = OpenSSL::SSL::VERIFY_NONE response = http.request(request) if response.is_a?(Net::HTTPRedirection) && response['location'] && max_redirect_count.positive? return get(response['location'], headers: headers, max_redirect_count: max_redirect_count - 1) end ensure_successful_response(response) response end |
.get_center_volume_id(url) ⇒ Object
23 24 25 26 |
# File 'lib/fitnesspark_api/http_client.rb', line 23 def get_center_volume_id(url) html = get_html(url) html.css('.centerVolume').first.attribute('centerId').value.to_i end |
.get_html(uri, headers: {}) ⇒ Object
17 18 19 20 21 |
# File 'lib/fitnesspark_api/http_client.rb', line 17 def get_html(uri, headers: {}) response = get(uri, headers: headers) Oga.parse_html(response.body.force_encoding('UTF-8')) end |
.get_json(uri, headers: {}) ⇒ Object
11 12 13 14 15 |
# File 'lib/fitnesspark_api/http_client.rb', line 11 def get_json(uri, headers: {}) response = get(uri, headers: headers) Oj.load(response.body) end |
.user_agent ⇒ Object
47 48 49 |
# File 'lib/fitnesspark_api/http_client.rb', line 47 def user_agent format(FitnessparkApi.config['user_agent'], version: VERSION) end |