sgx_jmp.rb

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