port_out_pin.rb

 1# frozen_string_literal: true
 2
 3require "blather"
 4require "blather/stanza/iq/command"
 5
 6class PortOutPin
 7	def initialize(sgx)
 8		@sgx = sgx
 9	end
10
11	def set(pin)
12		cmd = build_command(:execute)
13
14		IQ_MANAGER.write(cmd).then { |reply|
15			session_id = reply.command[:sessionid]
16			submit_cmd = build_submit_form(pin, session_id)
17
18			IQ_MANAGER.write(submit_cmd).then { |submit_reply|
19				validate_submit_reply!(submit_reply)
20			}.catch { |e|
21				handle_pin_submission_error(e)
22			}
23		}
24	end
25
26protected
27
28	def build_submit_form(pin, session_id)
29		build_command(:complete, session_id: session_id).tap { |iq|
30			iq.form.type = :submit
31			iq.form.fields = [
32				{ var: "pin", value: pin },
33				{ var: "confirm_pin", value: pin }
34			]
35		}
36	end
37
38	def build_command(action, session_id: nil)
39		@sgx.stanza(Blather::Stanza::Iq::Command.new.tap { |iq|
40			iq.to = ""
41			iq.node = "set-port-out-pin"
42			iq.action = action
43			iq.sessionid = session_id if session_id
44		})
45	end
46
47	def validate_submit_reply!(submit_reply)
48		sub_text = submit_reply.note&.text
49		case submit_reply.status
50		when :completed
51			raise sub_text if submit_reply.note&.[]("type") == "error"
52		when :canceled
53			raise CanceledError, reply.note&.text
54		else
55			raise sub_text
56		end
57	end
58
59	def handle_pin_submission_error(e)
60		if e.is_a?(Blather::StanzaError) || e.is_a?(RuntimeError)
61			EMPromise.reject(e)
62		else
63			Sentry.capture_exception(e)
64			EMPromise.reject(
65				RuntimeError.new(
66					"Unable to communicate with service. Please try again later."
67				)
68			)
69		end
70	end
71end