sgx_jmp.rb

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