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/notif.py | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 backend/notif.py (limited to 'backend/notif.py') 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