From 6d77d48699d44b6e69c9b5e0f748077f6eb24433 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dni=20=E2=9A=A1?= Date: Thu, 1 Aug 2024 09:32:18 +0200 Subject: [PATCH] fixes --- __init__.py | 29 ++++++++++++----------------- crud.py | 22 +++++++++++++--------- models.py | 3 ++- views.py | 22 +++++++++++++--------- views_api.py | 45 ++++++++++++++++++++++----------------------- 5 files changed, 62 insertions(+), 59 deletions(-) diff --git a/__init__.py b/__init__.py index 65acf0a..16f8789 100644 --- a/__init__.py +++ b/__init__.py @@ -1,16 +1,16 @@ import asyncio -from loguru import logger from fastapi import APIRouter +from loguru import logger -from lnbits.db import Database -from lnbits.helpers import template_renderer -from lnbits.tasks import create_permanent_unique_task - -db = Database("ext_events") - +from .crud import db +from .tasks import wait_for_paid_invoices +from .views import events_generic_router +from .views_api import events_api_router events_ext: APIRouter = APIRouter(prefix="/events", tags=["Events"]) +events_ext.include_router(events_generic_router) +events_ext.include_router(events_api_router) events_static_files = [ { @@ -19,16 +19,6 @@ } ] - -def events_renderer(): - return template_renderer(["events/templates"]) - - -from .tasks import wait_for_paid_invoices -from .views import * # noqa: F401,F403 -from .views_api import * # noqa: F401,F403 - - scheduled_tasks: list[asyncio.Task] = [] @@ -41,5 +31,10 @@ def events_stop(): def events_start(): + from lnbits.tasks import create_permanent_unique_task + task = create_permanent_unique_task("ext_events", wait_for_paid_invoices) scheduled_tasks.append(task) + + +__all__ = ["db", "events_ext", "events_static_files", "events_start", "events_stop"] diff --git a/crud.py b/crud.py index cde77cf..f0ab49d 100644 --- a/crud.py +++ b/crud.py @@ -1,12 +1,12 @@ -from typing import List, Optional, Union from datetime import datetime, timedelta +from typing import List, Optional, Union +from lnbits.db import Database from lnbits.helpers import urlsafe_short_hash -from . import db from .models import CreateEvent, Event, Ticket -# TICKETS +db = Database("ext_events") async def create_ticket( @@ -90,7 +90,8 @@ async def purge_unpaid_tickets(event_id: str) -> None: time_diff = datetime.now() - timedelta(hours=24) await db.execute( f""" - DELETE FROM events.ticket WHERE event = ? AND paid = false AND time < {db.timestamp_placeholder} + DELETE FROM events.ticket WHERE event = ? AND paid = false + AND time < {db.timestamp_placeholder} """, ( event_id, @@ -99,14 +100,14 @@ async def purge_unpaid_tickets(event_id: str) -> None: ) -# EVENTS - - async def create_event(data: CreateEvent) -> Event: event_id = urlsafe_short_hash() await db.execute( """ - INSERT INTO events.events (id, wallet, name, info, banner, closing_date, event_start_date, event_end_date, currency, amount_tickets, price_per_ticket, sold) + INSERT INTO events.events ( + id, wallet, name, info, banner, closing_date, event_start_date, + event_end_date, currency, amount_tickets, price_per_ticket, sold + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( @@ -174,7 +175,10 @@ async def get_event_tickets(event_id: str, wallet_id: str) -> List[Ticket]: async def reg_ticket(ticket_id: str) -> List[Ticket]: await db.execute( - f"UPDATE events.ticket SET registered = ?, reg_timestamp = {db.timestamp_now} WHERE id = ?", + f""" + UPDATE events.ticket SET registered = ?, + reg_timestamp = {db.timestamp_now} WHERE id = ? + """, (True, ticket_id), ) ticket = await db.fetchone("SELECT * FROM events.ticket WHERE id = ?", (ticket_id,)) diff --git a/models.py b/models.py index 2b24098..8cf945d 100644 --- a/models.py +++ b/models.py @@ -1,6 +1,7 @@ +from typing import Optional + from fastapi import Query from pydantic import BaseModel, EmailStr -from typing import Optional class CreateEvent(BaseModel): diff --git a/views.py b/views.py index 082c5a6..5df3693 100644 --- a/views.py +++ b/views.py @@ -1,28 +1,32 @@ from datetime import date, datetime from http import HTTPStatus -from fastapi import Depends, Request +from fastapi import APIRouter, Depends, Request from fastapi.templating import Jinja2Templates -from starlette.exceptions import HTTPException -from starlette.responses import HTMLResponse - from lnbits.core.models import User from lnbits.decorators import check_user_exists +from lnbits.helpers import template_renderer +from starlette.exceptions import HTTPException +from starlette.responses import HTMLResponse -from . import events_ext, events_renderer from .crud import get_event, get_ticket +events_generic_router = APIRouter() templates = Jinja2Templates(directory="templates") -@events_ext.get("/", response_class=HTMLResponse) +def events_renderer(): + return template_renderer(["events/templates"]) + + +@events_generic_router.get("/", response_class=HTMLResponse) async def index(request: Request, user: User = Depends(check_user_exists)): return events_renderer().TemplateResponse( "events/index.html", {"request": request, "user": user.dict()} ) -@events_ext.get("/{event_id}", response_class=HTMLResponse) +@events_generic_router.get("/{event_id}", response_class=HTMLResponse) async def display(request: Request, event_id): event = await get_event(event_id) if not event: @@ -63,7 +67,7 @@ async def display(request: Request, event_id): ) -@events_ext.get("/ticket/{ticket_id}", response_class=HTMLResponse) +@events_generic_router.get("/ticket/{ticket_id}", response_class=HTMLResponse) async def ticket(request: Request, ticket_id): ticket = await get_ticket(ticket_id) if not ticket: @@ -88,7 +92,7 @@ async def ticket(request: Request, ticket_id): ) -@events_ext.get("/register/{event_id}", response_class=HTMLResponse) +@events_generic_router.get("/register/{event_id}", response_class=HTMLResponse) async def register(request: Request, event_id): event = await get_event(event_id) if not event: diff --git a/views_api.py b/views_api.py index a2ba637..8deb212 100644 --- a/views_api.py +++ b/views_api.py @@ -1,23 +1,20 @@ from http import HTTPStatus -from fastapi import Depends, Query -from starlette.exceptions import HTTPException - +from fastapi import APIRouter, Depends, Query from lnbits.core.crud import get_standalone_payment, get_user +from lnbits.core.models import WalletTypeInfo from lnbits.core.services import create_invoice from lnbits.decorators import ( - WalletTypeInfo, get_key_type, require_admin_key, - require_invoice_key, ) from lnbits.utils.exchange_rates import ( currencies, fiat_amount_as_satoshis, get_fiat_rate_satoshis, ) +from starlette.exceptions import HTTPException -from . import events_ext from .crud import ( create_event, create_ticket, @@ -29,17 +26,17 @@ get_events, get_ticket, get_tickets, + purge_unpaid_tickets, reg_ticket, set_ticket_paid, update_event, - purge_unpaid_tickets, ) from .models import CreateEvent, CreateTicket -# Events +events_api_router = APIRouter() -@events_ext.get("/api/v1/events") +@events_api_router.get("/api/v1/events") async def api_events( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): @@ -52,8 +49,8 @@ async def api_events( return [event.dict() for event in await get_events(wallet_ids)] -@events_ext.post("/api/v1/events") -@events_ext.put("/api/v1/events/{event_id}") +@events_api_router.post("/api/v1/events") +@events_api_router.put("/api/v1/events/{event_id}") async def api_event_create( data: CreateEvent, event_id=None, @@ -77,7 +74,7 @@ async def api_event_create( return event.dict() -@events_ext.delete("/api/v1/events/{event_id}") +@events_api_router.delete("/api/v1/events/{event_id}") async def api_form_delete( event_id, wallet: WalletTypeInfo = Depends(require_admin_key) ): @@ -98,7 +95,7 @@ async def api_form_delete( #########Tickets########## -@events_ext.get("/api/v1/tickets") +@events_api_router.get("/api/v1/tickets") async def api_tickets( all_wallets: bool = Query(False), wallet: WalletTypeInfo = Depends(get_key_type) ): @@ -111,14 +108,14 @@ async def api_tickets( return [ticket.dict() for ticket in await get_tickets(wallet_ids)] -@events_ext.post("/api/v1/tickets/{event_id}") +@events_api_router.post("/api/v1/tickets/{event_id}") async def api_ticket_create(event_id: str, data: CreateTicket): name = data.name email = data.email return await api_ticket_make_ticket(event_id, name, email) -@events_ext.get("/api/v1/tickets/{event_id}/{name}/{email}") +@events_api_router.get("/api/v1/tickets/{event_id}/{name}/{email}") async def api_ticket_make_ticket(event_id, name, email): event = await get_event(event_id) if not event: @@ -151,12 +148,14 @@ async def api_ticket_make_ticket(event_id, name, email): name=name, email=email, ) - except Exception as e: - raise HTTPException(status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(e)) + except Exception as exc: + raise HTTPException( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, detail=str(exc) + ) from exc return {"payment_hash": payment_hash, "payment_request": payment_request} -@events_ext.post("/api/v1/tickets/{event_id}/{payment_hash}") +@events_api_router.post("/api/v1/tickets/{event_id}/{payment_hash}") async def api_ticket_send_ticket(event_id, payment_hash): event = await get_event(event_id) if not event: @@ -189,7 +188,7 @@ async def api_ticket_send_ticket(event_id, payment_hash): return {"paid": False} -@events_ext.delete("/api/v1/tickets/{ticket_id}") +@events_api_router.delete("/api/v1/tickets/{ticket_id}") async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_type)): ticket = await get_ticket(ticket_id) if not ticket: @@ -204,7 +203,7 @@ async def api_ticket_delete(ticket_id, wallet: WalletTypeInfo = Depends(get_key_ return "", HTTPStatus.NO_CONTENT -@events_ext.get("/api/v1/purge/{event_id}") +@events_api_router.get("/api/v1/purge/{event_id}") async def api_event_purge_tickets(event_id): event = await get_event(event_id) if not event: @@ -217,7 +216,7 @@ async def api_event_purge_tickets(event_id): # Event Tickets -@events_ext.get("/api/v1/eventtickets/{wallet_id}/{event_id}") +@events_api_router.get("/api/v1/eventtickets/{wallet_id}/{event_id}") async def api_event_tickets(wallet_id, event_id): return [ ticket.dict() @@ -225,7 +224,7 @@ async def api_event_tickets(wallet_id, event_id): ] -@events_ext.get("/api/v1/register/ticket/{ticket_id}") +@events_api_router.get("/api/v1/register/ticket/{ticket_id}") async def api_event_register_ticket(ticket_id): ticket = await get_ticket(ticket_id) @@ -247,6 +246,6 @@ async def api_event_register_ticket(ticket_id): return [ticket.dict() for ticket in await reg_ticket(ticket_id)] -@events_ext.get("/api/v1/currencies") +@events_api_router.get("/api/v1/currencies") async def api_list_currencies_available(): return list(currencies.keys())