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