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