# frozen_string_literal: true require "value_semantics/monkey_patched" class Catapult value_semantics do user String token String secret String application_id String domain String sip_host String end def import(body) post( "phoneNumbers", body: { applicationId: application_id }.merge(body) ) end def create_endpoint(body) post( "domains/#{@domain}/endpoints", body: { applicationId: @application_id }.merge(body) ).then do |http| unless http.response_header.status == 201 raise "Create new SIP account failed" end http.response_header["location"] end end def endpoint_list(page=0) get( "domains/#{@domain}/endpoints", query: { size: 1000, page: page } ).then do |http| next [] if http.response_header.status == 404 raise "Could not list endpoints" if http.response_header.status != 200 JSON.parse(http.response) end end def endpoint_find(name, page=0) endpoint_list(page).then do |list| next if list.empty? if (found = list.find { |e| e["name"] == name }) found.merge("url" => CATAPULT.mkurl( "domains/#{found['domainId']}/endpoints/#{found['id']}" )) else endpoint_find(name, page + 1) end end end def post(path, body:, head: {}) EM::HttpRequest.new( mkurl(path), tls: { verify_peer: true } ).apost( head: catapult_headers.merge(head), body: body.to_json ) end def delete(path, head: {}) EM::HttpRequest.new( mkurl(path), tls: { verify_peer: true } ).adelete(head: catapult_headers.merge(head)) end def get(path, head: {}, **kwargs) EM::HttpRequest.new( mkurl(path), tls: { verify_peer: true } ).aget(head: catapult_headers.merge(head), **kwargs) end def mkurl(path) base = "https://api.catapult.inetwork.com/v1/users/#{@user}/" return path if path.start_with?(base) "#{base}#{path}" end protected def catapult_headers { "Authorization" => [@token, @secret], "Content-Type" => "application/json" } end end CATAPULT = Catapult.new(**CONFIG[:catapult])