sgx_jmp.rb

   1# frozen_string_literal: true
   2
   3require "pg/em/connection_pool"
   4require "bandwidth"
   5require "bigdecimal"
   6require "blather/client/dsl"
   7require "braintree"
   8require "date"
   9require "dhall"
  10require "em-hiredis"
  11require "em_promise"
  12require "ougai"
  13require "ruby-bandwidth-iris"
  14require "sentry-ruby"
  15require "statsd-instrument"
  16
  17require_relative "lib/background_log"
  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	)
  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/snikket"
 106require_relative "lib/welcome_message"
 107require_relative "web"
 108require_relative "lib/statsd"
 109
 110ELECTRUM = Electrum.new(**CONFIG[:electrum])
 111EM::Hiredis::Client.load_scripts_from("./redis_lua")
 112
 113Faraday.default_adapter = :em_synchrony
 114BandwidthIris::Client.global_options = {
 115	account_id: CONFIG[:creds][:account],
 116	username: CONFIG[:creds][:username],
 117	password: CONFIG[:creds][:password]
 118}
 119BANDWIDTH_VOICE = Bandwidth::Client.new(
 120	voice_basic_auth_user_name: CONFIG[:creds][:username],
 121	voice_basic_auth_password: CONFIG[:creds][:password]
 122).voice_client.client
 123
 124class AuthError < StandardError; end
 125
 126# Braintree is not async, so wrap in EM.defer for now
 127class AsyncBraintree
 128	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
 129		@gateway = Braintree::Gateway.new(
 130			environment: environment,
 131			merchant_id: merchant_id,
 132			public_key: public_key,
 133			private_key: private_key
 134		)
 135		@gateway.config.logger = LOG
 136	end
 137
 138	def respond_to_missing?(m, *)
 139		@gateway.respond_to?(m) || super
 140	end
 141
 142	def method_missing(m, *args)
 143		return super unless respond_to_missing?(m, *args)
 144
 145		EM.promise_defer(klass: PromiseChain) do
 146			@gateway.public_send(m, *args)
 147		end
 148	end
 149
 150	class PromiseChain < EMPromise
 151		def respond_to_missing?(*)
 152			false && super # We don't actually know what we respond to...
 153		end
 154
 155		def method_missing(m, *args)
 156			return super if respond_to_missing?(m, *args)
 157
 158			self.then { |o| o.public_send(m, *args) }
 159		end
 160	end
 161end
 162
 163BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
 164
 165def panic(e, hub=nil)
 166	log.fatal(
 167		"Error raised during event loop: #{e.class}",
 168		e
 169	)
 170	if e.is_a?(::Exception)
 171		(hub || Sentry).capture_exception(e, hint: { background: false })
 172	else
 173		(hub || Sentry).capture_message(e.to_s, hint: { background: false })
 174	end
 175	exit 1
 176end
 177
 178EM.error_handler(&method(:panic))
 179
 180require_relative "lib/blather_client"
 181@client = BlatherClient.new
 182
 183setup(
 184	CONFIG[:component][:jid],
 185	CONFIG[:component][:secret],
 186	CONFIG[:server][:host],
 187	CONFIG[:server][:port],
 188	nil,
 189	nil,
 190	async: true
 191)
 192
 193# Infer anything we might have been notified about while we were down
 194def catchup_notify_low_balance(db)
 195	db.query(<<~SQL).each do |c|
 196		SELECT customer_id
 197		FROM balances INNER JOIN customer_plans USING (customer_id)
 198		WHERE balance < 5 AND expires_at > LOCALTIMESTAMP
 199	SQL
 200		db.query("SELECT pg_notify('low_balance', $1)", c.values)
 201	end
 202end
 203
 204def catchup_notify_possible_renewal(db)
 205	db.query(<<~SQL).each do |c|
 206		SELECT customer_id
 207		FROM customer_plans INNER JOIN balances USING (customer_id)
 208		WHERE
 209			expires_at < LOCALTIMESTAMP
 210			AND expires_at >= LOCALTIMESTAMP - INTERVAL '3 months'
 211			AND balance >= 5
 212	SQL
 213		db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
 214	end
 215end
 216
 217def poll_for_notify(db)
 218	db.wait_for_notify_defer.then { |notify|
 219		repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 220		repo.find(notify[:extra]).then do |customer|
 221			DbNotification.for(notify, customer, repo)
 222		end
 223	}.then(&:call).then {
 224		EM.add_timer(0.5) { poll_for_notify(db) }
 225	}.catch(&method(:panic))
 226end
 227
 228def load_plans_to_db!
 229	DB.transaction do
 230		DB.exec("TRUNCATE plans")
 231		CONFIG[:plans].each do |plan|
 232			DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
 233		end
 234	end
 235end
 236
 237when_ready do
 238	log.info "Ready"
 239	BLATHER = self
 240	REDIS = EM::Hiredis.connect
 241	MEMCACHE = EM::P::Memcache.connect
 242	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
 243	DB = Postgres.connect(dbname: "jmp")
 244	TEL_SELECTIONS = TelSelections.new
 245
 246	DB.hold do |conn|
 247		conn.query("LISTEN low_balance")
 248		conn.query("LISTEN possible_renewal")
 249		catchup_notify_low_balance(conn)
 250		catchup_notify_possible_renewal(conn)
 251		poll_for_notify(conn)
 252	end
 253
 254	load_plans_to_db!
 255
 256	EM.add_periodic_timer(3600) do
 257		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
 258		ping.from = CONFIG[:component][:jid]
 259		self << ping
 260	end
 261
 262	Web.run(LOG.child, *WEB_LISTEN)
 263end
 264
 265message to: /\Aaccount@/, body: /./ do |m|
 266	StatsD.increment("deprecated_account_bot")
 267
 268	self << m.reply.tap { |out|
 269		out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
 270	}
 271end
 272
 273before(
 274	:iq,
 275	type: [:error, :result],
 276	to: /\Acustomer_/,
 277	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
 278) { |iq| halt if IQ_MANAGER.fulfill(iq) }
 279
 280before nil, to: /\Acustomer_/, from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/ do |s|
 281	StatsD.increment("stanza_customer")
 282
 283	Sentry.get_current_scope.set_transaction_name("stanza_customer")
 284	CustomerRepo.new(set_user: Sentry.method(:set_user)).find(
 285		s.to.node.delete_prefix("customer_")
 286	).then do |customer|
 287		ReachabilityRepo::SMS.new
 288			.find(customer, s.from.node, stanza: s).then do |reach|
 289				reach.filter do
 290					customer.stanza_to(s)
 291				end
 292			end
 293	end
 294
 295	halt
 296end
 297
 298ADDRESSES_NS = "http://jabber.org/protocol/address"
 299message(
 300	to: /\A#{CONFIG[:component][:jid]}\Z/,
 301	from: /(\A|@)#{CONFIG[:sgx]}(\/|\Z)/
 302) do |m|
 303	StatsD.increment("inbound_group_text")
 304	Sentry.get_current_scope.set_transaction_name("inbound_group_text")
 305
 306	address = m.find("ns:addresses", ns: ADDRESSES_NS).first
 307		&.find("ns:address", ns: ADDRESSES_NS)
 308		&.find { |el| el["jid"].to_s.start_with?("customer_") }
 309	pass unless address
 310
 311	CustomerRepo
 312		.new(set_user: Sentry.method(:set_user))
 313		.find_by_jid(address["jid"]).then { |customer|
 314			m.from = m.from.with(domain: CONFIG[:component][:jid])
 315			m.to = m.to.with(domain: customer.jid.domain)
 316			address["jid"] = customer.jid.to_s
 317			BLATHER << m
 318		}.catch_only(CustomerRepo::NotFound) { |e|
 319			BLATHER << m.as_error("forbidden", :auth, e.message)
 320		}
 321end
 322
 323# Ignore groupchat messages
 324# Especially if we have the component join MUC for notifications
 325message(type: :groupchat) { true }
 326
 327def billable_message(m)
 328	b = m.body
 329	b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first
 330end
 331
 332class OverLimit < StandardError
 333	def initialize(customer, usage)
 334		super("Please contact support")
 335		@customer = customer
 336		@usage = usage
 337	end
 338
 339	def notify_admin
 340		ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
 341			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 342			BLATHER.say(
 343				CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
 344				"#{@usage} messages today", :groupchat
 345			)
 346		end
 347	end
 348end
 349
 350class CustomerExpired < StandardError; end
 351
 352CONFIG[:direct_targets].each do |(tel, jid)|
 353	customer_repo = CustomerRepo.new(
 354		sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
 355		set_user: Sentry.method(:set_user)
 356	)
 357
 358	message to: /\A#{Regexp.escape(tel)}@#{CONFIG[:component][:jid]}\/?/ do |m|
 359		customer_repo.find_by_jid(m.from.stripped).then { |customer|
 360			customer.stanza_from(m)
 361		}.catch_only(CustomerRepo::NotFound) {
 362			# This should not happen, but let's still get the message
 363			# to support at least if it does
 364			m.from = ProxiedJID.proxy(m.from, CONFIG[:component][:jid])
 365			m.to = jid
 366			BLATHER << m
 367		}
 368	end
 369
 370	message to: /\Acustomer_/, from: /\A#{Regexp.escape(jid)}\/?/ do |m|
 371		customer_repo.find(m.to.node.delete_prefix("customer_")).then { |customer|
 372			m.from = "#{tel}@sgx-jmp" # stanza_to will fix domain
 373			customer.stanza_to(m)
 374		}.catch_only(CustomerRepo::NotFound) { |e|
 375			BLATHER << m.as_error("item-not-found", :cancel, e.message)
 376		}
 377	end
 378end
 379
 380message do |m|
 381	StatsD.increment("message")
 382
 383	today = Time.now.utc.to_date
 384	CustomerRepo.new(set_user: Sentry.method(:set_user))
 385		.find_by_jid(m.from.stripped).then { |customer|
 386			next customer.stanza_from(m) unless billable_message(m)
 387
 388			if customer.plan_name && !customer.active?
 389				raise CustomerExpired, "Your account is expired, please top up"
 390			end
 391
 392			EMPromise.all([
 393				TrustLevelRepo.new.find(customer),
 394				customer.message_usage((today..today))
 395			]).then { |(tl, usage)|
 396				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
 397			}.then do
 398				EMPromise.all([
 399					customer.incr_message_usage, customer.stanza_from(m)
 400				])
 401			end
 402		}.catch_only(OverLimit) { |e|
 403			e.notify_admin
 404			BLATHER << m.as_error("policy-violation", :wait, e.message)
 405		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
 406			BLATHER << m.as_error("forbidden", :auth, e.message)
 407		}
 408end
 409
 410disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
 411	reply = iq.reply
 412	reply.identities = [{
 413		name: "JMP.chat",
 414		type: "sms",
 415		category: "gateway"
 416	}]
 417	reply.features = [
 418		"http://jabber.org/protocol/disco#info",
 419		"http://jabber.org/protocol/commands"
 420	]
 421	form = Blather::Stanza::X.find_or_create(reply.query)
 422	form.type = "result"
 423	form.fields = [
 424		{
 425			var: "FORM_TYPE",
 426			type: "hidden",
 427			value: "http://jabber.org/network/serverinfo"
 428		}
 429	] + CONFIG[:xep0157]
 430	self << reply
 431end
 432
 433disco_info do |iq|
 434	reply = iq.reply
 435	reply.identities = [{
 436		name: "JMP.chat",
 437		type: "sms",
 438		category: "client"
 439	}]
 440	reply.features = [
 441		"urn:xmpp:receipts"
 442	]
 443	self << reply
 444end
 445
 446disco_items(
 447	to: Blather::JID.new(CONFIG[:component][:jid]),
 448	node: "http://jabber.org/protocol/commands"
 449) do |iq|
 450	StatsD.increment("command_list")
 451
 452	reply = iq.reply
 453	reply.node = "http://jabber.org/protocol/commands"
 454
 455	CustomerRepo.new(
 456		sgx_repo: Bwmsgsv2Repo.new,
 457		set_user: Sentry.method(:set_user)
 458	).find_by_jid(
 459		iq.from.stripped
 460	).catch {
 461		nil
 462	}.then { |customer|
 463		CommandList.for(customer, iq.from)
 464	}.then { |list|
 465		reply.items = list.map { |item|
 466			Blather::Stanza::DiscoItems::Item.new(
 467				iq.to,
 468				item[:node],
 469				item[:name]
 470			)
 471		}
 472		self << reply
 473	}
 474end
 475
 476iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
 477	StatsD.increment("extdisco")
 478
 479	reply = iq.reply
 480	reply << Nokogiri::XML::Builder.new {
 481		services(xmlns: "urn:xmpp:extdisco:2") do
 482			service(
 483				type: "sip",
 484				host: CONFIG[:sip_host]
 485			)
 486		end
 487	}.doc.root
 488
 489	self << reply
 490end
 491
 492Command.new(
 493	"jabber:iq:register",
 494	"Register",
 495	list_for: ->(*) { true },
 496	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 497) {
 498	google_play_userid = if Command.execution.iq.from.domain == "cheogram.com"
 499		Command.execution.iq.command.find(
 500			"./ns:userId", ns: "https://ns.cheogram.com/google-play"
 501		)&.first&.content
 502	end
 503	Command.customer.catch_only(CustomerRepo::NotFound) {
 504		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
 505		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
 506	}.then { |customer|
 507		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
 508		Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
 509	}.then {
 510		StatsD.increment("registration.completed")
 511	}.catch_only(Command::Execution::FinalStanza) do |e|
 512		StatsD.increment("registration.completed")
 513		EMPromise.reject(e)
 514	end
 515}.register(self).then(&CommandList.method(:register))
 516
 517Command.new(
 518	"info",
 519	"👤 Show Account Info",
 520	list_for: ->(*) { true },
 521	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 522) {
 523	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
 524		Command.finish do |reply|
 525			reply.command << info.form
 526		end
 527	end
 528}.register(self).then(&CommandList.method(:register))
 529
 530Command.new(
 531	"cdrs",
 532	"📲 Show Call Logs"
 533) {
 534	report_for = ((Date.today << 1)..Date.today)
 535
 536	Command.customer.then { |customer|
 537		CDRRepo.new.find_range(customer, report_for)
 538	}.then do |cdrs|
 539		Command.finish do |reply|
 540			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
 541		end
 542	end
 543}.register(self).then(&CommandList.method(:register))
 544
 545Command.new(
 546	"transactions",
 547	"🧾 Show Transactions",
 548	list_for: ->(customer:, **) { !!customer&.currency }
 549) {
 550	Command.customer.then(&:transactions).then do |txs|
 551		Command.finish do |reply|
 552			reply.command << FormTemplate.render("transactions", transactions: txs)
 553		end
 554	end
 555}.register(self).then(&CommandList.method(:register))
 556
 557Command.new(
 558	"configure calls",
 559	"📞 Configure Calls",
 560	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 561) {
 562	Command.customer.then do |customer|
 563		cc_form = ConfigureCallsForm.new(customer)
 564		Command.reply { |reply|
 565			reply.allowed_actions = [:next]
 566			reply.command << cc_form.render
 567		}.then { |iq|
 568			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
 569				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
 570			})
 571		}.then { Command.finish("Configuration saved!") }
 572	end
 573}.register(self).then(&CommandList.method(:register))
 574
 575Command.new(
 576	"ogm",
 577	"⏺️ Record Voicemail Greeting",
 578	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
 579	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 580) {
 581	Command.customer.then do |customer|
 582		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
 583			cc.from = customer.registered?.phone
 584			cc.application_id = CONFIG[:sip][:app]
 585			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
 586			                "customer_id=#{customer.customer_id}"
 587		end
 588		Command.finish("You will now receive a call.")
 589	end
 590}.register(self).then(&CommandList.method(:register))
 591
 592Command.new(
 593	"migrate billing",
 594	"🏦 Switch to new billing",
 595	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
 596	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 597) {
 598	EMPromise.all([
 599		Command.customer,
 600		Command.reply do |reply|
 601			reply.allowed_actions = [:next]
 602			reply.command << FormTemplate.render("migrate_billing")
 603		end
 604	]).then do |(customer, iq)|
 605		plan_name = iq.form.field("plan_name").value.to_s
 606		customer = customer.with_plan(plan_name)
 607		customer.save_plan!.then {
 608			Registration::Payment.for(
 609				iq, customer, customer.registered?.phone,
 610				final_message: PaypalDone::MESSAGE,
 611				finish: PaypalDone
 612			)
 613		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 614			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 615			BLATHER.say(
 616				CONFIG[:notify_admin],
 617				"#{customer.customer_id} migrated to #{customer.currency}",
 618				:groupchat
 619			)
 620			EMPromise.reject(s)
 621		end
 622	end
 623}.register(self).then(&CommandList.method(:register))
 624
 625Command.new(
 626	"credit cards",
 627	"💳 Credit Card Settings and Management"
 628) {
 629	Command.customer.then do |customer|
 630		url = CONFIG[:credit_card_url].call(
 631			customer.jid.to_s.gsub("\\", "%5C"),
 632			customer.customer_id
 633		)
 634		desc = "Manage credits cards and settings"
 635		Command.finish("#{desc}: #{url}") do |reply|
 636			oob = OOB.find_or_create(reply.command)
 637			oob.url = url
 638			oob.desc = desc
 639		end
 640	end
 641}.register(self).then(&CommandList.method(:register))
 642
 643Command.new(
 644	"top up",
 645	"💲 Buy Account Credit by Credit Card",
 646	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 647	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 648) {
 649	Command.customer.then { |customer|
 650		BuyAccountCreditForm.for(customer).then do |credit_form|
 651			Command.reply { |reply|
 652				reply.allowed_actions = [:complete]
 653				reply.command << credit_form.form
 654			}.then do |iq|
 655				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 656			end
 657		end
 658	}.then { |transaction|
 659		Command.finish("#{transaction} added to your account balance.")
 660	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
 661		Command.finish(e.message, type: :error)
 662	end
 663}.register(self).then(&CommandList.method(:register))
 664
 665Command.new(
 666	"alt top up",
 667	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 668	list_for: ->(customer:, **) { !!customer&.currency }
 669) {
 670	Command.customer.then { |customer|
 671		AltTopUpForm.for(customer)
 672	}.then do |alt_form|
 673		Command.reply { |reply|
 674			reply.allowed_actions = [:complete]
 675			reply.command << alt_form.form
 676		}.then do |iq|
 677			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 678		end
 679	end
 680}.register(self).then(&CommandList.method(:register))
 681
 682Command.new(
 683	"plan settings",
 684	"📝 Manage your plan, including overage limits",
 685	list_for: ->(customer:, **) { !!customer&.currency }
 686) {
 687	Command.customer.then do |customer|
 688		Command.reply { |reply|
 689			reply.allowed_actions = [:next]
 690			reply.command << FormTemplate.render("plan_settings", customer: customer)
 691		}.then { |iq|
 692			Command.execution.customer_repo.put_monthly_overage_limit(
 693				customer,
 694				iq.form.field("monthly_overage_limit")&.value.to_i
 695			)
 696		}.then { Command.finish("Configuration saved!") }
 697	end
 698}.register(self).then(&CommandList.method(:register))
 699
 700Command.new(
 701	"referral codes",
 702	"👥 Refer a friend for free credit"
 703) {
 704	repo = InvitesRepo.new
 705	Command.customer.then { |customer|
 706		EMPromise.all([
 707			repo.find_or_create_group_code(customer.customer_id),
 708			repo.unused_invites(customer.customer_id)
 709		])
 710	}.then do |(group_code, invites)|
 711		if invites.empty?
 712			Command.finish(
 713				"This code will provide credit equivalent to one month of service " \
 714				"to anyone after they sign up and pay: #{group_code}\n\n" \
 715				"You will receive credit equivalent to one month of service once " \
 716				"their payment clears."
 717			)
 718		else
 719			Command.finish do |reply|
 720				reply.command << FormTemplate.render(
 721					"codes",
 722					invites: invites,
 723					group_code: group_code
 724				)
 725			end
 726		end
 727	end
 728}.register(self).then(&CommandList.method(:register))
 729
 730Command.new(
 731	"sims",
 732	"📶 (e)SIM Details",
 733	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency }
 734) {
 735	Command.customer.then(&SIMRepo.new.method(:owned_by)).then do |sims|
 736		if sims.empty?
 737			next Command.finish(
 738				"You have no (e)SIMs, you can get on the waitlist at https://jmp.chat/sim"
 739			)
 740		end
 741
 742		Command.finish do |reply|
 743			reply.command << FormTemplate.render(
 744				"sim_details",
 745				sims: sims
 746			)
 747		end
 748	end
 749}.register(self).then(&CommandList.method(:register))
 750
 751Command.new(
 752	"reset sip account",
 753	"☎️ Create or Reset SIP Account",
 754	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 755) {
 756	Command.customer.then do |customer|
 757		sip_account = customer.reset_sip_account
 758		Command.reply { |reply|
 759			reply.allowed_actions = [:next]
 760			form = sip_account.form
 761			form.type = :form
 762			form.fields += [{
 763				type: :boolean, var: "change_fwd",
 764				label: "Should inbound calls forward to this SIP account?"
 765			}]
 766			reply.command << form
 767		}.then do |fwd|
 768			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
 769				Command.execution.customer_repo.put_fwd(
 770					customer,
 771					customer.fwd.with(uri: sip_account.uri)
 772				).then { Command.finish("Inbound calls will now forward to SIP.") }
 773			else
 774				Command.finish
 775			end
 776		end
 777	end
 778}.register(self).then(&CommandList.method(:register))
 779
 780Command.new(
 781	"lnp",
 782	"#️⃣ Port in your number from another carrier",
 783	list_for: ->(**) { true }
 784) {
 785	EMPromise.all([
 786		Command.customer,
 787		Command.reply do |reply|
 788			reply.allowed_actions = [:next]
 789			reply.command << FormTemplate.render("lnp")
 790		end
 791	]).then { |(customer, iq)|
 792		PortInOrder.parse(customer, iq.form).complete_with do |form|
 793			Command.reply { |reply|
 794				reply.allowed_actions = [:next]
 795				reply.command << form
 796			}.then(&:form)
 797		end
 798	}.then do |order|
 799		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
 800		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 801		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
 802		Command.finish(
 803			"Your port-in request has been accepted, " \
 804			"support will contact you with next steps"
 805		)
 806	end
 807}.register(self).then(&CommandList.method(:register))
 808
 809Command.new(
 810	"terminate account",
 811	"❌ Cancel your account and terminate your phone number",
 812	list_for: ->(**) { false },
 813	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 814) {
 815	Command.reply { |reply|
 816		reply.allowed_actions = [:next]
 817		reply.note_text = "Press next to confirm your account termination."
 818	}.then { Command.customer }.then { |customer|
 819		AdminAction::CancelCustomer.call(
 820			customer,
 821			customer_repo: Command.execution.customer_repo
 822		)
 823	}.then do
 824		Command.finish("Account cancelled")
 825	end
 826}.register(self).then(&CommandList.method(:register))
 827
 828Command.new(
 829	"customer info",
 830	"Show Customer Info",
 831	list_for: ->(customer: nil, **) { customer&.admin? }
 832) {
 833	Command.customer.then do |customer|
 834		raise AuthError, "You are not an admin" unless customer&.admin?
 835
 836		customer_repo = CustomerRepo.new(
 837			sgx_repo: Bwmsgsv2Repo.new,
 838			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
 839		)
 840
 841		AdminCommand::NoUser.new(customer_repo).start
 842	end
 843}.register(self).then(&CommandList.method(:register))
 844
 845Command.new(
 846	"reachability",
 847	"Test Reachability",
 848	list_for: ->(customer: nil, **) { customer&.admin? }
 849) {
 850	Command.customer.then do |customer|
 851		raise AuthError, "You are not an admin" unless customer&.admin?
 852
 853		form = ReachabilityForm.new(CustomerRepo.new)
 854
 855		Command.reply { |reply|
 856			reply.allowed_actions = [:next]
 857			reply.command << form.render
 858		}.then { |response|
 859			form.parse(response.form)
 860		}.then { |result|
 861			result.repo.get_or_create(result.target).then { |v|
 862				result.target.stanza_from(result.prompt) if result.prompt
 863
 864				Command.finish { |reply|
 865					reply.command << form.render_result(v)
 866				}
 867			}
 868		}.catch_only(RuntimeError) { |e|
 869			Command.finish(e, type: :error)
 870		}
 871	end
 872}.register(self).then(&CommandList.method(:register))
 873
 874Command.new(
 875	"snikket",
 876	"Launch Snikket Instance",
 877	list_for: ->(customer: nil, **) { customer&.admin? }
 878) {
 879	Command.customer.then do |customer|
 880		raise AuthError, "You are not an admin" unless customer&.admin?
 881
 882		Command.reply { |reply|
 883			reply.allowed_actions = [:next]
 884			reply.command << FormTemplate.render("snikket_launch")
 885		}.then { |response|
 886			domain = response.form.field("domain").value.to_s
 887			IQ_MANAGER.write(Snikket::Launch.new(
 888				nil, CONFIG[:snikket_hosting_api],
 889				domain: domain
 890			)).then do |launched|
 891				Snikket::CustomerInstance.for(customer, domain, launched)
 892			end
 893		}.then { |instance|
 894			Command.finish do |reply|
 895				reply.command << FormTemplate.render(
 896					"snikket_launched",
 897					instance: instance
 898				)
 899			end
 900		}
 901	end
 902}.register(self).then(&CommandList.method(:register))
 903
 904def reply_with_note(iq, text, type: :info)
 905	reply = iq.reply
 906	reply.status = :completed
 907	reply.note_type = type
 908	reply.note_text = text
 909
 910	self << reply
 911end
 912
 913Command.new(
 914	"https://ns.cheogram.com/sgx/jid-switch",
 915	"Change JID",
 916	list_for: ->(customer: nil, **) { customer },
 917	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 918) {
 919	Command.customer.then { |customer|
 920		Command.reply { |reply|
 921			reply.command << FormTemplate.render("jid_switch")
 922		}.then { |response|
 923			new_jid = response.form.field("jid").value
 924			repo = Command.execution.customer_repo
 925			repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
 926				.then { |cust|
 927					next EMPromise.reject("Customer Already Exists") if cust
 928
 929					repo.change_jid(customer, new_jid)
 930				}
 931		}.then {
 932			StatsD.increment("changejid.completed")
 933			jid = ProxiedJID.new(customer.jid).unproxied
 934			if jid.domain == CONFIG[:onboarding_domain]
 935				CustomerRepo.new.find(customer.customer_id).then do |cust|
 936					WelcomeMessage.new(cust, customer.registered?.phone).welcome
 937				end
 938			end
 939			Command.finish { |reply|
 940				reply.note_type = :info
 941				reply.note_text = "Customer JID Changed"
 942			}
 943		}
 944	}
 945}.register(self).then(&CommandList.method(:register))
 946
 947Command.new(
 948	"web-register",
 949	"Initiate Register from Web",
 950	list_for: lambda { |from_jid: nil, **|
 951		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
 952	}
 953) {
 954	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
 955		next EMPromise.reject(
 956			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
 957		)
 958	end
 959
 960	Command.reply { |reply|
 961		reply.command << FormTemplate.render("web_register")
 962	}.then do |iq|
 963		jid = iq.form.field("jid")&.value.to_s.strip
 964		tel = iq.form.field("tel")&.value.to_s.strip
 965		if jid !~ /\./ || jid =~ /\s/
 966			Command.finish("The Jabber ID you entered was not valid.", type: :error)
 967		elsif tel !~ /\A\+\d+\Z/
 968			Command.finish("Invalid telephone number", type: :error)
 969		else
 970			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
 971				cmd.to = CONFIG[:web_register][:to]
 972				cmd.node = "push-register"
 973				cmd.form.fields = [{ var: "to", value: jid }]
 974				cmd.form.type = "submit"
 975			}).then { |result|
 976				TEL_SELECTIONS.set(result.form.field("from")&.value.to_s.strip, tel)
 977			}.then { Command.finish }
 978		end
 979	end
 980}.register(self).then(&CommandList.method(:register))
 981
 982command sessionid: /./ do |iq|
 983	COMMAND_MANAGER.fulfill(iq)
 984	IQ_MANAGER.fulfill(iq)
 985	true
 986end
 987
 988iq type: [:result, :error] do |iq|
 989	IQ_MANAGER.fulfill(iq)
 990	true
 991end
 992
 993iq type: [:get, :set] do |iq|
 994	StatsD.increment("unknown_iq")
 995
 996	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
 997end
 998
 999trap(:INT) { EM.stop }
1000trap(:TERM) { EM.stop }
1001EM.run { client.run }