sgx_jmp.rb

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