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

68 lines
2.1 KiB
Python
Raw Normal View History

2021-10-18 16:23:51 +01:00
import base64
2021-10-18 12:34:45 +01:00
import json
2021-10-18 16:23:51 +01:00
from http import HTTPStatus
from typing import Optional
2021-10-18 12:34:45 +01:00
import httpx
from fastapi import Request
2021-10-18 16:23:51 +01:00
from fastapi.param_functions import Query
from fastapi.params import Depends
2021-10-18 12:34:45 +01:00
from starlette.exceptions import HTTPException
from starlette.responses import HTMLResponse, JSONResponse # type: ignore
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 16:23:51 +01:00
from lnbits.decorators import WalletTypeInfo, get_key_type, require_admin_key
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)):
print(wallet)
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 16:23:51 +01:00
data: TargetPut, wallet: WalletTypeInfo = Depends(require_admin_key)
2021-10-18 12:34:45 +01:00
):
targets = []
for entry in data.targets:
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
)
if wallet.id == wallet.wallet.id:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Can't split to itself.",
)
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(
Target(wallet.id, wallet.wallet.id, entry.percent, entry.alias or "")
2021-10-18 12:34:45 +01:00
)
percent_sum = sum([target.percent for target in targets])
if percent_sum > 100:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Splitting over 100%.",
)
await set_targets(wallet.wallet.id, targets)
return ""