sgx_jmp.rb

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