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