From b36baf26eb965414424d0095d6f28d526b575b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A2u=20Cao?= Date: Sun, 21 Apr 2024 10:02:17 +0200 Subject: [PATCH] Refactor WebhooksController --- app/controllers/webhooks_controller.rb | 65 +++++++++++++++----------- 1 file changed, 38 insertions(+), 27 deletions(-) diff --git a/app/controllers/webhooks_controller.rb b/app/controllers/webhooks_controller.rb index e3657c1..446c39e 100644 --- a/app/controllers/webhooks_controller.rb +++ b/app/controllers/webhooks_controller.rb @@ -2,45 +2,56 @@ class WebhooksController < ApplicationController skip_forgery_protection before_action :authorize_request + before_action :process_payload def lndhub - begin - payload = JSON.parse(request.body.read, symbolize_names: true) - head :no_content and return unless payload[:type] == "incoming" - rescue - head :unprocessable_entity and return - end + @user = User.find_by!(ln_account: @payload[:user_login]) - user = User.find_by!(ln_account: payload[:user_login]) - notify = user.preferences[:lightning_notify_sats_received] - case notify - when "xmpp" - notify_xmpp(user.address, payload[:amount], payload[:memo]) - when "email" - NotificationMailer.with(user: user, amount_sats: payload[:amount]) - .lightning_sats_received.deliver_later - end + send_notifications head :ok end private - # TODO refactor into mailer-like generic class/service - def notify_xmpp(address, amt_sats, memo) - payload = { - type: "normal", - from: Setting.xmpp_notifications_from_address, - to: address, - subject: "Sats received!", - body: "#{helpers.number_with_delimiter amt_sats} sats received in your Lightning wallet:\n> #{memo}" - } - XmppSendMessageJob.perform_later(payload) - end - def authorize_request if !ENV['WEBHOOKS_ALLOWED_IPS'].split(',').include?(request.remote_ip) head :forbidden and return end end + + def process_payload + begin + @payload = JSON.parse(request.body.read, symbolize_names: true) + head :no_content and return unless @payload[:type] == "incoming" + rescue + head :unprocessable_entity and return + end + end + + def send_notifications + notify = @user.preferences[:lightning_notify_sats_received] + case notify + when "xmpp" + notify_xmpp + when "email" + notify_email + end + end + + # TODO refactor into mailer-like generic class/service + def notify_xmpp + XmppSendMessageJob.perform_later({ + type: "normal", + from: Setting.xmpp_notifications_from_address, + to: @user.address, + subject: "Sats received!", + body: "#{helpers.number_with_delimiter @payload[:amount]} sats received in your Lightning wallet:\n> #{@payload[:memo]}" + }) + end + + def notify_email + NotificationMailer.with(user: @user, amount_sats: @payload[:amount]) + .lightning_sats_received.deliver_later + end end