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