From 9080a0c516378dbb94c5178fbc26a8131a530263 Mon Sep 17 00:00:00 2001 From: altaf-creator Date: Mon, 29 Dec 2025 20:25:08 +0800 Subject: new notif everything --- backend/main.py | 12 ++++++++++++ backend/notif.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 backend/notif.py (limited to 'backend') diff --git a/backend/main.py b/backend/main.py index d77fdd1..fec436b 100644 --- a/backend/main.py +++ b/backend/main.py @@ -17,6 +17,7 @@ from enum import Enum, IntEnum from dotenv import load_dotenv from os import getenv import yaml +import notif # import notif.py # ## API, db, and scheduler initialisation app = fastapi.FastAPI(title="Victoria Hall LaundryWeb", description="LaundryWeb Backend API", version="0.1") @@ -443,3 +444,14 @@ def uri_to_information(data: InformationRequestData, response: fastapi.Response, return "NO INFORMATION PROVIDED. NO AUTH COOKIE." return {"block": info[0], "machine": info[1]} + + +# #### NOTIFICATION API END POINTS #### + + +# --- subscribe +@app.post("/notif_subscribe") +def notif_subscribe(data: notif.PushSubscriptionData, response: fastapi.Response): + endpoint = notif.subscribe(data) + response.set_cookie("subscription_endpoint", endpoint) + response.status_code = fastapi.status.HTTP_200_OK diff --git a/backend/notif.py b/backend/notif.py new file mode 100644 index 0000000..59bb3c3 --- /dev/null +++ b/backend/notif.py @@ -0,0 +1,59 @@ +from pydantic import BaseModel +import sqlite3 +from pywebpush import webpush + + +class PushSubscriptionData(BaseModel): + endpoint: str + expirationTime: float + keys: object + + +conn = sqlite3.connect("db.db", check_same_thread=False) +cursor = conn.cursor() + +f = open("private_key.pem", "r") +PRIVATE_VAPID_KEY = f.read() +f.close() + +cursor.execute(""" +CREATE TABLE IF NOT EXISTS subscriptions ( + endpoint TEXT PRIMARY KEY, + expiration_time REAL NOT NULL, + keys_p256dh TEXT NOT NULL, + keys_auth TEXT NOT NULL +);""") + + +# --- subscribe +def subscribe(data: PushSubscriptionData): + cursor.execute(""" + INSERT INTO subscriptions (endpoint, expiration_time, keys_p256dh, keys_auth) + VALUES (?, ?, ?, ?)""", (data.endpoint, data.expirationTime, data.keys["p256dh"], data.keys["auth"])) + conn.commit() + return data.endpoint + + +# --- send notification +def send_notification(endpoint: str): + cursor.execute("SELECT * FROM subscriptions WHERE endpoint = ?", (endpoint,)) + row = cursor.fetchall()[0] + subscription_info = { + "endpoint": endpoint, + "keys": { + "p256dh": row[2], + "auth": row[3], + }, + } + + try: + webpush( + subscription_info=subscription_info, + data="Hello, world!", + vapid_private_key=PRIVATE_VAPID_KEY, + vapid_claims={ + "sub": "mailto:dev@altafcreator.com", + }, + ) + except Exception as exception: + print(exception) -- cgit v1.2.3