api_client.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. require 'json'
  2. require 'net/http'
  3. require 'net/http/post/multipart'
  4. require 'uri'
  5. class ApiClient
  6. def initialize(host, base_id)
  7. @host = host
  8. @current_id = Integer(base_id)
  9. end
  10. def generate_id
  11. id = @current_id
  12. @current_id += 1
  13. id
  14. end
  15. def set_auth!(username, password)
  16. @username = username
  17. @password = password
  18. end
  19. def clear_auth!
  20. @username = nil
  21. @password = nil
  22. end
  23. def reboot
  24. post('/system', '{"command":"restart"}')
  25. end
  26. def request(type, path, req_body = nil)
  27. uri = URI("http://#{@host}#{path}")
  28. Net::HTTP.start(uri.host, uri.port) do |http|
  29. req_type = Net::HTTP.const_get(type)
  30. req = req_type.new(uri)
  31. if req_body
  32. req['Content-Type'] = 'application/json'
  33. req_body = req_body.to_json if !req_body.is_a?(String)
  34. req.body = req_body
  35. end
  36. if @username && @password
  37. req.basic_auth(@username, @password)
  38. end
  39. res = http.request(req)
  40. res.value
  41. body = res.body
  42. if res['content-type'].downcase == 'application/json'
  43. body = JSON.parse(body)
  44. end
  45. body
  46. end
  47. end
  48. def upload_json(path, file)
  49. `curl -s "http://#{@host}#{path}" -X POST -F 'f=@#{file}'`
  50. end
  51. def get(path)
  52. request(:Get, path)
  53. end
  54. def put(path, body)
  55. request(:Put, path, body)
  56. end
  57. def post(path, body)
  58. request(:Post, path, body)
  59. end
  60. def delete(path)
  61. request(:Delete, path)
  62. end
  63. def state_path(params = {})
  64. "/gateways/#{params[:id]}/#{params[:type]}/#{params[:group_id]}"
  65. end
  66. def delete_state(params = {})
  67. delete(state_path(params))
  68. end
  69. def get_state(params = {})
  70. get(state_path(params))
  71. end
  72. def patch_state(state, params = {})
  73. put(state_path(params), state.to_json)
  74. end
  75. end