lnbits-legend/lnbits/core/views/public_api.py

72 lines
2.1 KiB
Python
Raw Normal View History

import asyncio
import datetime
from http import HTTPStatus
2021-11-25 17:19:49 +00:00
from urllib.parse import urlparse
2021-10-29 16:43:26 +01:00
2021-09-11 11:02:48 +02:00
from fastapi import HTTPException
2022-07-16 14:23:03 +02:00
from loguru import logger
2021-10-29 16:43:26 +01:00
from starlette.requests import Request
from starlette.responses import HTMLResponse
2021-10-29 16:43:26 +01:00
from lnbits import bolt11
from .. import core_app
from ..crud import get_standalone_payment
from ..tasks import api_invoice_listeners
2021-10-29 16:43:26 +01:00
@core_app.get("/.well-known/lnurlp/{username}")
async def lnaddress(username: str, request: Request):
from lnbits.extensions.lnaddress.lnurl import lnurl_response
2021-11-26 05:58:20 +00:00
2021-11-25 17:24:03 +00:00
domain = urlparse(str(request.url)).netloc
2021-11-25 17:08:20 +00:00
return await lnurl_response(username, domain, request)
2021-10-29 16:43:26 +01:00
2021-08-22 23:05:39 +01:00
@core_app.get("/public/v1/payment/{payment_hash}")
async def api_public_payment_longpolling(payment_hash):
payment = await get_standalone_payment(payment_hash)
if not payment:
2021-09-11 11:02:48 +02:00
raise HTTPException(
2021-10-17 18:33:29 +01:00
status_code=HTTPStatus.NOT_FOUND, detail="Payment does not exist."
2021-09-11 11:02:48 +02:00
)
elif not payment.pending:
2021-09-11 11:02:48 +02:00
return {"status": "paid"}
try:
invoice = bolt11.decode(payment.bolt11)
expiration = datetime.datetime.fromtimestamp(invoice.date + invoice.expiry)
if expiration < datetime.datetime.now():
2021-09-11 11:02:48 +02:00
return {"status": "expired"}
except:
2021-09-11 11:02:48 +02:00
raise HTTPException(
2021-10-17 18:33:29 +01:00
status_code=HTTPStatus.BAD_REQUEST, detail="Invalid bolt11 invoice."
2021-09-11 11:02:48 +02:00
)
payment_queue = asyncio.Queue(0)
logger.debug("adding standalone invoice listener", payment_hash, payment_queue)
api_invoice_listeners.append(payment_queue)
response = None
async def payment_info_receiver(cancel_scope):
async for payment in payment_queue.get():
if payment.payment_hash == payment_hash:
nonlocal response
2021-09-11 11:02:48 +02:00
response = {"status": "paid"}
cancel_scope.cancel()
async def timeouter(cancel_scope):
await asyncio.sleep(45)
cancel_scope.cancel()
asyncio.create_task(payment_info_receiver())
asyncio.create_task(timeouter())
if response:
return response
else:
2021-10-17 18:33:29 +01:00
raise HTTPException(status_code=HTTPStatus.REQUEST_TIMEOUT, detail="timeout")