sgx_jmp.rb

  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 "date"
  9require "dhall"
 10require "em-hiredis"
 11require "em_promise"
 12require "ruby-bandwidth-iris"
 13require "sentry-ruby"
 14
 15Sentry.init
 16
 17CONFIG =
 18	Dhall::Coder
 19	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 20	.load(ARGV[0], transform_keys: ->(k) { k&.to_sym })
 21
 22Blather::Stanza.handler_list << :stanza
 23singleton_class.class_eval do
 24	include Blather::DSL
 25	Blather::DSL.append_features(self)
 26end
 27
 28require_relative "lib/backend_sgx"
 29require_relative "lib/bandwidth_tn_order"
 30require_relative "lib/btc_sell_prices"
 31require_relative "lib/buy_account_credit_form"
 32require_relative "lib/customer"
 33require_relative "lib/electrum"
 34require_relative "lib/em"
 35require_relative "lib/payment_methods"
 36require_relative "lib/registration"
 37require_relative "lib/transaction"
 38require_relative "lib/web_register_manager"
 39
 40ELECTRUM = Electrum.new(**CONFIG[:electrum])
 41
 42Faraday.default_adapter = :em_synchrony
 43BandwidthIris::Client.global_options = {
 44	account_id: CONFIG[:creds][:account],
 45	username: CONFIG[:creds][:username],
 46	password: CONFIG[:creds][:password]
 47}
 48
 49def new_sentry_hub(stanza, name: nil)
 50	hub = Sentry.get_current_hub&.new_from_top
 51	raise "Sentry.init has not been called" unless hub
 52
 53	hub.push_scope
 54	hub.current_scope.clear_breadcrumbs
 55	hub.current_scope.set_transaction_name(name) if name
 56	hub.current_scope.set_user(jid: stanza.from.stripped.to_s)
 57	hub
 58end
 59
 60# Braintree is not async, so wrap in EM.defer for now
 61class AsyncBraintree
 62	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
 63		@gateway = Braintree::Gateway.new(
 64			environment: environment,
 65			merchant_id: merchant_id,
 66			public_key: public_key,
 67			private_key: private_key
 68		)
 69	end
 70
 71	def respond_to_missing?(m, *)
 72		@gateway.respond_to?(m)
 73	end
 74
 75	def method_missing(m, *args)
 76		return super unless respond_to_missing?(m, *args)
 77
 78		EM.promise_defer(klass: PromiseChain) do
 79			@gateway.public_send(m, *args)
 80		end
 81	end
 82
 83	class PromiseChain < EMPromise
 84		def respond_to_missing?(*)
 85			false # We don't actually know what we respond to...
 86		end
 87
 88		def method_missing(m, *args)
 89			return super if respond_to_missing?(m, *args)
 90			self.then { |o| o.public_send(m, *args) }
 91		end
 92	end
 93end
 94
 95BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
 96
 97def panic(e, hub=nil)
 98	m = e.respond_to?(:message) ? e.message : e
 99	warn "Error raised during event loop: #{e.class}: #{m}"
100	warn e.backtrace if e.respond_to?(:backtrace)
101	if e.is_a?(::Exception)
102		(hub || Sentry).capture_exception(e, hint: { background: false })
103	else
104		(hub || Sentry).capture_message(e, hint: { background: false })
105	end
106	exit 1
107end
108
109EM.error_handler(&method(:panic))
110
111when_ready do
112	BLATHER = self
113	REDIS = EM::Hiredis.connect
114	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
115	DB = PG::EM::Client.new(dbname: "jmp")
116	DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
117	DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
118
119	EM.add_periodic_timer(3600) do
120		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
121		ping.from = CONFIG[:component][:jid]
122		self << ping
123	end
124end
125
126# workqueue_count MUST be 0 or else Blather uses threads!
127setup(
128	CONFIG[:component][:jid],
129	CONFIG[:component][:secret],
130	CONFIG[:server][:host],
131	CONFIG[:server][:port],
132	nil,
133	nil,
134	workqueue_count: 0
135)
136
137message to: /\Aaccount@/ do |m|
138	self << m.reply.tap do |out|
139		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
140	end
141end
142
143stanza to: /\Acustomer_/, from: /@#{CONFIG[:sgx]}(\/|\Z)/ do |s|
144	sentry_hub = new_sentry_hub(s, name: "stanza_customer")
145	Customer.for_customer_id(
146		m.to.node.delete_prefix("customer_")
147	).then { |customer|
148		sentry_hub.current_scope.set_user(
149			id: customer.customer_id,
150			jid: s.from.stripped.to_s
151		)
152		customer.stanza_to(s)
153	}.catch { |e| panic(e, sentry_hub) }
154end
155
156message do |m|
157	sentry_hub = new_sentry_hub(m, name: "message")
158	Customer.for_jid(m.from.stripped).then { |customer|
159		sentry_hub.current_scope.set_user(
160			id: customer.customer_id,
161			jid: m.from.stripped.to_s
162		)
163		today = Time.now.utc.to_date
164		EMPromise.all([
165			REDIS.zremrangebylex(
166				"jmp_customer_outbound_messages-#{customer.customer_id}",
167				"-",
168				# Store message counts per day for 1 year
169				"[#{(today << 12).strftime('%Y%m%d')}"
170			),
171			REDIS.zincrby(
172				"jmp_customer_outbound_messages-#{customer.customer_id}",
173				1,
174				today.strftime("%Y%m%d")
175			),
176			customer.stanza_from(m)
177		])
178	}.catch { |e| panic(e, sentry_hub) }
179end
180
181message :error? do |m|
182	puts "MESSAGE ERROR: #{m.inspect}"
183end
184
185class SessionManager
186	def initialize(blather, id_msg, timeout: 5)
187		@blather = blather
188		@sessions = {}
189		@id_msg = id_msg
190		@timeout = timeout
191	end
192
193	def promise_for(stanza)
194		id = "#{stanza.to.stripped}/#{stanza.public_send(@id_msg)}"
195		@sessions.fetch(id) do
196			@sessions[id] = EMPromise.new
197			EM.add_timer(@timeout) do
198				@sessions.delete(id)&.reject(:timeout)
199			end
200			@sessions[id]
201		end
202	end
203
204	def write(stanza)
205		promise = promise_for(stanza)
206		@blather << stanza
207		promise
208	end
209
210	def fulfill(stanza)
211		id = "#{stanza.from.stripped}/#{stanza.public_send(@id_msg)}"
212		if stanza.error?
213			@sessions.delete(id)&.reject(stanza)
214		else
215			@sessions.delete(id)&.fulfill(stanza)
216		end
217	end
218end
219
220IQ_MANAGER = SessionManager.new(self, :id)
221COMMAND_MANAGER = SessionManager.new(self, :sessionid, timeout: 60 * 60)
222web_register_manager = WebRegisterManager.new
223
224disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
225	reply = iq.reply
226	reply.identities = [{
227		name: "JMP.chat",
228		type: "sms",
229		category: "gateway"
230	}]
231	form = Blather::Stanza::X.find_or_create(reply.query)
232	form.type = "result"
233	form.fields = [
234		{
235			var: "FORM_TYPE",
236			type: "hidden",
237			value: "http://jabber.org/network/serverinfo"
238		}
239	] + CONFIG[:xep0157]
240	self << reply
241end
242
243disco_items node: "http://jabber.org/protocol/commands" do |iq|
244	reply = iq.reply
245	reply.items = [
246		{ node: "number-display", name: "Display JMP Number" },
247		{ node: "configure-calls", name: "Configure Calls" },
248		# TODO: don't show this item if no braintree methods available
249		# TODO: don't show this item if no plan for this customer
250		{ node: "buy-credit", name: "Buy account credit" },
251		{ node: "jabber:iq:register", name: "Register" },
252		{ node: "usage", name: "Show Monthly Usage" },
253		{ node: "reset sip account", name: "Create or Reset SIP Account" }
254	].map do |item|
255		Blather::Stanza::DiscoItems::Item.new(
256			iq.to,
257			item[:node],
258			item[:name]
259		)
260	end
261	self << reply
262end
263
264command :execute?, node: "jabber:iq:register", sessionid: nil do |iq|
265	sentry_hub = new_sentry_hub(iq, name: iq.node)
266	EMPromise.resolve(nil).then {
267		Customer.for_jid(iq.from.stripped)
268	}.catch {
269		sentry_hub.add_breadcrumb(Sentry::Breadcrumb.new(
270			message: "Customer.create"
271		))
272		Customer.create(iq.from.stripped)
273	}.then { |customer|
274		sentry_hub.current_scope.set_user(
275			id: customer.customer_id,
276			jid: iq.from.stripped.to_s
277		)
278		sentry_hub.add_breadcrumb(Sentry::Breadcrumb.new(
279			message: "Registration.for"
280		))
281		Registration.for(
282			iq,
283			customer,
284			web_register_manager
285		).then(&:write)
286	}.catch { |e| panic(e, sentry_hub) }
287end
288
289def reply_with_note(iq, text, type: :info)
290	reply = iq.reply
291	reply.status = :completed
292	reply.note_type = type
293	reply.note_text = text
294
295	self << reply
296end
297
298# Commands that just pass through to the SGX
299command node: ["number-display", "configure-calls"] do |iq|
300	sentry_hub = new_sentry_hub(iq, name: iq.node)
301	Customer.for_jid(iq.from.stripped).then { |customer|
302		sentry_hub.current_scope.set_user(
303			id: customer.customer_id,
304			jid: iq.from.stripped.to_s
305		)
306
307		customer.stanza_from(iq)
308	}.catch { |e| panic(e, sentry_hub) }
309end
310
311command :execute?, node: "buy-credit", sessionid: nil do |iq|
312	sentry_hub = new_sentry_hub(iq, name: iq.node)
313	reply = iq.reply
314	reply.allowed_actions = [:complete]
315
316	Customer.for_jid(iq.from.stripped).then { |customer|
317		BuyAccountCreditForm.for(customer).then do |credit_form|
318			credit_form.add_to_form(reply.form)
319			COMMAND_MANAGER.write(reply).then { |iq2| [customer, credit_form, iq2] }
320		end
321	}.then { |(customer, credit_form, iq2)|
322		iq = iq2 # This allows the catch to use it also
323		Transaction.sale(customer, **credit_form.parse(iq2.form))
324	}.then { |transaction|
325		transaction.insert.then { transaction.amount }
326	}.then { |amount|
327		reply_with_note(iq, "$#{'%.2f' % amount} added to your account balance.")
328	}.catch { |e|
329		sentry_hub.capture_exception(e)
330		text = "Failed to buy credit, system said: #{e.message}"
331		reply_with_note(iq, text, type: :error)
332	}.catch { |e| panic(e, sentry_hub) }
333end
334
335command :execute?, node: "reset sip account", sessionid: nil do |iq|
336	sentry_hub = new_sentry_hub(iq, name: iq.node)
337	Customer.for_jid(iq.from.stripped).then { |customer|
338		sentry_hub.current_scope.set_user(
339			id: customer.customer_id,
340			jid: iq.from.stripped.to_s
341		)
342		customer.reset_sip_account
343	}.then { |sip_account|
344		reply = iq.reply
345		reply.command << sip_account.form
346		BLATHER << reply
347	}.catch { |e| panic(e, sentry_hub) }
348end
349
350command :execute?, node: "usage", sessionid: nil do |iq|
351	sentry_hub = new_sentry_hub(iq, name: iq.node)
352	report_for = (Date.today..(Date.today << 1))
353
354	Customer.for_jid(iq.from.stripped).then { |customer|
355		sentry_hub.current_scope.set_user(
356			id: customer.customer_id,
357			jid: iq.from.stripped.to_s
358		)
359
360		customer.usage_report(report_for)
361	}.then { |usage_report|
362		reply = iq.reply
363		reply.status = :completed
364		reply.command << usage_report.form
365		BLATHER << reply
366	}.catch { |e| panic(e, sentry_hub) }
367end
368
369command :execute?, node: "web-register", sessionid: nil do |iq|
370	sentry_hub = new_sentry_hub(iq, name: iq.node)
371
372	begin
373		jid = iq.form.field("jid")&.value.to_s.strip
374		tel = iq.form.field("tel")&.value.to_s.strip
375		hub.current_scope.set_user(jid: jid, tel: tel)
376		if iq.from.stripped != CONFIG[:web_register][:from]
377			BLATHER << iq.as_error("forbidden", :auth)
378		elsif jid == "" || tel !~ /\A\+\d+\Z/
379			reply_with_note(iq, "Invalid JID or telephone number.", type: :error)
380		else
381			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
382				cmd.to = CONFIG[:web_register][:to]
383				cmd.from = CONFIG[:component][:jid]
384				cmd.node = "push-register"
385				cmd.form.fields = [var: "to", value: jid]
386				cmd.form.type = "submit"
387			}).then { |result|
388				final_jid = result.form.field("from")&.value.to_s.strip
389				web_register_manager[final_jid] = tel
390				BLATHER << iq.reply.tap { |reply| reply.status = :completed }
391			}.catch { |e| panic(e, sentry_hub) }
392		end
393	rescue StandardError => e
394		sentry_hub.capture_exception(e)
395	end
396end
397
398command sessionid: /./ do |iq|
399	COMMAND_MANAGER.fulfill(iq)
400end
401
402iq :result? do |iq|
403	IQ_MANAGER.fulfill(iq)
404end
405
406iq :error? do |iq|
407	IQ_MANAGER.fulfill(iq)
408end