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
31 http.response_header["location"]
32 end
33 end
34
35 def endpoint_list(page=0)
36 get(
37 "domains/#{@domain}/endpoints",
38 query: { size: 1000, page: page }
39 ).then do |http|
40 next [] if http.response_header.status == 404
41 raise "Could not list endpoints" if http.response_header.status != 200
42
43 JSON.parse(http.response)
44 end
45 end
46
47 def endpoint_find(name, page=0)
48 endpoint_list(page).then do |list|
49 next if list.empty?
50
51 if (found = list.find { |e| e["name"] == name })
52 found.merge("url" => CATAPULT.mkurl(
53 "domains/#{found['domainId']}/endpoints/#{found['id']}"
54 ))
55 else
56 endpoint_find(name, page + 1)
57 end
58 end
59 end
60
61 def post(path, body:, head: {})
62 EM::HttpRequest.new(
63 mkurl(path), tls: { verify_peer: true }
64 ).apost(
65 head: catapult_headers.merge(head),
66 body: body.to_json
67 )
68 end
69
70 def delete(path, head: {})
71 EM::HttpRequest.new(
72 mkurl(path), tls: { verify_peer: true }
73 ).adelete(head: catapult_headers.merge(head))
74 end
75
76 def get(path, head: {}, **kwargs)
77 EM::HttpRequest.new(
78 mkurl(path), tls: { verify_peer: true }
79 ).aget(head: catapult_headers.merge(head), **kwargs)
80 end
81
82 def mkurl(path)
83 base = "https://api.catapult.inetwork.com/v1/users/#{@user}/"
84 return path if path.start_with?(base)
85
86 "#{base}#{path}"
87 end
88
89protected
90
91 def catapult_headers
92 {
93 "Authorization" => [@token, @secret],
94 "Content-Type" => "application/json"
95 }
96 end
97end
98
99CATAPULT = Catapult.new(**CONFIG[:catapult])