sgx_jmp.rb

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