Created
January 19, 2022 18:51
-
-
Save pelted/1cf7ceeaf92fa4b277610d2c74d8d090 to your computer and use it in GitHub Desktop.
Quick wrapper around the Purple WiFI API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "time" | |
require "uri" | |
require "net/http" | |
require "json" | |
class PurpleAPIConnection | |
HOST = "purpleportal.net" | |
API_PATH = "/api/company/v1" | |
CONTENT_TYPE = "application/json" | |
attr_reader :uri, :response | |
def initialize(public_key, private_key) | |
@public_key = public_key | |
@private_key = private_key | |
end | |
def get_venues | |
get("venues") | |
parsed_response.dig("data", "venues") | |
end | |
def get_venue(venue_id) | |
get("venue/#{venue_id}") | |
parsed_response.dig("data", "venues")&.first | |
end | |
def get_venue_occupancy(venue_id) | |
get("venue/#{venue_id}/occupancy/sensors") | |
parsed_response.dig("data") | |
end | |
def get(endpoint, params = {}) | |
@uri = URI("https://#{host}#{api_path}/#{endpoint}") | |
@uri.query = URI.encode_www_form(params) | |
@response = | |
Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(request) } | |
end | |
private | |
def host | |
HOST | |
end | |
def api_path | |
API_PATH | |
end | |
def content_type | |
CONTENT_TYPE | |
end | |
def parsed_response | |
@response.is_a?(Net::HTTPSuccess) ? JSON.parse(@response.body) || {} : {} | |
end | |
def request | |
req = Net::HTTP::Get.new(uri) | |
req["Content-Type"] = content_type | |
req["Date"] = Time.now.httpdate | |
req["X-API-Authorization"] = "#{@public_key}:#{token}" | |
req | |
end | |
def path_and_query | |
[uri.path, uri.query].compact.join("?") | |
end | |
def token | |
token_data = [content_type, host, path_and_query, Time.now.httpdate, nil, nil].join("\n") | |
hash_for_token(token_data) | |
end | |
def hash_for_token(data) | |
OpenSSL::HMAC.hexdigest("SHA256", @private_key, data) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: