sgx_jmp.rb

   1# frozen_string_literal: true
   2
   3require "pg/em/connection_pool"
   4require "bandwidth"
   5require "bigdecimal"
   6require "blather/client/dsl"
   7require "date"
   8require "dhall"
   9require "em-hiredis"
  10require "em_promise"
  11require "ougai"
  12require "ruby-bandwidth-iris"
  13require "sentry-ruby"
  14require "statsd-instrument"
  15
  16require_relative "lib/background_log"
  17
  18$stdout.sync = true
  19LOG = Ougai::Logger.new(BackgroundLog.new($stdout))
  20LOG.level = ENV.fetch("LOG_LEVEL", "info")
  21LOG.formatter = Ougai::Formatters::Readable.new(
  22	nil,
  23	nil,
  24	plain: !$stdout.isatty
  25)
  26Blather.logger = LOG
  27EM::Hiredis.logger = LOG
  28StatsD.logger = LOG
  29LOG.info "Starting"
  30
  31def log
  32	Thread.current[:log] || LOG
  33end
  34
  35Sentry.init do |config|
  36	config.logger = LOG
  37	config.breadcrumbs_logger = [:sentry_logger]
  38end
  39
  40CONFIG = Dhall::Coder
  41	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
  42	.load(
  43		"(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
  44		transform_keys: ->(k) { k&.to_sym },
  45		timeout: 30
  46	)
  47WEB_LISTEN =
  48	if CONFIG[:web].is_a?(Hash)
  49		[CONFIG[:web][:interface], CONFIG[:web][:port]]
  50	else
  51		[CONFIG[:web]]
  52	end
  53
  54singleton_class.class_eval do
  55	include Blather::DSL
  56	Blather::DSL.append_features(self)
  57end
  58
  59require_relative "lib/session_manager"
  60
  61IQ_MANAGER = SessionManager.new(self, :id)
  62COMMAND_MANAGER = SessionManager.new(
  63	self,
  64	:sessionid,
  65	timeout: 60 * 60,
  66	error_if: ->(s) { s.cancel? }
  67)
  68
  69require_relative "lib/polyfill"
  70require_relative "lib/alt_top_up_form"
  71require_relative "lib/admin_command"
  72require_relative "lib/backend_sgx"
  73require_relative "lib/bwmsgsv2_repo"
  74require_relative "lib/bandwidth_iris_patch"
  75require_relative "lib/bandwidth_tn_order"
  76require_relative "lib/bandwidth_tn_repo"
  77require_relative "lib/btc_sell_prices"
  78require_relative "lib/buy_account_credit_form"
  79require_relative "lib/configure_calls_form"
  80require_relative "lib/command"
  81require_relative "lib/command_list"
  82require_relative "lib/customer"
  83require_relative "lib/customer_info"
  84require_relative "lib/customer_info_form"
  85require_relative "lib/customer_repo"
  86require_relative "lib/dummy_command"
  87require_relative "lib/db_notification"
  88require_relative "lib/electrum"
  89require_relative "lib/empty_repo"
  90require_relative "lib/expiring_lock"
  91require_relative "lib/em"
  92require_relative "lib/form_to_h"
  93require_relative "lib/low_balance"
  94require_relative "lib/port_in_order"
  95require_relative "lib/patches_for_sentry"
  96require_relative "lib/payment_methods"
  97require_relative "lib/paypal_done"
  98require_relative "lib/postgres"
  99require_relative "lib/reachability_form"
 100require_relative "lib/reachability_repo"
 101require_relative "lib/registration"
 102require_relative "lib/transaction"
 103require_relative "lib/tel_selections"
 104require_relative "lib/sim_repo"
 105require_relative "lib/sim_order"
 106require_relative "lib/snikket"
 107require_relative "lib/welcome_message"
 108require_relative "web"
 109require_relative "lib/statsd"
 110
 111ELECTRUM = Electrum.new(**CONFIG[:electrum])
 112ELECTRUM_BCH = Electrum.new(**CONFIG[:electrum_bch])
 113
 114LOG.info "Loading scripts from #{__dir__}/redis_lua"
 115EM::Hiredis::Client.load_scripts_from("#{__dir__}/redis_lua")
 116
 117Faraday.default_adapter = :em_synchrony
 118BandwidthIris::Client.global_options = {
 119	account_id: CONFIG[:creds][:account],
 120	username: CONFIG[:creds][:username],
 121	password: CONFIG[:creds][:password]
 122}
 123BANDWIDTH_VOICE = Bandwidth::Client.new(
 124	voice_basic_auth_user_name: CONFIG[:creds][:username],
 125	voice_basic_auth_password: CONFIG[:creds][:password]
 126).voice_client.client
 127
 128class AuthError < StandardError; end
 129
 130require_relative "lib/async_braintree"
 131BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
 132
 133def panic(e, hub=nil)
 134	log.fatal(
 135		"Error raised during event loop: #{e.class}",
 136		e
 137	)
 138	if e.is_a?(::Exception)
 139		(hub || Sentry).capture_exception(e, hint: { background: false })
 140	else
 141		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
 142	end
 143	exit 1
 144end
 145
 146EM.error_handler(&method(:panic))
 147
 148require_relative "lib/blather_client"
 149@client = BlatherClient.new
 150
 151setup(
 152	CONFIG[:component][:jid],
 153	CONFIG[:component][:secret],
 154	CONFIG[:server][:host],
 155	CONFIG[:server][:port],
 156	nil,
 157	nil,
 158	async: true
 159)
 160
 161# Infer anything we might have been notified about while we were down
 162def catchup_notify_low_balance(db)
 163	db.query(<<~SQL).each do |c|
 164		SELECT customer_id
 165		FROM balances INNER JOIN customer_plans USING (customer_id)
 166		WHERE balance < 5 AND expires_at > LOCALTIMESTAMP
 167	SQL
 168		db.query("SELECT pg_notify('low_balance', $1)", c.values)
 169	end
 170end
 171
 172def catchup_notify_possible_renewal(db)
 173	db.query(<<~SQL).each do |c|
 174		SELECT customer_id
 175		FROM customer_plans INNER JOIN balances USING (customer_id)
 176		WHERE
 177			expires_at < LOCALTIMESTAMP
 178			AND expires_at >= LOCALTIMESTAMP - INTERVAL '3 months'
 179			AND balance >= 5
 180	SQL
 181		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
 182	end
 183end
 184
 185def setup_sentry_scope(name)
 186	Sentry.clone_hub_to_current_thread
 187	Sentry.with_scope do |scope|
 188		scope.clear_breadcrumbs
 189		scope.set_transaction_name(name)
 190		Thread.current[:log] = ::LOG.child(transaction: scope.transaction_name)
 191		yield scope
 192	end
 193end
 194
 195def poll_for_notify(db, repo)
 196	db.wait_for_notify_defer.then { |notify|
 197		setup_sentry_scope("DB NOTIFY") do
 198			repo.find(notify[:extra]).then { |customer|
 199				DbNotification.for(notify, customer, repo)
 200			}.then(&:call).catch { |e|
 201				log.error("Error during poll_for_notify", e)
 202				Sentry.capture_exception(e)
 203			}.sync
 204		end
 205	}.then { EM.add_timer(0.5) { poll_for_notify(db, repo) } }
 206end
 207
 208def load_plans_to_db!
 209	DB.transaction do
 210		DB.exec("TRUNCATE plans")
 211		CONFIG[:plans].each do |plan|
 212			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
 213		end
 214	end
 215end
 216
 217when_ready do
 218	log.info "Ready"
 219	BLATHER = self
 220	REDIS = EM::Hiredis.connect
 221	MEMCACHE = EM::P::Memcache.connect
 222	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
 223	BCH_SELL_PRICES = BCHSellPrices.new(REDIS, CONFIG[:oxr_app_id])
 224	DB = Postgres.connect(dbname: "jmp", size: 5)
 225	TEL_SELECTIONS = TelSelections.new
 226
 227	EMPromise.resolve(nil).then {
 228		conn = DB.acquire
 229		conn.query("LISTEN low_balance")
 230		conn.query("LISTEN possible_renewal")
 231		catchup_notify_low_balance(conn)
 232		catchup_notify_possible_renewal(conn)
 233
 234		repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 235		poll_for_notify(conn, repo)
 236	}.catch(&method(:panic))
 237
 238	load_plans_to_db!
 239
 240	EM.add_periodic_timer(3600) do
 241		DB.finish # Clear idle connections
 242		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
 243		ping.from = CONFIG[:component][:jid]
 244		self << ping
 245	end
 246
 247	Web.run(LOG.child, *WEB_LISTEN)
 248end
 249
 250message to: /\Aaccount@/, body: /./ do |m|
 251	StatsD.increment("deprecated_account_bot")
 252
 253	self << m.reply.tap { |out|
 254		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
 255	}
 256end
 257
 258FROM_BACKEND =
 259	"(?:#{([CONFIG[:sgx]] + CONFIG[:sgx_creds].keys)
 260		.map(&Regexp.method(:escape)).join('|')})"
 261
 262before(
 263	:iq,
 264	type: [:error, :result],
 265	to: /\Acustomer_/,
 266	from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
 267) { |iq| halt if IQ_MANAGER.fulfill(iq) }
 268
 269before nil, to: /\Acustomer_/, from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/ do |s|
 270	StatsD.increment("stanza_customer")
 271
 272	Sentry.get_current_scope.set_transaction_name("stanza_customer")
 273	CustomerRepo.new(set_user: Sentry.method(:set_user)).find(
 274		s.to.node.delete_prefix("customer_")
 275	).then do |customer|
 276		ReachabilityRepo::SMS.new
 277			.find(customer, s.from.node, stanza: s).then do |reach|
 278				reach.filter do
 279					customer.stanza_to(s)
 280				end
 281			end
 282	end
 283
 284	halt
 285end
 286
 287ADDRESSES_NS = "http://jabber.org/protocol/address"
 288message(
 289	to: /\A#{CONFIG[:component][:jid]}\Z/,
 290	from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
 291) do |m|
 292	StatsD.increment("inbound_group_text")
 293	Sentry.get_current_scope.set_transaction_name("inbound_group_text")
 294	log.info "Possible group text #{m.from}"
 295
 296	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
 297		&.find("ns:address", ns: ADDRESSES_NS)
 298		&.find { |el| el["jid"].to_s.start_with?("customer_") }
 299	pass unless address
 300
 301	CustomerRepo
 302		.new(set_user: Sentry.method(:set_user))
 303		.find_by_jid(address["jid"]).then { |customer|
 304			m.from = m.from.with(domain: CONFIG[:component][:jid])
 305			m.to = m.to.with(domain: customer.jid.domain)
 306			address["jid"] = customer.jid.to_s
 307			BLATHER << m
 308		}.catch_only(CustomerRepo::NotFound) { |e|
 309			BLATHER << m.as_error("forbidden", :auth, e.message)
 310		}
 311end
 312
 313# Ignore groupchat messages
 314# Especially if we have the component join MUC for notifications
 315message(type: :groupchat) { true }
 316
 317def billable_message(m)
 318	b = m.body
 319	b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first
 320end
 321
 322class OverLimit < StandardError
 323	def initialize(customer, usage)
 324		super("Please contact support")
 325		@customer = customer
 326		@usage = usage
 327	end
 328
 329	def notify_admin
 330		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
 331			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 332			BLATHER.say(
 333				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
 334				"#{@usage} messages today", :groupchat
 335			)
 336		end
 337	end
 338end
 339
 340class CustomerExpired < StandardError; end
 341
 342CONFIG[:direct_targets].each do |(tel, jid)|
 343	customer_repo = CustomerRepo.new(
 344		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
 345		set_user: Sentry.method(:set_user)
 346	)
 347
 348	message to: /\A#{Regexp.escape(tel)}@#{CONFIG[:component][:jid]}\/?/ do |m|
 349		customer_repo.find_by_jid(m.from.stripped).then { |customer|
 350			customer.stanza_from(m)
 351		}.catch_only(CustomerRepo::NotFound) {
 352			# This should not happen, but let's still get the message
 353			# to support at least if it does
 354			m.from = ProxiedJID.proxy(m.from, CONFIG[:component][:jid])
 355			m.to = jid
 356			BLATHER << m
 357		}
 358	end
 359end
 360
 361CONFIG[:direct_sources].each do |(jid, tel)|
 362	customer_repo = CustomerRepo.new(
 363		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
 364		set_user: Sentry.method(:set_user)
 365	)
 366	message to: /\Acustomer_/, from: /\A#{Regexp.escape(jid)}\/?/ do |m|
 367		customer_repo.find(m.to.node.delete_prefix("customer_")).then { |customer|
 368			m.from = "#{tel}@sgx-jmp" # stanza_to will fix domain
 369			customer.stanza_to(m)
 370		}.catch_only(CustomerRepo::NotFound) { |e|
 371			BLATHER << m.as_error("item-not-found", :cancel, e.message)
 372		}
 373	end
 374end
 375
 376def find_from_and_to_customer(from, to)
 377	(
 378		# TODO: group text?
 379		to.node ? CustomerRepo.new.find_by_tel(to.node) : EMPromise.resolve(nil)
 380	).catch_only(CustomerRepo::NotFound) { nil }.then { |target_customer|
 381		sgx_repo = target_customer ? Bwmsgsv2Repo.new : TrivialBackendSgxRepo.new
 382		EMPromise.all([
 383			CustomerRepo.new(set_user: Sentry.method(:set_user), sgx_repo: sgx_repo)
 384				.find_by_jid(from.stripped),
 385			target_customer
 386		])
 387	}
 388end
 389
 390message do |m|
 391	StatsD.increment("message")
 392
 393	today = Time.now.utc.to_date
 394	find_from_and_to_customer(m.from, m.to).then { |(customer, target_customer)|
 395		if target_customer && customer.registered?
 396			m.from = "#{customer.registered?.phone}@sgx-jmp"
 397			next target_customer.stanza_to(m)
 398		end
 399
 400		next customer.stanza_from(m) unless billable_message(m)
 401
 402		if customer.plan_name && !customer.active?
 403			raise CustomerExpired, "Your account is expired, please top up"
 404		end
 405
 406		EMPromise.all([
 407			TrustLevelRepo.new.find(customer),
 408			customer.message_usage((today..today))
 409		]).then { |(tl, usage)|
 410			raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
 411		}.then do
 412			EMPromise.all([customer.incr_message_usage, customer.stanza_from(m)])
 413		end
 414	}.catch_only(OverLimit) { |e|
 415		e.notify_admin
 416		BLATHER << m.as_error("policy-violation", :wait, e.message)
 417	}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
 418		BLATHER << m.as_error("forbidden", :auth, e.message)
 419	}
 420end
 421
 422disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
 423	reply = iq.reply
 424	reply.identities = [{
 425		name: "JMP.chat",
 426		type: "sms",
 427		category: "gateway"
 428	}]
 429	reply.features = [
 430		"http://jabber.org/protocol/disco#info",
 431		"http://jabber.org/protocol/commands"
 432	]
 433	form = Blather::Stanza::X.find_or_create(reply.query)
 434	form.type = "result"
 435	form.fields = [
 436		{
 437			var: "FORM_TYPE",
 438			type: "hidden",
 439			value: "http://jabber.org/network/serverinfo"
 440		}
 441	] + CONFIG[:xep0157]
 442	self << reply
 443end
 444
 445disco_info do |iq|
 446	reply = iq.reply
 447	reply.identities = [{
 448		name: "JMP.chat",
 449		type: "sms",
 450		category: "client"
 451	}]
 452	reply.features = [
 453		"urn:xmpp:receipts"
 454	]
 455	self << reply
 456end
 457
 458disco_items(
 459	to: Blather::JID.new(CONFIG[:component][:jid]),
 460	node: "http://jabber.org/protocol/commands"
 461) do |iq|
 462	StatsD.increment("command_list")
 463
 464	reply = iq.reply
 465	reply.node = "http://jabber.org/protocol/commands"
 466
 467	CustomerRepo.new(
 468		sgx_repo: Bwmsgsv2Repo.new,
 469		set_user: Sentry.method(:set_user)
 470	).find_by_jid(
 471		iq.from.stripped
 472	).catch {
 473		nil
 474	}.then { |customer|
 475		CommandList.for(customer, iq.from)
 476	}.then { |list|
 477		reply.items = list.map { |item|
 478			Blather::Stanza::DiscoItems::Item.new(
 479				iq.to,
 480				item[:node],
 481				item[:name]
 482			)
 483		}
 484		self << reply
 485	}
 486end
 487
 488iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
 489	StatsD.increment("extdisco")
 490
 491	reply = iq.reply
 492	reply << Nokogiri::XML::Builder.new {
 493		services(xmlns: "urn:xmpp:extdisco:2") do
 494			service(
 495				type: "sip",
 496				host: CONFIG[:sip_host]
 497			)
 498		end
 499	}.doc.root
 500
 501	self << reply
 502end
 503
 504Command.new(
 505	"jabber:iq:register",
 506	"Register",
 507	list_for: ->(*) { true },
 508	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 509) {
 510	google_play_userid = if Command.execution.iq.from.domain == "cheogram.com"
 511		Command.execution.iq.command.find(
 512			"./ns:userId", ns: "https://ns.cheogram.com/google-play"
 513		)&.first&.content
 514	end
 515	Command.customer.catch_only(CustomerRepo::NotFound) {
 516		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
 517		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
 518	}.then { |customer|
 519		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
 520		Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
 521	}.then {
 522		StatsD.increment("registration.completed")
 523	}.catch_only(Command::Execution::FinalStanza) do |e|
 524		StatsD.increment("registration.completed")
 525		EMPromise.reject(e)
 526	end
 527}.register(self).then(&CommandList.method(:register))
 528
 529Command.new(
 530	"info",
 531	"👤 Show Account Info",
 532	list_for: ->(*) { true },
 533	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 534) {
 535	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
 536		Command.finish do |reply|
 537			reply.command << info.form
 538		end
 539	end
 540}.register(self).then(&CommandList.method(:register))
 541
 542Command.new(
 543	"cdrs",
 544	"📲 Show Call Logs"
 545) {
 546	report_for = ((Date.today << 1)..Date.today)
 547
 548	Command.customer.then { |customer|
 549		CDRRepo.new.find_range(customer, report_for)
 550	}.then do |cdrs|
 551		Command.finish do |reply|
 552			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
 553		end
 554	end
 555}.register(self).then(&CommandList.method(:register))
 556
 557Command.new(
 558	"transactions",
 559	"🧾 Show Transactions",
 560	list_for: ->(customer:, **) { !!customer&.currency }
 561) {
 562	Command.customer.then(&:transactions).then do |txs|
 563		Command.finish do |reply|
 564			reply.command << FormTemplate.render("transactions", transactions: txs)
 565		end
 566	end
 567}.register(self).then(&CommandList.method(:register))
 568
 569Command.new(
 570	"configure calls",
 571	"📞 Configure Calls",
 572	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 573) {
 574	Command.customer.then do |customer|
 575		cc_form = ConfigureCallsForm.new(customer)
 576		Command.reply { |reply|
 577			reply.allowed_actions = [:next]
 578			reply.command << cc_form.render
 579		}.then { |iq|
 580			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
 581				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
 582			})
 583		}.then { Command.finish("Configuration saved!") }
 584	end
 585}.register(self).then(&CommandList.method(:register))
 586
 587Command.new(
 588	"ogm",
 589	"⏺️ Record Voicemail Greeting",
 590	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
 591	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 592) {
 593	Command.customer.then do |customer|
 594		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
 595			cc.from = customer.registered?.phone
 596			cc.application_id = CONFIG[:sip][:app]
 597			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
 598			                "customer_id=#{customer.customer_id}"
 599		end
 600		Command.finish("You will now receive a call.")
 601	end
 602}.register(self).then(&CommandList.method(:register))
 603
 604Command.new(
 605	"migrate billing",
 606	"🏦 Switch to new billing",
 607	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
 608	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 609) {
 610	EMPromise.all([
 611		Command.customer,
 612		Command.reply do |reply|
 613			reply.allowed_actions = [:next]
 614			reply.command << FormTemplate.render("migrate_billing")
 615		end
 616	]).then do |(customer, iq)|
 617		plan_name = iq.form.field("plan_name").value.to_s
 618		customer = customer.with_plan(plan_name)
 619		customer.save_plan!.then {
 620			Registration::Payment.for(
 621				iq, customer, customer.registered?.phone,
 622				final_message: PaypalDone::MESSAGE,
 623				finish: PaypalDone
 624			)
 625		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 626			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 627			BLATHER.say(
 628				CONFIG[:notify_admin],
 629				"#{customer.customer_id} migrated to #{customer.currency}",
 630				:groupchat
 631			)
 632			EMPromise.reject(s)
 633		end
 634	end
 635}.register(self).then(&CommandList.method(:register))
 636
 637Command.new(
 638	"credit cards",
 639	"💳 Credit Card Settings and Management",
 640	list_for: ->(customer:, **) { !!customer&.currency }
 641) {
 642	Command.customer.then do |customer|
 643		url = CONFIG[:credit_card_url].call(
 644			customer.jid.to_s.gsub("\\", "%5C"),
 645			customer.customer_id
 646		)
 647		desc = "Manage credits cards and settings"
 648		Command.finish("#{desc}: #{url}") do |reply|
 649			oob = OOB.find_or_create(reply.command)
 650			oob.url = url
 651			oob.desc = desc
 652		end
 653	end
 654}.register(self).then(&CommandList.method(:register))
 655
 656Command.new(
 657	"top up",
 658	"💲 Buy Account Credit by Credit Card",
 659	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 660	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 661) {
 662	Command.customer.then { |customer|
 663		BuyAccountCreditForm.for(customer).then do |credit_form|
 664			Command.reply { |reply|
 665				reply.allowed_actions = [:complete]
 666				reply.command << credit_form.form
 667			}.then do |iq|
 668				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 669			end
 670		end
 671	}.then { |transaction|
 672		Command.finish("#{transaction} added to your account balance.")
 673	}.catch_only(
 674		AmountTooHighError,
 675		AmountTooLowError
 676	) do |e|
 677		Command.finish(e.message, type: :error)
 678	end
 679}.register(self).then(&CommandList.method(:register))
 680
 681Command.new(
 682	"alt top up",
 683	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 684	list_for: ->(customer:, **) { !!customer&.currency }
 685) {
 686	Command.customer.then { |customer|
 687		AltTopUpForm.for(customer)
 688	}.then do |alt_form|
 689		Command.reply { |reply|
 690			reply.allowed_actions = [:complete]
 691			reply.command << alt_form.form
 692		}.then do |iq|
 693			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 694		end
 695	end
 696}.register(self).then(&CommandList.method(:register))
 697
 698Command.new(
 699	"plan settings",
 700	"📝 Manage your plan, including overage limits",
 701	list_for: ->(customer:, **) { !!customer&.currency }
 702) {
 703	Command.customer.then { |customer|
 704		EMPromise.all([
 705			REDIS.get("jmp_customer_monthly_data_limit-#{customer.customer_id}"),
 706			SIMRepo.new.owned_by(customer)
 707		]).then { |(limit, sims)| [customer, sims, limit] }
 708	}.then do |(customer, sims, limit)|
 709		Command.reply { |reply|
 710			reply.allowed_actions = [:next]
 711			reply.command << FormTemplate.render(
 712				"plan_settings", customer: customer, sims: sims, data_limit: limit
 713			)
 714		}.then { |iq|
 715			kwargs = {
 716				monthly_overage_limit: iq.form.field("monthly_overage_limit")&.value,
 717				monthly_data_limit: iq.form.field("monthly_data_limit")&.value
 718			}.compact
 719			Command.execution.customer_repo.put_monthly_limits(customer, **kwargs)
 720		}.then { Command.finish("Configuration saved!") }
 721	end
 722}.register(self).then(&CommandList.method(:register))
 723
 724Command.new(
 725	"referral codes",
 726	"👥 Refer a friend for free credit",
 727	list_for: ->(customer:, **) { !!customer&.currency }
 728) {
 729	repo = InvitesRepo.new
 730	Command.customer.then { |customer|
 731		EMPromise.all([
 732			repo.find_or_create_group_code(customer.customer_id),
 733			repo.unused_invites(customer.customer_id)
 734		])
 735	}.then do |(group_code, invites)|
 736		if invites.empty?
 737			Command.finish(
 738				"This code will provide credit equivalent to one month of service " \
 739				"to anyone after they sign up and pay: #{group_code}\n\n" \
 740				"You will receive credit equivalent to one month of service once " \
 741				"their payment clears."
 742			)
 743		else
 744			Command.finish do |reply|
 745				reply.command << FormTemplate.render(
 746					"codes",
 747					invites: invites,
 748					group_code: group_code
 749				)
 750			end
 751		end
 752	end
 753}.register(self).then(&CommandList.method(:register))
 754
 755# Assumes notify_from is a direct target
 756notify_to = CONFIG[:direct_targets].fetch(
 757	Blather::JID.new(CONFIG[:notify_from]).node.to_sym
 758)
 759
 760Command.new(
 761	"sims",
 762	"📶 (e)SIM Details",
 763	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency },
 764	customer_repo: CustomerRepo.new(
 765		sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
 766	)
 767) {
 768	Command.customer.then { |customer|
 769		EMPromise.all([customer, SIMRepo.new.owned_by(customer)])
 770	}.then do |(customer, sims)|
 771		Command.reply { |reply|
 772			reply.command << FormTemplate.render("sim_details", sims: sims)
 773		}.then { |iq|
 774			case iq.form.field("http://jabber.org/protocol/commands#actions")&.value
 775			when "order-sim"
 776				SIMOrder.for(customer, **CONFIG.dig(:sims, :sim, customer.currency))
 777			when "order-esim"
 778				SIMOrder::ESIM.for(
 779					customer, **CONFIG.dig(:sims, :esim, customer.currency)
 780				)
 781			else
 782				Command.finish
 783			end
 784		}.then { |order|
 785			Command.reply { |reply|
 786				reply.allowed_actions = [:complete]
 787				reply.command << order.form
 788			}.then(&order.method(:complete))
 789		}
 790	end
 791}.register(self).then(&CommandList.method(:register))
 792
 793Command.new(
 794	"subaccount",
 795	"➕️ Create a new phone number linked to this balance",
 796	list_for: lambda do |customer:, **|
 797		!!customer&.currency &&
 798		customer&.billing_customer_id == customer&.customer_id
 799	end
 800) {
 801	cheogram = Command.execution.iq.from.resource =~ /\ACheogram/
 802	Command.customer.then do |customer|
 803		ParentCodeRepo.new.find_or_create(customer.customer_id).then do |code|
 804			Command.finish { |reply|
 805				reply.command << FormTemplate.render(
 806					"subaccount", code: code, cheogram: cheogram
 807				)
 808			}
 809		end
 810	end
 811}.register(self).then(&CommandList.method(:register))
 812
 813Command.new(
 814	"reset sip account",
 815	"☎️ Create or Reset SIP Account",
 816	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 817) {
 818	Command.customer.then do |customer|
 819		sip_account = customer.reset_sip_account
 820		Command.reply { |reply|
 821			reply.allowed_actions = [:next]
 822			form = sip_account.form
 823			form.type = :form
 824			form.fields += [{
 825				type: :boolean, var: "change_fwd",
 826				label: "Should inbound calls forward to this SIP account?"
 827			}]
 828			reply.command << form
 829		}.then do |fwd|
 830			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
 831				Command.execution.customer_repo.put_fwd(
 832					customer,
 833					customer.fwd.with(uri: sip_account.uri)
 834				).then { Command.finish("Inbound calls will now forward to SIP.") }
 835			else
 836				Command.finish
 837			end
 838		end
 839	end
 840}.register(self).then(&CommandList.method(:register))
 841
 842Command.new(
 843	"lnp",
 844	"#️⃣ Port in your number from another carrier",
 845	list_for: ->(**) { true },
 846	customer_repo: CustomerRepo.new(
 847		sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
 848	)
 849) {
 850	Command.customer.then do |customer|
 851		Command.reply { |reply|
 852			reply.allowed_actions = [:next]
 853			reply.command << FormTemplate.render("lnp")
 854		}.then { |iq|
 855			PortInOrder.parse(customer, iq.form).complete_with do |form|
 856				Command.reply { |reply|
 857					reply.allowed_actions = [:next]
 858					reply.command << form
 859				}.then(&:form)
 860			end
 861		}.then do |order|
 862			order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
 863			customer.stanza_from(Blather::Stanza::Message.new(
 864				"",
 865				order.message(order_id)
 866			))
 867			Command.finish(
 868				"Your port-in request has been accepted, " \
 869				"support will contact you with next steps"
 870			)
 871		end
 872	end
 873}.register(self).then(&CommandList.method(:register))
 874
 875Command.new(
 876	"terminate account",
 877	"❌ Cancel your account and terminate your phone number",
 878	list_for: ->(**) { false },
 879	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 880) {
 881	Command.reply { |reply|
 882		reply.allowed_actions = [:next]
 883		reply.note_text = "Press next to confirm your account termination."
 884	}.then { Command.customer }.then { |customer|
 885		AdminAction::CancelCustomer.call(
 886			customer,
 887			customer_repo: Command.execution.customer_repo
 888		)
 889	}.then do
 890		Command.finish("Account cancelled")
 891	end
 892}.register(self).then(&CommandList.method(:register))
 893
 894Command.new(
 895	"customer info",
 896	"Show Customer Info",
 897	list_for: ->(customer: nil, **) { customer&.admin? }
 898) {
 899	Command.customer.then do |customer|
 900		raise AuthError, "You are not an admin" unless customer&.admin?
 901
 902		customer_repo = CustomerRepo.new(
 903			sgx_repo: Bwmsgsv2Repo.new,
 904			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
 905		)
 906
 907		AdminCommand::NoUser.new(customer_repo).start
 908	end
 909}.register(self).then(&CommandList.method(:register))
 910
 911Command.new(
 912	"reachability",
 913	"Test Reachability",
 914	list_for: ->(customer: nil, **) { customer&.admin? }
 915) {
 916	Command.customer.then do |customer|
 917		raise AuthError, "You are not an admin" unless customer&.admin?
 918
 919		form = ReachabilityForm.new(CustomerRepo.new)
 920
 921		Command.reply { |reply|
 922			reply.allowed_actions = [:next]
 923			reply.command << form.render
 924		}.then { |response|
 925			form.parse(response.form)
 926		}.then { |result|
 927			result.repo.get_or_create(result.target).then { |v|
 928				result.target.stanza_from(result.prompt) if result.prompt
 929
 930				Command.finish { |reply|
 931					reply.command << form.render_result(v)
 932				}
 933			}
 934		}.catch_only(RuntimeError) { |e|
 935			Command.finish(e, type: :error)
 936		}
 937	end
 938}.register(self).then(&CommandList.method(:register))
 939
 940Command.new(
 941	"snikket",
 942	"Launch Snikket Instance",
 943	list_for: ->(customer: nil, **) { customer&.admin? }
 944) {
 945	Command.customer.then do |customer|
 946		raise AuthError, "You are not an admin" unless customer&.admin?
 947
 948		Command.reply { |reply|
 949			reply.allowed_actions = [:next]
 950			reply.command << FormTemplate.render("snikket_launch")
 951		}.then { |response|
 952			domain = response.form.field("domain").value.to_s
 953			IQ_MANAGER.write(Snikket::Launch.new(
 954				nil, CONFIG[:snikket_hosting_api],
 955				domain: domain
 956			)).then do |launched|
 957				Snikket::CustomerInstance.for(customer, domain, launched)
 958			end
 959		}.then { |instance|
 960			Command.finish do |reply|
 961				reply.command << FormTemplate.render(
 962					"snikket_launched",
 963					instance: instance
 964				)
 965			end
 966		}
 967	end
 968}.register(self).then(&CommandList.method(:register))
 969
 970Command.new(
 971	"stop snikket",
 972	"STOP Snikket Instance",
 973	list_for: ->(customer: nil, **) { customer&.admin? }
 974) {
 975	Command.customer.then do |customer|
 976		raise AuthError, "You are not an admin" unless customer&.admin?
 977
 978		Command.reply { |reply|
 979			reply.allowed_actions = [:next]
 980			reply.command << FormTemplate.render("snikket_stop")
 981		}.then { |response|
 982			instance_id = response.form.field("instance_id").value.to_s
 983			IQ_MANAGER.write(Snikket::Stop.new(
 984				nil, CONFIG[:snikket_hosting_api],
 985				instance_id: instance_id
 986			))
 987		}.then { |iq|
 988			Command.finish(iq.to_s)
 989		}
 990	end
 991}.register(self).then(&CommandList.method(:register))
 992
 993Command.new(
 994	"delete snikket",
 995	"DELETE Snikket Instance",
 996	list_for: ->(customer: nil, **) { customer&.admin? }
 997) {
 998	Command.customer.then do |customer|
 999		raise AuthError, "You are not an admin" unless customer&.admin?
1000
1001		Command.reply { |reply|
1002			reply.allowed_actions = [:next]
1003			reply.command << FormTemplate.render("snikket_delete")
1004		}.then { |response|
1005			instance_id = response.form.field("instance_id").value.to_s
1006			IQ_MANAGER.write(Snikket::Delete.new(
1007				nil, CONFIG[:snikket_hosting_api],
1008				instance_id: instance_id
1009			))
1010		}.then { |iq|
1011			Command.finish(iq.to_s)
1012		}
1013	end
1014}.register(self).then(&CommandList.method(:register))
1015
1016Command.new(
1017	"find snikket",
1018	"Lookup Snikket Instance",
1019	list_for: ->(customer: nil, **) { customer&.admin? }
1020) {
1021	Command.customer.then do |customer|
1022		raise AuthError, "You are not an admin" unless customer&.admin?
1023
1024		Command.reply { |reply|
1025			reply.allowed_actions = [:next]
1026			reply.command << FormTemplate.render("snikket_launch")
1027		}.then { |response|
1028			domain = response.form.field("domain").value.to_s
1029			IQ_MANAGER.write(Snikket::DomainInfo.new(
1030				nil, CONFIG[:snikket_hosting_api],
1031				domain: domain
1032			))
1033		}.then { |instance|
1034			Command.finish do |reply|
1035				reply.command << FormTemplate.render(
1036					"snikket_result",
1037					instance: instance
1038				)
1039			end
1040		}
1041	end
1042}.register(self).then(&CommandList.method(:register))
1043
1044def reply_with_note(iq, text, type: :info)
1045	reply = iq.reply
1046	reply.status = :completed
1047	reply.note_type = type
1048	reply.note_text = text
1049
1050	self << reply
1051end
1052
1053Command.new(
1054	"https://ns.cheogram.com/sgx/jid-switch",
1055	"Change JID",
1056	list_for: lambda { |customer: nil, from_jid: nil, **|
1057		customer || from_jid.to_s =~ Regexp.new(CONFIG[:onboarding_domain])
1058	},
1059	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
1060) {
1061	Command.customer.then { |customer|
1062		Command.reply { |reply|
1063			reply.command << FormTemplate.render("jid_switch")
1064		}.then { |response|
1065			new_jid = response.form.field("jid").value
1066			repo = Command.execution.customer_repo
1067			repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
1068				.then { |cust|
1069					next EMPromise.reject("Customer Already Exists") if cust
1070
1071					repo.change_jid(customer, new_jid)
1072				}
1073		}.then {
1074			StatsD.increment("changejid.completed")
1075			jid = ProxiedJID.new(customer.jid).unproxied
1076			if jid.domain == CONFIG[:onboarding_domain]
1077				CustomerRepo.new.find(customer.customer_id).then do |cust|
1078					WelcomeMessage.new(cust, customer.registered?.phone).welcome
1079				end
1080			end
1081			Command.finish { |reply|
1082				reply.note_type = :info
1083				reply.note_text = "Customer JID Changed"
1084			}
1085		}
1086	}
1087}.register(self).then(&CommandList.method(:register))
1088
1089Command.new(
1090	"web-register",
1091	"Initiate Register from Web",
1092	list_for: lambda { |from_jid: nil, **|
1093		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
1094	}
1095) {
1096	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
1097		next EMPromise.reject(
1098			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
1099		)
1100	end
1101
1102	Command.reply { |reply|
1103		reply.command << FormTemplate.render("web_register")
1104	}.then do |iq|
1105		jid = iq.form.field("jid")&.value.to_s.strip
1106		tel = iq.form.field("tel")&.value.to_s.strip
1107		if jid !~ /\./ || jid =~ /\s/
1108			Command.finish("The Jabber ID you entered was not valid.", type: :error)
1109		elsif tel !~ /\A\+\d+\Z/
1110			Command.finish("Invalid telephone number", type: :error)
1111		else
1112			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
1113				cmd.to = CONFIG[:web_register][:to]
1114				cmd.node = "push-register"
1115				cmd.form.fields = [{ var: "to", value: jid }]
1116				cmd.form.type = "submit"
1117			}).then { |result|
1118				TEL_SELECTIONS.set_tel(result.form.field("from")&.value.to_s.strip, tel)
1119			}.then { Command.finish }
1120		end
1121	end
1122}.register(self).then(&CommandList.method(:register))
1123
1124command sessionid: /./ do |iq|
1125	COMMAND_MANAGER.fulfill(iq)
1126	IQ_MANAGER.fulfill(iq)
1127	true
1128end
1129
1130iq type: [:result, :error] do |iq|
1131	IQ_MANAGER.fulfill(iq)
1132	true
1133end
1134
1135iq type: [:get, :set] do |iq|
1136	StatsD.increment("unknown_iq")
1137
1138	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
1139end
1140
1141trap(:INT) { EM.stop }
1142trap(:TERM) { EM.stop }
1143EM.run { client.run }