Short circuit sending to any JMP customer

Stephen Paul Weber created

No matter which route they use.

Also doesn't count internal messages for billing purposes or block them
if you're expired, etc.

Change summary

sgx_jmp.rb | 60 +++++++++++++++++++++++++++++++++++--------------------
1 file changed, 38 insertions(+), 22 deletions(-)

Detailed changes

sgx_jmp.rb 🔗

@@ -372,34 +372,50 @@ CONFIG[:direct_sources].each do |(jid, tel)|
 	end
 end
 
+def find_from_and_to_customer(from, to)
+	(
+		# TODO: group text?
+		to.node ? CustomerRepo.new.find_by_tel(o.node) : EMPromise.resolve(nil)
+	).catch_only(Customer::NotFound) { nil }.then { |target_customer|
+		sgx_repo = target_customer ? Bwmsgsv2Repo.new : TrivialBackendSgxRepo.new
+		EMPromise.all([
+			CustomerRepo.new(set_user: Sentry.method(:set_user), sgx_repo: sgx_repo)
+				.find_by_jid(from.stripped),
+			target_customer
+		])
+	}
+end
+
 message do |m|
 	StatsD.increment("message")
 
 	today = Time.now.utc.to_date
-	CustomerRepo.new(set_user: Sentry.method(:set_user))
-		.find_by_jid(m.from.stripped).then { |customer|
-			next customer.stanza_from(m) unless billable_message(m)
+	find_from_and_to_customer(m.from, m.to).then { |(customer, target_customer)|
+		if target_customer && customer.registered?
+			m.from = "#{customer.registered?.phone}@sgx-jmp"
+			next target_customer.stanza_to(m)
+		end
 
-			if customer.plan_name && !customer.active?
-				raise CustomerExpired, "Your account is expired, please top up"
-			end
+		next customer.stanza_from(m) unless billable_message(m)
 
-			EMPromise.all([
-				REDIS.exists("jmp_customer_spam_detected-#{customer.customer_id}"),
-				TrustLevelRepo.new.find(customer),
-				customer.message_usage((today..today))
-			]).then { |(spam, tl, usage)|
-				raise OverLimit.new(customer, "SPAM DETECTED") if spam.to_i == 1
-				raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
-			}.then do
-				EMPromise.all([customer.incr_message_usage, customer.stanza_from(m)])
-			end
-		}.catch_only(OverLimit) { |e|
-			e.notify_admin
-			BLATHER << m.as_error("policy-violation", :wait, e.message)
-		}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
-			BLATHER << m.as_error("forbidden", :auth, e.message)
-		}
+		if customer.plan_name && !customer.active?
+			raise CustomerExpired, "Your account is expired, please top up"
+		end
+
+		EMPromise.all([
+			TrustLevelRepo.new.find(customer),
+			customer.message_usage((today..today))
+		]).then { |(tl, usage)|
+			raise OverLimit.new(customer, usage) unless tl.send_message?(usage)
+		}.then do
+			EMPromise.all([customer.incr_message_usage, customer.stanza_from(m)])
+		end
+	}.catch_only(OverLimit) { |e|
+		e.notify_admin
+		BLATHER << m.as_error("policy-violation", :wait, e.message)
+	}.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
+		BLATHER << m.as_error("forbidden", :auth, e.message)
+	}
 end
 
 disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|