Skip to content

Commit

Permalink
Use the new username API
Browse files Browse the repository at this point in the history
  • Loading branch information
soffes committed Apr 5, 2016
1 parent 6bd25f4 commit 44503ac
Showing 1 changed file with 46 additions and 35 deletions.
81 changes: 46 additions & 35 deletions lib/hue/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

0 comments on commit 44503ac

Please sign in to comment.