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 "port_out_pin"
9require_relative "not_loaded"
10require_relative "form_to_h"
11
12class BackendSgx
13 COMMANDS_DISCO_NODE = "http://jabber.org/protocol/commands"
14
15 class CanceledError < StandardError; end
16
17 using FormToH
18
19 include PortOutPin
20
21 value_semantics do
22 jid Blather::JID
23 creds HashOf(Symbol => String)
24 from_jid Blather::JID
25 ogm_url Either(String, nil, NotLoaded)
26 fwd Either(CustomerFwd, nil, NotLoaded)
27 transcription_enabled Either(Bool(), NotLoaded)
28 registered? Either(Blather::Stanza::Iq::IBR, FalseClass, NotLoaded)
29 end
30
31 def register!(tel)
32 iq = ibr
33 iq.phone = tel
34 IQ_MANAGER.write(iq).then do
35 REDIS.set("catapult_jid-#{tel}", from_jid.to_s)
36 end
37 end
38
39 def deregister!
40 ibr = Blather::Stanza::Iq::IBR.new(:set, @jid)
41 ibr.from = from_jid
42 ibr.remove!
43 IQ_MANAGER.write(ibr)
44 end
45
46 def stanza(s)
47 s.dup.tap do |stanza|
48 stanza.to = stanza.to.with(
49 domain: jid.domain,
50 node: jid.node || stanza.to.node
51 )
52 stanza.from = from_jid.with(resource: stanza.from&.resource)
53 end
54 end
55
56 def set_ogm_url(url)
57 REDIS.set("catapult_ogm_url-#{from_jid}", url)
58 end
59
60 def commands
61 iq = Blather::Stanza::DiscoItems.new(:get, COMMANDS_DISCO_NODE)
62 iq.to = jid
63 iq.from = from_jid
64 IQ_MANAGER.write(iq).then(&:items).catch { |e|
65 Sentry.capture_exception(e)
66 []
67 }
68 end
69
70 def set_port_out_pin(pin)
71 cmd = build_port_out_command(:execute)
72
73 IQ_MANAGER.write(cmd).then { |reply|
74 session_id = reply.command[:sessionid]
75 submit_cmd = build_submit_form(pin, session_id)
76
77 IQ_MANAGER.write(submit_cmd).then { |submit_reply|
78 validate_submit_reply!(submit_reply)
79 }.catch { |e|
80 handle_pin_submission_error(e)
81 }
82 }
83 end
84
85protected
86
87 def ibr
88 s = Blather::Stanza::Iq::IBR.new(:set, jid)
89 s.from = from_jid
90 s.nick = creds[:account]
91 s.username = creds[:username]
92 s.password = creds[:password]
93 s
94 end
95end