sgx_jmp.rb

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