registration_repo.rb

 1# frozen_string_literal: true
 2
 3require "savon"
 4
 5class RegistrationRepo
 6	def initialize(redis:)
 7		@redis = redis
 8		@savon = Savon.client {
 9			wsdl "https://api.1pcom.net/ws2/DIDManagement.asmx?WSDL"
10			convert_request_keys_to :camelcase
11		}
12	end
13
14	def find(jid)
15		@redis.lrange("endstream_registration-#{jid.stripped}", 0, 2)
16	end
17
18	def put(jid, *creds)
19		setup_endstream_route(*creds, jid).then do |status|
20			next status unless status[:code].to_i.zero?
21
22			@redis.rpush(
23				"endstream_registration-#{jid.stripped}",
24				*creds
25			).then { status }
26		end
27	end
28
29	def delete(jid)
30		find(jid).then do |creds|
31			next { code: 0 } unless creds&.length&.positive?
32
33			EMPromise.all([
34				remove_endstream_route(*creds),
35				@redis.del("endstream_registration-#{jid.stripped}")
36			]).then { |(status, _)| status }
37		end
38	end
39
40protected
41
42	def setup_endstream_route(tel, username, password, jid)
43		EM.promise_defer {
44			@savon.call(
45				:did_route_sms_to_xmpp, message: {
46					auth: { username: username, password: password },
47					dID: tel.sub(/\A\+/, ""),
48					xMPP_user:
49						ProxiedJID.proxy(jid, CONFIG[:component][:jid]).stripped.to_s
50				}
51			).body.dig(:did_route_sms_to_xmpp_response, :did_route_sms_to_xmpp_result)
52		}
53	end
54
55	def remove_endstream_route(tel, username, password)
56		EM.promise_defer {
57			@savon.call(
58				:did_unroute_sms, message: {
59					auth: { username: username, password: password },
60					dID: tel.sub(/\A\+/, "")
61				}
62			).body.dig(:did_unroute_sms_response, :did_unroute_sms_result)
63		}
64	end
65end