fastAPI port views_api

This commit is contained in:
Tiago vasconcelos
2021-09-27 15:52:08 +01:00
parent a5c0a2bb50
commit 0891611d2b

View File

@@ -3,9 +3,13 @@ from quart import g, jsonify, request
from http import HTTPStatus from http import HTTPStatus
from fastapi import FastAPI, Query from fastapi import FastAPI, Query
from fastapi.params import Depends
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from pydantic import BaseModel from pydantic import BaseModel
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.responses import HTMLResponse, JSONResponse # type: ignore
from lnbits.core.crud import get_user, get_wallet from lnbits.core.crud import get_user, get_wallet
from lnbits.core.services import create_invoice, check_invoice_status from lnbits.core.services import create_invoice, check_invoice_status
@@ -29,17 +33,16 @@ from .crud import (
# FORMS # FORMS
@lnticket_ext.get("/api/v1/forms") @lnticket_ext.get("/api/v1/forms", status_code=HTTPStatus.OK)
@api_check_wallet_key("invoice") # @api_check_wallet_key("invoice")
async def api_forms(): async def api_forms(r: Request, wallet: WalletTypeInfo = Depends(get_key_type)):
wallet_ids = [g.wallet.id] wallet_ids = [wallet.wallet.id]
if "all_wallets" in request.args: if "all_wallets" in r.args:
wallet_ids = (await get_user(g.wallet.user)).wallet_ids wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
return ( return (
[form._asdict() for form in await get_forms(wallet_ids)], [form._asdict() for form in await get_forms(wallet_ids)],
HTTPStatus.OK,
) )
class CreateData(BaseModel): class CreateData(BaseModel):
@@ -50,9 +53,9 @@ class CreateData(BaseModel):
amount: int = Query(..., ge=0) amount: int = Query(..., ge=0)
flatrate: int = Query(...) flatrate: int = Query(...)
@lnticket_ext.post("/api/v1/forms") @lnticket_ext.post("/api/v1/forms", status_code=HTTPStatus.CREATED)
@lnticket_ext.put("/api/v1/forms/{form_id}") @lnticket_ext.put("/api/v1/forms/{form_id}")
@api_check_wallet_key("invoice") # @api_check_wallet_key("invoice")
# @api_validate_post_request( # @api_validate_post_request(
# schema={ # schema={
# "wallet": {"type": "string", "empty": False, "required": True}, # "wallet": {"type": "string", "empty": False, "required": True},
@@ -63,52 +66,68 @@ class CreateData(BaseModel):
# "flatrate": {"type": "integer", "required": True}, # "flatrate": {"type": "integer", "required": True},
# } # }
# ) # )
async def api_form_create(data: CreateData, form_id=None): async def api_form_create(data: CreateData, form_id=None, wallet: WalletTypeInfo = Depends(get_key_type)):
if form_id: if form_id:
form = await get_form(form_id) form = await get_form(form_id)
if not form: if not form:
return {"message": "Form does not exist."}, HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Form does not exist."
)
# return {"message": "Form does not exist."}, HTTPStatus.NOT_FOUND
if form.wallet != g.wallet.id: if form.wallet != wallet.wallet.id:
return jsonify{"message": "Not your form."}, HTTPStatus.FORBIDDEN raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail=f"Not your form."
)
# return {"message": "Not your form."}, HTTPStatus.FORBIDDEN
form = await update_form(form_id, **data) form = await update_form(form_id, **data)
else: else:
form = await create_form(**data) form = await create_form(**data)
return form._asdict(), HTTPStatus.CREATED return form._asdict()
@lnticket_ext.delete("/api/v1/forms/{form_id}") @lnticket_ext.delete("/api/v1/forms/{form_id}")
@api_check_wallet_key("invoice") # @api_check_wallet_key("invoice")
async def api_form_delete(form_id): async def api_form_delete(form_id, wallet: WalletTypeInfo = Depends(get_key_type)):
form = await get_form(form_id) form = await get_form(form_id)
if not form: if not form:
return {"message": "Form does not exist."}, HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Form does not exist."
)
# return {"message": "Form does not exist."}, HTTPStatus.NOT_FOUND
if form.wallet != g.wallet.id: if form.wallet != wallet.wallet.id:
return {"message": "Not your form."}, HTTPStatus.FORBIDDEN raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail=f"Not your form."
)
# return {"message": "Not your form."}, HTTPStatus.FORBIDDEN
await delete_form(form_id) await delete_form(form_id)
return "", HTTPStatus.NO_CONTENT # return "", HTTPStatus.NO_CONTENT
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
#########tickets########## #########tickets##########
@lnticket_ext.get("/api/v1/tickets") @lnticket_ext.get("/api/v1/tickets", status_code=HTTPStatus.OK)
@api_check_wallet_key("invoice") # @api_check_wallet_key("invoice")
async def api_tickets(all_wallets: bool = Query(None)): async def api_tickets(all_wallets: bool = Query(None), wallet: WalletTypeInfo = Depends(get_key_type)):
wallet_ids = [g.wallet.id] wallet_ids = [wallet.wallet.id]
if all_wallets: if all_wallets:
wallet_ids = (await get_user(g.wallet.user)).wallet_ids wallet_ids = (await get_user(wallet.wallet.user)).wallet_ids
return ( return (
[form._asdict() for form in await get_tickets(wallet_ids)], [form._asdict() for form in await get_tickets(wallet_ids)]
HTTPStatus.OK,
) )
class CreateTicketData(BaseModel): class CreateTicketData(BaseModel):
@@ -118,7 +137,7 @@ class CreateTicketData(BaseModel):
ltext: str = Query(...) ltext: str = Query(...)
sats: int = Query(..., ge=0) sats: int = Query(..., ge=0)
@lnticket_ext.post("/api/v1/tickets/{form_id}") @lnticket_ext.post("/api/v1/tickets/{form_id}", status_code=HTTPStatus.CREATED)
# @api_validate_post_request( # @api_validate_post_request(
# schema={ # schema={
# "form": {"type": "string", "empty": False, "required": True}, # "form": {"type": "string", "empty": False, "required": True},
@@ -131,7 +150,11 @@ class CreateTicketData(BaseModel):
async def api_ticket_make_ticket(data: CreateTicketData, form_id): async def api_ticket_make_ticket(data: CreateTicketData, form_id):
form = await get_form(form_id) form = await get_form(form_id)
if not form: if not form:
return {"message": "LNTicket does not exist."}, HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"LNTicket does not exist."
)
# return {"message": "LNTicket does not exist."}, HTTPStatus.NOT_FOUND
nwords = len(re.split(r"\s+", data["ltext"])) nwords = len(re.split(r"\s+", data["ltext"]))
sats = data["sats"] sats = data["sats"]
@@ -144,53 +167,70 @@ async def api_ticket_make_ticket(data: CreateTicketData, form_id):
extra={"tag": "lnticket"}, extra={"tag": "lnticket"},
) )
except Exception as e: except Exception as e:
return {"message": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR,
detail=str(e)
)
# return {"message": str(e)}, HTTPStatus.INTERNAL_SERVER_ERROR
ticket = await create_ticket( ticket = await create_ticket(
payment_hash=payment_hash, wallet=form.wallet, **data payment_hash=payment_hash, wallet=form.wallet, **data
) )
if not ticket: if not ticket:
return ( raise HTTPException(
{"message": "LNTicket could not be fetched."}, status_code=HTTPStatus.NOT_FOUND,
HTTPStatus.NOT_FOUND, detail="LNTicket could not be fetched."
) )
# return (
# {"message": "LNTicket could not be fetched."},
# HTTPStatus.NOT_FOUND,
# )
return return {
{"payment_hash": payment_hash, "payment_request": payment_request}, "payment_hash": payment_hash,
HTTPStatus.OK "payment_request": payment_request
}
@lnticket_ext.get("/api/v1/tickets/{payment_hash}") @lnticket_ext.get("/api/v1/tickets/{payment_hash}", status_code=HTTPStatus.OK)
async def api_ticket_send_ticket(payment_hash): async def api_ticket_send_ticket(payment_hash):
ticket = await get_ticket(payment_hash) ticket = await get_ticket(payment_hash)
try: try:
status = await check_invoice_status(ticket.wallet, payment_hash) status = await check_invoice_status(ticket.wallet, payment_hash)
is_paid = not status.pending is_paid = not status.pending
except Exception: except Exception:
return {"paid": False}, HTTPStatus.OK return {"paid": False}
if is_paid: if is_paid:
wallet = await get_wallet(ticket.wallet) wallet = await get_wallet(ticket.wallet)
payment = await wallet.get_payment(payment_hash) payment = await wallet.get_payment(payment_hash)
await payment.set_pending(False) await payment.set_pending(False)
ticket = await set_ticket_paid(payment_hash=payment_hash) ticket = await set_ticket_paid(payment_hash=payment_hash)
return {"paid": True}, HTTPStatus.OK return {"paid": True}
return {"paid": False}, HTTPStatus.OK return {"paid": False}
@lnticket_ext.delete("/api/v1/tickets/{ticket_id}") @lnticket_ext.delete("/api/v1/tickets/{ticket_id}")
@api_check_wallet_key("invoice") # @api_check_wallet_key("invoice")
async def api_ticket_delete(ticket_id): async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_type)):
ticket = await get_ticket(ticket_id) ticket = await get_ticket(ticket_id)
if not ticket: if not ticket:
return {"message": "Paywall does not exist."}, HTTPStatus.NOT_FOUND raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"LNTicket does not exist."
)
# return {"message": "Paywall does not exist."}, HTTPStatus.NOT_FOUND
if ticket.wallet != g.wallet.id: if ticket.wallet != wallet.wallet.id:
return {"message": "Not your ticket."}, HTTPStatus.FORBIDDEN raise HTTPException(
status_code=HTTPStatus.FORBIDDEN,
detail="Not your ticket."
)
# return {"message": "Not your ticket."}, HTTPStatus.FORBIDDEN
await delete_ticket(ticket_id) await delete_ticket(ticket_id)
raise HTTPException(status_code=HTTPStatus.NO_CONTENT)
return "", HTTPStatus.NO_CONTENT # return ""