1use std::fmt;
4
5use anyhow::{bail, Result};
6use serde::{Deserialize, Serialize};
7
8pub mod invoice;
9pub mod payment;
10pub mod wallet;
11pub mod webhook;
12
13#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
15pub enum LNBitsRequestKey {
16 Admin,
18 InvoiceRead,
20}
21
22#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
24pub enum LNBitsEndpoint {
25 Payments,
27 PaymentsDecode,
29 PaymentHash(String),
31 PaymentsFindInvoice(String),
33 Wallet,
35}
36
37impl fmt::Display for LNBitsEndpoint {
38 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 match self {
40 LNBitsEndpoint::Payments => write!(f, "api/v1/payments"),
41 LNBitsEndpoint::PaymentsDecode => write!(f, "api/v1/payments/decode"),
42 LNBitsEndpoint::PaymentHash(hash) => write!(f, "api/v1/payments/{}", hash),
43 LNBitsEndpoint::Wallet => write!(f, "api/v1/wallet"),
44 LNBitsEndpoint::PaymentsFindInvoice(checking_id) => {
45 write!(f, "api/v1/payments?checking_id={}", checking_id)
46 }
47 }
48 }
49}
50
51impl crate::LNBitsClient {
52 pub async fn make_get(
54 &self,
55 endpoint: LNBitsEndpoint,
56 key: LNBitsRequestKey,
57 ) -> Result<String> {
58 let url = self.lnbits_url.join(&endpoint.to_string())?;
59 let response = self
60 .reqwest_client
61 .get(url)
62 .header("X-Api-Key", {
63 match key {
64 LNBitsRequestKey::Admin => self.admin_key.clone(),
65 LNBitsRequestKey::InvoiceRead => self.invoice_read_key.clone(),
66 }
67 })
68 .send()
69 .await?;
70
71 if response.status() == reqwest::StatusCode::NOT_FOUND {
72 bail!("Not found")
73 }
74
75 let body = response.text().await?;
76
77 Ok(body)
78 }
79
80 pub async fn make_post(
82 &self,
83 endpoint: LNBitsEndpoint,
84 key: LNBitsRequestKey,
85 body: &str,
86 ) -> Result<String> {
87 let url = self.lnbits_url.join(&endpoint.to_string())?;
88 let response = self
89 .reqwest_client
90 .post(url)
91 .header("X-Api-Key", {
92 match key {
93 LNBitsRequestKey::Admin => self.admin_key.clone(),
94 LNBitsRequestKey::InvoiceRead => self.invoice_read_key.clone(),
95 }
96 })
97 .body(body.to_string())
98 .send()
99 .await?;
100
101 if response.status() == reqwest::StatusCode::NOT_FOUND {
102 bail!("Not Found")
103 }
104
105 if response.status() == reqwest::StatusCode::UNAUTHORIZED {
106 bail!("Unauthorized")
107 }
108
109 let body = response.text().await?;
110
111 Ok(body)
112 }
113}