lnbits-legend/lnbits/extensions/offlineshop/views.py

78 lines
2.5 KiB
Python
Raw Normal View History

import time
from datetime import datetime
from http import HTTPStatus
2021-09-19 13:34:31 +02:00
from typing import List
2021-09-19 13:34:31 +02:00
from fastapi.params import Depends, Query
2021-09-16 19:42:05 +02:00
from starlette.responses import HTMLResponse
from lnbits.decorators import check_user_exists
2021-09-16 19:42:05 +02:00
from lnbits.core.models import Payment, User
from lnbits.core.crud import get_standalone_payment
2021-09-16 19:42:05 +02:00
from . import offlineshop_ext, offlineshop_renderer
2021-09-19 13:34:31 +02:00
from .models import Item
from .crud import get_item, get_shop
2021-09-16 19:42:05 +02:00
from fastapi import Request, HTTPException
2021-09-16 19:42:05 +02:00
@offlineshop_ext.get("/", response_class=HTMLResponse)
async def index(request: Request, user: User = Depends(check_user_exists)):
return offlineshop_renderer().TemplateResponse("offlineshop/index.html", {"request": request, "user": user.dict()})
2021-09-16 19:42:05 +02:00
@offlineshop_ext.get("/print", response_class=HTMLResponse)
2021-09-19 13:34:31 +02:00
async def print_qr_codes(request: Request, items: List[int] = None):
items = []
2021-09-19 13:34:31 +02:00
for item_id in request.query_params.get("items").split(","):
item = await get_item(item_id) # type: Item
if item:
items.append(
{
2021-09-19 13:34:31 +02:00
"lnurl": item.lnurl(request),
"name": item.name,
"price": f"{item.price} {item.unit}",
}
)
2021-09-16 19:42:05 +02:00
return offlineshop_renderer().TemplateResponse("offlineshop/print.html", {"request": request,"items":items})
2021-09-19 13:34:31 +02:00
@offlineshop_ext.get("/confirmation/{p}", name="offlineshop.confirmation_code",
response_class=HTMLResponse)
async def confirmation_code(p: str = Query(...)):
style = "<style>* { font-size: 100px}</style>"
2021-09-16 19:42:05 +02:00
payment_hash = p
payment: Payment = await get_standalone_payment(payment_hash)
if not payment:
2021-09-16 19:42:05 +02:00
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND,
detail=f"Couldn't find the payment {payment_hash}." + style
)
if payment.pending:
2021-09-16 19:42:05 +02:00
raise HTTPException(
status_code=HTTPStatus.PAYMENT_REQUIRED,
detail=f"Payment {payment_hash} wasn't received yet. Please try again in a minute." + style
)
if payment.time + 60 * 15 < time.time():
2021-09-16 19:42:05 +02:00
raise HTTPException(
status_code=HTTPStatus.REQUEST_TIMEOUT,
detail="Too much time has passed." + style
)
item = await get_item(payment.extra.get("item"))
shop = await get_shop(item.shop)
return (
f"""
[{shop.get_code(payment_hash)}]<br>
{item.name}<br>
{item.price} {item.unit}<br>
{datetime.utcfromtimestamp(payment.time).strftime('%Y-%m-%d %H:%M:%S')}
"""
+ style
)