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