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