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