diff --git a/sgx_jmp.rb b/sgx_jmp.rb index 32df4997b3b8d58dd7a968485a81d41b9943db46..e102237c5b894975fda9781eb4a3196467048a9c 100644 --- a/sgx_jmp.rb +++ b/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|