lnbits-legend/lnbits/extensions/livestream/tasks.py

71 lines
2.2 KiB
Python
Raw Normal View History

2021-10-28 17:02:07 +01:00
import asyncio
from loguru import logger
2021-10-28 17:02:07 +01:00
from lnbits.core.models import Payment
2022-10-21 18:28:39 +02:00
from lnbits.core.services import create_invoice, pay_invoice
from lnbits.helpers import get_current_extension_name
from lnbits.tasks import register_invoice_listener
2021-10-28 17:02:07 +01:00
from .crud import get_livestream_by_track, get_producer, get_track
async def wait_for_paid_invoices():
invoice_queue = asyncio.Queue()
register_invoice_listener(invoice_queue, get_current_extension_name())
2021-10-28 17:02:07 +01:00
while True:
payment = await invoice_queue.get()
await on_invoice_paid(payment)
2021-11-12 04:14:55 +00:00
2021-10-28 17:02:07 +01:00
async def on_invoice_paid(payment: Payment) -> None:
2023-01-05 11:05:03 +00:00
2022-07-15 18:11:11 +01:00
if payment.extra.get("tag") != "livestream":
2021-10-28 17:02:07 +01:00
# not a livestream invoice
return
track = await get_track(payment.extra.get("track", -1))
if not track:
logger.error("this should never happen", payment)
2021-10-28 17:02:07 +01:00
return
if payment.extra.get("shared_with"):
logger.error("payment was shared already", payment)
2021-10-28 17:02:07 +01:00
return
producer = await get_producer(track.producer)
assert producer, f"track {track.id} is not associated with a producer"
ls = await get_livestream_by_track(track.id)
assert ls, f"track {track.id} is not associated with a livestream"
2023-01-06 11:31:19 +00:00
amount = int(payment.amount * (100 - ls.fee_pct) / 100)
2021-10-28 17:02:07 +01:00
2022-10-21 18:28:39 +02:00
payment_hash, payment_request = await create_invoice(
wallet_id=producer.wallet,
2023-01-06 11:31:19 +00:00
amount=int(amount / 1000),
2022-10-21 18:28:39 +02:00
internal=True,
2021-10-28 17:02:07 +01:00
memo=f"Revenue from '{track.name}'.",
)
logger.debug(
f"livestream: producer invoice created: {payment_hash}, {amount} msats"
)
2021-10-28 17:02:07 +01:00
2022-10-21 18:28:39 +02:00
checking_id = await pay_invoice(
payment_request=payment_request,
wallet_id=payment.wallet_id,
extra={
**payment.extra,
"shared_with": f"Producer ID: {producer.id}",
"received": payment.amount,
},
2022-10-21 18:28:39 +02:00
)
logger.debug(f"livestream: producer invoice paid: {checking_id}")
2021-10-28 17:02:07 +01:00
# so the flow is the following:
# - we receive, say, 1000 satoshis
# - if the fee_pct is, say, 30%, the amount we will send is 700
# - we change the amount of receiving payment on the database from 1000 to 300
# - we create a new payment on the producer's wallet with amount 700