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