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
 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")
 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	Command.customer.catch_only(CustomerRepo::NotFound) {
 475		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
 476		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
 477	}.then { |customer|
 478		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
 479		Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
 480	}.then {
 481		StatsD.increment("registration.completed")
 482	}.catch_only(Command::Execution::FinalStanza) do |e|
 483		StatsD.increment("registration.completed")
 484		EMPromise.reject(e)
 485	end
 486}.register(self).then(&CommandList.method(:register))
 487
 488Command.new(
 489	"info",
 490	"👤 Show Account Info",
 491	list_for: ->(*) { true },
 492	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 493) {
 494	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
 495		Command.finish do |reply|
 496			reply.command << info.form
 497		end
 498	end
 499}.register(self).then(&CommandList.method(:register))
 500
 501Command.new(
 502	"cdrs",
 503	"📲 Show Call Logs"
 504) {
 505	report_for = ((Date.today << 1)..Date.today)
 506
 507	Command.customer.then { |customer|
 508		CDRRepo.new.find_range(customer, report_for)
 509	}.then do |cdrs|
 510		Command.finish do |reply|
 511			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
 512		end
 513	end
 514}.register(self).then(&CommandList.method(:register))
 515
 516Command.new(
 517	"transactions",
 518	"🧾 Show Transactions",
 519	list_for: ->(customer:, **) { !!customer&.currency }
 520) {
 521	Command.customer.then(&:transactions).then do |txs|
 522		Command.finish do |reply|
 523			reply.command << FormTemplate.render("transactions", transactions: txs)
 524		end
 525	end
 526}.register(self).then(&CommandList.method(:register))
 527
 528Command.new(
 529	"configure calls",
 530	"📞 Configure Calls",
 531	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 532) {
 533	Command.customer.then do |customer|
 534		cc_form = ConfigureCallsForm.new(customer)
 535		Command.reply { |reply|
 536			reply.allowed_actions = [:next]
 537			reply.command << cc_form.render
 538		}.then { |iq|
 539			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
 540				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
 541			})
 542		}.then { Command.finish("Configuration saved!") }
 543	end
 544}.register(self).then(&CommandList.method(:register))
 545
 546Command.new(
 547	"ogm",
 548	"⏺️ Record Voicemail Greeting",
 549	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
 550	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 551) {
 552	Command.customer.then do |customer|
 553		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
 554			cc.from = customer.registered?.phone
 555			cc.application_id = CONFIG[:sip][:app]
 556			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
 557			                "customer_id=#{customer.customer_id}"
 558		end
 559		Command.finish("You will now receive a call.")
 560	end
 561}.register(self).then(&CommandList.method(:register))
 562
 563Command.new(
 564	"migrate billing",
 565	"🏦 Switch to new billing",
 566	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
 567	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 568) {
 569	EMPromise.all([
 570		Command.customer,
 571		Command.reply do |reply|
 572			reply.allowed_actions = [:next]
 573			reply.command << FormTemplate.render("migrate_billing")
 574		end
 575	]).then do |(customer, iq)|
 576		plan_name = iq.form.field("plan_name").value.to_s
 577		customer = customer.with_plan(plan_name)
 578		customer.save_plan!.then {
 579			Registration::Payment.for(
 580				iq, customer, customer.registered?.phone,
 581				final_message: PaypalDone::MESSAGE,
 582				finish: PaypalDone
 583			)
 584		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 585			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 586			BLATHER.say(
 587				CONFIG[:notify_admin],
 588				"#{customer.customer_id} migrated to #{customer.currency}",
 589				:groupchat
 590			)
 591			EMPromise.reject(s)
 592		end
 593	end
 594}.register(self).then(&CommandList.method(:register))
 595
 596Command.new(
 597	"credit cards",
 598	"💳 Credit Card Settings and Management"
 599) {
 600	Command.customer.then do |customer|
 601		url = CONFIG[:credit_card_url].call(
 602			customer.jid.to_s.gsub("\\", "%5C"),
 603			customer.customer_id
 604		)
 605		desc = "Manage credits cards and settings"
 606		Command.finish("#{desc}: #{url}") do |reply|
 607			oob = OOB.find_or_create(reply.command)
 608			oob.url = url
 609			oob.desc = desc
 610		end
 611	end
 612}.register(self).then(&CommandList.method(:register))
 613
 614Command.new(
 615	"top up",
 616	"💲 Buy Account Credit by Credit Card",
 617	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 618	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 619) {
 620	Command.customer.then { |customer|
 621		BuyAccountCreditForm.for(customer).then do |credit_form|
 622			Command.reply { |reply|
 623				reply.allowed_actions = [:complete]
 624				reply.command << credit_form.form
 625			}.then do |iq|
 626				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 627			end
 628		end
 629	}.then { |transaction|
 630		Command.finish("#{transaction} added to your account balance.")
 631	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
 632		Command.finish(e.message, type: :error)
 633	end
 634}.register(self).then(&CommandList.method(:register))
 635
 636Command.new(
 637	"alt top up",
 638	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 639	list_for: ->(customer:, **) { !!customer&.currency }
 640) {
 641	Command.customer.then { |customer|
 642		AltTopUpForm.for(customer)
 643	}.then do |alt_form|
 644		Command.reply { |reply|
 645			reply.allowed_actions = [:complete]
 646			reply.command << alt_form.form
 647		}.then do |iq|
 648			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 649		end
 650	end
 651}.register(self).then(&CommandList.method(:register))
 652
 653Command.new(
 654	"plan settings",
 655	"📝 Manage your plan, including overage limits",
 656	list_for: ->(customer:, **) { !!customer&.currency }
 657) {
 658	Command.customer.then { |customer|
 659		EMPromise.all([
 660			REDIS.get("jmp_customer_monthly_data_limit-#{customer.customer_id}"),
 661			SIMRepo.new.owned_by(customer)
 662		]).then { |(limit, sims)| [customer, sims, limit] }
 663	}.then do |(customer, sims, limit)|
 664		Command.reply { |reply|
 665			reply.allowed_actions = [:next]
 666			reply.command << FormTemplate.render(
 667				"plan_settings", customer: customer, sims: sims, data_limit: limit
 668			)
 669		}.then { |iq|
 670			kwargs = {
 671				monthly_overage_limit: iq.form.field("monthly_overage_limit")&.value,
 672				monthly_data_limit: iq.form.field("monthly_data_limit")&.value
 673			}.compact
 674			Command.execution.customer_repo.put_monthly_limits(customer, **kwargs)
 675		}.then { Command.finish("Configuration saved!") }
 676	end
 677}.register(self).then(&CommandList.method(:register))
 678
 679Command.new(
 680	"referral codes",
 681	"👥 Refer a friend for free credit"
 682) {
 683	repo = InvitesRepo.new
 684	Command.customer.then { |customer|
 685		EMPromise.all([
 686			repo.find_or_create_group_code(customer.customer_id),
 687			repo.unused_invites(customer.customer_id)
 688		])
 689	}.then do |(group_code, invites)|
 690		if invites.empty?
 691			Command.finish(
 692				"This code will provide credit equivalent to one month of service " \
 693				"to anyone after they sign up and pay: #{group_code}\n\n" \
 694				"You will receive credit equivalent to one month of service once " \
 695				"their payment clears."
 696			)
 697		else
 698			Command.finish do |reply|
 699				reply.command << FormTemplate.render(
 700					"codes",
 701					invites: invites,
 702					group_code: group_code
 703				)
 704			end
 705		end
 706	end
 707}.register(self).then(&CommandList.method(:register))
 708
 709# Assumes notify_from is a direct target
 710notify_to = CONFIG[:direct_targets].fetch(
 711	Blather::JID.new(CONFIG[:notify_from]).node.to_sym
 712)
 713
 714Command.new(
 715	"sims",
 716	"📶 (e)SIM Details",
 717	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency },
 718	customer_repo: CustomerRepo.new(
 719		sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
 720	)
 721) {
 722	Command.customer.then { |customer|
 723		EMPromise.all([customer, SIMRepo.new.owned_by(customer)])
 724	}.then do |(customer, sims)|
 725		Command.reply { |reply|
 726			buy = customer.feature_flags.include?(:buy_sim)
 727			reply.status = "completed" unless buy
 728			reply.command << FormTemplate.render("sim_details", sims: sims, buy: buy)
 729		}.then { |iq|
 730			case iq.form.field("http://jabber.org/protocol/commands#actions")&.value
 731			when "order-sim"
 732				SIMOrder.for(customer, **CONFIG.dig(:sims, :sim, customer.currency))
 733			when "order-esim"
 734				SIMOrder::ESIM.for(
 735					customer, **CONFIG.dig(:sims, :esim, customer.currency)
 736				)
 737			else
 738				Command.finish
 739			end
 740		}.then { |order|
 741			Command.reply { |reply|
 742				reply.allowed_actions = [:complete]
 743				reply.command << order.form
 744			}.then(&order.method(:complete))
 745		}
 746	end
 747}.register(self).then(&CommandList.method(:register))
 748
 749Command.new(
 750	"subaccount",
 751	"➕️ Create a new phone number linked to this balance",
 752	list_for: lambda do |customer:, **|
 753		!!customer&.currency &&
 754		customer&.billing_customer_id == customer&.customer_id
 755	end
 756) {
 757	cheogram = Command.execution.iq.from.resource =~ /\ACheogram/
 758	Command.customer.then do |customer|
 759		ParentCodeRepo.new.find_or_create(customer.customer_id).then do |code|
 760			Command.finish { |reply|
 761				reply.command << FormTemplate.render(
 762					"subaccount", code: code, cheogram: cheogram
 763				)
 764			}
 765		end
 766	end
 767}.register(self).then(&CommandList.method(:register))
 768
 769Command.new(
 770	"reset sip account",
 771	"☎️ Create or Reset SIP Account",
 772	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 773) {
 774	Command.customer.then do |customer|
 775		sip_account = customer.reset_sip_account
 776		Command.reply { |reply|
 777			reply.allowed_actions = [:next]
 778			form = sip_account.form
 779			form.type = :form
 780			form.fields += [{
 781				type: :boolean, var: "change_fwd",
 782				label: "Should inbound calls forward to this SIP account?"
 783			}]
 784			reply.command << form
 785		}.then do |fwd|
 786			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
 787				Command.execution.customer_repo.put_fwd(
 788					customer,
 789					customer.fwd.with(uri: sip_account.uri)
 790				).then { Command.finish("Inbound calls will now forward to SIP.") }
 791			else
 792				Command.finish
 793			end
 794		end
 795	end
 796}.register(self).then(&CommandList.method(:register))
 797
 798Command.new(
 799	"lnp",
 800	"#️⃣ Port in your number from another carrier",
 801	list_for: ->(**) { true }
 802) {
 803	EMPromise.all([
 804		Command.customer,
 805		Command.reply do |reply|
 806			reply.allowed_actions = [:next]
 807			reply.command << FormTemplate.render("lnp")
 808		end
 809	]).then { |(customer, iq)|
 810		PortInOrder.parse(customer, iq.form).complete_with do |form|
 811			Command.reply { |reply|
 812				reply.allowed_actions = [:next]
 813				reply.command << form
 814			}.then(&:form)
 815		end
 816	}.then do |order|
 817		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
 818		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 819		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
 820		Command.finish(
 821			"Your port-in request has been accepted, " \
 822			"support will contact you with next steps"
 823		)
 824	end
 825}.register(self).then(&CommandList.method(:register))
 826
 827Command.new(
 828	"terminate account",
 829	"❌ Cancel your account and terminate your phone number",
 830	list_for: ->(**) { false },
 831	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 832) {
 833	Command.reply { |reply|
 834		reply.allowed_actions = [:next]
 835		reply.note_text = "Press next to confirm your account termination."
 836	}.then { Command.customer }.then { |customer|
 837		AdminAction::CancelCustomer.call(
 838			customer,
 839			customer_repo: Command.execution.customer_repo
 840		)
 841	}.then do
 842		Command.finish("Account cancelled")
 843	end
 844}.register(self).then(&CommandList.method(:register))
 845
 846Command.new(
 847	"customer info",
 848	"Show Customer Info",
 849	list_for: ->(customer: nil, **) { customer&.admin? }
 850) {
 851	Command.customer.then do |customer|
 852		raise AuthError, "You are not an admin" unless customer&.admin?
 853
 854		customer_repo = CustomerRepo.new(
 855			sgx_repo: Bwmsgsv2Repo.new,
 856			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
 857		)
 858
 859		AdminCommand::NoUser.new(customer_repo).start
 860	end
 861}.register(self).then(&CommandList.method(:register))
 862
 863Command.new(
 864	"reachability",
 865	"Test Reachability",
 866	list_for: ->(customer: nil, **) { customer&.admin? }
 867) {
 868	Command.customer.then do |customer|
 869		raise AuthError, "You are not an admin" unless customer&.admin?
 870
 871		form = ReachabilityForm.new(CustomerRepo.new)
 872
 873		Command.reply { |reply|
 874			reply.allowed_actions = [:next]
 875			reply.command << form.render
 876		}.then { |response|
 877			form.parse(response.form)
 878		}.then { |result|
 879			result.repo.get_or_create(result.target).then { |v|
 880				result.target.stanza_from(result.prompt) if result.prompt
 881
 882				Command.finish { |reply|
 883					reply.command << form.render_result(v)
 884				}
 885			}
 886		}.catch_only(RuntimeError) { |e|
 887			Command.finish(e, type: :error)
 888		}
 889	end
 890}.register(self).then(&CommandList.method(:register))
 891
 892Command.new(
 893	"snikket",
 894	"Launch Snikket Instance",
 895	list_for: ->(customer: nil, **) { customer&.admin? }
 896) {
 897	Command.customer.then do |customer|
 898		raise AuthError, "You are not an admin" unless customer&.admin?
 899
 900		Command.reply { |reply|
 901			reply.allowed_actions = [:next]
 902			reply.command << FormTemplate.render("snikket_launch")
 903		}.then { |response|
 904			domain = response.form.field("domain").value.to_s
 905			IQ_MANAGER.write(Snikket::Launch.new(
 906				nil, CONFIG[:snikket_hosting_api],
 907				domain: domain
 908			)).then do |launched|
 909				Snikket::CustomerInstance.for(customer, domain, launched)
 910			end
 911		}.then { |instance|
 912			Command.finish do |reply|
 913				reply.command << FormTemplate.render(
 914					"snikket_launched",
 915					instance: instance
 916				)
 917			end
 918		}
 919	end
 920}.register(self).then(&CommandList.method(:register))
 921
 922Command.new(
 923	"find snikket",
 924	"Lookup Snikket Instance",
 925	list_for: ->(customer: nil, **) { customer&.admin? }
 926) {
 927	Command.customer.then do |customer|
 928		raise AuthError, "You are not an admin" unless customer&.admin?
 929
 930		Command.reply { |reply|
 931			reply.allowed_actions = [:next]
 932			reply.command << FormTemplate.render("snikket_launch")
 933		}.then { |response|
 934			domain = response.form.field("domain").value.to_s
 935			IQ_MANAGER.write(Snikket::DomainInfo.new(
 936				nil, CONFIG[:snikket_hosting_api],
 937				domain: domain
 938			))
 939		}.then { |instance|
 940			Command.finish do |reply|
 941				reply.command << FormTemplate.render(
 942					"snikket_result",
 943					instance: instance
 944				)
 945			end
 946		}
 947	end
 948}.register(self).then(&CommandList.method(:register))
 949
 950def reply_with_note(iq, text, type: :info)
 951	reply = iq.reply
 952	reply.status = :completed
 953	reply.note_type = type
 954	reply.note_text = text
 955
 956	self << reply
 957end
 958
 959Command.new(
 960	"https://ns.cheogram.com/sgx/jid-switch",
 961	"Change JID",
 962	list_for: ->(customer: nil, **) { customer },
 963	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 964) {
 965	Command.customer.then { |customer|
 966		Command.reply { |reply|
 967			reply.command << FormTemplate.render("jid_switch")
 968		}.then { |response|
 969			new_jid = response.form.field("jid").value
 970			repo = Command.execution.customer_repo
 971			repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
 972				.then { |cust|
 973					next EMPromise.reject("Customer Already Exists") if cust
 974
 975					repo.change_jid(customer, new_jid)
 976				}
 977		}.then {
 978			StatsD.increment("changejid.completed")
 979			jid = ProxiedJID.new(customer.jid).unproxied
 980			if jid.domain == CONFIG[:onboarding_domain]
 981				CustomerRepo.new.find(customer.customer_id).then do |cust|
 982					WelcomeMessage.new(cust, customer.registered?.phone).welcome
 983				end
 984			end
 985			Command.finish { |reply|
 986				reply.note_type = :info
 987				reply.note_text = "Customer JID Changed"
 988			}
 989		}
 990	}
 991}.register(self).then(&CommandList.method(:register))
 992
 993Command.new(
 994	"web-register",
 995	"Initiate Register from Web",
 996	list_for: lambda { |from_jid: nil, **|
 997		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
 998	}
 999) {
1000	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
1001		next EMPromise.reject(
1002			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
1003		)
1004	end
1005
1006	Command.reply { |reply|
1007		reply.command << FormTemplate.render("web_register")
1008	}.then do |iq|
1009		jid = iq.form.field("jid")&.value.to_s.strip
1010		tel = iq.form.field("tel")&.value.to_s.strip
1011		if jid !~ /\./ || jid =~ /\s/
1012			Command.finish("The Jabber ID you entered was not valid.", type: :error)
1013		elsif tel !~ /\A\+\d+\Z/
1014			Command.finish("Invalid telephone number", type: :error)
1015		else
1016			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
1017				cmd.to = CONFIG[:web_register][:to]
1018				cmd.node = "push-register"
1019				cmd.form.fields = [{ var: "to", value: jid }]
1020				cmd.form.type = "submit"
1021			}).then { |result|
1022				TEL_SELECTIONS.set_tel(result.form.field("from")&.value.to_s.strip, tel)
1023			}.then { Command.finish }
1024		end
1025	end
1026}.register(self).then(&CommandList.method(:register))
1027
1028command sessionid: /./ do |iq|
1029	COMMAND_MANAGER.fulfill(iq)
1030	IQ_MANAGER.fulfill(iq)
1031	true
1032end
1033
1034iq type: [:result, :error] do |iq|
1035	IQ_MANAGER.fulfill(iq)
1036	true
1037end
1038
1039iq type: [:get, :set] do |iq|
1040	StatsD.increment("unknown_iq")
1041
1042	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
1043end
1044
1045trap(:INT) { EM.stop }
1046trap(:TERM) { EM.stop }
1047EM.run { client.run }