catapult.rb

 1# frozen_string_literal: true
 2
 3require "value_semantics/monkey_patched"
 4
 5class Catapult
 6	value_semantics do
 7		user String
 8		token String
 9		secret String
10		application_id String
11		domain String
12		sip_host String
13	end
14
15	def import(body)
16		post(
17			"phoneNumbers",
18			body: { applicationId: application_id }.merge(body)
19		)
20	end
21
22	def create_endpoint(body)
23		post(
24			"domains/#{@domain}/endpoints",
25			body: { applicationId: @application_id }.merge(body)
26		).then do |http|
27			unless http.response_header.status == 201
28				raise "Create new SIP account failed"
29			end
30			http.response_header["location"]
31		end
32	end
33
34	def endpoint_list(page=0)
35		get(
36			"domains/#{@domain}/endpoints",
37			query: { size: 1000, page: page }
38		).then do |http|
39			next [] if http.response_header.status == 404
40			raise "Could not list endpoints" if http.response_header.status != 200
41
42			JSON.parse(http.response)
43		end
44	end
45
46	def endpoint_find(name, page=0)
47		endpoint_list(page).then do |list|
48			next if list.empty?
49
50			if (found = list.find { |e| e["name"] == name })
51				found.merge("url" => CATAPULT.mkurl(
52					"domains/#{found['domainId']}/endpoints/#{found['id']}"
53				))
54			else
55				endpoint_find(name, page + 1)
56			end
57		end
58	end
59
60	def post(path, body:, head: {})
61		EM::HttpRequest.new(
62			mkurl(path), tls: { verify_peer: true }
63		).apost(
64			head: catapult_headers.merge(head),
65			body: body.to_json
66		)
67	end
68
69	def delete(path, head: {})
70		EM::HttpRequest.new(
71			mkurl(path), tls: { verify_peer: true }
72		).adelete(head: catapult_headers.merge(head))
73	end
74
75	def get(path, head: {}, **kwargs)
76		EM::HttpRequest.new(
77			mkurl(path), tls: { verify_peer: true }
78		).aget(head: catapult_headers.merge(head), **kwargs)
79	end
80
81	def mkurl(path)
82		base = "https://api.catapult.inetwork.com/v1/users/#{@user}/"
83		return path if path.start_with?(base)
84		"#{base}#{path}"
85	end
86
87protected
88
89	def catapult_headers
90		{
91			"Authorization" => [@token, @secret],
92			"Content-Type" => "application/json"
93		}
94	end
95end
96
97CATAPULT = Catapult.new(**CONFIG[:catapult])