lnbits-legend/lnbits/extensions/splitpayments/views_api.py

66 lines
2 KiB
Python
Raw Normal View History

2021-10-18 16:23:51 +01:00
from http import HTTPStatus
2021-10-18 12:34:45 +01:00
from fastapi import Request
2021-10-18 16:23:51 +01:00
from fastapi.params import Depends
2021-10-18 12:34:45 +01:00
from starlette.exceptions import HTTPException
2021-10-18 16:23:51 +01:00
2021-10-18 12:34:45 +01:00
from lnbits.core.crud import get_wallet, get_wallet_for_key
2021-10-18 19:39:35 +01:00
from lnbits.decorators import WalletTypeInfo, require_admin_key
2021-10-18 16:23:51 +01:00
from . import splitpayments_ext
from .crud import get_targets, set_targets
from .models import Target, TargetPut
2021-10-18 12:34:45 +01:00
@splitpayments_ext.get("/api/v1/targets")
2021-10-18 16:23:51 +01:00
async def api_targets_get(wallet: WalletTypeInfo = Depends(require_admin_key)):
2021-10-18 12:34:45 +01:00
targets = await get_targets(wallet.wallet.id)
return [target.dict() for target in targets] or []
@splitpayments_ext.put("/api/v1/targets")
async def api_targets_set(
2021-10-18 19:39:35 +01:00
req: Request, wal: WalletTypeInfo = Depends(require_admin_key)
2021-10-18 12:34:45 +01:00
):
2021-10-18 19:39:35 +01:00
body = await req.json()
2021-10-18 12:34:45 +01:00
targets = []
2021-10-18 19:39:35 +01:00
data = TargetPut.parse_obj(body["targets"])
for entry in data.__root__:
wallet = await get_wallet(entry.wallet)
2021-10-18 12:34:45 +01:00
if not wallet:
wallet = await get_wallet_for_key(entry.wallet, "invoice")
2021-10-18 12:34:45 +01:00
if not wallet:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"Invalid wallet '{entry.wallet}'.",
2021-10-18 12:34:45 +01:00
)
2021-10-18 19:39:35 +01:00
if wallet.id == wal.wallet.id:
2021-10-18 12:34:45 +01:00
raise HTTPException(
2021-11-12 04:14:55 +00:00
status_code=HTTPStatus.BAD_REQUEST, detail="Can't split to itself."
2021-10-18 12:34:45 +01:00
)
if entry.percent < 0:
2021-10-18 12:34:45 +01:00
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail=f"Invalid percent '{entry.percent}'.",
2021-10-18 12:34:45 +01:00
)
targets.append(
2021-11-12 04:14:55 +00:00
Target(
wallet=wallet.id,
source=wal.wallet.id,
percent=entry.percent,
alias=entry.alias,
)
2021-10-18 12:34:45 +01:00
)
percent_sum = sum([target.percent for target in targets])
if percent_sum > 100:
raise HTTPException(
2021-11-12 04:14:55 +00:00
status_code=HTTPStatus.BAD_REQUEST, detail="Splitting over 100%."
2021-10-18 12:34:45 +01:00
)
2021-10-18 19:39:35 +01:00
await set_targets(wal.wallet.id, targets)
2021-10-18 12:34:45 +01:00
return ""