]> littlesong.place Git - littlesongplace.git/commitdiff
Push subscription improvements
authorChris Fulljames <christianfulljames@gmail.com>
Sat, 7 Jun 2025 16:28:33 +0000 (12:28 -0400)
committerChris Fulljames <christianfulljames@gmail.com>
Sat, 23 Aug 2025 11:30:17 +0000 (07:30 -0400)
src/littlesongplace/activity.py
src/littlesongplace/push_notifications.py
src/littlesongplace/static/nav.js
src/littlesongplace/templates/activity.html

index eb1ca5d3718f7dd8fb571c13bb89aab2c5655ac7..ea7865572012bbcced315c6597bdcb5f21f2cda6 100644 (file)
@@ -91,17 +91,7 @@ def activity():
             [timestamp, session["userid"]])
     db.commit()
 
-    comment_push = False
-    song_push = False
-    if "subid" in session:
-        row = db.query(
-                "SELECT settings FROM users_push_subscriptions WHERE subid = ?",
-                [session["subid"]], one=True)
-        if row:
-            comment_push = (row["settings"] & push_notifications.SubscriptionSetting.COMMENTS) > 0
-            song_push = (row["settings"] & push_notifications.SubscriptionSetting.SONGS) > 0
-
-    return render_template("activity.html", comments=notifications, comment_push=comment_push, song_push=song_push)
+    return render_template("activity.html", comments=notifications)
 
 @bp.get("/new-activity")
 def new_activity():
index d2f980f384feb922c6ee140856719b0e65b3d99b..15b3ada7e531862c6592d2d3a0928c790adf01de 100644 (file)
@@ -3,7 +3,7 @@ import threading
 import enum
 
 import pywebpush
-from flask import Blueprint, current_app, g, request, session
+from flask import Blueprint, current_app, g, request
 
 from . import auth, datadir, db
 
@@ -35,6 +35,22 @@ def subscribe():
 
     return {"status": "success", "subid": row["subid"]}
 
+@bp.get("/settings")
+@auth.requires_login
+def get_settings():
+    subid = request.args["subid"]
+    row = db.query(
+            """
+            SELECT settings FROM users_push_subscriptions
+            WHERE subid = ? AND userid = ?
+            """,
+            [subid, g.userid], expect_one=True)
+
+    comments = (row["settings"] & SubscriptionSetting.COMMENTS) > 0
+    songs = (row["settings"] & SubscriptionSetting.SONGS) > 0
+
+    return {"comments": comments, "songs": songs}
+
 @bp.post("/update-settings")
 @auth.requires_login
 def update_settings():
@@ -42,7 +58,6 @@ def update_settings():
         # Request must contain valid subscription JSON
         abort(400)
 
-
     bitfield = 0
     settings = request.json
 
@@ -65,7 +80,7 @@ def update_settings():
             [bitfield, subid, g.userid])
     db.commit()
 
-    current_app.logger.info(f"{g.username} updated push subscription settings: {bitfield:04x}")
+    current_app.logger.info(f"{g.username} updated push subscription settings: ({subid}) {bitfield:04x}")
 
     return {"status": "success"}
 
index 369f0f30ff3829d67678fd3d52e80960b6bfde13..efb7e9bee3821a977d9ddb2b2f31a3ea84f5b5c1 100644 (file)
@@ -50,11 +50,11 @@ document.addEventListener("DOMContentLoaded", async (e) => {
     // Register service worker
     if ("serviceWorker" in navigator)
     {
-        navigator.serviceWorker.register("service.js");
+        navigator.serviceWorker.register("/service.js");
     }
 });
 
-function onLinkClick(event) {
+async function onLinkClick(event) {
     if (event.defaultPrevented) {
         return;
     }
@@ -62,6 +62,18 @@ function onLinkClick(event) {
     if (urlIsOnSameSite(targetUrl) && !event.currentTarget.href.includes("/gitweb")) {
         event.preventDefault();
         event.stopPropagation();
+        if (targetUrl.pathname == "/logout")
+        {
+            console.log("logging out");
+            // Logging out - delete notification subscription
+            window.localStorage.removeItem("subid");
+            const registration = await navigator.serviceWorker.getRegistration();
+            const existingSubscription = await registration.pushManager.getSubscription();
+            if (existingSubscription)
+            {
+                existingSubscription.unsubscribe();
+            }
+        }
         fetch(targetUrl, {redirect: "follow"}).then(handleAjaxResponse).catch((err) => console.log(err));
     }
 }
index e9ee804d23bb5f0fb918c9bcf056c680b567271d..b6834006813e5ed3d1f707069bd4904d81773f3e 100644 (file)
     <!--<button onclick="enablePushNotifications()" class="button" style="float: right;">Enable</button>-->
     Send me a push notification on this device when:
     <br/>
-    <label><input type="checkbox" onclick="updateSettings()" id="comment-push" {% if comment_push %}checked{% endif %}>I get a new comment</label>
+    <label><input type="checkbox" onclick="updateSettings()" id="comment-push">I get a new comment</label>
     <br/>
-    <label><input type="checkbox" onclick="updateSettings()" id="song-push" {% if song_push %}checked{% endif %}>Anyone uploads a new song</label>
+    <label><input type="checkbox" onclick="updateSettings()" id="song-push">Anyone uploads a new song</label>
 </div>
 
 <br/>
 <br/>
 
 <script>
+
+function updateSelections() {
+    // Prevent this from getting called again on the next page load
+    document.removeEventListener("DOMContentLoaded", updateSelections);
+
+    if (window.localStorage.getItem("subid"))
+    {
+        const params = new URLSearchParams({subid: window.localStorage.getItem("subid")});
+        fetch(`/push-notifications/settings?${params}`).then((r) => {
+            r.json().then((j) => {
+                console.log(j);
+                document.getElementById("comment-push").checked = j.comments;
+                document.getElementById("song-push").checked = j.songs;
+            });
+        })
+    }
+}
+document.addEventListener("DOMContentLoaded", updateSelections());
+
 function showSettings() {
     document.getElementById("activity-settings").hidden = false;
     document.getElementById("btn-show-settings").hidden = true;