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