From 44503ac2c94a75f128f1e50990860cc1c8609940 Mon Sep 17 00:00:00 2001 From: Sam Soffes Date: Mon, 4 Apr 2016 20:30:02 -0700 Subject: [PATCH] Use the new username API --- lib/hue/client.rb | 81 +++++++++++++++++++++++++++-------------------- 1 file changed, 46 insertions(+), 35 deletions(-) diff --git a/lib/hue/client.rb b/lib/hue/client.rb index 13a4ca18..e40a546f 100644 --- a/lib/hue/client.rb +++ b/lib/hue/client.rb @@ -6,16 +6,18 @@ module Hue class Client attr_reader :username - def initialize(username = '1234567890') - unless USERNAME_RANGE.include?(username.length) - raise InvalidUsername, "Usernames must be between #{USERNAME_RANGE.first} and #{USERNAME_RANGE.last}." - end + def initialize(username = nil) + username = find_username unless @username @username = username - begin - validate_user - rescue Hue::UnauthorizedUser + if @username + begin + validate_user + rescue Hue::UnauthorizedUser + register_user + end + else register_user end end @@ -75,44 +77,53 @@ def scene(id) scenes.select { |s| s.id == id }.first end - private + private - def validate_user - response = JSON(Net::HTTP.get(URI.parse("http://#{bridge.ip}/api/#{@username}"))) - - if response.is_a? Array - response = response.first - end + def find_username + return ENV['HUE_USERNAME'] if ENV['HUE_USERNAME'] - if error = response['error'] - raise get_error(error) + json = JSON(File.read(File.expand_path('~/.hue'))) + json['username'] + rescue + return nil end - response['success'] - end + def validate_user + response = JSON(Net::HTTP.get(URI.parse("http://#{bridge.ip}/api/#{@username}"))) - def register_user - body = JSON.dump({ - devicetype: 'Ruby', - username: @username - }) + if response.is_a? Array + response = response.first + end - uri = URI.parse("http://#{bridge.ip}/api") - http = Net::HTTP.new(uri.host) - response = JSON(http.request_post(uri.path, body).body).first + if error = response['error'] + raise get_error(error) + end - if error = response['error'] - raise get_error(error) + response['success'] end - response['success'] - end + def register_user + body = JSON.dump({ + devicetype: 'Ruby' + }) - def get_error(error) - # Find error class and return instance - klass = Hue::ERROR_MAP[error['type']] || UnknownError unless klass - klass.new(error['description']) - end + uri = URI.parse("http://#{bridge.ip}/api") + http = Net::HTTP.new(uri.host) + response = JSON(http.request_post(uri.path, body).body).first + + if error = response['error'] + raise get_error(error) + end + if @username = response['success']['username'] + File.write(File.expand_path('~/.hue'), JSON.dump({username: @username})) + end + end + + def get_error(error) + # Find error class and return instance + klass = Hue::ERROR_MAP[error['type']] || UnknownError unless klass + klass.new(error['description']) + end end end