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