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