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