feat(project): PC tray notifier for mentions and assignments

Windows tray app (desktop/notifier, C# .NET Framework 4.8 WinForms,
single exe, no installer/admin) that shows the same big alert popup as
the web even when the browser is in the background: layered topmost
window that does not steal focus, blinking border, open/close actions,
sound, autostart toggle, DPAPI-encrypted token.

Server side (project_db migration 023):
- notifier_links / notifier_tokens (SHA-256 hashes only)
- device link flow: link/start -> browser approve at /project/notifier
  -> link/poll issues token once
- Bearer API for alerts/read/logout reusing _alerts_payload; token
  re-checks current user record and project permission each call
- /project/notifier page (approve, connected PCs, revoke, download)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 10:21:58 +09:00
parent 8f46d6c13a
commit 06af036f86
24 changed files with 2093 additions and 3 deletions
+162 -1
View File
@@ -2299,19 +2299,180 @@ def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
user = _require_user(request)
st = _db_or_503(request)
return JSONResponse(_alerts_payload(st, user, after))
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)
latest = int(newest[0]["id"]) if newest else 0
out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0:
return JSONResponse(out)
return out
rows = [n for n in st.list_notifications(recipient_email=user["email"], unread_only=True, limit=50)
if n.get("type") in ("mention", "assigned") and int(n["id"]) > after]
rows = sorted(_visible_notifications(st, user, rows), key=lambda n: int(n["id"]))[:10]
out["alerts"] = [{k: n.get(k) for k in ("id", "type", "title", "body", "task_id", "project_id", "actor_email", "created_at")}
for n in rows]
return out
# ────────────────────────────────────────────────────────────
# PC 알림 프로그램(desktop/notifier, 023) — 브라우저 쿠키 대신 PC별 연결 토큰(Authorization: Bearer).
# 연결: 프로그램 POST link/start → 사용자가 브라우저 /project/notifier?code= 에서 [연결] → 프로그램 POST link/poll 로 토큰 1회.
# ────────────────────────────────────────────────────────────
_NOTIFIER_MIGRATION_MSG = "PC 알림 연결이 아직 준비되지 않았습니다(project_db 023 마이그레이션 필요)."
def _notifier_call(fn: Any, **kwargs: Any) -> Any:
try:
return fn(**kwargs)
except UndefinedTable:
raise HTTPException(status_code=503, detail=_NOTIFIER_MIGRATION_MSG)
def _notifier_token(request: Request) -> str:
auth = request.headers.get("authorization", "")
return auth[7:].strip() if auth.lower().startswith("bearer ") else ""
def _user_by_email(email: str) -> dict[str, Any] | None:
from app.main import user_store # noqa: WPS433
return user_store.get(email)
def _notifier_user(request: Request, st: Any) -> dict[str, Any]:
"""토큰 → 지금 사용자 레코드(권한 포함). 토큰 해제·사용자 삭제·프로젝트 권한 회수면 401."""
from app.store import has_module # noqa: WPS433
email = _notifier_call(st.notifier_token_email, token=_notifier_token(request))
user = _user_by_email(email) if email else None
if user is None or not has_module(user, "project"):
raise HTTPException(status_code=401, detail="연결이 해제되었습니다. 다시 연결하세요.")
return user
@router.post("/api/notifier/link/start")
def api_notifier_link_start(request: Request, payload: dict[str, Any] = Body(default={})) -> JSONResponse:
"""연결 요청(로그인 없이) — 화면 코드 + poll 비밀값. 사용자는 /project/notifier?code= 에서 승인."""
st = _db_or_503(request)
device = store.norm_str(payload.get("device") or "")[:80]
try:
link = _notifier_call(st.notifier_start_link, device_name=device)
except OverflowError as exc:
raise HTTPException(status_code=429, detail=str(exc))
return JSONResponse({**link, "approve_path": "/project/notifier?code=" + link["code"]})
@router.post("/api/notifier/link/poll")
def api_notifier_link_poll(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
st = _db_or_503(request)
poll = store.norm_str(payload.get("poll") or "")
if not poll:
raise HTTPException(status_code=400, detail="poll 이 필요합니다.")
return JSONResponse(_notifier_call(st.notifier_poll_link, poll=poll))
@router.post("/api/notifier/link/approve")
def api_notifier_link_approve(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
"""브라우저(로그인 사용자)가 [연결] — 이 코드의 PC 를 내 알림에 연결."""
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_approve_link, code=str(payload.get("code") or ""), email=user["email"]):
raise HTTPException(status_code=404, detail="연결 코드가 없거나 만료되었습니다. 프로그램에서 다시 연결하세요.")
return JSONResponse({"ok": True})
@router.post("/api/notifier/devices/{device_id}/revoke")
def api_notifier_revoke_device(request: Request, device_id: int) -> JSONResponse:
user = _require_user(request)
st = _db_or_503(request)
if not _notifier_call(st.notifier_revoke_device, device_id=device_id, email=user["email"]):
raise HTTPException(status_code=404, detail="연결된 PC 를 찾을 수 없습니다.")
return JSONResponse({"ok": True})
@router.get("/api/notifier/alerts")
def api_notifier_alerts(request: Request, after: int = -1) -> JSONResponse:
"""PC 알림 프로그램 — 웹 큰 팝업과 같은 알림. name = 표시 이름(트레이 메뉴용)."""
st = _db_or_503(request)
user = _notifier_user(request, st)
out = _alerts_payload(st, user, after)
out["name"] = user.get("name") or user["email"]
return JSONResponse(out)
@router.post("/api/notifier/alerts/{notification_id}/read")
def api_notifier_alert_read(request: Request, notification_id: int) -> JSONResponse:
st = _db_or_503(request)
user = _notifier_user(request, st)
st.mark_read(notification_id=notification_id, recipient_email=user["email"])
return JSONResponse({"ok": True})
@router.post("/api/notifier/logout")
def api_notifier_logout(request: Request) -> JSONResponse:
st = _db_or_503(request)
_notifier_call(st.notifier_revoke_token, token=_notifier_token(request))
return JSONResponse({"ok": True})
@router.get("/notifier/download")
def notifier_download(request: Request) -> Any:
"""PC 알림 프로그램 내려받기 — 서버 DATA_DIR/notifier/DBXNotifier.exe 를 그대로(없으면 404)."""
from app.main import DATA_DIR # noqa: WPS433
_require_user(request)
exe = Path(DATA_DIR) / "notifier" / "DBXNotifier.exe"
if not exe.is_file():
raise HTTPException(status_code=404, detail="아직 서버에 프로그램 파일이 없습니다. 관리자에게 문의하세요.")
return FileResponse(exe, filename="DBXNotifier.exe", media_type="application/octet-stream")
@router.get("/notifier", response_class=HTMLResponse)
def notifier_page(request: Request) -> Any:
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
from urllib.parse import quote # noqa: WPS433
if get_current_user_record(request) is None:
return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + (
"?" + request.url.query if request.url.query else ""), safe=""), status_code=303)
user = _require_user(request)
st = _store(request)
if st is None:
return _render_config_needed(request, user)
admin = is_admin(user)
enabled = st.notifier_enabled()
code = store.norm_str(request.query_params.get("code") or "").upper()[:9]
link = st.notifier_get_link(code=code) if enabled and code else None
return render_template(
request,
"project/notifier.html",
{
"user": user,
"is_admin": admin,
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
"my_open_total": _my_open_count(st, user),
"mention_unread": _safe_mention_unread(st, user),
"page_title": "PC 알림 프로그램",
"page_subtitle": "브라우저가 뒤에 있어도 태그·작업 배정 알림을 화면 위에 크게",
"force_sidebar_collapsed": True,
"color_palette": list(store.COLOR_PALETTE),
"project_icons": list(store.PROJECT_ICONS),
"notifier_enabled": enabled,
"code": code,
"link": link,
"devices": st.notifier_list_devices(email=user["email"]) if enabled else [],
"download_ready": (Path(DATA_DIR) / "notifier" / "DBXNotifier.exe").is_file(),
},
)
@router.get("/api/notifications/unread-count")
def api_notif_count(request: Request) -> JSONResponse:
user = _require_user(request)