sgx_jmp.rb

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