summaryrefslogtreecommitdiff
path: root/backend/notif.py
diff options
context:
space:
mode:
Diffstat (limited to 'backend/notif.py')
-rw-r--r--backend/notif.py76
1 files changed, 76 insertions, 0 deletions
diff --git a/backend/notif.py b/backend/notif.py
new file mode 100644
index 0000000..eb25793
--- /dev/null
+++ b/backend/notif.py
@@ -0,0 +1,76 @@
+from pydantic import BaseModel
+import sqlite3
+from pywebpush import webpush
+from dotenv import load_dotenv
+from os import getenv
+import json
+
+class PushSubscriptionData(BaseModel):
+ endpoint: str
+ keys: object
+
+
+conn = sqlite3.connect("db.db", check_same_thread=False)
+cursor = conn.cursor()
+
+load_dotenv()
+
+PRIVATE_VAPID_KEY = getenv("PRIVATE_VAPID_KEY")
+
+cursor.execute("""
+CREATE TABLE IF NOT EXISTS subscriptions (
+ endpoint TEXT PRIMARY KEY,
+ keys_p256dh TEXT NOT NULL,
+ keys_auth TEXT NOT NULL
+);""")
+
+
+# --- subscribe
+def subscribe(data: PushSubscriptionData):
+ cursor.execute("SELECT * FROM subscriptions WHERE endpoint = ?", (data.endpoint,))
+ result = cursor.fetchall()
+
+ if len(result) > 0:
+ return data.endpoint
+
+ cursor.execute("""
+ INSERT INTO subscriptions (endpoint, keys_p256dh, keys_auth)
+ VALUES (?, ?, ?)""", (data.endpoint, data.keys["p256dh"], data.keys["auth"]))
+ conn.commit()
+
+ cursor.execute("SELECT * FROM subscriptions")
+ result = cursor.fetchall()
+
+ for row in result:
+ print(row)
+
+ return data.endpoint
+
+
+# --- send notification
+# ---- not used yet
+def send_notification(endpoint: str, notification_payload: object):
+ cursor.execute(f"""SELECT * FROM subscriptions WHERE endpoint = \"{endpoint}\"""")
+ row = cursor.fetchall()[0]
+ print(row)
+
+ subscription_info = {
+ "endpoint": endpoint,
+ "keys": {
+ "p256dh": row[1],
+ "auth": row[2],
+ },
+ }
+
+ try:
+ webpush(
+ subscription_info=subscription_info,
+ data=json.dumps(notification_payload),
+ vapid_private_key=PRIVATE_VAPID_KEY,
+ vapid_claims={
+ "sub": "mailto:dev@altafcreator.com",
+ },
+ headers={"Urgency": "high"}
+ )
+ except Exception as exception:
+ print(exception)