~singpolyma/sgx-jmp

ref: 2d687b1a39c8318d4efba9300f428f58ed4ad713 sgx-jmp/lib/catapult.rb -rw-r--r-- 2.0 KiB
2d687b1aStephen Paul Weber Patch bandwidth-iris to raise useful exceptions 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# 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])