sgx_jmp.rb

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