2021-12-29 12:57:43 +00:00
|
|
|
import asyncio
|
|
|
|
|
2022-11-24 16:57:59 +02:00
|
|
|
import httpx
|
2022-07-07 14:30:16 +02:00
|
|
|
from loguru import logger
|
|
|
|
|
2021-12-29 12:57:43 +00:00
|
|
|
from lnbits.core.models import Payment
|
|
|
|
from lnbits.extensions.satspay.crud import check_address_balance, get_charge
|
2022-10-04 09:51:47 +02:00
|
|
|
from lnbits.helpers import get_current_extension_name
|
2021-12-29 12:57:43 +00:00
|
|
|
from lnbits.tasks import register_invoice_listener
|
|
|
|
|
2022-11-24 16:57:59 +02:00
|
|
|
from .helpers import compact_charge
|
|
|
|
from .models import Charges
|
2021-12-29 12:57:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def wait_for_paid_invoices():
|
|
|
|
invoice_queue = asyncio.Queue()
|
2022-10-04 09:51:47 +02:00
|
|
|
register_invoice_listener(invoice_queue, get_current_extension_name())
|
2021-12-29 12:57:43 +00:00
|
|
|
|
|
|
|
while True:
|
|
|
|
payment = await invoice_queue.get()
|
|
|
|
await on_invoice_paid(payment)
|
|
|
|
|
|
|
|
|
|
|
|
async def on_invoice_paid(payment: Payment) -> None:
|
2022-07-15 18:11:11 +01:00
|
|
|
if payment.extra.get("tag") != "charge":
|
2021-12-29 12:57:43 +00:00
|
|
|
# not a charge invoice
|
|
|
|
return
|
|
|
|
|
|
|
|
charge = await get_charge(payment.memo)
|
|
|
|
if not charge:
|
2022-07-07 14:30:16 +02:00
|
|
|
logger.error("this should never happen", payment)
|
2021-12-29 12:57:43 +00:00
|
|
|
return
|
|
|
|
|
|
|
|
await payment.set_pending(False)
|
2022-11-24 16:57:59 +02:00
|
|
|
charge = await check_address_balance(charge_id=charge.id)
|
|
|
|
|
|
|
|
if charge.paid and charge.webhook:
|
|
|
|
await call_webhook(charge)
|
|
|
|
|
|
|
|
|
|
|
|
async def call_webhook(charge: Charges):
|
|
|
|
async with httpx.AsyncClient() as client:
|
|
|
|
try:
|
|
|
|
r = await client.post(
|
|
|
|
charge.webhook,
|
|
|
|
json=compact_charge(charge),
|
|
|
|
timeout=40,
|
|
|
|
)
|
|
|
|
except AssertionError:
|
|
|
|
charge.webhook = None
|
|
|
|
except Exception as e:
|
|
|
|
logger.warning(f"Failed to call webhook for charge {charge.id}")
|
|
|
|
logger.warning(e)
|