feat(project): silence web alert popup while PC notifier is running
If the user has a non-revoked notifier token seen in the last 3 minutes, /api/notifications/alerts returns only the baseline with desktop=true; the web marks it seen so alerts resume on the web after the app stops. A failing check keeps the web popup. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1657,6 +1657,20 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
return row["email"] if row else None
|
||||
|
||||
def notifier_active(self, *, email: str, within_sec: int = 180) -> bool:
|
||||
"""이 사용자의 PC 알림 프로그램이 지금 돌고 있나 — 해제 안 된 토큰 중 최근(기본 3분) 확인한 것이 있으면 True.
|
||||
프로그램은 20초마다 확인하고 last_seen_at 은 1분에 한 번 갱신되므로 3분이면 꺼진 PC 는 곧 빠진다. 023 미적용이면 False."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM notifier_tokens WHERE email = %s AND revoked_at IS NULL "
|
||||
"AND last_seen_at > now() - make_interval(secs => %s) LIMIT 1",
|
||||
(store.norm_str(email, lower=True), within_sec),
|
||||
).fetchone()
|
||||
except psycopg_errors.UndefinedTable:
|
||||
return False
|
||||
return row is not None
|
||||
|
||||
def notifier_revoke_token(self, *, token: str) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute("UPDATE notifier_tokens SET revoked_at = now() WHERE token_hash = %s AND revoked_at IS NULL",
|
||||
|
||||
@@ -2299,9 +2299,22 @@ def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
|
||||
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
# PC 알림 프로그램이 돌고 있으면(023, 최근 3분 안에 확인) 웹 팝업은 띄우지 않는다 — 기준점(latest_id)만 주고
|
||||
# desktop=True. 웹은 그 번호까지 본 것으로 두어, 프로그램을 끄면 그 뒤에 온 알림부터 다시 웹에 뜬다.
|
||||
if _notifier_active(st, user):
|
||||
out = _alerts_payload(st, user, -1)
|
||||
out["desktop"] = True
|
||||
return JSONResponse(out)
|
||||
return JSONResponse(_alerts_payload(st, user, after))
|
||||
|
||||
|
||||
def _notifier_active(st: Any, user: dict[str, Any]) -> bool:
|
||||
try:
|
||||
return bool(st.notifier_active(email=user["email"]))
|
||||
except Exception: # noqa: BLE001 — 확인 실패면 웹 팝업을 그대로(알림을 놓치지 않게)
|
||||
return False
|
||||
|
||||
|
||||
def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]:
|
||||
"""큰 팝업 알림 — 웹 화면(initTaskAlerts)과 PC 알림 프로그램이 같이 쓴다."""
|
||||
newest = st.list_notifications(recipient_email=user["email"], limit=1)
|
||||
|
||||
@@ -10912,7 +10912,13 @@
|
||||
me = res.me;
|
||||
after = readSeen();
|
||||
if (after == null) writeSeen(res.latest_id || 0); // 처음 — 지금까지 온 알림은 띄우지 않는다
|
||||
else if (after < (res.latest_id || 0)) res = await api("GET", "/project/api/notifications/alerts?after=" + after);
|
||||
else if (after < (res.latest_id || 0) && !res.desktop) res = await api("GET", "/project/api/notifications/alerts?after=" + after);
|
||||
}
|
||||
// PC 알림 프로그램이 켜져 있으면 웹 팝업은 쉰다 — 지금까지 온 것은 본 것으로(프로그램을 끄면 그 뒤 알림부터 웹에)
|
||||
if (res && res.desktop) {
|
||||
if ((res.latest_id || 0) > (readSeen() || 0)) writeSeen(res.latest_id || 0);
|
||||
if (pop) { shown.clear(); pop.remove(); pop = null; }
|
||||
return;
|
||||
}
|
||||
((res && res.alerts) || []).forEach(function (n) { if (!shown.has(n.id)) shown.set(n.id, n); });
|
||||
if (shown.size) render();
|
||||
|
||||
@@ -1062,6 +1062,9 @@ Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Frame
|
||||
- **화면** `/project/notifier`(수신함 머리의 [PC 알림] 버튼으로 들어감, 사이드바는 수신함 활성): 연결 승인 카드, 설치 안내, 내 연결된 PC 목록·[연결 해제]
|
||||
(`POST /project/api/notifier/devices/{id}/revoke`). 내려받기 `GET /project/notifier/download` = 서버
|
||||
`DATA_DIR/notifier/DBXNotifier.exe`(컨테이너 `/data/notifier/`) — 파일이 없으면 버튼 대신 "관리자에게 받으세요".
|
||||
- **웹 팝업 쉬기**: 그 사용자의 PC 알림 프로그램이 돌고 있으면(해제 안 된 토큰 중 `last_seen_at` 3분 안 — `st.notifier_active`)
|
||||
웹 `/api/notifications/alerts` 는 알림 없이 `latest_id` + `desktop: true` 만 준다. 웹은 그 번호까지 본 것으로 두므로, 프로그램을 끄면
|
||||
3분쯤 뒤 그 뒤에 온 알림부터 웹 팝업이 다시 뜬다. 사용자 단위(어느 PC 에서 켰든 모든 브라우저 팝업이 쉼). 확인 실패면 웹 팝업 그대로.
|
||||
- 023 미적용이면 화면은 안내만, notifier API 는 503.
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
@@ -18,6 +18,11 @@ ROWS = [ # 최신순(list_notifications 와 같게)
|
||||
|
||||
|
||||
class FakeStore:
|
||||
desktop = False
|
||||
|
||||
def notifier_active(self, email):
|
||||
return self.desktop
|
||||
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
rows = [r for r in ROWS if not unread_only or not r["is_read"]]
|
||||
return rows[:limit]
|
||||
@@ -29,9 +34,11 @@ class AlertsApiTests(unittest.TestCase):
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def get(self, qs=""):
|
||||
def get(self, qs="", desktop=False):
|
||||
st = FakeStore()
|
||||
st.desktop = desktop
|
||||
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=FakeStore()), \
|
||||
patch.object(api, "_db_or_503", return_value=st), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
return self.client.get("/project/api/notifications/alerts" + qs).json()
|
||||
|
||||
@@ -43,6 +50,21 @@ class AlertsApiTests(unittest.TestCase):
|
||||
out = self.get("?after=5")
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8]) # 완료 알림(9)·읽은 것(7)·옛것(2) 제외
|
||||
self.assertEqual(out["alerts"][1]["type"], "mention")
|
||||
self.assertNotIn("desktop", out)
|
||||
|
||||
def test_pc_notifier_running_silences_web_popup(self):
|
||||
out = self.get("?after=5", desktop=True)
|
||||
self.assertEqual((out["alerts"], out["latest_id"], out["desktop"]), ([], 9, True))
|
||||
|
||||
def test_notifier_check_failure_keeps_web_popup(self):
|
||||
class Broken(FakeStore):
|
||||
def notifier_active(self, email):
|
||||
raise RuntimeError("db down")
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=Broken()), \
|
||||
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items):
|
||||
out = self.client.get("/project/api/notifications/alerts?after=5").json()
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user