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