Chore, applied black

This commit is contained in:
benarc 2021-11-26 05:58:20 +00:00
parent cfac70d394
commit 56397026c8
30 changed files with 143 additions and 159 deletions

View File

@ -16,6 +16,7 @@ from ..tasks import api_invoice_listeners
@core_app.get("/.well-known/lnurlp/{username}")
async def lnaddress(username: str, request: Request):
from lnbits.extensions.lnaddress.lnurl import lnurl_response
domain = urlparse(str(request.url)).netloc
return await lnurl_response(username, domain, request)

View File

@ -33,8 +33,7 @@ from .crud import (
@events_ext.get("/api/v1/events")
async def api_events(
all_wallets: bool = Query(False),
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
):
wallet_ids = [wallet.wallet.id]
@ -88,8 +87,7 @@ async def api_form_delete(event_id, wallet: WalletTypeInfo = Depends(get_key_typ
@events_ext.get("/api/v1/tickets")
async def api_tickets(
all_wallets: bool = Query(False),
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
):
wallet_ids = [wallet.wallet.id]

View File

@ -236,7 +236,7 @@ async def api_get_jukebox_device_check(
async def api_get_jukebox_invoice(juke_id, song_id):
try:
jukebox = await get_jukebox(juke_id)
except:
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="No jukebox")
try:
@ -267,7 +267,7 @@ async def api_get_jukebox_invoice(juke_id, song_id):
invoice=invoice[1], payment_hash=payment_hash, juke_id=juke_id, song_id=song_id
)
jukebox_payment = await create_jukebox_payment(data)
return data

View File

@ -76,11 +76,10 @@ class Track(BaseModel):
return None
url = request.url_for("livestream.track_redirect_download", track_id=self.id)
url_with_query = f"{url}?p={payment_hash}"
url_with_query = f"{url}?p={payment_hash}"
return UrlAction(
url=url_with_query,
description=f"Download the track {self.name}!",
url=url_with_query, description=f"Download the track {self.name}!"
)

View File

@ -29,7 +29,7 @@ async def api_livestream_from_wallet(
ls = await get_or_create_livestream_by_wallet(g.wallet.id)
tracks = await get_tracks(ls.id)
producers = await get_producers(ls.id)
try:
return {
**ls.dict(),

View File

@ -8,10 +8,8 @@ from lnbits.tasks import catch_everything_and_restart
db = Database("ext_lnaddress")
lnaddress_ext: APIRouter = APIRouter(
prefix="/lnaddress",
tags=["lnaddress"]
)
lnaddress_ext: APIRouter = APIRouter(prefix="/lnaddress", tags=["lnaddress"])
def lnaddress_renderer():
return template_renderer(["lnbits/extensions/lnaddress/templates"])

View File

@ -5,9 +5,7 @@ import httpx
from lnbits.extensions.lnaddress.models import Domains
async def cloudflare_create_record(
domain: Domains, ip: str
):
async def cloudflare_create_record(domain: Domains, ip: str):
url = (
"https://api.cloudflare.com/client/v4/zones/"
+ domain.cf_zone_id
@ -51,11 +49,7 @@ async def cloudflare_deleterecord(domain: Domains, domain_id: str):
}
async with httpx.AsyncClient() as client:
try:
r = await client.delete(
url + "/" + domain_id,
headers=header,
timeout=40,
)
r = await client.delete(url + "/" + domain_id, headers=header, timeout=40)
cf_response = r.text
except AssertionError:
cf_response = "Error occured"

View File

@ -7,9 +7,7 @@ from . import db
from .models import Addresses, CreateAddress, CreateDomain, Domains
async def create_domain(
data: CreateDomain
) -> Domains:
async def create_domain(data: CreateDomain) -> Domains:
domain_id = urlsafe_short_hash()
await db.execute(
"""
@ -37,22 +35,21 @@ async def update_domain(domain_id: str, **kwargs) -> Domains:
await db.execute(
f"UPDATE lnaddress.domain SET {q} WHERE id = ?", (*kwargs.values(), domain_id)
)
row = await db.fetchone(
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
)
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
assert row, "Newly updated domain couldn't be retrieved"
return Domains(**row)
async def delete_domain(domain_id: str) -> None:
await db.execute("DELETE FROM lnaddress.domain WHERE id = ?", (domain_id,))
async def get_domain(domain_id: str) -> Optional[Domains]:
row = await db.fetchone(
"SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,)
)
row = await db.fetchone("SELECT * FROM lnaddress.domain WHERE id = ?", (domain_id,))
return Domains(**row) if row else None
async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
@ -64,12 +61,12 @@ async def get_domains(wallet_ids: Union[str, List[str]]) -> List[Domains]:
return [Domains(**row) for row in rows]
## ADRESSES
async def create_address(
payment_hash: str,
wallet: str,
data: CreateAddress
payment_hash: str, wallet: str, data: CreateAddress
) -> Addresses:
await db.execute(
"""
@ -94,6 +91,7 @@ async def create_address(
assert new_address, "Newly created address couldn't be retrieved"
return new_address
async def get_address(address_id: str) -> Optional[Addresses]:
row = await db.fetchone(
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.id = ? AND a.domain = d.id",
@ -101,28 +99,31 @@ async def get_address(address_id: str) -> Optional[Addresses]:
)
return Addresses(**row) if row else None
async def get_address_by_username(username: str, domain: str) -> Optional[Addresses]:
row = await db.fetchone(
"SELECT a.* FROM lnaddress.address AS a INNER JOIN lnaddress.domain AS d ON a.username = ? AND d.domain = ?",
(username, domain,),
(username, domain),
)
return Addresses(**row) if row else None
async def delete_address(address_id: str) -> None:
await db.execute("DELETE FROM lnaddress.address WHERE id = ?", (address_id,))
async def get_addresses(wallet_ids: Union[str, List[str]]) -> List[Addresses]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join(["?"] * len(wallet_ids))
rows = await db.fetchall(
f"SELECT * FROM lnaddress.address WHERE wallet IN ({q})",
(*wallet_ids,),
f"SELECT * FROM lnaddress.address WHERE wallet IN ({q})", (*wallet_ids,)
)
return [Addresses(**row) for row in rows]
async def set_address_paid(payment_hash: str) -> Addresses:
address = await get_address(payment_hash)
@ -140,6 +141,7 @@ async def set_address_paid(payment_hash: str) -> Addresses:
assert new_address, "Newly paid address couldn't be retrieved"
return new_address
async def set_address_renewed(address_id: str, duration: int):
address = await get_address(address_id)
@ -150,7 +152,7 @@ async def set_address_renewed(address_id: str, duration: int):
SET duration = ?
WHERE id = ?
""",
(extend_duration, address_id,),
(extend_duration, address_id),
)
updated_address = await get_address(address_id)
assert updated_address, "Renewed address couldn't be retrieved"
@ -160,15 +162,15 @@ async def set_address_renewed(address_id: str, duration: int):
async def check_address_available(username: str, domain: str):
row, = await db.fetchone(
"SELECT COUNT(username) FROM lnaddress.address WHERE username = ? AND domain = ?",
(username, domain,),
(username, domain),
)
return row
async def purge_addresses(domain_id: str):
rows = await db.fetchall(
"SELECT * FROM lnaddress.address WHERE domain = ?",
(domain_id, ),
"SELECT * FROM lnaddress.address WHERE domain = ?", (domain_id,)
)
now = datetime.now().timestamp()
@ -178,8 +180,10 @@ async def purge_addresses(domain_id: str):
start = datetime.fromtimestamp(r["time"])
paid = r["paid"]
pay_expire = now > start.timestamp() + 86400 #if payment wasn't made in 1 day
expired = now > (start + timedelta(days = r["duration"] + 1)).timestamp() #give user 1 day to topup is address
pay_expire = now > start.timestamp() + 86400 # if payment wasn't made in 1 day
expired = (
now > (start + timedelta(days=r["duration"] + 1)).timestamp()
) # give user 1 day to topup is address
if not paid and pay_expire:
print("DELETE UNP_PAY_EXP", r["username"])

View File

@ -23,7 +23,7 @@ async def lnurl_response(username: str, domain: str, request: Request):
## CHECK IF USER IS STILL VALID/PAYING
now = datetime.now().timestamp()
start = datetime.fromtimestamp(address.time)
expiration = (start + timedelta(days = address.duration)).timestamp()
expiration = (start + timedelta(days=address.duration)).timestamp()
if now > expiration:
return LnurlErrorResponse(reason="Address has expired.").dict()
@ -37,30 +37,38 @@ async def lnurl_response(username: str, domain: str, request: Request):
return resp.dict()
@lnaddress_ext.get("/lnurl/cb/{address_id}", name="lnaddress.lnurl_callback")
async def lnurl_callback(address_id, amount: int = Query(...)):
address = await get_address(address_id)
if not address:
return LnurlErrorResponse(
reason=f"Address not found"
).dict()
return LnurlErrorResponse(reason=f"Address not found").dict()
amount_received = amount
domain = await get_domain(address.domain)
base_url = address.wallet_endpoint[:-1] if address.wallet_endpoint.endswith('/') else address.wallet_endpoint
base_url = (
address.wallet_endpoint[:-1]
if address.wallet_endpoint.endswith("/")
else address.wallet_endpoint
)
async with httpx.AsyncClient() as client:
try:
call = await client.post(
base_url + "/api/v1/payments",
headers={"X-Api-Key": address.wallet_key, "Content-Type": "application/json"},
headers={
"X-Api-Key": address.wallet_key,
"Content-Type": "application/json",
},
json={
"out": False,
"amount": int(amount_received / 1000),
"description_hash": hashlib.sha256((await address.lnurlpay_metadata()).encode("utf-8")).hexdigest(),
"description_hash": hashlib.sha256(
(await address.lnurlpay_metadata()).encode("utf-8")
).hexdigest(),
"extra": {"tag": f"Payment to {address.username}@{domain.domain}"},
},
timeout=40,
@ -70,9 +78,6 @@ async def lnurl_callback(address_id, amount: int = Query(...)):
except AssertionError as e:
return LnurlErrorResponse(reason="ERROR")
resp = LnurlPayActionResponse(
pr=r["payment_request"],
routes=[],
)
resp = LnurlPayActionResponse(pr=r["payment_request"], routes=[])
return resp.dict()

View File

@ -16,6 +16,7 @@ async def m001_initial(db):
"""
)
async def m002_addresses(db):
await db.execute(
"""

View File

@ -7,13 +7,14 @@ from pydantic.main import BaseModel # type: ignore
class CreateDomain(BaseModel):
wallet: str = Query(...)
wallet: str = Query(...)
domain: str = Query(...)
cf_token: str = Query(...)
cf_zone_id: str = Query(...)
webhook: str = Query(None)
cost: int = Query(..., ge=0)
class Domains(BaseModel):
id: str
wallet: str
@ -24,6 +25,7 @@ class Domains(BaseModel):
cost: int
time: int
class CreateAddress(BaseModel):
domain: str = Query(...)
username: str = Query(...)
@ -33,6 +35,7 @@ class CreateAddress(BaseModel):
sats: int = Query(..., ge=0)
duration: int = Query(..., ge=1)
class Addresses(BaseModel):
id: str
wallet: str

View File

@ -52,7 +52,9 @@ async def on_invoice_paid(payment: Payment) -> None:
elif "renew lnaddress" == payment.extra.get("tag"):
await payment.set_pending(False)
await set_address_renewed(address_id=payment.extra["id"], duration=payment.extra["duration"])
await set_address_renewed(
address_id=payment.extra["id"], duration=payment.extra["duration"]
)
await call_webhook_on_paid(payment.payment_hash)
else:

View File

@ -18,7 +18,10 @@ templates = Jinja2Templates(directory="templates")
@lnaddress_ext.get("/", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_user_exists)):
return lnaddress_renderer().TemplateResponse("lnaddress/index.html", {"request": request, "user": user.dict()})
return lnaddress_renderer().TemplateResponse(
"lnaddress/index.html", {"request": request, "user": user.dict()}
)
@lnaddress_ext.get("/{domain_id}", response_class=HTMLResponse)
async def display(domain_id, request: Request):
@ -33,11 +36,12 @@ async def display(domain_id, request: Request):
wallet = await get_wallet(domain.wallet)
return lnaddress_renderer().TemplateResponse(
"lnaddress/display.html",{
"lnaddress/display.html",
{
"request": request,
"domain_id":domain.id,
"domain_id": domain.id,
"domain_domain": domain.domain,
"domain_cost": domain.cost,
"domain_wallet_inkey": wallet.inkey
}
"domain_wallet_inkey": wallet.inkey,
},
)

View File

@ -30,8 +30,7 @@ from .crud import (
# DOMAINS
@lnaddress_ext.get("/api/v1/domains")
async def api_domains(
g: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False),
g: WalletTypeInfo = Depends(get_key_type), all_wallets: bool = Query(False)
):
wallet_ids = [g.wallet.id]
@ -43,20 +42,23 @@ async def api_domains(
@lnaddress_ext.post("/api/v1/domains")
@lnaddress_ext.put("/api/v1/domains/{domain_id}")
async def api_domain_create(request: Request,data: CreateDomain, domain_id=None, g: WalletTypeInfo = Depends(get_key_type)):
async def api_domain_create(
request: Request,
data: CreateDomain,
domain_id=None,
g: WalletTypeInfo = Depends(get_key_type),
):
if domain_id:
domain = await get_domain(domain_id)
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Domain does not exist.",
status_code=HTTPStatus.NOT_FOUND, detail="Domain does not exist."
)
if domain.wallet != g.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your domain",
status_code=HTTPStatus.FORBIDDEN, detail="Not your domain"
)
domain = await update_domain(domain_id, **data.dict())
@ -65,45 +67,41 @@ async def api_domain_create(request: Request,data: CreateDomain, domain_id=None,
domain = await create_domain(data=data)
root_url = urlparse(str(request.url)).netloc
cf_response = await cloudflare_create_record(
domain=domain,
ip=root_url,
)
cf_response = await cloudflare_create_record(domain=domain, ip=root_url)
if not cf_response or cf_response["success"] != True:
await delete_domain(domain.id)
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Problem with cloudflare: " + cf_response["errors"][0]["message"],
detail="Problem with cloudflare: "
+ cf_response["errors"][0]["message"],
)
return domain.dict()
@lnaddress_ext.delete("/api/v1/domains/{domain_id}")
async def api_domain_delete(domain_id, g: WalletTypeInfo = Depends(get_key_type)):
domain = await get_domain(domain_id)
if not domain:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Domain does not exist.",
)
status_code=HTTPStatus.NOT_FOUND, detail="Domain does not exist."
)
if domain.wallet != g.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your domain",
)
raise HTTPException(status_code=HTTPStatus.FORBIDDEN, detail="Not your domain")
await delete_domain(domain_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
# ADDRESSES
@lnaddress_ext.get("/api/v1/addresses")
async def api_addresses(
g: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False),
g: WalletTypeInfo = Depends(get_key_type), all_wallets: bool = Query(False)
):
wallet_ids = [g.wallet.id]
@ -112,65 +110,66 @@ async def api_addresses(
return [address.dict() for address in await get_addresses(wallet_ids)]
@lnaddress_ext.get("/api/v1/address/availabity/{domain_id}/{username}")
async def api_check_available_username(domain_id, username):
used_username = await check_address_available(username, domain_id)
return used_username
@lnaddress_ext.get("/api/v1/address/{domain}/{username}/{wallet_key}")
async def api_get_user_info(username, wallet_key, domain):
address = await get_address_by_username(username, domain)
if not address:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Address does not exist.",
status_code=HTTPStatus.NOT_FOUND, detail="Address does not exist."
)
if address.wallet_key != wallet_key:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Incorrect user/wallet information.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="Incorrect user/wallet information.",
)
return address.dict()
@lnaddress_ext.post("/api/v1/address/{domain_id}")
@lnaddress_ext.put("/api/v1/address/{domain_id}/{user}/{wallet_key}")
async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None, wallet_key=None):
async def api_lnaddress_make_address(
domain_id, data: CreateAddress, user=None, wallet_key=None
):
domain = await get_domain(domain_id)
# If the request is coming for the non-existant domain
if not domain:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="The domain does not exist.",
)
status_code=HTTPStatus.FORBIDDEN, detail="The domain does not exist."
)
domain_cost = domain.cost
sats = data.sats
## FAILSAFE FOR CREATING ADDRESSES BY API
if(domain_cost * data.duration != data.sats):
if domain_cost * data.duration != data.sats:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
)
status_code=HTTPStatus.FORBIDDEN,
detail="The amount is not correct. Either 'duration', or 'sats' are wrong.",
)
if user:
address = await get_address_by_username(user, domain.domain)
if not address:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="The address does not exist.",
status_code=HTTPStatus.NOT_FOUND, detail="The address does not exist."
)
if address.wallet_key != wallet_key:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your address.",
status_code=HTTPStatus.FORBIDDEN, detail="Not your address."
)
try:
@ -181,14 +180,13 @@ async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None,
extra={
"tag": "renew lnaddress",
"id": address.id,
"duration": data.duration
"duration": data.duration,
},
)
except Exception as e:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=str(e),
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)
)
else:
used_username = await check_address_available(data.username, data.domain)
@ -210,10 +208,9 @@ async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None,
)
except Exception as e:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=str(e),
status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)
)
address = await create_address(
payment_hash=payment_hash, wallet=domain.wallet, data=data
)
@ -226,6 +223,7 @@ async def api_lnaddress_make_address(domain_id, data: CreateAddress, user=None,
return {"payment_hash": payment_hash, "payment_request": payment_request}
@lnaddress_ext.get("/api/v1/addresses/{payment_hash}")
async def api_address_send_address(payment_hash):
address = await get_address(payment_hash)
@ -234,27 +232,25 @@ async def api_address_send_address(payment_hash):
status = await check_invoice_status(domain.wallet, payment_hash)
is_paid = not status.pending
except Exception as e:
return {"paid": False, 'error': str(e)}
return {"paid": False, "error": str(e)}
if is_paid:
return {"paid": True}
return {"paid": False}
@lnaddress_ext.delete("/api/v1/addresses/{address_id}")
async def api_address_delete(address_id, g: WalletTypeInfo = Depends(get_key_type)):
address = await get_address(address_id)
if not address:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail="Address does not exist.",
)
status_code=HTTPStatus.NOT_FOUND, detail="Address does not exist."
)
if address.wallet != g.wallet.id:
raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your address.",
)
status_code=HTTPStatus.FORBIDDEN, detail="Not your address."
)
await delete_address(address_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)

View File

@ -8,10 +8,7 @@ from lnbits.tasks import catch_everything_and_restart
db = Database("ext_lnticket")
lnticket_ext: APIRouter = APIRouter(
prefix="/lnticket",
tags=["LNTicket"]
)
lnticket_ext: APIRouter = APIRouter(prefix="/lnticket", tags=["LNTicket"])
def lnticket_renderer():

View File

@ -30,8 +30,7 @@ from .crud import (
@lnticket_ext.get("/api/v1/forms")
async def api_forms_get(
all_wallets: bool = Query(False),
wallet: WalletTypeInfo = Depends(get_key_type),
all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type)
):
wallet_ids = [wallet.wallet.id]

View File

@ -17,10 +17,7 @@ lnurlp_static_files = [
}
]
lnurlp_ext: APIRouter = APIRouter(
prefix="/lnurlp",
tags=["lnurlp"]
)
lnurlp_ext: APIRouter = APIRouter(prefix="/lnurlp", tags=["lnurlp"])
def lnurlp_renderer():

View File

@ -59,6 +59,7 @@ async def get_lnurlposs(wallet_ids: Union[str, List[str]]) -> List[lnurlposs]:
return [lnurlposs(**row) if row else None for row in rows]
async def delete_lnurlpos(lnurlpos_id: str) -> None:
await db.execute("DELETE FROM lnurlpos.lnurlposs WHERE id = ?", (lnurlpos_id,))

View File

@ -45,9 +45,7 @@ async def api_lnurlpos_create_or_update(
@lnurlpos_ext.get("/api/v1/lnurlpos")
async def api_lnurlposs_retrieve(
wallet: WalletTypeInfo = Depends(get_key_type)
):
async def api_lnurlposs_retrieve(wallet: WalletTypeInfo = Depends(get_key_type)):
wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
try:
return [{**lnurlpos.dict()} for lnurlpos in await get_lnurlposs(wallet_ids)]
@ -73,8 +71,7 @@ async def api_lnurlpos_retrieve(
@lnurlpos_ext.delete("/api/v1/lnurlpos/{lnurlpos_id}")
async def api_lnurlpos_delete(
wallet: WalletTypeInfo = Depends(require_admin_key),
lnurlpos_id: str = Query(None),
wallet: WalletTypeInfo = Depends(require_admin_key), lnurlpos_id: str = Query(None)
):
lnurlpos = await get_lnurlpos(lnurlpos_id)

View File

@ -1,4 +1,3 @@
from os import getenv
from fastapi import Request

View File

@ -14,10 +14,7 @@ offlineshop_static_files = [
}
]
offlineshop_ext: APIRouter = APIRouter(
prefix="/offlineshop",
tags=["Offlineshop"],
)
offlineshop_ext: APIRouter = APIRouter(prefix="/offlineshop", tags=["Offlineshop"])
def offlineshop_renderer():

View File

@ -128,6 +128,7 @@ async def api_lnurlw_response(req: Request, unique_hash: str = Query(None)):
# CALLBACK
@satsdice_ext.get(
"/api/v1/lnurlw/cb/{unique_hash}",
status_code=HTTPStatus.OK,

View File

@ -46,8 +46,7 @@ async def api_links(
@satsdice_ext.get("/api/v1/links/{link_id}")
async def api_link_retrieve(
link_id: str = Query(None),
wallet: WalletTypeInfo = Depends(get_key_type),
link_id: str = Query(None), wallet: WalletTypeInfo = Depends(get_key_type)
):
link = await get_satsdice_pay(link_id)

View File

@ -24,6 +24,7 @@ splitpayments_ext: APIRouter = APIRouter(
def splitpayments_renderer():
return template_renderer(["lnbits/extensions/splitpayments/templates"])
from .tasks import wait_for_paid_invoices
from .views import * # noqa
from .views_api import * # noqa

View File

@ -14,6 +14,7 @@ from .models import CreateUserData, Users, Wallets
### Users
async def create_usermanager_user(data: CreateUserData) -> Users:
account = await create_account()
user = await get_user(account.id)

View File

@ -25,6 +25,7 @@ from .models import CreateUserData, CreateUserWallet
### Users
@usermanager_ext.get("/api/v1/users", status_code=HTTPStatus.OK)
async def api_usermanager_users(wallet: WalletTypeInfo = Depends(get_key_type)):
user_id = wallet.wallet.user

View File

@ -15,10 +15,7 @@ withdraw_static_files = [
]
withdraw_ext: APIRouter = APIRouter(
prefix="/withdraw",
tags=["withdraw"],
)
withdraw_ext: APIRouter = APIRouter(prefix="/withdraw", tags=["withdraw"])
def withdraw_renderer():

View File

@ -28,12 +28,9 @@ async def api_lnurl_response(request: Request, unique_hash):
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Withdraw link does not exist."
)
if link.is_spent:
raise HTTPException(
detail="Withdraw is spent."
)
raise HTTPException(detail="Withdraw is spent.")
url = request.url_for("withdraw.api_lnurl_callback", unique_hash=link.unique_hash)
withdrawResponse = {
"tag": "withdrawRequest",
@ -48,15 +45,10 @@ async def api_lnurl_response(request: Request, unique_hash):
# CALLBACK
@withdraw_ext.get(
"/api/v1/lnurl/cb/{unique_hash}",
name="withdraw.api_lnurl_callback",
)
@withdraw_ext.get("/api/v1/lnurl/cb/{unique_hash}", name="withdraw.api_lnurl_callback")
async def api_lnurl_callback(
unique_hash,
request: Request,
k1: str = Query(...),
pr: str = Query(...)
unique_hash, request: Request, k1: str = Query(...), pr: str = Query(...)
):
link = await get_withdraw_link_by_hash(unique_hash)
now = int(datetime.now().timestamp())
@ -94,8 +86,8 @@ async def api_lnurl_callback(
"usescsv": usescsv,
}
await update_withdraw_link(link.id, **changes)
payment_request=pr
payment_request = pr
await pay_invoice(
wallet_id=link.wallet,

View File

@ -98,7 +98,7 @@ async def print_qr(request: Request, link_id):
count = count + 1
page_link = list(chunks(links, 2))
linked = list(chunks(page_link, 5))
return withdraw_renderer().TemplateResponse(
"withdraw/print_qr.html", {"request": request, "link": linked, "unique": True}
)

View File

@ -63,7 +63,7 @@ class LNbitsWallet(Wallet):
async with httpx.AsyncClient() as client:
r = await client.post(
url=f"{self.endpoint}/api/v1/payments", headers=self.key, json=data,
url=f"{self.endpoint}/api/v1/payments", headers=self.key, json=data
)
ok, checking_id, payment_request, error_message = (
not r.is_error,
@ -85,7 +85,7 @@ class LNbitsWallet(Wallet):
r = await client.post(
url=f"{self.endpoint}/api/v1/payments",
headers=self.key,
json={"out": True, "bolt11": bolt11},
json={"out": True, "bolt11": bolt11},
timeout=100,
)
ok, checking_id, fee_msat, error_message = not r.is_error, None, 0, None