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