"""Phone and laptop notifications (Web Push) for a child who has left StepWise mid-task. A page in the background can't ring on a phone (the phone pauses it), so the page tells the server when it is hidden and when it is back, and the server sends the notification: - quiz: at once, on the first slip ("come back in 15 seconds or it's submitted"); - chat: when the expected reply time runs out, and once more 3 minutes later, unless she has come back or replied. Subscriptions are stored per login in the results dataset (push/.json). The signing key comes from the VAPID_PRIVATE Space secret (base64url, raw 32-byte P-256 key). """ from __future__ import annotations import base64 import json import os import threading import time AGAIN_SEC = 180 # second reminder in a chat, then quiet CLAIM_SUB = "https://ashish-k-stepwise.hf.space" def _b64u(b: bytes) -> str: return base64.urlsafe_b64encode(b).rstrip(b"=").decode() def _public_key(private_b64u: str) -> str | None: try: from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives import serialization raw = base64.urlsafe_b64decode(private_b64u + "=" * (-len(private_b64u) % 4)) key = ec.derive_private_key(int.from_bytes(raw, "big"), ec.SECP256R1()) return _b64u(key.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint)) except Exception: return None class Push: def __init__(self, store, chats_of) -> None: self.store = store # app.Store: .push (uid -> {"subs": [...]}) and queue_write() self.chats = chats_of # callable: session id -> chat dict or None self.private = os.environ.get("VAPID_PRIVATE", "").strip() self.public = _public_key(self.private) if self.private else None self.pending: dict[str, dict] = {} # uid -> {"sid", "due", "n", "msgs"} self.lock = threading.Lock() if self.public: threading.Thread(target=self._loop, daemon=True).start() # ---------------------------------------------------------------- subscriptions def subscribe(self, uid: str, sub: dict) -> int: rec = self.store.push.setdefault(uid, {"subs": []}) rec["subs"] = [s for s in rec["subs"] if s.get("endpoint") != sub["endpoint"]][-4:] + [sub] self.store.queue_write(f"push/{uid}.json", rec) return len(rec["subs"]) def unsubscribe(self, uid: str, endpoint: str) -> None: rec = self.store.push.get(uid) if rec: rec["subs"] = [s for s in rec["subs"] if s.get("endpoint") != endpoint] self.store.queue_write(f"push/{uid}.json", rec) def has(self, uid: str) -> bool: return bool((self.store.push.get(uid) or {}).get("subs")) # ---------------------------------------------------------------- sending def send(self, uid: str, title: str, body: str, url: str = "/", tag: str = "stepwise") -> int: if not self.public: return 0 from pywebpush import WebPushException, webpush rec = self.store.push.get(uid) or {"subs": []} sent, dead = 0, [] for sub in list(rec["subs"]): try: webpush(subscription_info=sub, data=json.dumps({"title": title, "body": body, "url": url, "tag": tag}), vapid_private_key=self.private, vapid_claims={"sub": CLAIM_SUB}, ttl=300, timeout=10) sent += 1 except WebPushException as e: if getattr(e, "response", None) is not None and e.response.status_code in (404, 410): dead.append(sub.get("endpoint")) # that phone or browser unsubscribed except Exception: pass if dead: rec["subs"] = [s for s in rec["subs"] if s.get("endpoint") not in dead] self.store.queue_write(f"push/{uid}.json", rec) return sent # ---------------------------------------------------------------- away / back def away(self, uid: str, kind: str, session_id: str | None = None, due_in_ms: int = 0) -> None: if kind == "back": with self.lock: self.pending.pop(uid, None) return if kind == "quiz": threading.Thread(target=self.send, args=(uid, "⚠️ Come back to your quiz", "Switching away submits the quiz. Come back within 15 seconds to keep going.", "/", "quiz"), daemon=True).start() return if kind == "chat" and session_id: s = self.chats(session_id) if not s: return with self.lock: self.pending[uid] = {"sid": session_id, "due": time.time() + max(0, due_in_ms) / 1000, "n": 0, "msgs": s.get("studentMessages", 0)} def _loop(self) -> None: while True: time.sleep(10) now = time.time() fire = [] with self.lock: for uid, p in list(self.pending.items()): s = self.chats(p["sid"]) if not s or s.get("studentMessages", 0) != p["msgs"] or p["n"] >= 2: self.pending.pop(uid, None) continue if now >= p["due"]: p["n"] += 1 p["due"] = now + AGAIN_SEC fire.append((uid, p["sid"])) for uid, sid in fire: self.send(uid, "⏰ Your tutor is waiting", "Reply when you're ready. If it's hard, ask the tutor to ask again more simply.", f"/#/chat/{sid}", "chat")