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