Skip to content

Commit

Permalink
fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dni committed Aug 1, 2024
1 parent 5d91585 commit 6d77d48
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 59 deletions.
29 changes: 12 additions & 17 deletions __init__.py
Original file line number Diff line number Diff line change
@@ -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 = [
{
Expand All @@ -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] = []


Expand All @@ -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"]
22 changes: 13 additions & 9 deletions crud.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
Expand Down Expand Up @@ -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,))
Expand Down
3 changes: 2 additions & 1 deletion models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from typing import Optional

from fastapi import Query
from pydantic import BaseModel, EmailStr
from typing import Optional


class CreateEvent(BaseModel):
Expand Down
22 changes: 13 additions & 9 deletions views.py
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down
45 changes: 22 additions & 23 deletions views_api.py
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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)
):
Expand All @@ -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,
Expand All @@ -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)
):
Expand All @@ -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)
):
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand All @@ -217,15 +216,15 @@ 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()
for ticket in await get_event_tickets(wallet_id=wallet_id, event_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)

Expand All @@ -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())

0 comments on commit 6d77d48

Please sign in to comment.