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