sgx_jmp.rb

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