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