1# frozen_string_literal: true
2
3require "pg/em"
4require "bigdecimal"
5require "blather/client/dsl" # Require this first to not auto-include
6require "blather/client"
7require "braintree"
8require "dhall"
9require "em-hiredis"
10require "em_promise"
11require "ruby-bandwidth-iris"
12
13CONFIG =
14 Dhall::Coder
15 .new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
16 .load(ARGV[0], transform_keys: ->(k) { k&.to_sym })
17
18singleton_class.class_eval do
19 include Blather::DSL
20 Blather::DSL.append_features(self)
21end
22
23require_relative "lib/backend_sgx"
24require_relative "lib/bandwidth_tn_order"
25require_relative "lib/btc_sell_prices"
26require_relative "lib/buy_account_credit_form"
27require_relative "lib/customer"
28require_relative "lib/electrum"
29require_relative "lib/em"
30require_relative "lib/payment_methods"
31require_relative "lib/registration"
32require_relative "lib/transaction"
33require_relative "lib/web_register_manager"
34
35ELECTRUM = Electrum.new(**CONFIG[:electrum])
36
37Faraday.default_adapter = :em_synchrony
38BandwidthIris::Client.global_options = {
39 account_id: CONFIG[:creds][:account],
40 username: CONFIG[:creds][:username],
41 password: CONFIG[:creds][:password]
42}
43
44# Braintree is not async, so wrap in EM.defer for now
45class AsyncBraintree
46 def initialize(environment:, merchant_id:, public_key:, private_key:, **)
47 @gateway = Braintree::Gateway.new(
48 environment: environment,
49 merchant_id: merchant_id,
50 public_key: public_key,
51 private_key: private_key
52 )
53 end
54
55 def respond_to_missing?(m, *)
56 @gateway.respond_to?(m)
57 end
58
59 def method_missing(m, *args)
60 return super unless respond_to_missing?(m, *args)
61
62 EM.promise_defer(klass: PromiseChain) do
63 @gateway.public_send(m, *args)
64 end
65 end
66
67 class PromiseChain < EMPromise
68 def respond_to_missing?(*)
69 false # We don't actually know what we respond to...
70 end
71
72 def method_missing(m, *args)
73 return super if respond_to_missing?(m, *args)
74 self.then { |o| o.public_send(m, *args) }
75 end
76 end
77end
78
79BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
80BACKEND_SGX = BackendSgx.new
81
82def panic(e)
83 m = e.respond_to?(:message) ? e.message : e
84 warn "Error raised during event loop: #{e.class}: #{m}"
85 warn e.backtrace if e.respond_to?(:backtrace)
86 exit 1
87end
88
89EM.error_handler(&method(:panic))
90
91when_ready do
92 BLATHER = self
93 REDIS = EM::Hiredis.connect
94 BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
95 DB = PG::EM::Client.new(dbname: "jmp")
96 DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
97 DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
98
99 EM.add_periodic_timer(3600) do
100 ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
101 ping.from = CONFIG[:component][:jid]
102 self << ping
103 end
104end
105
106# workqueue_count MUST be 0 or else Blather uses threads!
107setup(
108 CONFIG[:component][:jid],
109 CONFIG[:component][:secret],
110 CONFIG[:server][:host],
111 CONFIG[:server][:port],
112 nil,
113 nil,
114 workqueue_count: 0
115)
116
117message :error? do |m|
118 puts "MESSAGE ERROR: #{m.inspect}"
119end
120
121class SessionManager
122 def initialize(blather, id_msg, timeout: 5)
123 @blather = blather
124 @sessions = {}
125 @id_msg = id_msg
126 @timeout = timeout
127 end
128
129 def promise_for(stanza)
130 id = "#{stanza.to.stripped}/#{stanza.public_send(@id_msg)}"
131 @sessions.fetch(id) do
132 @sessions[id] = EMPromise.new
133 EM.add_timer(@timeout) do
134 @sessions.delete(id)&.reject(:timeout)
135 end
136 @sessions[id]
137 end
138 end
139
140 def write(stanza)
141 promise = promise_for(stanza)
142 @blather << stanza
143 promise
144 end
145
146 def fulfill(stanza)
147 id = "#{stanza.from.stripped}/#{stanza.public_send(@id_msg)}"
148 if stanza.error?
149 @sessions.delete(id)&.reject(stanza)
150 else
151 @sessions.delete(id)&.fulfill(stanza)
152 end
153 end
154end
155
156IQ_MANAGER = SessionManager.new(self, :id)
157COMMAND_MANAGER = SessionManager.new(self, :sessionid, timeout: 60 * 60)
158web_register_manager = WebRegisterManager.new
159
160disco_items node: "http://jabber.org/protocol/commands" do |iq|
161 reply = iq.reply
162 reply.items = [
163 # TODO: don't show this item if no braintree methods available
164 # TODO: don't show this item if no plan for this customer
165 Blather::Stanza::DiscoItems::Item.new(
166 iq.to,
167 "buy-credit",
168 "Buy account credit"
169 ),
170 Blather::Stanza::DiscoItems::Item.new(
171 iq.to,
172 "jabber:iq:register",
173 "Register"
174 )
175 ]
176 self << reply
177end
178
179command :execute?, node: "jabber:iq:register", sessionid: nil do |iq|
180 Customer.for_jid(iq.from.stripped).catch {
181 nil
182 }.then { |customer|
183 Registration.for(
184 iq,
185 customer,
186 web_register_manager
187 ).then(&:write)
188 }.catch(&method(:panic))
189end
190
191def reply_with_note(iq, text, type: :info)
192 reply = iq.reply
193 reply.status = :completed
194 reply.note_type = type
195 reply.note_text = text
196
197 self << reply
198end
199
200command :execute?, node: "buy-credit", sessionid: nil do |iq|
201 reply = iq.reply
202 reply.allowed_actions = [:complete]
203
204 Customer.for_jid(iq.from.stripped).then { |customer|
205 BuyAccountCreditForm.new(customer).add_to_form(reply.form).then { customer }
206 }.then { |customer|
207 EMPromise.all([
208 customer.payment_methods,
209 customer.merchant_account,
210 COMMAND_MANAGER.write(reply)
211 ])
212 }.then { |(payment_methods, merchant_account, iq2)|
213 iq = iq2 # This allows the catch to use it also
214 payment_method = payment_methods.fetch(
215 iq.form.field("payment_method")&.value.to_i
216 )
217 amount = iq.form.field("amount").value.to_s
218 Transaction.sale(merchant_account, payment_method, amount)
219 }.then { |transaction|
220 transaction.insert.then { transaction.amount }
221 }.then { |amount|
222 reply_with_note(iq, "$#{'%.2f' % amount} added to your account balance.")
223 }.catch { |e|
224 text = "Failed to buy credit, system said: #{e.message}"
225 reply_with_note(iq, text, type: :error)
226 }.catch(&method(:panic))
227end
228
229command sessionid: /./ do |iq|
230 COMMAND_MANAGER.fulfill(iq)
231end
232
233iq :result? do |iq|
234 IQ_MANAGER.fulfill(iq)
235end
236
237iq :error? do |iq|
238 IQ_MANAGER.fulfill(iq)
239end