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