lnbits-legend/lnbits/extensions/copilot/lnurl.py

88 lines
2.7 KiB
Python
Raw Normal View History

2021-04-16 11:28:50 +01:00
import json
import hashlib
import math
from quart import jsonify, url_for, request
from lnurl import LnurlPayResponse, LnurlPayActionResponse, LnurlErrorResponse # type: ignore
2021-04-16 09:18:24 +01:00
from lnurl.types import LnurlPayMetadata
from lnbits.core.services import create_invoice
from . import copilot_ext
from .crud import get_copilot
@copilot_ext.route("/lnurl/<cp_id>", methods=["GET"])
async def lnurl_response(cp_id):
cp = await get_copilot(cp_id)
2021-04-16 21:17:30 +01:00
print(cp)
if not cp:
return jsonify({"status": "ERROR", "reason": "Copilot not found."})
resp = LnurlPayResponse(
2021-04-16 12:20:05 +01:00
callback=url_for("copilot.lnurl_callback", cp_id=cp_id, _external=True),
2021-04-16 11:34:21 +01:00
min_sendable=10000,
2021-04-16 11:31:31 +01:00
max_sendable=50000000,
2021-04-16 21:33:47 +01:00
metadata=LnurlPayMetadata(json.dumps([["text/plain", str(cp.lnurl_title)]])),
)
params = resp.dict()
2021-04-19 09:32:41 +01:00
if cp.show_message:
params["commentAllowed"] = 300
return jsonify(params)
@copilot_ext.route("/lnurl/cb/<cp_id>", methods=["GET"])
async def lnurl_callback(cp_id):
cp = await get_copilot(cp_id)
if not cp:
return jsonify({"status": "ERROR", "reason": "Copilot not found."})
amount_received = int(request.args.get("amount"))
2021-04-16 11:34:21 +01:00
if amount_received < 10000:
return (
jsonify(
LnurlErrorResponse(
reason=f"Amount {round(amount_received / 1000)} is smaller than minimum 10 sats."
).dict()
),
)
2021-04-16 12:20:05 +01:00
elif amount_received / 1000 > 50000000:
return (
jsonify(
LnurlErrorResponse(
reason=f"Amount {round(amount_received / 1000)} is greater than maximum 50000."
).dict()
),
)
2021-04-19 09:32:41 +01:00
comment = ""
if request.args.get("comment"):
comment = request.args.get("comment")
if len(comment or "") > 300:
return jsonify(
LnurlErrorResponse(
reason=f"Got a comment with {len(comment)} characters, but can only accept 300"
).dict()
)
if len(comment) < 1:
comment = "none"
payment_hash, payment_request = await create_invoice(
wallet_id=cp.wallet,
amount=int(amount_received / 1000),
memo=cp.lnurl_title,
2021-04-16 22:22:36 +01:00
description_hash=hashlib.sha256(
(
LnurlPayMetadata(json.dumps([["text/plain", str(cp.lnurl_title)]]))
).encode("utf-8")
).digest(),
2021-04-19 23:45:40 +01:00
extra={"tag": "copilot", "copilot": cp.id, "comment": comment},
)
2021-04-16 21:41:24 +01:00
resp = LnurlPayActionResponse(
pr=payment_request,
2021-04-16 21:42:16 +01:00
success_action=None,
2021-04-16 21:44:20 +01:00
disposable=False,
2021-04-16 21:41:24 +01:00
routes=[],
)
2021-04-16 22:22:36 +01:00
return jsonify(resp.dict())