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