1# frozen_string_literal: true
2
3require "blather"
4require "blather/stanza/iq/command"
5require "value_semantics/monkey_patched"
6
7require_relative "customer_fwd"
8require_relative "not_loaded"
9require_relative "form_to_h"
10
11class BackendSgx
12 class CanceledError < StandardError; end
13
14 using FormToH
15
16 value_semantics do
17 jid Blather::JID
18 creds HashOf(Symbol => String)
19 from_jid Blather::JID
20 ogm_url Either(String, nil, NotLoaded)
21 fwd Either(CustomerFwd, nil, NotLoaded)
22 transcription_enabled Either(Bool(), NotLoaded)
23 registered? Either(Blather::Stanza::Iq::IBR, FalseClass, NotLoaded)
24 end
25
26 def register!(tel)
27 iq = ibr
28 iq.phone = tel
29 IQ_MANAGER.write(iq).then do
30 REDIS.set("catapult_jid-#{tel}", from_jid.to_s)
31 end
32 end
33
34 def deregister!
35 ibr = Blather::Stanza::Iq::IBR.new(:set, @jid)
36 ibr.from = from_jid
37 ibr.remove!
38 IQ_MANAGER.write(ibr)
39 end
40
41 def stanza(s)
42 s.dup.tap do |stanza|
43 stanza.to = stanza.to.with(
44 domain: jid.domain,
45 node: jid.node || stanza.to.node
46 )
47 stanza.from = from_jid.with(resource: stanza.from&.resource)
48 end
49 end
50
51 def set_ogm_url(url)
52 REDIS.set("catapult_ogm_url-#{from_jid}", url)
53 end
54
55 def set_port_out_pin(pin)
56 cmd = build_port_out_command(:execute)
57
58 IQ_MANAGER.write(cmd).then { |reply|
59 session_id = reply.command[:sessionid]
60 submit_cmd = build_submit_form(pin, session_id)
61
62 IQ_MANAGER.write(submit_cmd).then { |submit_reply|
63 validate_submit_reply!(submit_reply)
64 }.catch { |e|
65 handle_pin_submission_error(e)
66 }
67 }
68 end
69
70protected
71
72 def ibr
73 s = Blather::Stanza::Iq::IBR.new(:set, jid)
74 s.from = from_jid
75 s.nick = creds[:account]
76 s.username = creds[:username]
77 s.password = creds[:password]
78 s
79 end
80
81 def build_submit_form(pin, session_id)
82 build_port_out_command(:complete, session_id: session_id).tap { |iq|
83 iq.form.type = :submit
84 iq.form.fields = [
85 { var: "pin", value: pin, type: "text-private" },
86 { var: "confirm_pin", value: pin, type: "text-private" }
87 ]
88 }
89 end
90
91 def build_port_out_command(action, session_id: nil)
92 Blather::Stanza::Iq::Command.new.tap { |iq|
93 iq.to = jid
94 iq.from = from_jid
95 iq.node = "set-port-out-pin"
96 iq.action = action
97 iq.sessionid = session_id if session_id
98 }
99 end
100
101 def validate_submit_reply!(submit_reply)
102 sub_text = submit_reply.note&.text
103 case submit_reply.status
104 when :completed
105 raise sub_text if submit_reply.note&.[]("type") == "error"
106 when :canceled
107 raise CanceledError, reply.note&.text
108 else
109 raise sub_text
110 end
111 end
112
113 def handle_pin_submission_error(e)
114 if e.is_a?(Blather::StanzaError) || e.is_a?(RuntimeError)
115 EMPromise.reject(e)
116 else
117 Sentry.capture_exception(e)
118 EMPromise.reject(
119 RuntimeError.new(
120 "Unable to communicate with service. Please try again later."
121 )
122 )
123 end
124 end
125end