1# frozen_string_literal: true
2
3require "pg/em/connection_pool"
4require "bandwidth-sdk"
5require "bigdecimal"
6require "blather/client/dsl"
7require "date"
8require "dhall"
9require "em-hiredis"
10require "em_promise"
11require "faraday/em_synchrony"
12require "ougai"
13require "ruby-bandwidth-iris"
14require "sentry-ruby"
15require "statsd-instrument"
16
17require_relative "lib/background_log"
18require_relative "lib/utils"
19
20$stdout.sync = true
21LOG = Ougai::Logger.new(BackgroundLog.new($stdout))
22LOG.level = ENV.fetch("LOG_LEVEL", "info")
23LOG.formatter = Ougai::Formatters::Readable.new(
24 nil,
25 nil,
26 plain: !$stdout.isatty
27)
28Blather.logger = LOG
29EM::Hiredis.logger = LOG
30StatsD.logger = LOG
31LOG.info "Starting"
32
33def log
34 Thread.current[:log] || LOG
35end
36
37Sentry.init do |config|
38 config.logger = LOG
39 config.breadcrumbs_logger = [:sentry_logger]
40end
41
42CONFIG = Dhall::Coder
43 .new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
44 .load(
45 "(#{ARGV[0]}) : #{__dir__}/config-schema.dhall",
46 transform_keys: ->(k) { k&.to_sym },
47 timeout: 30
48 )
49WEB_LISTEN =
50 if CONFIG[:web].is_a?(Hash)
51 [CONFIG[:web][:interface], CONFIG[:web][:port]]
52 else
53 [CONFIG[:web]]
54 end
55
56singleton_class.class_eval do
57 include Blather::DSL
58 Blather::DSL.append_features(self)
59end
60
61require_relative "lib/session_manager"
62
63IQ_MANAGER = SessionManager.new(self, :id)
64COMMAND_MANAGER = SessionManager.new(
65 self,
66 :sessionid,
67 timeout: 60 * 60,
68 error_if: ->(s) { s.cancel? }
69)
70
71require_relative "lib/polyfill"
72require_relative "lib/alt_top_up_form"
73require_relative "lib/admin_command"
74require_relative "lib/backend_sgx"
75require_relative "lib/bwmsgsv2_repo"
76require_relative "lib/bandwidth_iris_patch"
77require_relative "lib/bandwidth_tn_order"
78require_relative "lib/bandwidth_tn_repo"
79require_relative "lib/btc_sell_prices"
80require_relative "lib/buy_account_credit_form"
81require_relative "lib/configure_calls_form"
82require_relative "lib/command"
83require_relative "lib/command_list"
84require_relative "lib/customer"
85require_relative "lib/customer_info"
86require_relative "lib/customer_info_form"
87require_relative "lib/customer_repo"
88require_relative "lib/dummy_command"
89require_relative "lib/db_notification"
90require_relative "lib/electrum"
91require_relative "lib/empty_repo"
92require_relative "lib/expiring_lock"
93require_relative "lib/em"
94require_relative "lib/form_to_h"
95require_relative "lib/low_balance"
96require_relative "lib/port_in_order"
97require_relative "lib/patches_for_sentry"
98require_relative "lib/payment_methods"
99require_relative "lib/paypal_done"
100require_relative "lib/migrate_billing"
101require_relative "lib/postgres"
102require_relative "lib/reachability_form"
103require_relative "lib/reachability_repo"
104require_relative "lib/registration"
105require_relative "lib/transaction"
106require_relative "lib/tel_selections"
107require_relative "lib/sim_repo"
108require_relative "lib/sim_order"
109require_relative "lib/edit_sim_nicknames"
110require_relative "lib/snikket"
111require_relative "lib/welcome_message"
112require_relative "web"
113require_relative "lib/statsd"
114
115ELECTRUM = Electrum.new(**CONFIG[:electrum])
116ELECTRUM_BCH = Electrum.new(**CONFIG[:electrum_bch])
117
118LOG.info "Loading scripts from #{__dir__}/redis_lua"
119EM::Hiredis::Client.load_scripts_from("#{__dir__}/redis_lua")
120
121Faraday.default_adapter = :em_synchrony
122BandwidthIris::Client.global_options = {
123 account_id: CONFIG[:creds][:account],
124 client_id: CONFIG[:creds][:client_id],
125 client_secret: CONFIG[:creds][:client_secret]
126}
127Bandwidth.configure do |config|
128 config.client_id = CONFIG[:creds][:client_id]
129 config.client_secret = CONFIG[:creds][:client_secret]
130end
131BANDWIDTH_VOICE = Bandwidth::CallsApi.new
132
133class AuthError < StandardError; end
134
135require_relative "lib/async_braintree"
136BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
137
138def panic(e, hub=nil)
139 log.fatal(
140 "Error raised during event loop: #{e.class}",
141 e
142 )
143 if e.is_a?(::Exception)
144 (hub || Sentry).capture_exception(e, hint: { background: false })
145 else
146 (hub || Sentry).capture_message(e.to_s, hint: { background: false })
147 end
148 exit 1
149end
150
151EM.error_handler(&method(:panic))
152
153require_relative "lib/blather_client"
154@client = BlatherClient.new
155
156setup(
157 CONFIG[:component][:jid],
158 CONFIG[:component][:secret],
159 CONFIG[:server][:host],
160 CONFIG[:server][:port],
161 nil,
162 nil,
163 async: true
164)
165
166# Infer anything we might have been notified about while we were down
167def catchup_notify_low_balance(db)
168 db.query(<<~SQL).each do |c|
169 SELECT customer_id
170 FROM balances INNER JOIN customer_plans USING (customer_id)
171 WHERE balance < 5 AND expires_at > LOCALTIMESTAMP
172 SQL
173 db.query("SELECT pg_notify('low_balance', $1)", c.values)
174 end
175end
176
177def catchup_notify_possible_renewal(db)
178 db.query(<<~SQL).each do |c|
179 SELECT customer_id
180 FROM customer_plans INNER JOIN balances USING (customer_id)
181 WHERE
182 expires_at < LOCALTIMESTAMP
183 AND expires_at >= LOCALTIMESTAMP - INTERVAL '3 months'
184 AND balance >= 5
185 SQL
186 db.query("SELECT pg_notify('possible_renewal', $1)", c.values)
187 end
188end
189
190def setup_sentry_scope(name)
191 Sentry.clone_hub_to_current_thread
192 Sentry.with_scope do |scope|
193 scope.clear_breadcrumbs
194 scope.set_transaction_name(name)
195 Thread.current[:log] = ::LOG.child(transaction: scope.transaction_name)
196 yield scope
197 end
198end
199
200def poll_for_notify(db, repo)
201 db.wait_for_notify_defer.then { |notify|
202 setup_sentry_scope("DB NOTIFY") do
203 repo.find(notify[:extra]).then { |customer|
204 DbNotification.for(notify, customer, repo)
205 }.then(&:call).catch { |e|
206 log.error("Error during poll_for_notify", e)
207 Sentry.capture_exception(e)
208 }.sync
209 end
210 }.then { EM.add_timer(0.5) { poll_for_notify(db, repo) } }
211end
212
213def load_plans_to_db!
214 DB.transaction do
215 DB.exec("TRUNCATE plans")
216 CONFIG[:plans].each do |plan|
217 DB.exec("INSERT INTO plans VALUES ($1)", [plan.to_json])
218 end
219 end
220end
221
222when_ready do
223 log.info "Ready"
224 BLATHER = self
225 REDIS = EM::Hiredis.connect
226 MEMCACHE = EM::P::Memcache.connect
227 BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
228 BCH_SELL_PRICES = BCHSellPrices.new(REDIS, CONFIG[:oxr_app_id])
229 DB = Postgres.connect(dbname: "jmp", size: 5)
230 TEL_SELECTIONS = TelSelections.new
231
232 EMPromise.resolve(nil).then {
233 conn = DB.acquire
234 conn.query("LISTEN low_balance")
235 conn.query("LISTEN possible_renewal")
236 catchup_notify_low_balance(conn)
237 catchup_notify_possible_renewal(conn)
238
239 repo = CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
240 poll_for_notify(conn, repo)
241 }.catch(&method(:panic))
242
243 load_plans_to_db!
244
245 EM.add_periodic_timer(3600) do
246 DB.finish # Clear idle connections
247 ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
248 ping.from = CONFIG[:component][:jid]
249 self << ping
250 end
251
252 Web.run(LOG.child, *WEB_LISTEN)
253end
254
255message to: /\Aaccount@/, body: /./ do |m|
256 StatsD.increment("deprecated_account_bot")
257
258 self << m.reply.tap { |out|
259 out.body = "This bot is deprecated. Please talk to xmpp:cheogram.com"
260 }
261end
262
263FROM_BACKEND =
264 "(?:#{([CONFIG[:sgx]] + CONFIG[:sgx_creds].keys)
265 .map(&Regexp.method(:escape)).join('|')})"
266
267before(
268 :iq,
269 type: [:error, :result],
270 to: /\Acustomer_/,
271 from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
272) { |iq| halt if IQ_MANAGER.fulfill(iq) }
273
274before nil, to: /\Acustomer_/, from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/ do |s|
275 StatsD.increment("stanza_customer")
276
277 Sentry.get_current_scope.set_transaction_name("stanza_customer")
278 CustomerRepo.new(set_user: Sentry.method(:set_user)).find(
279 s.to.node.delete_prefix("customer_")
280 ).then do |customer|
281 # Intentionally called outside filter so ported-in numbers activate here
282 TrustLevelRepo.new.incoming_message(customer, s)
283 ReachabilityRepo::SMS.new
284 .find(customer, s.from.node, stanza: s).then do |reach|
285 reach.filter do
286 customer.stanza_to(s)
287 end
288 end
289 end
290
291 halt
292end
293
294ADDRESSES_NS = "http://jabber.org/protocol/address"
295message(
296 to: /\A#{CONFIG[:component][:jid]}\Z/,
297 from: /(\A|@)#{FROM_BACKEND}(\/|\Z)/
298) do |m|
299 StatsD.increment("inbound_group_text")
300 Sentry.get_current_scope.set_transaction_name("inbound_group_text")
301 log.info "Possible group text #{m.from}"
302
303 address = m.find("ns:addresses", ns: ADDRESSES_NS).first
304 &.find("ns:address", ns: ADDRESSES_NS)
305 &.find { |el| el["jid"].to_s.start_with?("customer_") }
306 pass unless address
307
308 CustomerRepo
309 .new(set_user: Sentry.method(:set_user))
310 .find_by_jid(address["jid"]).then { |customer|
311 TrustLevelRepo.new.incoming_message(customer, m)
312 m.from = m.from.with(domain: CONFIG[:component][:jid])
313 m.to = m.to.with(domain: customer.jid.domain)
314 address["jid"] = customer.jid.to_s
315 BLATHER << m
316 }.catch_only(CustomerRepo::NotFound) { |e|
317 BLATHER << m.as_error("forbidden", :auth, e.message)
318 }
319end
320
321# Ignore groupchat messages
322# Especially if we have the component join MUC for notifications
323message(type: :groupchat) { true }
324
325def billable_message(m)
326 return false if m.to.node == "+12266669977"
327
328 b = m.body
329 b && !b.empty? || m.find("ns:x", ns: OOB.registered_ns).first
330end
331
332def expired_guard(customer)
333 return if !customer.plan_name || customer.active?
334
335 raise CustomerExpired, "Your account is expired, please top up"
336end
337
338class OverLimit < StandardError
339 def initialize(customer, usage)
340 super("Please contact support: https://jmp.chat/faq#support")
341 @customer = customer
342 @usage = usage
343 end
344
345 def notify_admin
346 ExpiringLock.new("jmp_usage_notify-#{@customer.customer_id}").with do
347 BLATHER.join(CONFIG[:notify_admin], "sgx-jmp")
348 BLATHER.say(
349 CONFIG[:notify_admin], "#{@customer.customer_id} has used " \
350 "#{@usage[:today]} messages today (global #{@usage[:body]} this body)",
351 :groupchat
352 )
353 end
354 end
355end
356
357class CustomerExpired < StandardError; end
358
359CONFIG[:direct_targets].each do |(tel, jid)|
360 customer_repo = CustomerRepo.new(
361 sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
362 set_user: Sentry.method(:set_user)
363 )
364
365 message to: /\A#{Regexp.escape(tel)}@#{CONFIG[:component][:jid]}\/?/ do |m|
366 customer_repo.find_by_jid(m.from.stripped).then { |customer|
367 customer.stanza_from(m)
368 }.catch_only(CustomerRepo::NotFound) {
369 # This should not happen, but let's still get the message
370 # to support at least if it does
371 m.from = ProxiedJID.proxy(m.from, CONFIG[:component][:jid])
372 m.to = jid
373 BLATHER << m
374 }
375 end
376end
377
378CONFIG[:direct_sources].each do |(jid, tel)|
379 customer_repo = CustomerRepo.new(
380 sgx_repo: TrivialBackendSgxRepo.new(jid: jid),
381 set_user: Sentry.method(:set_user)
382 )
383 message to: /\Acustomer_/, from: /\A#{Regexp.escape(jid)}\/?/ do |m|
384 customer_repo.find(m.to.node.delete_prefix("customer_")).then { |customer|
385 m.from = "#{tel}@sgx-jmp" # stanza_to will fix domain
386 customer.stanza_to(m)
387 }.catch_only(CustomerRepo::NotFound) { |e|
388 BLATHER << m.as_error("item-not-found", :cancel, e.message)
389 }
390 end
391end
392
393def find_from_and_to_customer(from, to)
394 (
395 # TODO: group text?
396 to.node ? CustomerRepo.new.find_by_tel(to.node) : EMPromise.resolve(nil)
397 ).catch_only(CustomerRepo::NotFound) { nil }.then { |target_customer|
398 sgx_repo = target_customer ? Bwmsgsv2Repo.new : TrivialBackendSgxRepo.new
399 EMPromise.all([
400 CustomerRepo.new(set_user: Sentry.method(:set_user), sgx_repo: sgx_repo)
401 .find_by_jid(from.stripped),
402 target_customer
403 ])
404 }
405end
406
407def usage_guard(m, to, customer, trust_level, usage)
408 return if trust_level.send_message?(to, usage[:today]) && usage[:body] < 5
409
410 log.warn "OverLimit", m
411
412 if usage[:body] >= 5 && (m.body.to_s.length < 30 || usage[:body] < 10)
413 OverLimit.new(customer, usage).notify_admin
414 return
415 end
416
417 raise OverLimit.new(customer, usage)
418end
419
420message do |m|
421 StatsD.increment("message")
422
423 find_from_and_to_customer(m.from, m.to).then { |(customer, target_customer)|
424 if target_customer && customer.registered?
425 m.from = "#{customer.registered?.phone}@sgx-jmp"
426 next target_customer.stanza_to(m)
427 end
428
429 next customer.stanza_from(m) unless billable_message(m)
430
431 expired_guard(customer)
432
433 EMPromise.all([
434 TrustLevelRepo.new.find(customer),
435 customer.incr_message_usage(1, m.body)
436 ]).then { |(tl, usage)|
437 usage_guard(m, m.to.node.to_s, customer, tl, usage)
438 }.then do
439 customer.stanza_from(m)
440 end
441 }.catch_only(OverLimit) { |e|
442 e.notify_admin
443 BLATHER << m.as_error("policy-violation", :wait, e.message)
444 }.catch_only(CustomerRepo::NotFound, CustomerExpired) { |e|
445 BLATHER << m.as_error("forbidden", :auth, e.message)
446 }
447end
448
449disco_info to: Blather::JID.new(CONFIG[:component][:jid]) do |iq|
450 reply = iq.reply
451 reply.identities = [{
452 name: "JMP.chat",
453 type: "sms",
454 category: "gateway"
455 }]
456 reply.features = [
457 "http://jabber.org/protocol/disco#info",
458 "http://jabber.org/protocol/commands"
459 ]
460 form = Blather::Stanza::X.find_or_create(reply.query)
461 form.type = "result"
462 form.fields = [
463 {
464 var: "FORM_TYPE",
465 type: "hidden",
466 value: "http://jabber.org/network/serverinfo"
467 }
468 ] + CONFIG[:xep0157]
469 self << reply
470end
471
472disco_info do |iq|
473 reply = iq.reply
474 reply.identities = [{
475 name: "JMP.chat",
476 type: "sms",
477 category: "client"
478 }]
479 reply.features = [
480 "urn:xmpp:receipts"
481 ]
482 self << reply
483end
484
485disco_items(
486 to: Blather::JID.new(CONFIG[:component][:jid]),
487 node: "http://jabber.org/protocol/commands"
488) do |iq|
489 StatsD.increment("command_list")
490
491 reply = iq.reply
492 reply.node = "http://jabber.org/protocol/commands"
493
494 CustomerRepo.new(
495 sgx_repo: Bwmsgsv2Repo.new,
496 set_user: Sentry.method(:set_user)
497 ).find_by_jid(
498 iq.from.stripped
499 ).catch {
500 nil
501 }.then { |customer|
502 CommandList.for(customer, iq.from)
503 }.then { |list|
504 reply.items = list.map { |item|
505 Blather::Stanza::DiscoItems::Item.new(
506 iq.to,
507 item[:node],
508 item[:name]
509 )
510 }
511 self << reply
512 }
513end
514
515iq "/iq/ns:services", ns: "urn:xmpp:extdisco:2" do |iq|
516 StatsD.increment("extdisco")
517
518 reply = iq.reply
519 reply << Nokogiri::XML::Builder.new {
520 services(xmlns: "urn:xmpp:extdisco:2") do
521 service(
522 type: "sip",
523 host: CONFIG[:sip_host]
524 )
525 end
526 }.doc.root
527
528 self << reply
529end
530
531Command.new(
532 "jabber:iq:register",
533 "Register",
534 list_for: ->(*) { true },
535 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
536) {
537 google_play_userid = if Command.execution.iq.from.domain == "cheogram.com"
538 Command.execution.iq.command.find(
539 "./ns:userId", ns: "https://ns.cheogram.com/google-play"
540 )&.first&.content
541 end
542 Command.customer.catch_only(CustomerRepo::NotFound) {
543 Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Customer.create"))
544 Command.execution.customer_repo.create(Command.execution.iq.from.stripped)
545 }.then { |customer|
546 Sentry.add_breadcrumb(Sentry::Breadcrumb.new(message: "Registration.for"))
547 Registration.for(customer, google_play_userid, TEL_SELECTIONS).then(&:write)
548 }.then {
549 StatsD.increment("registration.completed")
550 }.catch_only(Command::Execution::FinalStanza) do |e|
551 StatsD.increment("registration.completed")
552 EMPromise.reject(e)
553 end
554}.register(self).then(&CommandList.method(:register))
555
556Command.new(
557 "info",
558 "👤 Show Account Info",
559 list_for: ->(*) { true },
560 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
561) {
562 Command.customer.then(&CustomerInfo.method(:for)).then do |info|
563 Command.finish do |reply|
564 reply.command << info.form
565 end
566 end
567}.register(self).then(&CommandList.method(:register))
568
569Command.new(
570 "cdrs",
571 "📲 Show Call Logs"
572) {
573 report_for = ((Date.today << 1)..Date.today)
574
575 Command.customer.then { |customer|
576 CDRRepo.new.find_range(customer, report_for)
577 }.then do |cdrs|
578 Command.finish do |reply|
579 reply.command << FormTemplate.render("customer_cdr", cdrs: cdrs)
580 end
581 end
582}.register(self).then(&CommandList.method(:register))
583
584Command.new(
585 "transactions",
586 "🧾 Show Transactions",
587 list_for: ->(customer:, **) { !!customer&.currency }
588) {
589 Command.customer.then(&:transactions).then do |txs|
590 Command.finish do |reply|
591 reply.command << FormTemplate.render("transactions", transactions: txs)
592 end
593 end
594}.register(self).then(&CommandList.method(:register))
595
596Command.new(
597 "configure calls",
598 "📞 Configure Calls",
599 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
600) {
601 Command.customer.then do |customer|
602 cc_form = ConfigureCallsForm.new(customer)
603 Command.reply { |reply|
604 reply.allowed_actions = [:next]
605 reply.command << cc_form.render
606 }.then { |iq|
607 EMPromise.all(cc_form.parse(iq.form).map { |k, v|
608 Command.execution.customer_repo.public_send("put_#{k}", customer, v)
609 })
610 }.then { Command.finish("Configuration saved!") }
611 end
612}.register(self).then(&CommandList.method(:register))
613
614Command.new(
615 "ogm",
616 "⏺️ Record Voicemail Greeting",
617 list_for: ->(fwd: nil, **) { fwd&.voicemail_enabled? },
618 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
619) {
620 Command.customer.then do |customer|
621 customer.fwd.create_call(CONFIG[:creds][:account]) do |cc|
622 cc.from = customer.registered?.phone
623 cc.application_id = CONFIG[:sip][:app]
624 cc.answer_url = "#{CONFIG[:web_root]}/ogm/start?" \
625 "customer_id=#{customer.customer_id}"
626 end
627 Command.finish("You will now receive a call.")
628 end
629}.register(self).then(&CommandList.method(:register))
630
631Command.new(
632 "migrate billing",
633 "🏦 Switch to new billing",
634 list_for: ->(tel:, customer:, **) { tel && !customer&.currency },
635 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
636) {
637 Command.customer.then(&MigrateBilling.method(:new)).then(&:write)
638}.register(self).then(&CommandList.method(:register))
639
640Command.new(
641 "credit cards",
642 "💳 Credit Card Settings and Management",
643 list_for: ->(customer:, **) { !!customer&.currency }
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(
677 AmountTooHighError,
678 AmountTooLowError
679 ) do |e|
680 Command.finish(e.message, type: :error)
681 end
682}.register(self).then(&CommandList.method(:register))
683
684Command.new(
685 "alt top up",
686 "🪙 Buy Account Credit by Bitcoin, Mail, or Interac e-Transfer",
687 list_for: ->(customer:, **) { !!customer&.currency }
688) {
689 Command.customer.then { |customer|
690 AltTopUpForm.for(customer)
691 }.then do |alt_form|
692 Command.reply { |reply|
693 reply.allowed_actions = [:complete]
694 reply.command << alt_form.form
695 }.then do |iq|
696 Command.finish { |reply| alt_form.parse(iq.form).action(reply) }
697 end
698 end
699}.register(self).then(&CommandList.method(:register))
700
701Command.new(
702 "plan settings",
703 "📝 Manage your plan, including overage limits",
704 list_for: ->(customer:, **) { !!customer&.currency }
705) {
706 Command.customer.then { |customer|
707 EMPromise.all([
708 REDIS.get("jmp_customer_monthly_data_limit-#{customer.customer_id}"),
709 SIMRepo.new.owned_by(customer)
710 ]).then { |(limit, sims)| [customer, sims, limit] }
711 }.then do |(customer, sims, limit)|
712 Command.reply { |reply|
713 reply.allowed_actions = [:next]
714 reply.command << FormTemplate.render(
715 "plan_settings", customer: customer, sims: sims, data_limit: limit
716 )
717 }.then { |iq|
718 kwargs = {
719 monthly_overage_limit: iq.form.field("monthly_overage_limit")&.value,
720 monthly_data_limit: iq.form.field("monthly_data_limit")&.value
721 }.compact
722 Command.execution.customer_repo.put_monthly_limits(customer, **kwargs)
723 }.then { Command.finish("Configuration saved!") }
724 end
725}.register(self).then(&CommandList.method(:register))
726
727Command.new(
728 "referral codes",
729 "👥 Refer a friend for free credit",
730 list_for: ->(customer:, **) { !!customer&.currency }
731) {
732 repo = InvitesRepo.new
733 Command.customer.then { |customer|
734 EMPromise.all([
735 repo.find_or_create_group_code(customer.customer_id),
736 repo.unused_invites(customer)
737 ])
738 }.then do |(group_code, invites)|
739 if invites.empty?
740 Command.finish(
741 "This code will provide credit equivalent to one month of service " \
742 "to anyone after they sign up and pay: #{group_code}\n\n" \
743 "You will receive credit equivalent to one month of service once " \
744 "their payment clears."
745 )
746 else
747 Command.finish do |reply|
748 reply.command << FormTemplate.render(
749 "codes",
750 invites: invites,
751 group_code: group_code
752 )
753 end
754 end
755 end
756}.register(self).then(&CommandList.method(:register))
757
758# Assumes notify_from is a direct target
759notify_to = CONFIG[:direct_targets].fetch(
760 Blather::JID.new(CONFIG[:notify_from]).node.to_sym
761)
762
763Command.new(
764 "sims",
765 "📶 (e)SIM Details",
766 list_for: ->(customer:, **) { CONFIG[:keepgo] && !!customer&.currency },
767 customer_repo: CustomerRepo.new(
768 sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
769 )
770) {
771 Command.customer.then { |customer|
772 EMPromise.all([customer, SIMRepo.new.owned_by(customer)])
773 }.then do |(customer, sims)|
774 Command.reply { |reply|
775 reply.command << FormTemplate.render("sim_details", sims: sims)
776 }.then { |iq|
777 case iq.form.field("http://jabber.org/protocol/commands#actions")&.value
778 when "order-sim"
779 SIMOrder.for(customer, **CONFIG.dig(:sims, :sim, customer.currency))
780 when "order-esim"
781 SIMOrder::ESIM.for(
782 customer, **CONFIG.dig(:sims, :esim, customer.currency)
783 )
784 when "edit-nicknames"
785 EditSimNicknames.new(customer, sims)
786 else
787 Command.finish
788 end
789 }.then(&:process)
790 end
791}.register(self).then(&CommandList.method(:register))
792
793Command.new(
794 "subaccount",
795 "➕️ Create a new phone number linked to this balance",
796 list_for: lambda do |customer:, **|
797 !!customer&.currency &&
798 customer&.billing_customer_id == customer&.customer_id
799 end
800) {
801 cheogram = Command.execution.iq.from.resource =~ /\ACheogram/
802 Command.customer.then do |customer|
803 ParentCodeRepo.new.find_or_create(customer.customer_id).then do |code|
804 Command.finish { |reply|
805 reply.command << FormTemplate.render(
806 "subaccount", code: code, cheogram: cheogram
807 )
808 }
809 end
810 end
811}.register(self).then(&CommandList.method(:register))
812
813Command.new(
814 "reset sip account",
815 "☎️ Create or Reset SIP Account",
816 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
817) {
818 Command.customer.then { |customer|
819 TrustLevelRepo.new.find(customer).then { |tl| [customer, tl] }
820 }.then do |(customer, tl)|
821 raise "Please contact JMP support" unless tl.support_call?(0, 1, :outbound)
822
823 sip_account = customer.reset_sip_account
824 Command.reply { |reply|
825 reply.allowed_actions = [:next]
826 form = sip_account.form
827 form.type = :form
828 form.fields += [{
829 type: :boolean, var: "change_fwd",
830 label: "Should inbound calls forward to this SIP account?"
831 }]
832 reply.command << form
833 }.then do |fwd|
834 if ["1", "true"].include?(fwd.form.field("change_fwd")&.value.to_s)
835 Command.execution.customer_repo.put_fwd(
836 customer,
837 customer.fwd.with(uri: sip_account.uri)
838 ).then { Command.finish("Inbound calls will now forward to SIP.") }
839 else
840 Command.finish
841 end
842 end
843 end
844}.register(self).then(&CommandList.method(:register))
845
846Command.new(
847 "lnp",
848 "#️⃣ Port in your number from another carrier",
849 list_for: ->(**) { true },
850 customer_repo: CustomerRepo.new(
851 sgx_repo: TrivialBackendSgxRepo.new(jid: notify_to)
852 )
853) {
854 Command.customer.then do |customer|
855 Command.reply { |reply|
856 reply.allowed_actions = [:next]
857 reply.command << FormTemplate.render("lnp")
858 }.then { |iq|
859 PortInOrder.parse(customer, iq.form).complete_with do |form|
860 Command.reply { |reply|
861 reply.allowed_actions = [:next]
862 reply.command << form
863 }.then(&:form)
864 end
865 }.then do |order|
866 unless order.already_inservice?
867 order_id = BandwidthIris::PortIn.create(order.to_h)[:order_id]
868 customer.stanza_from(Blather::Stanza::Message.new(
869 "",
870 order.message(order_id)
871 ))
872 Command.finish(
873 "Your port-in request has been accepted, " \
874 "support will contact you with next steps"
875 )
876 end
877 end
878 end
879}.register(self).then(&CommandList.method(:register))
880
881Command.new(
882 "set-port-out-pin",
883 "🔐 Set Port-out PIN",
884 list_for: lambda do |sgx_commands:, **|
885 sgx_commands.any? { |item|
886 item.node == "set-port-out-pin"
887 }
888 end
889) {
890 Command.customer.then do |customer|
891 Command.reply { |reply|
892 reply.command << FormTemplate.render("set_port_out_pin")
893 }.then { |iq|
894 pin = iq.form.field("pin")&.value.to_s
895 confirm_pin = iq.form.field("confirm_pin")&.value.to_s
896
897 unless pin.match?(/\A[\w\d]{4,10}\Z/)
898 raise "PIN must be between 4 and 10 alphanumeric characters."
899 end
900
901 raise "PIN and confirm PIN must match." unless pin == confirm_pin
902
903 customer.port_out_pin.set(pin)
904 }.then {
905 Command.finish("Your port-out PIN has been set.")
906 }.catch_only(BackendSgx::CanceledError) do |e|
907 Command.finish(e.message, status: :canceled)
908 end
909 end
910}.register(self).then(&CommandList.method(:register))
911
912Command.new(
913 "terminate account",
914 "❌ Cancel your account and terminate your phone number",
915 list_for: ->(**) { false },
916 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
917) {
918 Command.reply { |reply|
919 reply.allowed_actions = [:next]
920 reply.note_text = "Press next to confirm your account termination."
921 }.then { Command.customer }.then { |customer|
922 AdminAction::CancelCustomer.call(
923 customer,
924 customer_repo: Command.execution.customer_repo
925 )
926 }.then do
927 Command.finish("Account cancelled")
928 end
929}.register(self).then(&CommandList.method(:register))
930
931Command.new(
932 "customer info",
933 "Show Customer Info",
934 list_for: ->(customer: nil, **) { customer&.admin? }
935) {
936 Command.customer.then do |customer|
937 raise AuthError, "You are not an admin" unless customer&.admin?
938
939 customer_repo = CustomerRepo.new(
940 sgx_repo: Bwmsgsv2Repo.new,
941 bandwidth_tn_repo: EmptyRepo.new(BandwidthTnRepo.new) # No CNAM in admin
942 )
943
944 AdminCommand::NoUser.new(customer_repo).start
945 end
946}.register(self).then(&CommandList.method(:register))
947
948Command.new(
949 "reachability",
950 "Test Reachability",
951 list_for: ->(customer: nil, **) { customer&.admin? }
952) {
953 Command.customer.then do |customer|
954 raise AuthError, "You are not an admin" unless customer&.admin?
955
956 form = ReachabilityForm.new(CustomerRepo.new)
957
958 Command.reply { |reply|
959 reply.allowed_actions = [:next]
960 reply.command << form.render
961 }.then { |response|
962 form.parse(response.form)
963 }.then { |result|
964 result.repo.get_or_create(result.target).then { |v|
965 result.target.stanza_from(result.prompt) if result.prompt
966
967 Command.finish { |reply|
968 reply.command << form.render_result(v)
969 }
970 }
971 }.catch_only(RuntimeError) { |e|
972 Command.finish(e, type: :error)
973 }
974 end
975}.register(self).then(&CommandList.method(:register))
976
977Command.new(
978 "snikket",
979 "Launch Snikket Instance",
980 list_for: ->(customer: nil, **) { customer&.admin? }
981) {
982 Command.customer.then do |customer|
983 raise AuthError, "You are not an admin" unless customer&.admin?
984
985 Command.reply { |reply|
986 reply.allowed_actions = [:next]
987 reply.command << FormTemplate.render("snikket_launch")
988 }.then { |response|
989 domain = response.form.field("domain").value.to_s
990 test_instance = response.form.field("test_instance")&.value.to_s
991 IQ_MANAGER.write(Snikket::Launch.new(
992 nil, CONFIG[:snikket_hosting_api],
993 domain: domain, test_instance: test_instance
994 )).then do |launched|
995 Snikket::CustomerInstance.for(customer, domain, launched)
996 end
997 }.then { |instance|
998 Command.finish do |reply|
999 reply.command << FormTemplate.render(
1000 "snikket_launched",
1001 instance: instance
1002 )
1003 end
1004 }
1005 end
1006}.register(self).then(&CommandList.method(:register))
1007
1008Command.new(
1009 "stop snikket",
1010 "STOP Snikket Instance",
1011 list_for: ->(customer: nil, **) { customer&.admin? }
1012) {
1013 Command.customer.then do |customer|
1014 raise AuthError, "You are not an admin" unless customer&.admin?
1015
1016 Command.reply { |reply|
1017 reply.allowed_actions = [:next]
1018 reply.command << FormTemplate.render("snikket_stop")
1019 }.then { |response|
1020 instance_id = response.form.field("instance_id").value.to_s
1021 IQ_MANAGER.write(Snikket::Stop.new(
1022 nil, CONFIG[:snikket_hosting_api],
1023 instance_id: instance_id
1024 ))
1025 }.then { |iq|
1026 Command.finish(iq.to_s)
1027 }
1028 end
1029}.register(self).then(&CommandList.method(:register))
1030
1031Command.new(
1032 "delete snikket",
1033 "DELETE Snikket Instance",
1034 list_for: ->(customer: nil, **) { customer&.admin? }
1035) {
1036 Command.customer.then do |customer|
1037 raise AuthError, "You are not an admin" unless customer&.admin?
1038
1039 Command.reply { |reply|
1040 reply.allowed_actions = [:next]
1041 reply.command << FormTemplate.render("snikket_delete")
1042 }.then { |response|
1043 instance_id = response.form.field("instance_id").value.to_s
1044 IQ_MANAGER.write(Snikket::Delete.new(
1045 nil, CONFIG[:snikket_hosting_api],
1046 instance_id: instance_id
1047 ))
1048 }.then { |iq|
1049 Command.finish(iq.to_s)
1050 }
1051 end
1052}.register(self).then(&CommandList.method(:register))
1053
1054Command.new(
1055 "find snikket",
1056 "Lookup Snikket Instance",
1057 list_for: ->(customer: nil, **) { customer&.admin? }
1058) {
1059 Command.customer.then do |customer|
1060 raise AuthError, "You are not an admin" unless customer&.admin?
1061
1062 Command.reply { |reply|
1063 reply.allowed_actions = [:next]
1064 reply.command << FormTemplate.render("snikket_launch")
1065 }.then { |response|
1066 domain = response.form.field("domain").value.to_s
1067 IQ_MANAGER.write(Snikket::DomainInfo.new(
1068 nil, CONFIG[:snikket_hosting_api],
1069 domain: domain
1070 ))
1071 }.then { |instance|
1072 Command.finish do |reply|
1073 reply.command << FormTemplate.render(
1074 "snikket_result",
1075 instance: instance
1076 )
1077 end
1078 }
1079 end
1080}.register(self).then(&CommandList.method(:register))
1081
1082def reply_with_note(iq, text, type: :info)
1083 reply = iq.reply
1084 reply.status = :completed
1085 reply.note_type = type
1086 reply.note_text = text
1087
1088 self << reply
1089end
1090
1091Command.new(
1092 "https://ns.cheogram.com/sgx/jid-switch",
1093 "Change JID",
1094 list_for: lambda { |customer: nil, from_jid: nil, **|
1095 customer || from_jid.to_s =~ Regexp.new(CONFIG[:onboarding_domain])
1096 },
1097 customer_repo: CustomerRepo.new(sgx_repo: Bwmsgsv2Repo.new)
1098) {
1099 Command.customer.then { |customer|
1100 Command.reply { |reply|
1101 reply.command << FormTemplate.render("jid_switch")
1102 }.then { |response|
1103 new_jid = response.form.field("jid").value
1104 repo = Command.execution.customer_repo
1105 repo.find_by_jid(new_jid).catch_only(CustomerRepo::NotFound) { nil }
1106 .then { |cust|
1107 next EMPromise.reject("Customer Already Exists") if cust
1108
1109 repo.change_jid(customer, new_jid)
1110 }
1111 }.then {
1112 StatsD.increment("changejid.completed")
1113 jid = ProxiedJID.new(customer.jid).unproxied
1114 if jid.domain == CONFIG[:onboarding_domain]
1115 CustomerRepo.new.find(customer.customer_id).then do |cust|
1116 WelcomeMessage.for(cust, customer.registered?.phone).then(&:welcome)
1117 end
1118 end
1119 Command.finish { |reply|
1120 reply.note_type = :info
1121 reply.note_text = "Customer JID Changed"
1122 }
1123 }
1124 }
1125}.register(self).then(&CommandList.method(:register))
1126
1127Command.new(
1128 "web-register",
1129 "Initiate Register from Web",
1130 list_for: lambda { |from_jid: nil, **|
1131 from_jid&.stripped.to_s == CONFIG[:web_register][:from]
1132 }
1133) {
1134 if Command.execution.iq.from.stripped != CONFIG[:web_register][:from]
1135 next EMPromise.reject(
1136 Command::Execution::FinalStanza.new(iq.as_error("forbidden", :auth))
1137 )
1138 end
1139
1140 Command.reply { |reply|
1141 reply.command << FormTemplate.render("web_register")
1142 }.then do |iq|
1143 jid = iq.form.field("jid")&.value.to_s.strip
1144 tel = iq.form.field("tel")&.value.to_s.strip
1145 if jid !~ /\./ || jid =~ /\s/
1146 Command.finish("The Jabber ID you entered was not valid.", type: :error)
1147 elsif tel !~ /\A\+\d+\Z/
1148 Command.finish("Invalid telephone number", type: :error)
1149 else
1150 IQ_MANAGER.write(Blather::Stanza::Iq::Command.new.tap { |cmd|
1151 cmd.to = CONFIG[:web_register][:to]
1152 cmd.node = "push-register"
1153 cmd.form.fields = [{ var: "to", value: jid }]
1154 cmd.form.type = "submit"
1155 }).then { |result|
1156 TEL_SELECTIONS.set_tel(result.form.field("from")&.value.to_s.strip, tel)
1157 }.then { Command.finish }
1158 end
1159 end
1160}.register(self).then(&CommandList.method(:register))
1161
1162command sessionid: /./ do |iq|
1163 COMMAND_MANAGER.fulfill(iq)
1164 IQ_MANAGER.fulfill(iq)
1165 true
1166end
1167
1168iq type: [:result, :error] do |iq|
1169 IQ_MANAGER.fulfill(iq)
1170 true
1171end
1172
1173iq type: [:get, :set] do |iq|
1174 StatsD.increment("unknown_iq")
1175
1176 self << Blather::StanzaError.new(iq, "feature-not-implemented", :cancel)
1177end
1178
1179trap(:INT) { EM.stop }
1180trap(:TERM) { EM.stop }
1181EM.run { client.run }