diff --git a/API_DOCUMENTATION.md b/API_DOCUMENTATION.md
new file mode 100644
index 0000000..9ad0d5f
--- /dev/null
+++ b/API_DOCUMENTATION.md
@@ -0,0 +1,56 @@
+# Events API Documentation
+
+## Public Events Endpoint
+
+### GET `/api/v1/events/public`
+
+Retrieve all events in the database with read-only access. No authentication required.
+
+**Authentication:** None required (public endpoint)
+
+**Headers:**
+```
+None required
+```
+
+**Query Parameters:**
+- None
+
+**Response:**
+```json
+[
+ {
+ "id": "event_id",
+ "wallet": "wallet_id",
+ "name": "Event Name",
+ "info": "Event description",
+ "closing_date": "2024-12-31",
+ "event_start_date": "2024-12-01",
+ "event_end_date": "2024-12-02",
+ "currency": "sat",
+ "amount_tickets": 100,
+ "price_per_ticket": 1000.0,
+ "time": "2024-01-01T00:00:00Z",
+ "sold": 0,
+ "banner": null
+ }
+]
+```
+
+**Example Usage:**
+```bash
+curl http://your-lnbits-instance/events/api/v1/events/public
+```
+
+**Notes:**
+- This endpoint allows read-only access to all events in the database
+- No authentication required (truly public endpoint)
+- Returns events ordered by creation time (newest first)
+- Suitable for public event listings or read-only integrations
+
+## Comparison with Existing Endpoints
+
+| Endpoint | Authentication | Scope | Use Case |
+|----------|---------------|-------|----------|
+| `/api/v1/events` | Invoice Key | User's wallets only | Private event management |
+| `/api/v1/events/public` | None | All events | Public event browsing |
\ No newline at end of file
diff --git a/README.md b/README.md
index ebd7194..f356ba7 100644
--- a/README.md
+++ b/README.md
@@ -2,9 +2,9 @@
For more about LNBits extension check [this tutorial](https://github.com/lnbits/lnbits/wiki/LNbits-Extensions)
-## Sell tickets for events and use the built-in scanner for registering attendants
+## Sell tickets for events and use the built-in scanner for registering attendees
-Events alows you to make tickets for an event. Each ticket is in the form of a uniqque QR code. After registering, and paying for ticket, the user gets a QR code to present at registration/entrance.
+Events alows you to make tickets for an event. Each ticket is in the form of a unique QR code. After registering, and paying for ticket, the user gets a QR code to present at registration/entrance.
Events includes a shareable ticket scanner, which can be used to register attendees.
diff --git a/__init__.py b/__init__.py
index 14c1590..8d42ecf 100644
--- a/__init__.py
+++ b/__init__.py
@@ -21,6 +21,9 @@ events_static_files = [
scheduled_tasks: list[asyncio.Task] = []
+# Module-level NostrClient — None when nostrclient is unavailable
+nostr_client = None
+
def events_stop():
for task in scheduled_tasks:
@@ -29,12 +32,50 @@ def events_stop():
except Exception as ex:
logger.warning(ex)
+ global nostr_client
+ if nostr_client:
+ asyncio.get_event_loop().create_task(nostr_client.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)
+ task1 = create_permanent_unique_task("ext_events", wait_for_paid_invoices)
+ scheduled_tasks.append(task1)
+
+ async def _start_nostr_client():
+ global nostr_client
+ await asyncio.sleep(10) # Wait for nostrclient to be ready
+ try:
+ from .nostr.nostr_client import NostrClient
+
+ nostr_client = NostrClient()
+ logger.info("[EVENTS] Starting NostrClient for NIP-52 sync")
+ await nostr_client.run_forever()
+ except Exception as e:
+ logger.warning(f"[EVENTS] NostrClient failed to start: {e}")
+ logger.info("[EVENTS] Events will work without Nostr sync")
+
+ task2 = create_permanent_unique_task("ext_events_nostr", _start_nostr_client)
+ scheduled_tasks.append(task2)
+
+ async def _sync_nostr_events():
+ global nostr_client
+ await asyncio.sleep(15) # Wait for NostrClient to connect
+ if not nostr_client:
+ logger.info("[EVENTS] No NostrClient, skipping Nostr sync")
+ return
+ try:
+ from .nostr_sync import wait_for_nostr_events
+
+ await wait_for_nostr_events(nostr_client)
+ except Exception as e:
+ logger.error(f"[EVENTS] Nostr sync task failed: {e}")
+
+ task3 = create_permanent_unique_task(
+ "ext_events_nostr_sync", _sync_nostr_events
+ )
+ scheduled_tasks.append(task3)
__all__ = ["db", "events_ext", "events_start", "events_static_files", "events_stop"]
diff --git a/crud.py b/crud.py
index 6d19761..1a9c761 100644
--- a/crud.py
+++ b/crud.py
@@ -1,54 +1,145 @@
+import json
from datetime import datetime, timedelta, timezone
+from typing import Optional
from lnbits.db import Database
from lnbits.helpers import urlsafe_short_hash
-from .models import CreateEvent, Event, Ticket
+from .models import CreateEvent, Event, EventsSettings, Ticket, TicketExtra
+
+
+def _parse_ticket_row(row) -> dict:
+ """
+ Parse a database row into a dict suitable for Ticket model creation.
+ Handles:
+ - Empty string to None conversion for name/email
+ - JSON string to dict conversion for extra field
+ """
+ ticket_data = dict(row)
+
+ # Convert empty strings back to None for the model
+ if ticket_data.get("name") == "":
+ ticket_data["name"] = None
+ if ticket_data.get("email") == "":
+ ticket_data["email"] = None
+
+ # Parse extra field from JSON string if needed
+ # (db.insert() serializes to JSON, but manual fetchone/fetchall returns string)
+ extra = ticket_data.get("extra")
+ if isinstance(extra, str):
+ ticket_data["extra"] = json.loads(extra)
+
+ return ticket_data
db = Database("ext_events")
async def create_ticket(
- payment_hash: str, wallet: str, event: str, name: str, email: str
+ payment_hash: str,
+ wallet: str,
+ event: str,
+ name: Optional[str] = None,
+ email: Optional[str] = None,
+ user_id: Optional[str] = None,
+ extra: Optional[dict] = None,
) -> Ticket:
now = datetime.now(timezone.utc)
- ticket = Ticket(
+
+ # TODO: Check if this empty string workaround is still needed.
+ # This converts None to empty strings for database storage because:
+ # 1. Database may have NOT NULL constraints on name/email columns
+ # 2. When user_id is provided, name/email are not used (mutually exclusive)
+ # 3. The get_ticket() functions convert empty strings back to None when reading
+ # Consider using nullable columns instead of this empty string pattern.
+ if user_id:
+ db_name = ""
+ db_email = ""
+ else:
+ db_name = name or ""
+ db_email = email or ""
+
+ # Create ticket with database-compatible values for insertion
+ # Using db.insert() ensures proper serialization of the extra field (TicketExtra)
+ # across all database backends (SQLite, PostgreSQL, CockroachDB)
+ db_ticket = Ticket(
+ id=payment_hash,
+ wallet=wallet,
+ event=event,
+ name=db_name,
+ email=db_email,
+ user_id=user_id,
+ registered=False,
+ paid=False,
+ reg_timestamp=now,
+ time=now,
+ extra=TicketExtra(**extra) if extra else TicketExtra(),
+ )
+
+ await db.insert("events.ticket", db_ticket)
+
+ # Return ticket with original name/email values (not empty strings)
+ # This maintains consistency with how get_ticket() converts empty strings back to None
+ return Ticket(
id=payment_hash,
wallet=wallet,
event=event,
name=name,
email=email,
+ user_id=user_id,
registered=False,
paid=False,
reg_timestamp=now,
time=now,
+ extra=TicketExtra(**extra) if extra else TicketExtra(),
)
- await db.insert("events.ticket", ticket)
- return ticket
async def update_ticket(ticket: Ticket) -> Ticket:
- await db.update("events.ticket", ticket)
+ # Create a new Ticket object with corrected values for database constraints
+ ticket_dict = ticket.dict()
+
+ # Convert None values to empty strings for database constraints
+ if ticket_dict.get("name") is None:
+ ticket_dict["name"] = ""
+ if ticket_dict.get("email") is None:
+ ticket_dict["email"] = ""
+
+ # Create a new Ticket object with the corrected values
+ corrected_ticket = Ticket(**ticket_dict)
+
+ await db.update("events.ticket", corrected_ticket)
return ticket
-async def get_ticket(payment_hash: str) -> Ticket | None:
- return await db.fetchone(
+async def get_ticket(payment_hash: str) -> Optional[Ticket]:
+ row = await db.fetchone(
"SELECT * FROM events.ticket WHERE id = :id",
{"id": payment_hash},
- Ticket,
)
+ if not row:
+ return None
+
+ return Ticket(**_parse_ticket_row(row))
async def get_tickets(wallet_ids: str | list[str]) -> list[Ticket]:
if isinstance(wallet_ids, str):
wallet_ids = [wallet_ids]
q = ",".join([f"'{wallet_id}'" for wallet_id in wallet_ids])
- return await db.fetchall(
- f"SELECT * FROM events.ticket WHERE wallet IN ({q})",
- model=Ticket,
+ rows = await db.fetchall(f"SELECT * FROM events.ticket WHERE wallet IN ({q})")
+
+ return [Ticket(**_parse_ticket_row(row)) for row in rows]
+
+
+async def get_tickets_by_user_id(user_id: str) -> list[Ticket]:
+ """Get all tickets for a specific user by their user_id"""
+ rows = await db.fetchall(
+ "SELECT * FROM events.ticket WHERE user_id = :user_id ORDER BY time DESC",
+ {"user_id": user_id}
)
+ return [Ticket(**_parse_ticket_row(row)) for row in rows]
+
async def delete_ticket(payment_hash: str) -> None:
await db.execute("DELETE FROM events.ticket WHERE id = :id", {"id": payment_hash})
@@ -73,6 +164,12 @@ async def purge_unpaid_tickets(event_id: str) -> None:
async def create_event(data: CreateEvent) -> Event:
event_id = urlsafe_short_hash()
+ # Default end date to start date if not provided
+ if not data.event_end_date:
+ data.event_end_date = data.event_start_date
+ # Default closing date to end date if not provided
+ if not data.closing_date:
+ data.closing_date = data.event_end_date
event = Event(id=event_id, time=datetime.now(timezone.utc), **data.dict())
await db.insert("events.events", event)
return event
@@ -101,13 +198,63 @@ async def get_events(wallet_ids: str | list[str]) -> list[Event]:
)
+async def get_all_events() -> list[Event]:
+ """Get all events from the database without wallet filtering."""
+ return await db.fetchall(
+ "SELECT * FROM events.events ORDER BY time DESC",
+ model=Event,
+ )
+
+
+async def get_public_events() -> list[Event]:
+ """Get approved, non-canceled events for public display."""
+ return await db.fetchall(
+ """
+ SELECT * FROM events.events
+ WHERE status = 'approved' AND canceled = FALSE
+ ORDER BY event_start_date ASC
+ """,
+ model=Event,
+ )
+
+
+async def get_pending_events() -> list[Event]:
+ """Get proposed events awaiting admin approval."""
+ return await db.fetchall(
+ "SELECT * FROM events.events WHERE status = 'proposed' ORDER BY time DESC",
+ model=Event,
+ )
+
+
+async def get_settings() -> EventsSettings:
+ """Get extension settings (single row, always exists after migration)."""
+ row = await db.fetchone("SELECT * FROM events.settings WHERE id = 1")
+ if row:
+ return EventsSettings(**dict(row))
+ return EventsSettings()
+
+
+async def update_settings(settings: EventsSettings) -> EventsSettings:
+ """Update extension settings."""
+ await db.execute(
+ """
+ UPDATE events.settings
+ SET auto_approve = :auto_approve
+ WHERE id = 1
+ """,
+ {"auto_approve": settings.auto_approve},
+ )
+ return settings
+
+
async def delete_event(event_id: str) -> None:
await db.execute("DELETE FROM events.events WHERE id = :id", {"id": event_id})
async def get_event_tickets(event_id: str) -> list[Ticket]:
- return await db.fetchall(
+ rows = await db.fetchall(
"SELECT * FROM events.ticket WHERE event = :event",
{"event": event_id},
- Ticket,
)
+
+ return [Ticket(**_parse_ticket_row(row)) for row in rows]
diff --git a/migrations.py b/migrations.py
index 87a0dd4..2800810 100644
--- a/migrations.py
+++ b/migrations.py
@@ -160,3 +160,86 @@ async def m005_add_image_banner(db):
Add a column to allow an image banner for the event
"""
await db.execute("ALTER TABLE events.events ADD COLUMN banner TEXT;")
+
+
+async def m006_add_user_id_support(db):
+ """
+ Add user_id column to tickets table to support LNbits user-id as identifier
+ Make name and email optional when user_id is provided
+ """
+ await db.execute("ALTER TABLE events.ticket ADD COLUMN user_id TEXT;")
+
+ # Since SQLite doesn't support changing column constraints directly,
+ # we'll work around this by allowing the application logic to handle
+ # the validation that either (name AND email) OR user_id is provided
+ # The database will continue to expect name and email as NOT NULL
+ # but we'll insert empty strings for user_id tickets
+
+async def m007_add_extra_fields(db):
+ """
+ Add a canceled and 'extra' column to events and ticket tables
+ to support promo codes and ticket metadata.
+ """
+ # Add canceled and 'extra' columns to events table
+ # SQLite requires separate ALTER TABLE statements for each column
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN canceled BOOLEAN NOT NULL DEFAULT FALSE;"
+ )
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN extra TEXT;"
+ )
+
+ # Add 'extra' column to ticket table
+ await db.execute("ALTER TABLE events.ticket ADD COLUMN extra TEXT;")
+
+
+async def m008_add_event_status(db):
+ """
+ Add status column to events table for proposal/approval workflow.
+ Values: 'proposed', 'approved', 'rejected'.
+ Default 'approved' for backward compatibility with existing events.
+ """
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN status TEXT NOT NULL DEFAULT 'approved';"
+ )
+
+
+async def m009_add_nostr_columns(db):
+ """
+ Add columns to track published NIP-52 Nostr calendar events.
+ """
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN nostr_event_id TEXT;"
+ )
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN nostr_event_created_at INTEGER;"
+ )
+
+
+async def m010_add_events_settings(db):
+ """
+ Create extension settings table for admin-configurable options.
+ """
+ await db.execute(
+ """
+ CREATE TABLE IF NOT EXISTS events.settings (
+ id INTEGER PRIMARY KEY DEFAULT 1,
+ auto_approve BOOLEAN NOT NULL DEFAULT FALSE
+ );
+ """
+ )
+ await db.execute(
+ "INSERT OR IGNORE INTO events.settings (id, auto_approve) VALUES (1, FALSE);"
+ )
+
+
+async def m011_add_location_and_categories(db):
+ """
+ Add location and categories columns for NIP-52 calendar event support.
+ """
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN location TEXT;"
+ )
+ await db.execute(
+ "ALTER TABLE events.events ADD COLUMN categories TEXT;"
+ )
diff --git a/models.py b/models.py
index f0a52b2..47d163b 100644
--- a/models.py
+++ b/models.py
@@ -1,50 +1,122 @@
+import json
from datetime import datetime
+from typing import Optional
from fastapi import Query
-from pydantic import BaseModel, EmailStr
+from pydantic import BaseModel, EmailStr, Field, root_validator, validator
+
+
+class PromoCode(BaseModel):
+ code: str
+ discount_percent: float = 0.0
+ active: bool = True
+
+ # make the promo code uppercase
+ @validator("code")
+ def uppercase_code(cls, v):
+ return v.upper()
+
+ @validator("discount_percent")
+ def validate_discount_percent(cls, v):
+ assert 0 <= v <= 100, "Discount must be between 0 and 100."
+ return v
+
+
+class EventExtra(BaseModel):
+ promo_codes: list[PromoCode] = Field(default_factory=list)
+ conditional: bool = False
+ min_tickets: int = 1
class CreateEvent(BaseModel):
- wallet: str
- name: str
- info: str
- closing_date: str
- event_start_date: str
- event_end_date: str
+ wallet: Optional[str] = None
+ name: str # title (required)
+ info: str = "" # description (optional, visible by default)
+ closing_date: Optional[str] = None # defaults to event_end_date or event_start_date
+ event_start_date: str # required
+ event_end_date: Optional[str] = None # defaults to event_start_date
currency: str = "sat"
- amount_tickets: int = Query(..., ge=0)
- price_per_ticket: float = Query(..., ge=0)
- banner: str | None = None
+ amount_tickets: int = 0 # 0 = unlimited / not ticketed
+ price_per_ticket: float = 0 # 0 = free
+ banner: Optional[str] = None # image URL (optional, visible by default)
+ location: Optional[str] = None # venue/address (optional, visible by default)
+ categories: list[str] = Field(default_factory=list) # NIP-52 't' tags
+ extra: EventExtra = Field(default_factory=EventExtra)
+ status: str = "approved" # proposed, approved, rejected
class CreateTicket(BaseModel):
- name: str
- email: EmailStr
+ name: Optional[str] = None
+ email: Optional[EmailStr] = None
+ user_id: Optional[str] = None
+ promo_code: Optional[str] = None
+ refund_address: Optional[str] = None
+
+ @root_validator
+ def validate_identifiers(cls, values):
+ # Ensure either (name AND email) OR user_id is provided
+ name = values.get('name')
+ email = values.get('email')
+ user_id = values.get('user_id')
+
+ if not user_id and not (name and email):
+ raise ValueError("Either user_id or both name and email must be provided")
+ if user_id and (name or email):
+ raise ValueError("Cannot provide both user_id and name/email")
+ return values
class Event(BaseModel):
id: str
wallet: str
name: str
- info: str
- closing_date: str
+ info: str = ""
+ closing_date: str | None = None
+ canceled: bool = False
event_start_date: str
- event_end_date: str
- currency: str
- amount_tickets: int
- price_per_ticket: float
+ event_end_date: str | None = None
+ currency: str = "sat"
+ amount_tickets: int = 0
+ price_per_ticket: float = 0
time: datetime
sold: int = 0
banner: str | None = None
+ location: str | None = None
+ categories: list[str] = Field(default_factory=list)
+ extra: EventExtra = Field(default_factory=EventExtra)
+ status: str = "approved" # proposed, approved, rejected
+ nostr_event_id: str | None = None
+ nostr_event_created_at: int | None = None
+
+ @validator("categories", pre=True)
+ def parse_categories(cls, v):
+ if isinstance(v, str):
+ return json.loads(v) if v else []
+ return v or []
+
+
+class EventsSettings(BaseModel):
+ """Extension-level settings for the events extension."""
+
+ auto_approve: bool = False # Skip approval for all users
+
+
+class TicketExtra(BaseModel):
+ applied_promo_code: str | None = None
+ sats_paid: int | None = None
+ refund_address: str | None = None
+ refunded: bool = False
class Ticket(BaseModel):
id: str
wallet: str
event: str
- name: str
- email: str
+ name: Optional[str] = None
+ email: Optional[str] = None
+ user_id: Optional[str] = None
registered: bool
paid: bool
time: datetime
reg_timestamp: datetime
+ extra: TicketExtra = Field(default_factory=TicketExtra)
diff --git a/nostr/__init__.py b/nostr/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/nostr/event.py b/nostr/event.py
new file mode 100644
index 0000000..7da8288
--- /dev/null
+++ b/nostr/event.py
@@ -0,0 +1,27 @@
+import hashlib
+import json
+from typing import List, Optional
+
+from pydantic import BaseModel
+
+
+class NostrEvent(BaseModel):
+ id: str = ""
+ pubkey: str
+ created_at: int
+ kind: int
+ tags: List[List[str]] = []
+ content: str = ""
+ sig: Optional[str] = None
+
+ def serialize(self) -> List:
+ return [0, self.pubkey, self.created_at, self.kind, self.tags, self.content]
+
+ def serialize_json(self) -> str:
+ e = self.serialize()
+ return json.dumps(e, separators=(",", ":"), ensure_ascii=False)
+
+ @property
+ def event_id(self) -> str:
+ data = self.serialize_json()
+ return hashlib.sha256(data.encode()).hexdigest()
diff --git a/nostr/nostr_client.py b/nostr/nostr_client.py
new file mode 100644
index 0000000..f8f63de
--- /dev/null
+++ b/nostr/nostr_client.py
@@ -0,0 +1,144 @@
+"""
+Bidirectional Nostr client for the events extension.
+
+Connects to the nostrclient extension's internal WebSocket to publish
+and subscribe to NIP-52 calendar events. Based on nostrmarket's
+NostrClient pattern.
+"""
+
+import asyncio
+import json
+from asyncio import Queue
+from collections import OrderedDict
+from typing import Optional
+
+from loguru import logger
+from websocket import WebSocketApp
+
+from lnbits.helpers import encrypt_internal_message, urlsafe_short_hash
+from lnbits.settings import settings
+
+from .event import NostrEvent
+
+MAX_SEEN_EVENTS = 500
+
+
+class NostrClient:
+ def __init__(self):
+ self.receive_event_queue: Queue = Queue()
+ self.send_req_queue: Queue = Queue()
+ self.ws: Optional[WebSocketApp] = None
+ self.subscription_id = "events-" + urlsafe_short_hash()[:32]
+ self.running = False
+ self._seen_events: OrderedDict[str, None] = OrderedDict()
+
+ @property
+ def is_websocket_connected(self):
+ if not self.ws:
+ return False
+ return self.ws.keep_running
+
+ async def connect(self) -> WebSocketApp:
+ relay_endpoint = encrypt_internal_message("relay", urlsafe=True)
+ ws_url = (
+ f"ws://localhost:{settings.port}"
+ f"/nostrclient/api/v1/{relay_endpoint}"
+ )
+
+ logger.info("[EVENTS] Connecting to nostrclient WebSocket...")
+
+ def on_open(_):
+ logger.info("[EVENTS] Connected to nostrclient WebSocket")
+
+ def on_message(_, message):
+ try:
+ self.receive_event_queue.put_nowait(message)
+ except Exception as e:
+ logger.error(f"[EVENTS] Failed to queue message: {e}")
+
+ def on_error(_, error):
+ logger.warning(f"[EVENTS] WebSocket error: {error}")
+
+ def on_close(_, status_code, message):
+ logger.warning(
+ f"[EVENTS] WebSocket closed: {status_code} {message}"
+ )
+ self.receive_event_queue.put_nowait(
+ ValueError("WebSocket closed")
+ )
+
+ ws = WebSocketApp(
+ ws_url,
+ on_message=on_message,
+ on_open=on_open,
+ on_close=on_close,
+ on_error=on_error,
+ )
+
+ from threading import Thread
+
+ wst = Thread(target=ws.run_forever)
+ wst.daemon = True
+ wst.start()
+
+ return ws
+
+ async def run_forever(self):
+ self.running = True
+ while self.running:
+ try:
+ if not self.is_websocket_connected:
+ self.ws = await self.connect()
+ await asyncio.sleep(5)
+
+ req = await self.send_req_queue.get()
+ assert self.ws
+ self.ws.send(json.dumps(req))
+ except Exception as ex:
+ logger.warning(f"[EVENTS] NostrClient error: {ex}")
+ await asyncio.sleep(60)
+
+ def is_duplicate_event(self, event_id: str) -> bool:
+ """Check if an event has been seen recently."""
+ if event_id in self._seen_events:
+ return True
+ self._seen_events[event_id] = None
+ if len(self._seen_events) > MAX_SEEN_EVENTS:
+ self._seen_events.popitem(last=False)
+ return False
+
+ async def get_event(self):
+ """Get next event from the receive queue."""
+ value = await self.receive_event_queue.get()
+ if isinstance(value, ValueError):
+ raise value
+ return value
+
+ async def publish_nostr_event(self, e: NostrEvent):
+ await self.send_req_queue.put(["EVENT", e.dict()])
+
+ async def subscribe(self, filters: list[dict]):
+ """Subscribe to events matching the given filters."""
+ self.subscription_id = "events-" + urlsafe_short_hash()[:32]
+ await self.send_req_queue.put(
+ ["REQ", self.subscription_id] + filters
+ )
+ logger.info(
+ f"[EVENTS] Subscribed to NIP-52 events "
+ f"(sub: {self.subscription_id[:20]}...)"
+ )
+
+ async def unsubscribe(self):
+ """Unsubscribe from current subscription."""
+ await self.send_req_queue.put(["CLOSE", self.subscription_id])
+
+ async def stop(self):
+ await self.unsubscribe()
+ self.running = False
+ await asyncio.sleep(2)
+ if self.ws:
+ try:
+ self.ws.close()
+ except Exception:
+ pass
+ self.ws = None
diff --git a/nostr_publisher.py b/nostr_publisher.py
new file mode 100644
index 0000000..f76cd97
--- /dev/null
+++ b/nostr_publisher.py
@@ -0,0 +1,119 @@
+"""
+NIP-52 calendar event publishing for the events extension.
+
+Builds kind 31922 (date-based) calendar events from the Event model,
+signs them with the event creator's Account keypair, and publishes
+via the NostrClient to nostrclient relays.
+
+Reference: https://github.com/nostr-protocol/nips/blob/master/52.md
+"""
+
+import time
+from typing import Optional
+
+import coincurve
+from loguru import logger
+
+from .models import Event
+from .nostr.event import NostrEvent
+
+
+def build_nip52_event(event: Event, pubkey: str) -> NostrEvent:
+ """
+ Convert an Event model to a NIP-52 kind 31922 (date-based) calendar event.
+
+ Tags:
+ d - event.id (addressable identifier)
+ title - event.name
+ start - event.event_start_date (ISO date string)
+ end - event.event_end_date (optional)
+ image - event.banner (optional)
+ Content: event.info (description)
+ """
+ tags = [
+ ["d", event.id],
+ ["title", event.name],
+ ["start", event.event_start_date],
+ ]
+
+ if event.event_end_date:
+ tags.append(["end", event.event_end_date])
+ if event.banner:
+ tags.append(["image", event.banner])
+ if event.location:
+ tags.append(["location", event.location])
+ for cat in (event.categories or []):
+ tags.append(["t", cat])
+
+ nostr_event = NostrEvent(
+ pubkey=pubkey,
+ created_at=int(time.time()),
+ kind=31922,
+ tags=tags,
+ content=event.info or "",
+ )
+ nostr_event.id = nostr_event.event_id
+ return nostr_event
+
+
+def build_nip52_delete_event(event: Event, pubkey: str) -> NostrEvent:
+ """
+ Build a kind 5 delete event for a published NIP-52 calendar event.
+
+ Uses an 'a' tag to reference the parameterized replaceable event
+ (kind 31922) per NIP-09.
+ """
+ nostr_event = NostrEvent(
+ pubkey=pubkey,
+ created_at=int(time.time()),
+ kind=5,
+ tags=[
+ ["a", f"31922:{pubkey}:{event.id}"],
+ ],
+ content="Event canceled",
+ )
+ nostr_event.id = nostr_event.event_id
+ return nostr_event
+
+
+def sign_nostr_event(nostr_event: NostrEvent, private_key_hex: str) -> None:
+ """Sign a NostrEvent in-place using Schnorr signature."""
+ privkey = coincurve.PrivateKey(bytes.fromhex(private_key_hex))
+ sig = privkey.sign_schnorr(bytes.fromhex(nostr_event.id))
+ nostr_event.sig = sig.hex()
+
+
+async def publish_event_to_nostr(
+ nostr_client,
+ event: Event,
+ account_pubkey: str,
+ account_prvkey: str,
+ delete: bool = False,
+) -> Optional[NostrEvent]:
+ """
+ Build, sign, and publish a NIP-52 calendar event (or delete event).
+
+ Returns the published NostrEvent for metadata storage, or None on failure.
+ """
+ if not nostr_client:
+ logger.debug("[EVENTS] No NostrClient available, skipping publish")
+ return None
+
+ try:
+ if delete:
+ nostr_event = build_nip52_delete_event(event, account_pubkey)
+ else:
+ nostr_event = build_nip52_event(event, account_pubkey)
+
+ sign_nostr_event(nostr_event, account_prvkey)
+ await nostr_client.publish_nostr_event(nostr_event)
+
+ logger.info(
+ f"[EVENTS] Published NIP-52 {'delete' if delete else 'calendar'} "
+ f"event: {nostr_event.id[:16]}... (kind {nostr_event.kind})"
+ )
+ return nostr_event
+
+ except Exception as e:
+ logger.warning(f"[EVENTS] Failed to publish to Nostr: {e}")
+ return None
diff --git a/nostr_sync.py b/nostr_sync.py
new file mode 100644
index 0000000..1c508dc
--- /dev/null
+++ b/nostr_sync.py
@@ -0,0 +1,170 @@
+"""
+Bidirectional Nostr sync for the events extension.
+
+Subscribes to NIP-52 calendar events (kind 31922/31923) from relays
+and upserts them into the local database. Enables federated event
+discovery — events published by other LNbits instances or Nostr
+clients appear in the local events listing.
+"""
+
+import json
+from datetime import datetime, timezone
+
+from loguru import logger
+
+from .crud import create_event, db, get_event, update_event
+from .models import CreateEvent, Event
+from .nostr.nostr_client import NostrClient
+
+
+async def process_nostr_message(nostr_client: NostrClient, message: str):
+ """Process an incoming Nostr relay message."""
+ try:
+ data = json.loads(message)
+ except json.JSONDecodeError:
+ return
+
+ if not isinstance(data, list) or len(data) < 2:
+ return
+
+ msg_type = data[0]
+
+ if msg_type == "EVENT" and len(data) >= 3:
+ event_data = data[2]
+ await _handle_calendar_event(nostr_client, event_data)
+ elif msg_type == "EOSE":
+ logger.debug("[EVENTS] End of stored events from relay")
+ elif msg_type == "NOTICE":
+ logger.info(f"[EVENTS] Relay notice: {data[1]}")
+
+
+async def _handle_calendar_event(nostr_client: NostrClient, event_data: dict):
+ """Handle an incoming NIP-52 calendar event (kind 31922 or 31923)."""
+ kind = event_data.get("kind")
+ if kind not in (31922, 31923):
+ return
+
+ event_id = event_data.get("id", "")
+ if nostr_client.is_duplicate_event(event_id):
+ return
+
+ tags = {t[0]: t[1] for t in event_data.get("tags", []) if len(t) >= 2}
+ tag_lists = {}
+ for t in event_data.get("tags", []):
+ if len(t) >= 2:
+ tag_lists.setdefault(t[0], []).append(t[1])
+
+ d_tag = tags.get("d")
+ if not d_tag:
+ return
+
+ title = tags.get("title", "Untitled Event")
+ start = tags.get("start")
+ if not start:
+ return
+
+ end = tags.get("end")
+ description = event_data.get("content", "")
+ image = tags.get("image")
+ location = tags.get("location")
+ categories = tag_lists.get("t", [])
+
+ # Check if we already have this event (by d-tag as our event ID
+ # or by nostr_event_id)
+ existing = await get_event(d_tag)
+ if not existing:
+ # Check by nostr_event_id
+ existing = await db.fetchone(
+ "SELECT * FROM events.events WHERE nostr_event_id = :nid",
+ {"nid": event_id},
+ Event,
+ )
+
+ if existing:
+ # Update if the incoming event is newer
+ incoming_created_at = event_data.get("created_at", 0)
+ if (
+ existing.nostr_event_created_at
+ and incoming_created_at <= existing.nostr_event_created_at
+ ):
+ return # We already have a newer version
+
+ existing.name = title
+ existing.info = description
+ existing.event_start_date = start
+ existing.event_end_date = end
+ existing.banner = image
+ existing.location = location
+ existing.categories = categories
+ existing.nostr_event_id = event_id
+ existing.nostr_event_created_at = incoming_created_at
+ await update_event(existing)
+ logger.info(f"[EVENTS] Updated event from Nostr: {title}")
+ else:
+ # Create new event from Nostr
+ # Events discovered from Nostr are auto-approved (they're already public)
+ event = CreateEvent(
+ wallet="", # No wallet — discovered from Nostr, not ticketed locally
+ name=title,
+ info=description,
+ event_start_date=start,
+ event_end_date=end,
+ banner=image,
+ location=location,
+ categories=categories,
+ status="approved",
+ )
+ # Use the d-tag as the event ID for correlation
+ from lnbits.db import Database
+
+ new_event = Event(
+ id=d_tag,
+ wallet="",
+ name=title,
+ info=description,
+ event_start_date=start,
+ event_end_date=end,
+ banner=image,
+ location=location,
+ categories=categories,
+ status="approved",
+ time=datetime.now(timezone.utc),
+ nostr_event_id=event_id,
+ nostr_event_created_at=event_data.get("created_at", 0),
+ )
+ try:
+ await db.insert("events.events", new_event)
+ logger.info(f"[EVENTS] Discovered event from Nostr: {title}")
+ except Exception as e:
+ # Likely duplicate key — skip
+ logger.debug(f"[EVENTS] Skipped duplicate event: {e}")
+
+
+async def wait_for_nostr_events(nostr_client: NostrClient):
+ """
+ Background task: subscribe to NIP-52 events and process them.
+ """
+ logger.info("[EVENTS] Starting Nostr event sync...")
+
+ while True:
+ try:
+ # Subscribe to NIP-52 calendar events
+ await nostr_client.subscribe([
+ {"kinds": [31922, 31923]},
+ ])
+
+ # Process incoming events
+ while True:
+ message = await nostr_client.get_event()
+ await process_nostr_message(nostr_client, message)
+
+ except ValueError:
+ # WebSocket closed — will reconnect
+ logger.warning("[EVENTS] Nostr connection lost, resubscribing...")
+ await asyncio.sleep(10)
+ except Exception as e:
+ logger.error(f"[EVENTS] Nostr sync error: {e}")
+ await asyncio.sleep(30)
+
+
+import asyncio # noqa: E402
diff --git a/services.py b/services.py
index 1286534..9099ef0 100644
--- a/services.py
+++ b/services.py
@@ -1,4 +1,13 @@
-from .crud import get_event, update_event, update_ticket
+from lnurl import execute
+from loguru import logger
+
+from .crud import (
+ get_event,
+ get_event_tickets,
+ purge_unpaid_tickets,
+ update_event,
+ update_ticket,
+)
from .models import Ticket
@@ -16,3 +25,30 @@ async def set_ticket_paid(ticket: Ticket) -> Ticket:
await update_event(event)
return ticket
+
+
+async def refund_tickets(event_id: str):
+ """
+ Refund tickets for an event that has not met the minimum ticket requirement.
+ This function should be called when the event is closed and the minimum ticket
+ condition is not met.
+ """
+ await purge_unpaid_tickets(event_id)
+ tickets = await get_event_tickets(event_id)
+
+ if not tickets:
+ return
+
+ for ticket in tickets:
+ if ticket.extra.refunded:
+ continue
+ if ticket.paid and ticket.extra.refund_address and ticket.extra.sats_paid:
+ try:
+ res = await execute(
+ ticket.extra.refund_address, str(ticket.extra.sats_paid)
+ )
+ if res:
+ ticket.extra.refunded = True
+ await update_ticket(ticket)
+ except Exception as e:
+ logger.error(f"Error refunding ticket {ticket.id}: {e}")
diff --git a/static/js/display.js b/static/js/display.js
index 4884751..6098e5a 100644
--- a/static/js/display.js
+++ b/static/js/display.js
@@ -9,7 +9,8 @@ window.app = Vue.createApp({
show: false,
data: {
name: '',
- email: ''
+ email: '',
+ refund: ''
}
},
ticketLink: {
@@ -29,7 +30,8 @@ window.app = Vue.createApp({
this.info = event_info
this.info = this.info.substring(1, this.info.length - 1)
this.banner = event_banner
- await this.purgeUnpaidTickets()
+ this.extra = event_extra
+ this.hasPromoCodes = has_promoCodes
},
computed: {
formatDescription() {
@@ -41,6 +43,7 @@ window.app = Vue.createApp({
e.preventDefault()
this.formDialog.data.name = ''
this.formDialog.data.email = ''
+ this.formDialog.data.refund = ''
},
closeReceiveDialog() {
@@ -60,12 +63,12 @@ window.app = Vue.createApp({
const regex = /^[\w\.-]+@[a-zA-Z\d\.-]+\.[a-zA-Z]{2,}$/
return regex.test(val) || 'Please enter valid email.'
},
-
Invoice() {
axios
.post(`/events/api/v1/tickets/${event_id}`, {
name: this.formDialog.data.name,
- email: this.formDialog.data.email
+ email: this.formDialog.data.email,
+ promo_code: this.formDialog.data.promo_code || null
})
.then(response => {
this.paymentReq = response.data.payment_request
@@ -122,13 +125,6 @@ window.app = Vue.createApp({
}, 2000)
})
.catch(LNbits.utils.notifyApiError)
- },
- async purgeUnpaidTickets() {
- try {
- await LNbits.api.request('GET', `/events/api/v1/purge/${event_id}`)
- } catch (error) {
- LNbits.utils.notifyApiError(error)
- }
}
}
})
diff --git a/static/js/index.js b/static/js/index.js
index cccbe82..09c5cba 100644
--- a/static/js/index.js
+++ b/static/js/index.js
@@ -1,9 +1,6 @@
const mapEvents = function (obj) {
- obj.date = Quasar.date.formatDate(
- new Date(obj.time * 1000),
- 'YYYY-MM-DD HH:mm'
- )
- obj.fsat = new Intl.NumberFormat(LOCALE).format(obj.price_per_ticket)
+ obj.date = LNbits.utils.formatTimestamp(obj.time)
+ obj.fsat = new Intl.NumberFormat(window.g.locale).format(obj.price_per_ticket)
obj.displayUrl = ['/events/', obj.id].join('')
return obj
}
@@ -14,14 +11,18 @@ window.app = Vue.createApp({
data() {
return {
events: [],
+ allUserEvents: [],
+ pendingEvents: [],
+ isAdmin: false,
+ settings: {
+ auto_approve: false
+ },
tickets: [],
currencies: [],
eventsTable: {
columns: [
{name: 'id', align: 'left', label: 'ID', field: 'id'},
{name: 'name', align: 'left', label: 'Name', field: 'name'},
- {name: 'info', align: 'left', label: 'Info', field: 'info'},
- {name: 'banner', align: 'left', label: 'Banner', field: 'banner'},
{
name: 'event_start_date',
align: 'left',
@@ -40,6 +41,17 @@ window.app = Vue.createApp({
label: 'Ticket close',
field: 'closing_date'
},
+ {
+ name: 'canceled',
+ align: 'left',
+ label: 'Canceled',
+ field: row => {
+ if (row.extra.conditional && row.canceled) {
+ return 'Yes'
+ }
+ return 'No'
+ }
+ },
{
name: 'price_per_ticket',
align: 'left',
@@ -65,7 +77,10 @@ window.app = Vue.createApp({
align: 'left',
label: 'Sold',
field: 'sold'
- }
+ },
+ {name: 'info', align: 'left', label: 'Info', field: 'info'},
+ {name: 'banner', align: 'left', label: 'Banner', field: 'banner'},
+ {name: 'status', align: 'left', label: 'Status', field: 'status'}
],
pagination: {
rowsPerPage: 10
@@ -73,7 +88,6 @@ window.app = Vue.createApp({
},
ticketsTable: {
columns: [
- {name: 'id', align: 'left', label: 'ID', field: 'id'},
{name: 'event', align: 'left', label: 'Event', field: 'event'},
{name: 'name', align: 'left', label: 'Name', field: 'name'},
{name: 'email', align: 'left', label: 'Email', field: 'email'},
@@ -82,7 +96,14 @@ window.app = Vue.createApp({
align: 'left',
label: 'Registered',
field: 'registered'
- }
+ },
+ {
+ name: 'promo_code',
+ align: 'left',
+ label: 'Promo Code',
+ field: row => row.extra.applied_promo_code || ''
+ },
+ {name: 'id', align: 'left', label: 'ID', field: 'id'}
],
pagination: {
rowsPerPage: 10
@@ -90,11 +111,82 @@ window.app = Vue.createApp({
},
formDialog: {
show: false,
- data: {}
+ data: {
+ extra: {
+ promo_codes: []
+ }
+ }
}
}
},
methods: {
+ getSettings() {
+ LNbits.api
+ .request('GET', '/events/api/v1/settings')
+ .then(response => {
+ this.settings = response.data
+ })
+ .catch(() => {
+ // Not admin or settings not available
+ })
+ },
+ saveSettings() {
+ LNbits.api
+ .request('PUT', '/events/api/v1/settings', null, this.settings)
+ .then(() => {
+ this.$q.notify({
+ type: 'positive',
+ message: 'Settings saved'
+ })
+ })
+ .catch(err => {
+ LNbits.utils.notifyApiError(err)
+ })
+ },
+ approveEvent(eventId) {
+ LNbits.utils
+ .confirmDialog('Approve this event?')
+ .onOk(() => {
+ LNbits.api
+ .request(
+ 'PUT',
+ '/events/api/v1/events/' + eventId + '/approve'
+ )
+ .then(() => {
+ this.$q.notify({
+ type: 'positive',
+ message: 'Event approved'
+ })
+ this.getEvents()
+ this.getPendingEvents()
+ })
+ .catch(err => {
+ LNbits.utils.notifyApiError(err)
+ })
+ })
+ },
+ rejectEvent(eventId) {
+ LNbits.utils
+ .confirmDialog('Reject this event?')
+ .onOk(() => {
+ LNbits.api
+ .request(
+ 'PUT',
+ '/events/api/v1/events/' + eventId + '/reject'
+ )
+ .then(() => {
+ this.$q.notify({
+ type: 'positive',
+ message: 'Event rejected'
+ })
+ this.getEvents()
+ this.getPendingEvents()
+ })
+ .catch(err => {
+ LNbits.utils.notifyApiError(err)
+ })
+ })
+ },
getTickets() {
LNbits.api
.request(
@@ -136,6 +228,7 @@ window.app = Vue.createApp({
LNbits.utils.exportCSV(this.ticketsTable.columns, this.tickets)
},
getEvents() {
+ // Always fetch own events
LNbits.api
.request(
'GET',
@@ -143,9 +236,45 @@ window.app = Vue.createApp({
this.g.user.wallets[0].inkey
)
.then(response => {
- this.events = response.data.map(function (obj) {
+ this.events = response.data.map(obj => {
return mapEvents(obj)
})
+ this.checkCanceledEvents()
+ })
+
+ // Admin: also fetch all users' events
+ LNbits.api
+ .request(
+ 'GET',
+ '/events/api/v1/events/all'
+ )
+ .then(response => {
+ this.isAdmin = true
+ // Exclude own events (already in this.events)
+ const ownWalletIds = this.g.user.wallets.map(w => w.id)
+ this.allUserEvents = response.data
+ .filter(obj => !ownWalletIds.includes(obj.wallet))
+ .map(obj => mapEvents(obj))
+ })
+ .catch(() => {
+ this.isAdmin = false
+ this.allUserEvents = []
+ })
+ },
+ getPendingEvents() {
+ LNbits.api
+ .request(
+ 'GET',
+ '/events/api/v1/events/pending'
+ )
+ .then(response => {
+ this.pendingEvents = response.data.map(obj => {
+ return mapEvents(obj)
+ })
+ })
+ .catch(() => {
+ // Not an admin or no pending events
+ this.pendingEvents = []
})
},
sendEventData() {
@@ -153,6 +282,11 @@ window.app = Vue.createApp({
id: this.formDialog.data.wallet
})
const data = this.formDialog.data
+ if (data.extra && !data.extra.promo_codes) {
+ data.extra.promo_codes = data.extra.promo_codes
+ .filter(code => code.trim() !== '')
+ .map(code => code.trim().toUpperCase())
+ }
if (data.id) {
this.updateEvent(wallet, data)
@@ -161,20 +295,41 @@ window.app = Vue.createApp({
}
},
+ openEventDialog(data = false) {
+ if (data && data.id) {
+ this.formDialog.data = {...data}
+ } else {
+ this.formDialog.data = {
+ extra: {
+ conditional: false,
+ min_tickets: 1,
+ promo_codes: []
+ }
+ }
+ }
+ this.formDialog.show = true
+ },
+ resetEventDialog() {
+ this.formDialog.show = false
+ this.formDialog.data = {
+ extra: {
+ promo_codes: []
+ }
+ }
+ },
+
createEvent(wallet, data) {
LNbits.api
.request('POST', '/events/api/v1/events', wallet.adminkey, data)
.then(response => {
this.events.push(mapEvents(response.data))
- this.formDialog.show = false
- this.formDialog.data = {}
+ this.resetEventDialog()
})
.catch(LNbits.utils.notifyApiError)
},
updateformDialog(formId) {
const link = _.findWhere(this.events, {id: formId})
- this.formDialog.data = {...link}
- this.formDialog.show = true
+ this.openEventDialog(link)
},
updateEvent(wallet, data) {
LNbits.api
@@ -189,8 +344,7 @@ window.app = Vue.createApp({
return obj.id == data.id
})
this.events.push(mapEvents(response.data))
- this.formDialog.show = false
- this.formDialog.data = {}
+ this.resetEventDialog()
})
.catch(LNbits.utils.notifyApiError)
},
@@ -216,12 +370,38 @@ window.app = Vue.createApp({
},
exporteventsCSV() {
LNbits.utils.exportCSV(this.eventsTable.columns, this.events)
+ },
+ async checkCanceledEvents() {
+ const events = this.events
+ .filter(event => event.extra.conditional)
+ .filter(e => !e.canceled)
+ if (!events.length) return
+ const now = new Date()
+ events.forEach(async ev => {
+ if (new Date(ev.closing_date) < now && ev.sold < ev.extra.min_tickets) {
+ const {data} = await LNbits.api.request(
+ 'PUT',
+ '/events/api/v1/events/' + ev.id + '/cancel',
+ _.findWhere(this.g.user.wallets, {id: ev.wallet}).adminkey
+ )
+ Quasar.Notify.create({
+ type: 'warning',
+ message: `Event ${ev.name} has been canceled and refunds have been issued.`,
+ icon: null
+ })
+ this.events = this.events.map(e =>
+ e.id === ev.id ? mapEvents(data) : e
+ )
+ }
+ })
}
},
async created() {
if (this.g.user.wallets.length) {
this.getTickets()
this.getEvents()
+ this.getPendingEvents()
+ this.getSettings()
this.currencies = await LNbits.api.getCurrencies()
}
}
diff --git a/tasks.py b/tasks.py
index f7300bb..67d5d45 100644
--- a/tasks.py
+++ b/tasks.py
@@ -21,8 +21,12 @@ async def on_invoice_paid(payment: Payment) -> None:
if not payment.extra or "events" != payment.extra.get("tag"):
return
- if not payment.extra.get("name") or not payment.extra.get("email"):
- logger.warning(f"Ticket {payment.payment_hash} missing name or email.")
+ # Check if ticket has either name/email or user_id
+ has_name_email = payment.extra.get("name") and payment.extra.get("email")
+ has_user_id = payment.extra.get("user_id")
+
+ if not has_name_email and not has_user_id:
+ logger.warning(f"Ticket {payment.payment_hash} missing name/email or user_id.")
return
ticket = await get_ticket(payment.payment_hash)
diff --git a/templates/events/display.html b/templates/events/display.html
index 24a64e4..73d279d 100644
--- a/templates/events/display.html
+++ b/templates/events/display.html
@@ -6,7 +6,7 @@
{{ event_name }}
-
+