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: 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
 375message do |m|
 376	StatsD.increment("message")
 377
 378	today = Time.now.utc.to_date
 379	CustomerRepo.new(set_user: Sentry.method(:set_user))
 380		.find_by_jid(m.from.stripped).then { |customer|
 381			next customer.stanza_from(m) unless billable_message(m)
 382
 383			if customer.plan_name && !customer.active?
 384				raise CustomerExpired, "Your account is expired, please top up"
 385			end
 386
 387			EMPromise.all([
 388				REDIS.exists("jmp_customer_spam_detected-#{customer.customer_id}"),
 389				TrustLevelRepo.new.find(customer),
 390				customer.message_usage((today..today))
 391			]).then { |(spam, tl, usage)|
 392				raise OverLimit.new(customer, "SPAM DETECTED") if spam.to_i == 1
 393				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
 394			}.then do
 395				EMPromise.all([customer.incr_message_usage, customer.stanza_from(m)])
 396			end
 397		}.catch_only(OverLimit) { |e|
 398			e.notify_admin
 399			BLATHER << m.as_error("policy-violation", :wait, e.message)
 400		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
 401			BLATHER << m.as_error("forbidden", :auth, e.message)
 402		}
 403end
 404
 405disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
 406	reply = iq.reply
 407	reply.identities = [{
 408		name: "JMP.chat",
 409		type: "sms",
 410		category: "gateway"
 411	}]
 412	reply.features = [
 413		"http://jabber.org/protocol/disco#info",
 414		"http://jabber.org/protocol/commands"
 415	]
 416	form = Blather::Stanza::X.find_or_create(reply.query)
 417	form.type = "result"
 418	form.fields = [
 419		{
 420			var: "FORM_TYPE",
 421			type: "hidden",
 422			value: "http://jabber.org/network/serverinfo"
 423		}
 424	] + CONFIG[:xep0157]
 425	self << reply
 426end
 427
 428disco_info do |iq|
 429	reply = iq.reply
 430	reply.identities = [{
 431		name: "JMP.chat",
 432		type: "sms",
 433		category: "client"
 434	}]
 435	reply.features = [
 436		"urn:xmpp:receipts"
 437	]
 438	self << reply
 439end
 440
 441disco_items(
 442	to: Blather::JID.new(CONFIG[:component][:jid]),
 443	node: "http://jabber.org/protocol/commands"
 444) do |iq|
 445	StatsD.increment("command_list")
 446
 447	reply = iq.reply
 448	reply.node = "http://jabber.org/protocol/commands"
 449
 450	CustomerRepo.new(
 451		sgx_repo: Bwmsgsv2Repo.new,
 452		set_user: Sentry.method(:set_user)
 453	).find_by_jid(
 454		iq.from.stripped
 455	).catch {
 456		nil
 457	}.then { |customer|
 458		CommandList.for(customer, iq.from)
 459	}.then { |list|
 460		reply.items = list.map { |item|
 461			Blather::Stanza::DiscoItems::Item.new(
 462				iq.to,
 463				item[:node],
 464				item[:name]
 465			)
 466		}
 467		self << reply
 468	}
 469end
 470
 471iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
 472	StatsD.increment("extdisco")
 473
 474	reply = iq.reply
 475	reply << Nokogiri::XML::Builder.new {
 476		services(xmlns: "urn:xmpp:extdisco:2") do
 477			service(
 478				type: "sip",
 479				host: CONFIG[:sip_host]
 480			)
 481		end
 482	}.doc.root
 483
 484	self << reply
 485end
 486
 487Command.new(
 488	"jabber:iq:register",
 489	"Register",
 490	list_for: ->(*) { true },
 491	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 492) {
 493	google_play_userid = if Command.execution.iq.from.domain == "cheogram.com"
 494		Command.execution.iq.command.find(
 495			"./ns:userId", ns: "https://ns.cheogram.com/google-play"
 496		)&.first&.content
 497	end
 498	Command.customer.catch_only(CustomerRepo::NotFound) {
 499		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
 500		Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
 501	}.then { |customer|
 502		Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
 503		Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
 504	}.then {
 505		StatsD.increment("registration.completed")
 506	}.catch_only(Command::Execution::FinalStanza) do |e|
 507		StatsD.increment("registration.completed")
 508		EMPromise.reject(e)
 509	end
 510}.register(self).then(&CommandList.method(:register))
 511
 512Command.new(
 513	"info",
 514	"👤 Show Account Info",
 515	list_for: ->(*) { true },
 516	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 517) {
 518	Command.customer.then(&CustomerInfo.method(:for)).then do |info|
 519		Command.finish do |reply|
 520			reply.command << info.form
 521		end
 522	end
 523}.register(self).then(&CommandList.method(:register))
 524
 525Command.new(
 526	"cdrs",
 527	"📲 Show Call Logs"
 528) {
 529	report_for = ((Date.today << 1)..Date.today)
 530
 531	Command.customer.then { |customer|
 532		CDRRepo.new.find_range(customer, report_for)
 533	}.then do |cdrs|
 534		Command.finish do |reply|
 535			reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
 536		end
 537	end
 538}.register(self).then(&CommandList.method(:register))
 539
 540Command.new(
 541	"transactions",
 542	"🧾 Show Transactions",
 543	list_for: ->(customer:, **) { !!customer&.currency }
 544) {
 545	Command.customer.then(&:transactions).then do |txs|
 546		Command.finish do |reply|
 547			reply.command << FormTemplate.render("transactions", transactions: txs)
 548		end
 549	end
 550}.register(self).then(&CommandList.method(:register))
 551
 552Command.new(
 553	"configure calls",
 554	"📞 Configure Calls",
 555	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 556) {
 557	Command.customer.then do |customer|
 558		cc_form = ConfigureCallsForm.new(customer)
 559		Command.reply { |reply|
 560			reply.allowed_actions = [:next]
 561			reply.command << cc_form.render
 562		}.then { |iq|
 563			EMPromise.all(cc_form.parse(iq.form).map { |k, v|
 564				Command.execution.customer_repo.public_send("put_#{k}", customer, v)
 565			})
 566		}.then { Command.finish("Configuration saved!") }
 567	end
 568}.register(self).then(&CommandList.method(:register))
 569
 570Command.new(
 571	"ogm",
 572	"⏺️ Record Voicemail Greeting",
 573	list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
 574	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 575) {
 576	Command.customer.then do |customer|
 577		customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
 578			cc.from = customer.registered?.phone
 579			cc.application_id = CONFIG[:sip][:app]
 580			cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
 581			                "customer_id=#{customer.customer_id}"
 582		end
 583		Command.finish("You will now receive a call.")
 584	end
 585}.register(self).then(&CommandList.method(:register))
 586
 587Command.new(
 588	"migrate billing",
 589	"🏦 Switch to new billing",
 590	list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
 591	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 592) {
 593	EMPromise.all([
 594		Command.customer,
 595		Command.reply do |reply|
 596			reply.allowed_actions = [:next]
 597			reply.command << FormTemplate.render("migrate_billing")
 598		end
 599	]).then do |(customer, iq)|
 600		plan_name = iq.form.field("plan_name").value.to_s
 601		customer = customer.with_plan(plan_name)
 602		customer.save_plan!.then {
 603			Registration::Payment.for(
 604				iq, customer, customer.registered?.phone,
 605				final_message: PaypalDone::MESSAGE,
 606				finish: PaypalDone
 607			)
 608		}.then(&:write).catch_only(Command::Execution::FinalStanza) do |s|
 609			BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 610			BLATHER.say(
 611				CONFIG[:notify_admin],
 612				"#{customer.customer_id} migrated to #{customer.currency}",
 613				:groupchat
 614			)
 615			EMPromise.reject(s)
 616		end
 617	end
 618}.register(self).then(&CommandList.method(:register))
 619
 620Command.new(
 621	"credit cards",
 622	"💳 Credit Card Settings and Management",
 623	list_for: ->(customer:, **) { !!customer&.currency }
 624) {
 625	Command.customer.then do |customer|
 626		url = CONFIG[:credit_card_url].call(
 627			customer.jid.to_s.gsub("\\", "%5C"),
 628			customer.customer_id
 629		)
 630		desc = "Manage credits cards and settings"
 631		Command.finish("#{desc}: #{url}") do |reply|
 632			oob = OOB.find_or_create(reply.command)
 633			oob.url = url
 634			oob.desc = desc
 635		end
 636	end
 637}.register(self).then(&CommandList.method(:register))
 638
 639Command.new(
 640	"top up",
 641	"💲 Buy Account Credit by Credit Card",
 642	list_for: ->(payment_methods: [], **) { !payment_methods.empty? },
 643	format_error: ->(e) { "Failed to buy credit, system said: #{e.message}" }
 644) {
 645	Command.customer.then { |customer|
 646		BuyAccountCreditForm.for(customer).then do |credit_form|
 647			Command.reply { |reply|
 648				reply.allowed_actions = [:complete]
 649				reply.command << credit_form.form
 650			}.then do |iq|
 651				CreditCardSale.create(customer, **credit_form.parse(iq.form))
 652			end
 653		end
 654	}.then { |transaction|
 655		Command.finish("#{transaction} added to your account balance.")
 656	}.catch_only(BuyAccountCreditForm::AmountValidationError) do |e|
 657		Command.finish(e.message, type: :error)
 658	end
 659}.register(self).then(&CommandList.method(:register))
 660
 661Command.new(
 662	"alt top up",
 663	"🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
 664	list_for: ->(customer:, **) { !!customer&.currency }
 665) {
 666	Command.customer.then { |customer|
 667		AltTopUpForm.for(customer)
 668	}.then do |alt_form|
 669		Command.reply { |reply|
 670			reply.allowed_actions = [:complete]
 671			reply.command << alt_form.form
 672		}.then do |iq|
 673			Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
 674		end
 675	end
 676}.register(self).then(&CommandList.method(:register))
 677
 678Command.new(
 679	"plan settings",
 680	"📝 Manage your plan, including overage limits",
 681	list_for: ->(customer:, **) { !!customer&.currency }
 682) {
 683	Command.customer.then { |customer|
 684		EMPromise.all([
 685			REDIS.get("jmp_customer_monthly_data_limit-#{customer.customer_id}"),
 686			SIMRepo.new.owned_by(customer)
 687		]).then { |(limit, sims)| [customer, sims, limit] }
 688	}.then do |(customer, sims, limit)|
 689		Command.reply { |reply|
 690			reply.allowed_actions = [:next]
 691			reply.command << FormTemplate.render(
 692				"plan_settings", customer: customer, sims: sims, data_limit: limit
 693			)
 694		}.then { |iq|
 695			kwargs = {
 696				monthly_overage_limit: iq.form.field("monthly_overage_limit")&.value,
 697				monthly_data_limit: iq.form.field("monthly_data_limit")&.value
 698			}.compact
 699			Command.execution.customer_repo.put_monthly_limits(customer, **kwargs)
 700		}.then { Command.finish("Configuration saved!") }
 701	end
 702}.register(self).then(&CommandList.method(:register))
 703
 704Command.new(
 705	"referral codes",
 706	"👥 Refer a friend for free credit",
 707	list_for: ->(customer:, **) { !!customer&.currency }
 708) {
 709	repo = InvitesRepo.new
 710	Command.customer.then { |customer|
 711		EMPromise.all([
 712			repo.find_or_create_group_code(customer.customer_id),
 713			repo.unused_invites(customer.customer_id)
 714		])
 715	}.then do |(group_code, invites)|
 716		if invites.empty?
 717			Command.finish(
 718				"This code will provide credit equivalent to one month of service " \
 719				"to anyone after they sign up and pay: #{group_code}\n\n" \
 720				"You will receive credit equivalent to one month of service once " \
 721				"their payment clears."
 722			)
 723		else
 724			Command.finish do |reply|
 725				reply.command << FormTemplate.render(
 726					"codes",
 727					invites: invites,
 728					group_code: group_code
 729				)
 730			end
 731		end
 732	end
 733}.register(self).then(&CommandList.method(:register))
 734
 735# Assumes notify_from is a direct target
 736notify_to = CONFIG[:direct_targets].fetch(
 737	Blather::JID.new(CONFIG[:notify_from]).node.to_sym
 738)
 739
 740Command.new(
 741	"sims",
 742	"📶 (e)SIM Details",
 743	list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency },
 744	customer_repo: CustomerRepo.new(
 745		sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
 746	)
 747) {
 748	Command.customer.then { |customer|
 749		EMPromise.all([customer, SIMRepo.new.owned_by(customer)])
 750	}.then do |(customer, sims)|
 751		Command.reply { |reply|
 752			reply.command << FormTemplate.render("sim_details", sims: sims)
 753		}.then { |iq|
 754			case iq.form.field("http://jabber.org/protocol/commands#actions")&.value
 755			when "order-sim"
 756				SIMOrder.for(customer, **CONFIG.dig(:sims, :sim, customer.currency))
 757			when "order-esim"
 758				SIMOrder::ESIM.for(
 759					customer, **CONFIG.dig(:sims, :esim, customer.currency)
 760				)
 761			else
 762				Command.finish
 763			end
 764		}.then { |order|
 765			Command.reply { |reply|
 766				reply.allowed_actions = [:complete]
 767				reply.command << order.form
 768			}.then(&order.method(:complete))
 769		}
 770	end
 771}.register(self).then(&CommandList.method(:register))
 772
 773Command.new(
 774	"subaccount",
 775	"➕️ Create a new phone number linked to this balance",
 776	list_for: lambda do |customer:, **|
 777		!!customer&.currency &&
 778		customer&.billing_customer_id == customer&.customer_id
 779	end
 780) {
 781	cheogram = Command.execution.iq.from.resource =~ /\ACheogram/
 782	Command.customer.then do |customer|
 783		ParentCodeRepo.new.find_or_create(customer.customer_id).then do |code|
 784			Command.finish { |reply|
 785				reply.command << FormTemplate.render(
 786					"subaccount", code: code, cheogram: cheogram
 787				)
 788			}
 789		end
 790	end
 791}.register(self).then(&CommandList.method(:register))
 792
 793Command.new(
 794	"reset sip account",
 795	"☎️ Create or Reset SIP Account",
 796	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 797) {
 798	Command.customer.then do |customer|
 799		sip_account = customer.reset_sip_account
 800		Command.reply { |reply|
 801			reply.allowed_actions = [:next]
 802			form = sip_account.form
 803			form.type = :form
 804			form.fields += [{
 805				type: :boolean, var: "change_fwd",
 806				label: "Should inbound calls forward to this SIP account?"
 807			}]
 808			reply.command << form
 809		}.then do |fwd|
 810			if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
 811				Command.execution.customer_repo.put_fwd(
 812					customer,
 813					customer.fwd.with(uri: sip_account.uri)
 814				).then { Command.finish("Inbound calls will now forward to SIP.") }
 815			else
 816				Command.finish
 817			end
 818		end
 819	end
 820}.register(self).then(&CommandList.method(:register))
 821
 822Command.new(
 823	"lnp",
 824	"#️⃣ Port in your number from another carrier",
 825	list_for: ->(**) { true }
 826) {
 827	EMPromise.all([
 828		Command.customer,
 829		Command.reply do |reply|
 830			reply.allowed_actions = [:next]
 831			reply.command << FormTemplate.render("lnp")
 832		end
 833	]).then { |(customer, iq)|
 834		PortInOrder.parse(customer, iq.form).complete_with do |form|
 835			Command.reply { |reply|
 836				reply.allowed_actions = [:next]
 837				reply.command << form
 838			}.then(&:form)
 839		end
 840	}.then do |order|
 841		order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
 842		BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
 843		BLATHER.say(CONFIG[:notify_admin], order.message(order_id), :groupchat)
 844		Command.finish(
 845			"Your port-in request has been accepted, " \
 846			"support will contact you with next steps"
 847		)
 848	end
 849}.register(self).then(&CommandList.method(:register))
 850
 851Command.new(
 852	"terminate account",
 853	"❌ Cancel your account and terminate your phone number",
 854	list_for: ->(**) { false },
 855	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
 856) {
 857	Command.reply { |reply|
 858		reply.allowed_actions = [:next]
 859		reply.note_text = "Press next to confirm your account termination."
 860	}.then { Command.customer }.then { |customer|
 861		AdminAction::CancelCustomer.call(
 862			customer,
 863			customer_repo: Command.execution.customer_repo
 864		)
 865	}.then do
 866		Command.finish("Account cancelled")
 867	end
 868}.register(self).then(&CommandList.method(:register))
 869
 870Command.new(
 871	"customer info",
 872	"Show Customer Info",
 873	list_for: ->(customer: nil, **) { customer&.admin? }
 874) {
 875	Command.customer.then do |customer|
 876		raise AuthError, "You are not an admin" unless customer&.admin?
 877
 878		customer_repo = CustomerRepo.new(
 879			sgx_repo: Bwmsgsv2Repo.new,
 880			bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
 881		)
 882
 883		AdminCommand::NoUser.new(customer_repo).start
 884	end
 885}.register(self).then(&CommandList.method(:register))
 886
 887Command.new(
 888	"reachability",
 889	"Test Reachability",
 890	list_for: ->(customer: nil, **) { customer&.admin? }
 891) {
 892	Command.customer.then do |customer|
 893		raise AuthError, "You are not an admin" unless customer&.admin?
 894
 895		form = ReachabilityForm.new(CustomerRepo.new)
 896
 897		Command.reply { |reply|
 898			reply.allowed_actions = [:next]
 899			reply.command << form.render
 900		}.then { |response|
 901			form.parse(response.form)
 902		}.then { |result|
 903			result.repo.get_or_create(result.target).then { |v|
 904				result.target.stanza_from(result.prompt) if result.prompt
 905
 906				Command.finish { |reply|
 907					reply.command << form.render_result(v)
 908				}
 909			}
 910		}.catch_only(RuntimeError) { |e|
 911			Command.finish(e, type: :error)
 912		}
 913	end
 914}.register(self).then(&CommandList.method(:register))
 915
 916Command.new(
 917	"snikket",
 918	"Launch Snikket Instance",
 919	list_for: ->(customer: nil, **) { customer&.admin? }
 920) {
 921	Command.customer.then do |customer|
 922		raise AuthError, "You are not an admin" unless customer&.admin?
 923
 924		Command.reply { |reply|
 925			reply.allowed_actions = [:next]
 926			reply.command << FormTemplate.render("snikket_launch")
 927		}.then { |response|
 928			domain = response.form.field("domain").value.to_s
 929			IQ_MANAGER.write(Snikket::Launch.new(
 930				nil, CONFIG[:snikket_hosting_api],
 931				domain: domain
 932			)).then do |launched|
 933				Snikket::CustomerInstance.for(customer, domain, launched)
 934			end
 935		}.then { |instance|
 936			Command.finish do |reply|
 937				reply.command << FormTemplate.render(
 938					"snikket_launched",
 939					instance: instance
 940				)
 941			end
 942		}
 943	end
 944}.register(self).then(&CommandList.method(:register))
 945
 946Command.new(
 947	"stop snikket",
 948	"STOP Snikket Instance",
 949	list_for: ->(customer: nil, **) { customer&.admin? }
 950) {
 951	Command.customer.then do |customer|
 952		raise AuthError, "You are not an admin" unless customer&.admin?
 953
 954		Command.reply { |reply|
 955			reply.allowed_actions = [:next]
 956			reply.command << FormTemplate.render("snikket_stop")
 957		}.then { |response|
 958			instance_id = response.form.field("instance_id").value.to_s
 959			IQ_MANAGER.write(Snikket::Stop.new(
 960				nil, CONFIG[:snikket_hosting_api],
 961				instance_id: instance_id
 962			))
 963		}.then { |iq|
 964			Command.finish(iq.to_s)
 965		}
 966	end
 967}.register(self).then(&CommandList.method(:register))
 968
 969Command.new(
 970	"delete snikket",
 971	"DELETE Snikket Instance",
 972	list_for: ->(customer: nil, **) { customer&.admin? }
 973) {
 974	Command.customer.then do |customer|
 975		raise AuthError, "You are not an admin" unless customer&.admin?
 976
 977		Command.reply { |reply|
 978			reply.allowed_actions = [:next]
 979			reply.command << FormTemplate.render("snikket_delete")
 980		}.then { |response|
 981			instance_id = response.form.field("instance_id").value.to_s
 982			IQ_MANAGER.write(Snikket::Delete.new(
 983				nil, CONFIG[:snikket_hosting_api],
 984				instance_id: instance_id
 985			))
 986		}.then { |iq|
 987			Command.finish(iq.to_s)
 988		}
 989	end
 990}.register(self).then(&CommandList.method(:register))
 991
 992Command.new(
 993	"find snikket",
 994	"Lookup Snikket Instance",
 995	list_for: ->(customer: nil, **) { customer&.admin? }
 996) {
 997	Command.customer.then do |customer|
 998		raise AuthError, "You are not an admin" unless customer&.admin?
 999
1000		Command.reply { |reply|
1001			reply.allowed_actions = [:next]
1002			reply.command << FormTemplate.render("snikket_launch")
1003		}.then { |response|
1004			domain = response.form.field("domain").value.to_s
1005			IQ_MANAGER.write(Snikket::DomainInfo.new(
1006				nil, CONFIG[:snikket_hosting_api],
1007				domain: domain
1008			))
1009		}.then { |instance|
1010			Command.finish do |reply|
1011				reply.command << FormTemplate.render(
1012					"snikket_result",
1013					instance: instance
1014				)
1015			end
1016		}
1017	end
1018}.register(self).then(&CommandList.method(:register))
1019
1020def reply_with_note(iq, text, type: :info)
1021	reply = iq.reply
1022	reply.status = :completed
1023	reply.note_type = type
1024	reply.note_text = text
1025
1026	self << reply
1027end
1028
1029Command.new(
1030	"https://ns.cheogram.com/sgx/jid-switch",
1031	"Change JID",
1032	list_for: lambda { |customer: nil, from_jid: nil, **|
1033		customer || from_jid.to_s =~ /onboarding.cheogram.com/
1034	},
1035	customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
1036) {
1037	Command.customer.then { |customer|
1038		Command.reply { |reply|
1039			reply.command << FormTemplate.render("jid_switch")
1040		}.then { |response|
1041			new_jid = response.form.field("jid").value
1042			repo = Command.execution.customer_repo
1043			repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
1044				.then { |cust|
1045					next EMPromise.reject("Customer Already Exists") if cust
1046
1047					repo.change_jid(customer, new_jid)
1048				}
1049		}.then {
1050			StatsD.increment("changejid.completed")
1051			jid = ProxiedJID.new(customer.jid).unproxied
1052			if jid.domain == CONFIG[:onboarding_domain]
1053				CustomerRepo.new.find(customer.customer_id).then do |cust|
1054					WelcomeMessage.new(cust, customer.registered?.phone).welcome
1055				end
1056			end
1057			Command.finish { |reply|
1058				reply.note_type = :info
1059				reply.note_text = "Customer JID Changed"
1060			}
1061		}
1062	}
1063}.register(self).then(&CommandList.method(:register))
1064
1065Command.new(
1066	"web-register",
1067	"Initiate Register from Web",
1068	list_for: lambda { |from_jid: nil, **|
1069		from_jid&.stripped.to_s == CONFIG[:web_register][:from]
1070	}
1071) {
1072	if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
1073		next EMPromise.reject(
1074			Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
1075		)
1076	end
1077
1078	Command.reply { |reply|
1079		reply.command << FormTemplate.render("web_register")
1080	}.then do |iq|
1081		jid = iq.form.field("jid")&.value.to_s.strip
1082		tel = iq.form.field("tel")&.value.to_s.strip
1083		if jid !~ /\./ || jid =~ /\s/
1084			Command.finish("The Jabber ID you entered was not valid.", type: :error)
1085		elsif tel !~ /\A\+\d+\Z/
1086			Command.finish("Invalid telephone number", type: :error)
1087		else
1088			IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
1089				cmd.to = CONFIG[:web_register][:to]
1090				cmd.node = "push-register"
1091				cmd.form.fields = [{ var: "to", value: jid }]
1092				cmd.form.type = "submit"
1093			}).then { |result|
1094				TEL_SELECTIONS.set_tel(result.form.field("from")&.value.to_s.strip, tel)
1095			}.then { Command.finish }
1096		end
1097	end
1098}.register(self).then(&CommandList.method(:register))
1099
1100command sessionid: /./ do |iq|
1101	COMMAND_MANAGER.fulfill(iq)
1102	IQ_MANAGER.fulfill(iq)
1103	true
1104end
1105
1106iq type: [:result, :error] do |iq|
1107	IQ_MANAGER.fulfill(iq)
1108	true
1109end
1110
1111iq type: [:get, :set] do |iq|
1112	StatsD.increment("unknown_iq")
1113
1114	self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
1115end
1116
1117trap(:INT) { EM.stop }
1118trap(:TERM) { EM.stop }
1119EM.run { client.run }