akkounts/app/services/lndhub.rb
Râu Cao 69b3afb8f7
DRY up btcpay and lndhub services
Removing initialize methods from the main/manager class also allows for
different iniitalizers in specific task services
2024-03-02 14:31:48 +01:00

82 lines
1.8 KiB
Ruby

class Lndhub < ApplicationService
attr_accessor :auth_token
def post(path, payload)
headers = { "Content-Type" => "application/json" }
if auth_token
headers.merge!({ "Authorization" => "Bearer #{auth_token}" })
end
res = Faraday.post endpoint_url(path), payload.to_json, headers
log_error(res) if res.status != 200
JSON.parse(res.body)
end
def get(path, auth_token)
res = Faraday.get(endpoint_url(path), {}, {
"Content-Type" => "application/json",
"Accept" => "application/json",
"Authorization" => "Bearer #{auth_token}"
})
data = JSON.parse(res.body)
if data.is_a?(Hash) && data["error"] && data["message"] == "bad auth"
raise AuthError
else
data
end
end
def create(payload)
post "create", payload
end
def authenticate(user)
credentials = post "auth?type=auth", { login: user.ln_account, password: user.ln_password }
self.auth_token = credentials["access_token"]
self.auth_token
end
def fetch_balance(user_token=nil)
get "balance", user_token || auth_token
end
def gettxs(user_token=nil)
get "gettxs", user_token || auth_token
end
def getuserinvoices(user_token=nil)
get "getuserinvoices", user_token || auth_token
end
def addinvoice(payload)
invoice = post "addinvoice", {
amt: payload[:amount],
memo: payload[:memo],
description_hash: payload[:description_hash]
}
invoice["payment_request"]
end
def log_error(res)
Rails.logger.error "[lndhub] API request failed:"
Rails.logger.error res.body
if Setting.sentry_enabled?
Sentry.capture_message("Lndhub API request failed: #{res.body}")
end
end
private
def base_url
@base_url ||= Setting.lndhub_api_url
end
def endpoint_url(path)
"#{base_url}/#{path.gsub(/^\//, '')}"
end
end