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))
 147
 148require_relative "lib/blather_client"
 149@client = BlatherClient.new
 150
 151setup(
 152	CONFIG[:component][:jid],
 153	CONFIG[:component][:secret],
 154	CONFIG[:server][:host],
 155	CONFIG[:server][:port],
 156	nil,
 157	nil,
 158	async: true
 159)
 160
 161# Infer anything we might have been notified about while we were down
 162def catchup_notify_low_balance(db)
 163	db.query(<<~SQL).each do |c|
 164		SELECT customer_id
 165		FROM balances INNER JOIN customer_plans USING (customer_id)
 166		WHERE balance < 5 AND expires_at > LOCALTIMESTAMP
 167	SQL
 168		db.query("SELECT pg_notify('low_balance', $1)", c.values)
 169	end
 170end
 171
 172def catchup_notify_possible_renewal(db)
 173	db.query(<<~SQL).each do |c|
 174		SELECT customer_id
 175		FROM customer_plans INNER JOIN balances USING (customer_id)
 176		WHERE
 177			expires_at < LOCALTIMESTAMP
 178			AND expires_at >= LOCALTIMESTAMP - INTERVAL '3 months'
 179			AND balance >= 5
 180	SQL
 181		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
 182	end
 183end
 184
 185def setup_sentry_scope(name)
 186	Sentry.clone_hub_to_current_thread
 187	Sentry.with_scope do |scope|
 188		scope.clear_breadcrumbs
 189		scope.set_transaction_name(name)
 190		Thread.current[:log] = ::LOG.child(transaction: scope.transaction_name)
 191		yield scope
 192	end
 193end
 194
 195def poll_for_notify(db, repo)
 196	db.wait_for_notify_defer.then { |notify|
 197		setup_sentry_scope("DB NOTIFY") do
 198			repo.find(notify[:extra]).then { |customer|
 199				DbNotification.for(notify, customer, repo)
 200			}.then(&:call).catch { |e|
 201				log.error("Error during poll_for_notify", e)
 202				Sentry.capture_exception(e)
 203			}.sync
 204		end
 205	}.then { EM.add_timer(0.5) { poll_for_notify(db, repo) } }
 206end
 207
 208def load_plans_to_db!
 209	DB.transaction do
 210		DB.exec("TRUNCATE plans")
 211		CONFIG[:plans].each do |plan|
 212			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
 213		end
 214	end
 215end
 216
 217when_ready do
 218	log.info "Ready"
 219	BLATHER = self
 220	REDIS = EM::Hiredis.connect
 221	MEMCACHE = EM::P::Memcache.connect
 222	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
 223	DB = Postgres.connect(dbname: "jmp", size: 5)
 224	TEL_SELECTIONS = TelSelections.new
 225
 226	EMPromise.resolve(nil).then {
 227		conn = DB.acquire
 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	}.catch(&method(:panic))
 236
 237	load_plans_to_db!
 238
 239	EM.add_periodic_timer(3600) do
 240		DB.finish # Clear idle connections
 241		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
 242		ping.from = CONFIG[:component][:jid]
 243		self << ping
 244	end
 245
 246	Web.run(LOG.child, *WEB_LISTEN)
 247end
 248
 249message to: /\Aaccount@/, body: /./ do |m|
 250	StatsD.increment("deprecated_account_bot")
 251
 252	self << m.reply.tap { |out|
 253		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
 254	}
 255end
 256
 257FROM_BACKEND =
 258	"(?:#{([CONFIG[:sgx]] + CONFIG[:sgx_creds].keys)
 259		.map(&Regexp.method(:escape)).join('|')})"
 260
 261before(
 262	:iq,
 263	type: [:error, :result],
 264	to: /\Acustomer_/,
 265	from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
 266) { |iq| halt if IQ_MANAGER.fulfill(iq) }
 267
 268SPAM_ERRS = [
 269	"rejected-spam-detected",
 270	"destination-spam-detected",
 271	"destination-rejected-due-to-spam-detection"
 272].freeze
 273
 274before nil, to: /\Acustomer_/, from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/ do |s|
 275	StatsD.increment("stanza_customer")
 276
 277	Sentry.get_current_scope.set_transaction_name("stanza_customer")
 278	CustomerRepo.new(set_user: Sentry.method(:set_user)).find(
 279		s.to.node.delete_prefix("customer_")
 280	).then do |customer|
 281		if s.is_a?(Blather::Stanza::Message) && s.error?
 282			err = Blather::StanzaError.import(s).text
 283			if SPAM_ERRS.include?(err)
 284				REDIS.setex(
 285					"jmp_customer_spam_detected-#{customer.customer_id}",
 286					5 * 60,
 287					err
 288				)
 289			end
 290		end
 291
 292		ReachabilityRepo::SMS.new
 293			.find(customer, s.from.node, stanza: s).then do |reach|
 294				reach.filter do
 295					customer.stanza_to(s)
 296				end
 297			end
 298	end
 299
 300	halt
 301end
 302
 303ADDRESSES_NS = "http://jabber.org/protocol/address"
 304message(
 305	to: /\A#{CONFIG[:component][:jid]}\Z/,
 306	from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
 307) do |m|
 308	StatsD.increment("inbound_group_text")
 309	Sentry.get_current_scope.set_transaction_name("inbound_group_text")
 310	log.info "Possible group text #{m.from}"
 311
 312	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
 313		&.find("ns:address", ns: ADDRESSES_NS)
 314		&.find { |el| el["jid"].to_s.start_with?("customer_") }
 315	pass unless address
 316
 317	CustomerRepo
 318		.new(set_user: Sentry.method(:set_user))
 319		.find_by_jid(address["jid"]).then { |customer|
 320			m.from = m.from.with(domain: CONFIG[:component][:jid])
 321			m.to = m.to.with(domain: customer.jid.domain)
 322			address["jid"] = customer.jid.to_s
 323			BLATHER << m
 324		}.catch_only(CustomerRepo::NotFound) { |e|
 325			BLATHER << m.as_error("forbidden", :auth, e.message)
 326		}
 327end
 328
 329# Ignore groupchat messages
 330# Especially if we have the component join MUC for notifications
 331message(type: :groupchat) { true }
 332
 333def billable_message(m)
 334	b = m.body
 335	b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first
 336end
 337
 338class OverLimit < StandardError
 339	def initialize(customer, usage)
 340		super("Please contact support")
 341		@customer = customer
 342		@usage = usage
 343	end
 344
 345	def notify_admin
 346		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
 347			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 348			BLATHER.say(
 349				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
 350				"#{@usage} messages today", :groupchat
 351			)
 352		end
 353	end
 354end
 355
 356class CustomerExpired < StandardError; end
 357
 358CONFIG[:direct_targets].each do |(tel, jid)|
 359	customer_repo = CustomerRepo.new(
 360		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
 361		set_user: Sentry.method(:set_user)
 362	)
 363
 364	message to: /\A#{Regexp.escape(tel)}@#{CONFIG[:component][:jid]}\/?/ do |m|
 365		customer_repo.find_by_jid(m.from.stripped).then { |customer|
 366			customer.stanza_from(m)
 367		}.catch_only(CustomerRepo::NotFound) {
 368			# This should not happen, but let's still get the message
 369			# to support at least if it does
 370			m.from = ProxiedJID.proxy(m.from, CONFIG[:component][:jid])
 371			m.to = jid
 372			BLATHER << m
 373		}
 374	end
 375end
 376
 377CONFIG[:direct_sources].each do |(jid, tel)|
 378	customer_repo = CustomerRepo.new(
 379		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
 380		set_user: Sentry.method(:set_user)
 381	)
 382	message to: /\Acustomer_/, from: /\A#{Regexp.escape(jid)}\/?/ do |m|
 383		customer_repo.find(m.to.node.delete_prefix("customer_")).then { |customer|
 384			m.from = "#{tel}@sgx-jmp" # stanza_to will fix domain
 385			customer.stanza_to(m)
 386		}.catch_only(CustomerRepo::NotFound) { |e|
 387			BLATHER << m.as_error("item-not-found", :cancel, e.message)
 388		}
 389	end
 390end
 391
 392message do |m|
 393	StatsD.increment("message")
 394
 395	today = Time.now.utc.to_date
 396	CustomerRepo.new(set_user: Sentry.method(:set_user))
 397		.find_by_jid(m.from.stripped).then { |customer|
 398			next customer.stanza_from(m) unless billable_message(m)
 399
 400			if customer.plan_name && !customer.active?
 401				raise CustomerExpired, "Your account is expired, please top up"
 402			end
 403
 404			EMPromise.all([
 405				REDIS.exists("jmp_customer_spam_detected-#{customer.customer_id}"),
 406				TrustLevelRepo.new.find(customer),
 407				customer.message_usage((today..today))
 408			]).then { |(spam, tl, usage)|
 409				raise OverLimit.new(customer, "SPAM DETECTED") if spam.to_i == 1
 410				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
 411			}.then do
 412				EMPromise.all([customer.incr_message_usage, customer.stanza_from(m)])
 413			end
 414		}.catch_only(OverLimit) { |e|
 415			e.notify_admin
 416			BLATHER << m.as_error("policy-violation", :wait, e.message)
 417		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
 418			BLATHER << m.as_error("forbidden", :auth, e.message)
 419		}
 420end
 421
 422disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
 423	reply = iq.reply
 424	reply.identities = [{
 425		name: "JMP.chat",
 426		type: "sms",
 427		category: "gateway"
 428	}]
 429	reply.features = [
 430		"http://jabber.org/protocol/disco#info",
 431		"http://jabber.org/protocol/commands"
 432	]
 433	form = Blather::Stanza::X.find_or_create(reply.query)
 434	form.type = "result"
 435	form.fields = [
 436		{
 437			var: "FORM_TYPE",
 438			type: "hidden",
 439			value: "http://jabber.org/network/serverinfo"
 440		}
 441	] + CONFIG[:xep0157]
 442	self << reply
 443end
 444
 445disco_info do |iq|
 446	reply = iq.reply
 447	reply.identities = [{
 448		name: "JMP.chat",
 449		type: "sms",
 450		category: "client"
 451	}]
 452	reply.features = [
 453		"urn:xmpp:receipts"
 454	]
 455	self << reply
 456end
 457
 458disco_items(
 459	to: Blather::JID.new(CONFIG[:component][:jid]),
 460	node: "http://jabber.org/protocol/commands"
 461) do |iq|
 462	StatsD.increment("command_list")
 463
 464	reply = iq.reply
 465	reply.node = "http://jabber.org/protocol/commands"
 466
 467	CustomerRepo.new(
 468		sgx_repo: Bwmsgsv2Repo.new,
 469		set_user: Sentry.method(:set_user)
 470	).find_by_jid(
 471		iq.from.stripped
 472	).catch {
 473		nil
 474	}.then { |customer|
 475		CommandList.for(customer, iq.from)
 476	}.then { |list|
 477		reply.items = list.map { |item|
 478			Blather::Stanza::DiscoItems::Item.new(
 479				iq.to,
 480				item[:node],
 481				item[:name]
 482			)
 483		}
 484		self << reply
 485	}
 486end
 487
 488iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
 489	StatsD.increment("extdisco")
 490
 491	reply = iq.reply
 492	reply << Nokogiri::XML::Builder.new {
 493		services(xmlns: "urn:xmpp:extdisco:2") do
 494			service(
 495				type: "sip",
 496				host: CONFIG[:sip_host]
 497			)
 498		end
 499	}.doc.root
 500
 501	self << reply
 502end
 503
 504Command.new(
 505	"jabber:iq:register",
 506	"Register",
 507	list_for: ->(*) { true },
 508	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 509) {
 510	google_play_userid = if Command.execution.iq.from.domain == "cheogram.com"
 511		Command.execution.iq.command.find(
 512			"./ns:userId", ns: "https://ns.cheogram.com/google-play"
 513		)&.first&.content
 514	end
 515	Command.customer.catch_only(CustomerRepo::NotFound) {
 516		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
 517		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
 518	}.then { |customer|
 519		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
 520		Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
 521	}.then {
 522		StatsD.increment("registration.completed")
 523	}.catch_only(Command::Execution::FinalStanza) do |e|
 524		StatsD.increment("registration.completed")
 525		EMPromise.reject(e)
 526	end
 527}.register(self).then(&CommandList.method(:register))
 528
 529Command.new(
 530	"info",
 531	"👤 Show Account Info",
 532	list_for: ->(*) { true },
 533	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 534) {
 535	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
 536		Command.finish do |reply|
 537			reply.command << info.form
 538		end
 539	end
 540}.register(self).then(&CommandList.method(:register))
 541
 542Command.new(
 543	"cdrs",
 544	"📲 Show Call Logs"
 545) {
 546	report_for = ((Date.today << 1)..Date.today)
 547
 548	Command.customer.then { |customer|
 549		CDRRepo.new.find_range(customer, report_for)
 550	}.then do |cdrs|
 551		Command.finish do |reply|
 552			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
 553		end
 554	end
 555}.register(self).then(&CommandList.method(:register))
 556
 557Command.new(
 558	"transactions",
 559	"🧾 Show Transactions",
 560	list_for: ->(customer:, **) { !!customer&.currency }
 561) {
 562	Command.customer.then(&:transactions).then do |txs|
 563		Command.finish do |reply|
 564			reply.command << FormTemplate.render("transactions", transactions: txs)
 565		end
 566	end
 567}.register(self).then(&CommandList.method(:register))
 568
 569Command.new(
 570	"configure calls",
 571	"📞 Configure Calls",
 572	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 573) {
 574	Command.customer.then do |customer|
 575		cc_form = ConfigureCallsForm.new(customer)
 576		Command.reply { |reply|
 577			reply.allowed_actions = [:next]
 578			reply.command << cc_form.render
 579		}.then { |iq|
 580			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
 581				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
 582			})
 583		}.then { Command.finish("Configuration saved!") }
 584	end
 585}.register(self).then(&CommandList.method(:register))
 586
 587Command.new(
 588	"ogm",
 589	"⏺️ Record Voicemail Greeting",
 590	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
 591	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 592) {
 593	Command.customer.then do |customer|
 594		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
 595			cc.from = customer.registered?.phone
 596			cc.application_id = CONFIG[:sip][:app]
 597			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
 598			                "customer_id=#{customer.customer_id}"
 599		end
 600		Command.finish("You will now receive a call.")
 601	end
 602}.register(self).then(&CommandList.method(:register))
 603
 604Command.new(
 605	"migrate billing",
 606	"🏦 Switch to new billing",
 607	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
 608	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 609) {
 610	EMPromise.all([
 611		Command.customer,
 612		Command.reply do |reply|
 613			reply.allowed_actions = [:next]
 614			reply.command << FormTemplate.render("migrate_billing")
 615		end
 616	]).then do |(customer, iq)|
 617		plan_name = iq.form.field("plan_name").value.to_s
 618		customer = customer.with_plan(plan_name)
 619		customer.save_plan!.then {
 620			Registration::Payment.for(
 621				iq, customer, customer.registered?.phone,
 622				final_message: PaypalDone::MESSAGE,
 623				finish: PaypalDone
 624			)
 625		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 626			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 627			BLATHER.say(
 628				CONFIG[:notify_admin],
 629				"#{customer.customer_id} migrated to #{customer.currency}",
 630				:groupchat
 631			)
 632			EMPromise.reject(s)
 633		end
 634	end
 635}.register(self).then(&CommandList.method(:register))
 636
 637Command.new(
 638	"credit cards",
 639	"💳 Credit Card Settings and Management",
 640	list_for: ->(customer:, **) { !!customer&.currency }
 641) {
 642	Command.customer.then do |customer|
 643		url = CONFIG[:credit_card_url].call(
 644			customer.jid.to_s.gsub("\\", "%5C"),
 645			customer.customer_id
 646		)
 647		desc = "Manage credits cards and settings"
 648		Command.finish("#{desc}: #{url}") do |reply|
 649			oob = OOB.find_or_create(reply.command)
 650			oob.url = url
 651			oob.desc = desc
 652		end
 653	end
 654}.register(self).then(&CommandList.method(:register))
 655
 656Command.new(
 657	"top up",
 658	"💲 Buy Account Credit by Credit Card",
 659	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 660	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 661) {
 662	Command.customer.then { |customer|
 663		BuyAccountCreditForm.for(customer).then do |credit_form|
 664			Command.reply { |reply|
 665				reply.allowed_actions = [:complete]
 666				reply.command << credit_form.form
 667			}.then do |iq|
 668				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 669			end
 670		end
 671	}.then { |transaction|
 672		Command.finish("#{transaction} added to your account balance.")
 673	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
 674		Command.finish(e.message, type: :error)
 675	end
 676}.register(self).then(&CommandList.method(:register))
 677
 678Command.new(
 679	"alt top up",
 680	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 681	list_for: ->(customer:, **) { !!customer&.currency }
 682) {
 683	Command.customer.then { |customer|
 684		AltTopUpForm.for(customer)
 685	}.then do |alt_form|
 686		Command.reply { |reply|
 687			reply.allowed_actions = [:complete]
 688			reply.command << alt_form.form
 689		}.then do |iq|
 690			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 691		end
 692	end
 693}.register(self).then(&CommandList.method(:register))
 694
 695Command.new(
 696	"plan settings",
 697	"📝 Manage your plan, including overage limits",
 698	list_for: ->(customer:, **) { !!customer&.currency }
 699) {
 700	Command.customer.then { |customer|
 701		EMPromise.all([
 702			REDIS.get("jmp_customer_monthly_data_limit-#{customer.customer_id}"),
 703			SIMRepo.new.owned_by(customer)
 704		]).then { |(limit, sims)| [customer, sims, limit] }
 705	}.then do |(customer, sims, limit)|
 706		Command.reply { |reply|
 707			reply.allowed_actions = [:next]
 708			reply.command << FormTemplate.render(
 709				"plan_settings", customer: customer, sims: sims, data_limit: limit
 710			)
 711		}.then { |iq|
 712			kwargs = {
 713				monthly_overage_limit: iq.form.field("monthly_overage_limit")&.value,
 714				monthly_data_limit: iq.form.field("monthly_data_limit")&.value
 715			}.compact
 716			Command.execution.customer_repo.put_monthly_limits(customer, **kwargs)
 717		}.then { Command.finish("Configuration saved!") }
 718	end
 719}.register(self).then(&CommandList.method(:register))
 720
 721Command.new(
 722	"referral codes",
 723	"👥 Refer a friend for free credit",
 724	list_for: ->(customer:, **) { !!customer&.currency }
 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 }