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
+2 -1
View File
File diff suppressed because one or more lines are too long
+119
View File
@@ -12,8 +12,10 @@
from __future__ import annotations from __future__ import annotations
import hashlib
import logging import logging
import re import re
import secrets
import time import time
import uuid import uuid
from datetime import date, datetime, timedelta from datetime import date, datetime, timedelta
@@ -1560,6 +1562,123 @@ class ProjectStore:
) )
return cur.rowcount or 0 return cur.rowcount or 0
# ════════════════════════════════════════════════════════════
# PC 알림 프로그램 연결(023) — notifier_links → notifier_tokens. 원문은 저장하지 않고 SHA-256 만.
# ════════════════════════════════════════════════════════════
NOTIFIER_LINK_TTL_MIN = 10
NOTIFIER_MAX_PENDING = 200 # 로그인 없이 부르는 연결 요청이 쌓이지 않게(만료 전 대기 건 상한)
_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # 헷갈리는 0·O·1·I 제외
@staticmethod
def _sha(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()
def notifier_enabled(self) -> bool:
with self._pool.connection() as conn:
return self._table_exists(conn, "notifier_tokens")
def notifier_start_link(self, *, device_name: str) -> dict[str, Any]:
"""연결 요청 — 화면 코드와 poll 비밀값(원문은 여기서만 돌려준다)."""
poll = secrets.token_urlsafe(32)
with self._pool.connection() as conn:
with conn.transaction():
conn.execute("DELETE FROM notifier_links WHERE expires_at < now() - interval '1 day'")
row = conn.execute("SELECT count(*) AS n FROM notifier_links WHERE expires_at > now() AND approved_at IS NULL").fetchone()
if int(row["n"]) >= self.NOTIFIER_MAX_PENDING:
raise OverflowError("연결 요청이 너무 많습니다. 잠시 뒤 다시 시도하세요.")
for _ in range(5):
raw = "".join(secrets.choice(self._CODE_ALPHABET) for _ in range(8))
code = raw[:4] + "-" + raw[4:]
hit = conn.execute(
"INSERT INTO notifier_links (code, poll_hash, device_name, expires_at) "
"VALUES (%s, %s, %s, now() + make_interval(mins => %s)) ON CONFLICT (code) DO NOTHING RETURNING id",
(code, self._sha(poll), device_name[:80], self.NOTIFIER_LINK_TTL_MIN),
).fetchone()
if hit:
return {"code": code, "poll": poll, "expires_in": self.NOTIFIER_LINK_TTL_MIN * 60}
raise RuntimeError("연결 코드를 만들지 못했습니다.")
def notifier_get_link(self, *, code: str) -> dict[str, Any] | None:
"""승인 화면용 — 아직 유효한(만료 전·토큰 미발급) 요청만."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT code, device_name, email, approved_at, expires_at FROM notifier_links "
"WHERE code = %s AND expires_at > now() AND consumed_at IS NULL",
(store.norm_str(code).upper(),),
).fetchone()
return self._serialize(row) if row else None
def notifier_approve_link(self, *, code: str, email: str) -> bool:
"""[연결] — 아직 아무도 승인하지 않은 유효한 요청만 이 사용자로 승인."""
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_links SET email = %s, approved_at = now() "
"WHERE code = %s AND expires_at > now() AND approved_at IS NULL AND consumed_at IS NULL",
(store.norm_str(email, lower=True), store.norm_str(code).upper()),
)
return bool(cur.rowcount)
def notifier_poll_link(self, *, poll: str) -> dict[str, Any]:
"""프로그램의 확인 — 승인됐으면 토큰을 한 번만 발급. {"status": pending|expired|ok, ...}"""
with self._pool.connection() as conn:
with conn.transaction():
row = conn.execute(
"SELECT id, email, device_name, approved_at, consumed_at, expires_at > now() AS alive "
"FROM notifier_links WHERE poll_hash = %s FOR UPDATE",
(self._sha(poll),),
).fetchone()
if not row or row["consumed_at"] or not row["alive"]:
return {"status": "expired"}
if not row["approved_at"]:
return {"status": "pending"}
token = secrets.token_urlsafe(32)
conn.execute("UPDATE notifier_links SET consumed_at = now() WHERE id = %s", (row["id"],))
conn.execute(
"INSERT INTO notifier_tokens (email, token_hash, device_name) VALUES (%s, %s, %s)",
(row["email"], self._sha(token), row["device_name"]),
)
return {"status": "ok", "token": token, "email": row["email"]}
def notifier_token_email(self, *, token: str) -> str | None:
"""토큰 → 사용자 이메일(해제된 토큰은 None). 마지막 접속 시각은 1분에 한 번만 갱신."""
if not token:
return None
with self._pool.connection() as conn:
row = conn.execute(
"UPDATE notifier_tokens SET last_seen_at = now() "
"WHERE token_hash = %s AND revoked_at IS NULL "
"AND (last_seen_at IS NULL OR last_seen_at < now() - interval '1 minute') RETURNING email",
(self._sha(token),),
).fetchone()
if row is None:
row = conn.execute(
"SELECT email FROM notifier_tokens WHERE token_hash = %s AND revoked_at IS NULL",
(self._sha(token),),
).fetchone()
return row["email"] if row else 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",
(self._sha(token),))
def notifier_list_devices(self, *, email: str) -> list[dict[str, Any]]:
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT id, device_name, created_at, last_seen_at FROM notifier_tokens "
"WHERE email = %s AND revoked_at IS NULL ORDER BY created_at DESC",
(store.norm_str(email, lower=True),),
).fetchall()
return [self._serialize(r) for r in rows]
def notifier_revoke_device(self, *, device_id: int, email: str) -> bool:
with self._pool.connection() as conn:
cur = conn.execute(
"UPDATE notifier_tokens SET revoked_at = now() WHERE id = %s AND email = %s AND revoked_at IS NULL",
(device_id, store.norm_str(email, lower=True)),
)
return bool(cur.rowcount)
# ════════════════════════════════════════════════════════════ # ════════════════════════════════════════════════════════════
# 멘션(@태그) — task_mentions # 멘션(@태그) — task_mentions
# #
+162 -1
View File
@@ -2299,19 +2299,180 @@ def api_notification_alerts(request: Request, after: int = -1) -> JSONResponse:
처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게.""" 처음 쓰는 브라우저가 쌓인 옛 알림을 한꺼번에 띄우지 않게."""
user = _require_user(request) user = _require_user(request)
st = _db_or_503(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) newest = st.list_notifications(recipient_email=user["email"], limit=1)
latest = int(newest[0]["id"]) if newest else 0 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": []} out: dict[str, Any] = {"me": store.norm_str(user["email"], lower=True), "latest_id": latest, "alerts": []}
if after < 0: 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) 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] 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] 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")} 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] 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) 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") @router.get("/api/notifications/unread-count")
def api_notif_count(request: Request) -> JSONResponse: def api_notif_count(request: Request) -> JSONResponse:
user = _require_user(request) user = _require_user(request)
@@ -7,7 +7,7 @@
my_open_total 진행 중인 내 업무 개수 (내 업무 배지) my_open_total 진행 중인 내 업무 개수 (내 업무 배지)
nav_projects 프로젝트 목록(평면) nav_projects 프로젝트 목록(평면)
current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0) current_pid 지금 보고 있는 프로젝트 id (내 업무/수신함 화면이면 0)
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시 side_active 'inbox' | 'mytasks' | 'notifier' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함) goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
goal_year_active 목표 화면에서 보고 있는 연도 goal_year_active 목표 화면에서 보고 있는 연도
is_admin 프로젝트 생성/수정/삭제 권한 is_admin 프로젝트 생성/수정/삭제 권한
@@ -44,6 +44,11 @@
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge" <span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span> {% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
</a> </a>
{# PC 알림 — 트레이 프로그램(desktop/notifier) 내려받기·연결 승인·연결된 PC 해제(023) #}
<a class="pj-side-navlink {% if side_active == 'notifier' %}is-active{% endif %}" href="/project/notifier">
<span class="material-symbols-outlined pj-side-navic">desktop_windows</span>
<span class="pj-side-navtext">PC 알림</span>
</a>
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #} {# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
{% if is_admin %} {% if is_admin %}
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash"> <a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
@@ -0,0 +1,112 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261008a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
{% block content %}
{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제.
토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #}
<div class="pj-wrap pj-inbox-view pj-notifier-view">
<div class="pj-layout">
{% with current_pid = 0, side_active = "notifier" %}{% include "project/_side.html" %}{% endwith %}
<section class="pj-main">
<div class="pj-section-head"><h2>PC 알림 프로그램</h2></div>
<div class="pj-view pj-inbox-pane pj-notifier-pane">
{% if not notifier_enabled %}
<div class="pj-empty">PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).</div>
{% else %}
{% if code %}
<div class="pj-notifier-card is-link" id="pj-notifier-link" data-code="{{ code }}">
{% if link and not link.approved_at %}
<h3>이 PC 를 내 알림에 연결할까요?</h3>
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
{% elif link %}
<h3>이미 연결을 승인했습니다</h3>
<p class="pj-notifier-note">알림 프로그램이 곧 연결을 마칩니다. 이 창은 닫아도 됩니다.</p>
{% else %}
<h3>연결 코드가 없거나 만료되었습니다</h3>
<p class="pj-notifier-note">연결 코드는 10분 동안만 쓸 수 있습니다. 알림 프로그램에서 [연결]을 다시 누르세요.</p>
{% endif %}
</div>
{% endif %}
<div class="pj-notifier-card">
<h3>설치</h3>
<ol class="pj-notifier-steps">
<li>{% if download_ready %}<a class="pj-btn pj-btn-primary pj-btn-sm" href="/project/notifier/download">DBXNotifier.exe 내려받기</a>
{% else %}관리자에게 <b>DBXNotifier.exe</b> 파일을 받으세요.{% endif %}
설치 없이 파일 하나로 실행됩니다(Windows 10·11).</li>
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
</ol>
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
</div>
<div class="pj-notifier-card">
<h3>연결된 PC</h3>
{% if devices %}
<table class="pj-table pj-notifier-table">
<thead><tr><th>PC 이름</th><th>연결한 때</th><th>마지막 확인</th><th></th></tr></thead>
<tbody>
{% for d in devices %}
<tr>
<td>{{ d.device_name or '-' }}</td>
<td>{{ (d.created_at or '')[:16] | replace('T', ' ') }}</td>
<td>{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}</td>
<td class="pj-trash-act"><button type="button" class="pj-btn pj-btn-sm pj-notifier-revoke"
data-id="{{ d.id }}" data-name="{{ d.device_name }}">연결 해제</button></td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p class="pj-notifier-note">연결된 PC 가 없습니다.</p>
{% endif %}
</div>
{% endif %}
</div>
</section>
</div>
</div>
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script>
(function () {
async function post(url, body) {
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
const data = await res.json().catch(function () { return {}; });
if (!res.ok) throw new Error(data.detail || ("HTTP " + res.status));
return data;
}
const approve = document.getElementById("pj-notifier-approve");
if (approve) approve.addEventListener("click", async function () {
approve.disabled = true;
try {
await post("/project/api/notifier/link/approve", { code: document.getElementById("pj-notifier-link").dataset.code });
location.replace("/project/notifier?code=" + encodeURIComponent(document.getElementById("pj-notifier-link").dataset.code));
} catch (e) { approve.disabled = false; alert("연결 실패: " + e.message); }
});
document.querySelectorAll(".pj-notifier-revoke").forEach(function (b) {
b.addEventListener("click", async function () {
if (!confirm((b.dataset.name || "이 PC") + " 의 알림 연결을 해제할까요?")) return;
b.disabled = true;
try { await post("/project/api/notifier/devices/" + b.dataset.id + "/revoke"); location.reload(); }
catch (e) { b.disabled = false; alert("해제 실패: " + e.message); }
});
});
})();
</script>
<script src="/static/project.js?v=20261007m" defer></script>
{% endblock %}
+11
View File
@@ -2994,3 +2994,14 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p
.pj-goal-text-swatch[aria-pressed="true"] { outline: 2px solid var(--pj-accent); outline-offset: 2px; } .pj-goal-text-swatch[aria-pressed="true"] { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
.pj-goal-text-swatch:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; } .pj-goal-text-swatch:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
.pj-goal-format :disabled { opacity: .45; cursor: default; } .pj-goal-format :disabled { opacity: .45; cursor: default; }
/* PC 알림 프로그램 화면(/project/notifier, 023) */
.pj-notifier-pane { display: flex; flex-direction: column; gap: 14px; max-width: 760px; padding: 16px; }
.pj-notifier-card { padding: 14px 16px; border: 1px solid var(--pj-border); border-radius: 12px; background: #fff; }
.pj-notifier-card.is-link { border: 2px solid var(--pj-accent); background: #faf8ff; }
.pj-notifier-card h3 { margin: 0 0 8px; font-size: 15px; }
.pj-notifier-card p { margin: 6px 0; }
.pj-notifier-code { font-family: ui-monospace, Consolas, monospace; font-size: 16px; letter-spacing: 1px; color: var(--pj-accent-dark); }
.pj-notifier-note { color: var(--pj-ink-soft); font-size: 13px; }
.pj-notifier-steps { margin: 4px 0 8px; padding-left: 20px; line-height: 1.9; }
.pj-notifier-table { width: 100%; }
+3
View File
@@ -0,0 +1,3 @@
bin/
obj/
dist/
+355
View File
@@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>
/// 큰 알림 창 — 웹 프로젝트 화면의 큰 팝업(.pj-alert-pop)과 같은 모양: 흰 카드·둥근 모서리 16·연분홍 머리(종 + "새 알림 N건" + 닫기)·
/// 줄마다 배지(작업 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛.
/// 다른 프로그램 위(맨 위)에 뜨지만 포커스는 빼앗지 않는다(입력 중이던 창 그대로). 둥근 모서리·그림자를 위해
/// 픽셀 단위 투명 창(UpdateLayeredWindow)으로 직접 그린다.
/// </summary>
internal sealed class AlertForm : Form
{
public event Action<Alert> OpenClicked;
public event Action CloseClicked;
public event Action MoreClicked;
private const int MaxRows = 6;
private const float CardW = 560, HeadH = 54, RowH = 62, Pad = 6, MoreH = 38, ShadowM = 40, BottomGap = 28, Radius = 16;
private static readonly Color Accent = Gfx.Hex("#7b68ee");
private static readonly Color AccentDark = Gfx.Hex("#6453d6");
private static readonly Color Orange = Gfx.Hex("#ff6b4a");
private static readonly Color Ink = Gfx.Hex("#050505");
private static readonly Color InkSoft = Gfx.Hex("#636363");
private const string FontName = "Malgun Gothic";
private readonly List<Alert> _items = new List<Alert>();
private readonly List<RectangleF> _rows = new List<RectangleF>();
private readonly Timer _blink = new Timer { Interval = 70 };
private readonly DateTime _t0 = DateTime.Now;
private int _total;
private float _s = 1f, _fontScale = -1f;
private RectangleF _card, _close, _more;
private int _hoverRow = -1;
private bool _hoverClose, _hoverMore;
private Font _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn;
public AlertForm()
{
FormBorderStyle = FormBorderStyle.None;
ShowInTaskbar = false;
StartPosition = FormStartPosition.Manual;
TopMost = true;
Text = "DBX 알림";
_blink.Tick += (s, e) => Render();
}
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE;
return cp;
}
}
protected override bool ShowWithoutActivation => true;
/// <summary>알림 목록을 보여 준다(처음이면 띄우고, 이미 떠 있으면 내용만 바꾼다).</summary>
public void SetAlerts(IList<Alert> all)
{
_items.Clear();
for (int i = 0; i < all.Count && i < MaxRows; i++) _items.Add(all[i]);
_total = all.Count;
_hoverRow = -1;
_hoverClose = _hoverMore = false;
if (!IsHandleCreated) CreateHandle();
LayoutCard();
Render();
if (!Visible) Show();
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
_blink.Start();
}
public void HidePopup()
{
_blink.Stop();
Hide();
}
private void EnsureFonts()
{
if (Math.Abs(_fontScale - _s) < 0.01f) return;
DisposeFonts();
_fontScale = _s;
_fHead = new Font(FontName, 15f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fTitle = new Font(FontName, 14.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fSmall = new Font(FontName, 12f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
_fBadge = new Font(FontName, 11.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fGo = new Font(FontName, 12.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
_fBtn = new Font(FontName, 13f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
}
private void DisposeFonts()
{
foreach (Font f in new[] { _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn }) f?.Dispose();
}
/// <summary>카드 크기·위치 — 마우스가 있는 화면의 작업 영역 아래 가운데(웹 팝업처럼 아래에서 28px 위).</summary>
private void LayoutCard()
{
_s = Gfx.SystemScale();
EnsureFonts();
int extra = _total - _items.Count;
float cardH = HeadH + Pad * 2 + _items.Count * RowH + (extra > 0 ? MoreH : 0);
float m = ShadowM * _s;
_card = new RectangleF(m, m, CardW * _s, cardH * _s);
_close = new RectangleF(_card.Right - 72 * _s, _card.Y + (HeadH - 32) / 2 * _s, 58 * _s, 32 * _s);
_rows.Clear();
float y = _card.Y + (HeadH + Pad) * _s;
foreach (Alert _ in _items)
{
_rows.Add(new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, RowH * _s));
y += RowH * _s;
}
_more = extra > 0 ? new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, MoreH * _s) : RectangleF.Empty;
int bw = (int)Math.Ceiling(_card.Width + 2 * m), bh = (int)Math.Ceiling(_card.Height + 2 * m);
Rectangle wa = Screen.FromPoint(Cursor.Position).WorkingArea;
int x = wa.Left + (wa.Width - bw) / 2;
int top = (int)(wa.Bottom - BottomGap * _s - _card.Height - m);
Bounds = new Rectangle(x, Math.Max(wa.Top, top), bw, bh);
}
private static void DrawText(Graphics g, string t, Font f, Color c, RectangleF r,
StringAlignment h = StringAlignment.Near, StringAlignment v = StringAlignment.Center)
{
// GenericTypographic — 한글 글자 사이가 벌어지지 않게(기본 StringFormat 은 글자마다 여백을 둔다)
using (var sf = (StringFormat)StringFormat.GenericTypographic.Clone())
using (var b = new SolidBrush(c))
{
sf.FormatFlags |= StringFormatFlags.NoWrap;
sf.Trimming = StringTrimming.EllipsisCharacter;
sf.Alignment = h;
sf.LineAlignment = v;
g.DrawString(t ?? "", f, b, r, sf);
}
}
private static void Fill(Graphics g, RectangleF r, float radius, Color c)
{
using (GraphicsPath p = Gfx.Round(r, radius))
using (var b = new SolidBrush(c))
g.FillPath(b, p);
}
private void Render()
{
if (!IsHandleCreated || Width <= 0 || Height <= 0) return;
double phase = (DateTime.Now - _t0).TotalSeconds % 1.0;
double k = (1 - Math.Cos(phase * 2 * Math.PI)) / 2; // 0 → 1 → 0 (보라 → 주황 → 보라)
float s = _s, rad = Radius * s;
RectangleF c = _card;
using (var bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb))
using (Graphics g = Graphics.FromImage(bmp))
{
g.SmoothingMode = SmoothingMode.AntiAlias;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.TextRenderingHint = TextRenderingHint.AntiAlias;
g.Clear(Color.Transparent);
// 그림자(0 18px 50px rgba(16,24,40,.28) 비슷하게 — 겹겹이 옅게)
for (int i = 12; i >= 1; i--)
{
RectangleF r = c;
r.Offset(0, 12 * s);
r.Inflate(i * 2.2f * s, i * 2.2f * s);
Fill(g, r, rad + i * 2.2f * s, Color.FromArgb(6, 16, 24, 40));
}
// 깜박이는 주황 빛(0 0 0 10px rgba(255,107,74,.18))
if (k > 0.02)
{
RectangleF r = c;
float sp = (float)(k * 10 * s);
r.Inflate(sp, sp);
Fill(g, r, rad + sp, Color.FromArgb((int)(k * 0.18 * 255), Orange));
}
using (GraphicsPath cardPath = Gfx.Round(c, rad))
{
using (var b = new SolidBrush(Color.White)) g.FillPath(b, cardPath);
GraphicsState gs = g.Save();
g.SetClip(cardPath, CombineMode.Intersect);
var head = new RectangleF(c.X, c.Y, c.Width, HeadH * s);
using (var b = new SolidBrush(Gfx.Hex("#fff4f0"))) g.FillRectangle(b, head);
using (var p = new Pen(Gfx.Hex("#f6d6cc"), Math.Max(1f, s))) g.DrawLine(p, c.X, head.Bottom, c.Right, head.Bottom);
Gfx.Bell(g, new RectangleF(c.X + 16 * s, head.Y + (HeadH - 24) / 2 * s, 24 * s, 24 * s), Gfx.Hex("#e5532f"));
DrawText(g, "새 알림 " + _total + "건", _fHead, Ink, new RectangleF(c.X + 50 * s, head.Y, _close.X - c.X - 60 * s, head.Height));
Fill(g, _close, 8 * s, _hoverClose ? Gfx.Hex("#f2f4f7") : Color.White);
using (GraphicsPath bp = Gfx.Round(_close, 8 * s))
using (var p = new Pen(Gfx.Hex("#d0d5dd"), Math.Max(1f, s)))
g.DrawPath(p, bp);
DrawText(g, "닫기", _fBtn, Gfx.Hex("#344054"), _close, StringAlignment.Center);
for (int i = 0; i < _items.Count; i++) DrawRow(g, _items[i], _rows[i], i == _hoverRow);
if (!_more.IsEmpty)
{
if (_hoverMore) Fill(g, _more, 10 * s, Gfx.Hex("#f5f6f8"));
DrawText(g, "외 " + (_total - _items.Count) + "건 더 — 수신함에서 보기 ›", _fGo, AccentDark, _more, StringAlignment.Center);
}
g.Restore(gs);
RectangleF br = c;
br.Inflate(-s, -s);
using (GraphicsPath bp = Gfx.Round(br, rad - s))
using (var pen = new Pen(Gfx.Mix(Accent, Orange, k), 2 * s))
g.DrawPath(pen, bp);
}
Push(bmp);
}
}
private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover)
{
float s = _s;
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
string kind = a.IsMention ? "나를 태그" : "작업 배정";
SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic);
var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s);
Fill(g, kr, 11 * s, a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec"));
DrawText(g, kind, _fBadge, a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center);
const string go = "열기 ›";
SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic);
float goX = r.Right - 12 * s - gsz.Width;
DrawText(g, go, _fGo, AccentDark, new RectangleF(goX - 2 * s, r.Y, gsz.Width + 8 * s, r.Height));
float tx = kr.Right + 12 * s, tw = Math.Max(10, goX - 14 * s - tx);
DrawText(g, a.CleanTitle, _fTitle, Ink, new RectangleF(tx, r.Y + 8 * s, tw, 24 * s));
DrawText(g, a.SubLine, _fSmall, InkSoft, new RectangleF(tx, r.Y + 33 * s, tw, 20 * s));
}
protected override void OnMouseMove(MouseEventArgs e)
{
base.OnMouseMove(e);
int row = -1;
for (int i = 0; i < _rows.Count; i++) if (_rows[i].Contains(e.Location)) row = i;
bool close = _close.Contains(e.Location);
bool more = !_more.IsEmpty && _more.Contains(e.Location);
if (row != _hoverRow || close != _hoverClose || more != _hoverMore)
{
_hoverRow = row;
_hoverClose = close;
_hoverMore = more;
Render();
}
Cursor = row >= 0 || close || more ? Cursors.Hand : Cursors.Default;
}
protected override void OnMouseLeave(EventArgs e)
{
base.OnMouseLeave(e);
_hoverRow = -1;
_hoverClose = _hoverMore = false;
Render();
}
protected override void OnMouseUp(MouseEventArgs e)
{
base.OnMouseUp(e);
if (e.Button != MouseButtons.Left) return;
if (_close.Contains(e.Location)) { CloseClicked?.Invoke(); return; }
if (!_more.IsEmpty && _more.Contains(e.Location)) { MoreClicked?.Invoke(); return; }
for (int i = 0; i < _rows.Count; i++)
if (_rows[i].Contains(e.Location)) { OpenClicked?.Invoke(_items[i]); return; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_blink.Dispose();
DisposeFonts();
}
base.Dispose(disposing);
}
// ── Win32: 픽셀 단위 투명 창 ──
private void Push(Bitmap bmp)
{
IntPtr screenDc = GetDC(IntPtr.Zero);
IntPtr memDc = CreateCompatibleDC(screenDc);
IntPtr hBmp = IntPtr.Zero, old = IntPtr.Zero;
try
{
hBmp = bmp.GetHbitmap(Color.FromArgb(0));
old = SelectObject(memDc, hBmp);
var size = new SIZE { cx = bmp.Width, cy = bmp.Height };
var src = new POINT();
var dst = new POINT { x = Left, y = Top };
var blend = new BLENDFUNCTION { BlendOp = 0, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = 1 };
UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, ULW_ALPHA);
}
finally
{
if (old != IntPtr.Zero) SelectObject(memDc, old);
if (hBmp != IntPtr.Zero) DeleteObject(hBmp);
DeleteDC(memDc);
ReleaseDC(IntPtr.Zero, screenDc);
}
}
private const int WS_EX_LAYERED = 0x80000, WS_EX_TOOLWINDOW = 0x80, WS_EX_TOPMOST = 0x8, WS_EX_NOACTIVATE = 0x08000000;
private const int ULW_ALPHA = 2;
private const uint SWP_NOSIZE = 0x1, SWP_NOMOVE = 0x2, SWP_NOACTIVATE = 0x10, SWP_SHOWWINDOW = 0x40;
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int x, y; }
[StructLayout(LayoutKind.Sequential)]
private struct SIZE { public int cx, cy; }
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct BLENDFUNCTION { public byte BlendOp, BlendFlags, SourceConstantAlpha, AlphaFormat; }
[DllImport("user32.dll", SetLastError = true)]
private static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize,
IntPtr hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
private static extern bool DeleteDC(IntPtr hdc);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);
}
}
+164
View File
@@ -0,0 +1,164 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace DbxNotifier
{
internal sealed class Alert
{
public long Id;
public string Type = "";
public string Title = "";
public string Body = "";
public string Actor = "";
public long TaskId;
public long ProjectId;
public bool IsMention => Type == "mention";
/// <summary>제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
}
/// <summary>둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).</summary>
public string SubLine
{
get
{
string who = Actor;
int at = who.IndexOf('@');
if (at > 0) who = who.Substring(0, at);
if (who.Length > 0) who = char.ToUpperInvariant(who[0]) + who.Substring(1);
if (Body.Length > 0 && who.Length > 0) return Body + " · " + who;
return Body.Length > 0 ? Body : who;
}
}
public string Path => ProjectId > 0
? "/project/p/" + ProjectId + (TaskId > 0 ? "?task=" + TaskId : "")
: "/project/inbox";
}
internal sealed class AlertResult
{
public string Name = "";
public long LatestId;
public List<Alert> Alerts = new List<Alert>();
}
internal sealed class ApiException : Exception
{
public readonly int Status;
public ApiException(int status, string message) : base(message) { Status = status; }
}
/// <summary>ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.</summary>
internal sealed class Api : IDisposable
{
private readonly HttpClient _http;
private static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
public Api()
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("DBXNotifier/" + typeof(Api).Assembly.GetName().Version.ToString(3));
}
public void Dispose() => _http.Dispose();
/// <summary>서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).</summary>
public static string NormalizeServer(string raw)
{
string s = (raw ?? "").Trim().TrimEnd('/');
if (!Uri.TryCreate(s, UriKind.Absolute, out Uri u) || (u.AbsolutePath != "/" && u.AbsolutePath.Length > 0))
throw new ArgumentException("ERP 주소가 올바르지 않습니다. 예: " + Settings.DefaultServer);
bool local = u.Host == "localhost" || u.Host == "127.0.0.1";
if (u.Scheme != Uri.UriSchemeHttps && !(local && u.Scheme == Uri.UriSchemeHttp))
throw new ArgumentException("ERP 주소는 https:// 로 시작해야 합니다.");
return u.GetLeftPart(UriPartial.Authority);
}
private async Task<Dictionary<string, object>> Send(HttpMethod method, string url, string token, object body)
{
using (var req = new HttpRequestMessage(method, url))
{
if (!string.IsNullOrEmpty(token)) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null) req.Content = new StringContent(Json.Serialize(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await _http.SendAsync(req).ConfigureAwait(false))
{
string text = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary<string, object> d = null;
try { d = Json.Deserialize<Dictionary<string, object>>(text); } catch { /* HTML 오류 화면 등 */ }
if (!res.IsSuccessStatusCode)
{
string detail = d != null && d.TryGetValue("detail", out var x) ? x as string : null;
throw new ApiException((int)res.StatusCode, detail ?? ("서버 오류 HTTP " + (int)res.StatusCode));
}
return d ?? new Dictionary<string, object>();
}
}
}
private static string Str(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
private static long Num(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToInt64(v) : 0;
public async Task<(string Code, string Poll, string ApprovePath, int ExpiresIn)> StartLink(string server, string device)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/start", null, new { device }).ConfigureAwait(false);
return (Str(d, "code"), Str(d, "poll"), Str(d, "approve_path"), (int)Num(d, "expires_in"));
}
/// <summary>연결 확인 — status: pending | expired | ok(token, email).</summary>
public async Task<(string Status, string Token, string Email)> PollLink(string server, string poll)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/poll", null, new { poll }).ConfigureAwait(false);
return (Str(d, "status"), Str(d, "token"), Str(d, "email"));
}
public async Task<AlertResult> Alerts(string server, string token, long after)
{
var d = await Send(HttpMethod.Get, server + "/project/api/notifier/alerts?after=" + after, token, null).ConfigureAwait(false);
var r = new AlertResult { Name = Str(d, "name"), LatestId = Num(d, "latest_id") };
if (d.TryGetValue("alerts", out var list) && list is IEnumerable items)
{
foreach (object o in items)
{
if (!(o is Dictionary<string, object> a)) continue;
r.Alerts.Add(new Alert
{
Id = Num(a, "id"),
Type = Str(a, "type"),
Title = Str(a, "title"),
Body = Str(a, "body"),
Actor = Str(a, "actor_email"),
TaskId = Num(a, "task_id"),
ProjectId = Num(a, "project_id"),
});
}
}
return r;
}
public Task MarkRead(string server, string token, long id) =>
Send(HttpMethod.Post, server + "/project/api/notifier/alerts/" + id + "/read", token, new { });
public Task Logout(string server, string token) =>
Send(HttpMethod.Post, server + "/project/api/notifier/logout", token, new { });
}
}
+195
View File
@@ -0,0 +1,195 @@
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
namespace DbxNotifier
{
internal static class Browser
{
/// <summary>기본 브라우저로 연다. 실패하면 주소를 클립보드에 복사하고 false.</summary>
public static bool Open(string url)
{
try
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
return true;
}
catch
{
try { Clipboard.SetText(url); } catch { /* 클립보드 사용 중 */ }
return false;
}
}
}
/// <summary>
/// PC 연결 창 — [브라우저에서 연결] → 서버가 준 코드를 크게 보여 주고 브라우저로 승인 화면(/project/notifier?code=)을 연다.
/// 사용자가 브라우저(이미 로그인)에서 [연결]을 누르면 2초마다 확인하던 이 창이 토큰을 받아 닫힌다.
/// </summary>
internal sealed class ConnectForm : Form
{
public string Server { get; private set; } = "";
public string Token { get; private set; } = "";
public string Email { get; private set; } = "";
public bool AutoStartChecked => _auto.Checked;
private readonly Api _api;
private readonly TextBox _server;
private readonly CheckBox _auto;
private readonly Button _go;
private readonly Label _code, _status;
private readonly Timer _poll = new Timer { Interval = 2000 };
private string _pollSecret = "", _approveUrl = "";
private DateTime _expires;
private bool _busy;
public ConnectForm(Api api, string server, bool autoStart)
{
_api = api;
Text = "DBX 알림 — PC 연결";
Icon = Gfx.AppIcon(new Size(32, 32));
Font = new Font("Malgun Gothic", 9.75f);
AutoScaleDimensions = new SizeF(96f, 96f);
AutoScaleMode = AutoScaleMode.Dpi;
FormBorderStyle = FormBorderStyle.FixedDialog;
MaximizeBox = MinimizeBox = false;
StartPosition = FormStartPosition.CenterScreen;
ClientSize = new Size(440, 344);
BackColor = Color.White;
Controls.Add(new Label
{
Text = "이 PC 에 ERP 알림(나를 태그·작업 배정)을 띄우려면\n내 ERP 계정에 연결하세요.",
Location = new Point(20, 18), AutoSize = true, MaximumSize = new Size(400, 0),
});
Controls.Add(new Label { Text = "ERP 주소", Location = new Point(20, 84), AutoSize = true });
_server = new TextBox { Text = server, Location = new Point(20, 106), Width = 400 };
Controls.Add(_server);
_auto = new CheckBox { Text = "Windows 시작 시 자동 실행", Checked = autoStart, Location = new Point(20, 140), AutoSize = true };
Controls.Add(_auto);
_go = new Button
{
Text = "브라우저에서 연결", Location = new Point(20, 174), Size = new Size(170, 34),
BackColor = Gfx.Hex("#7b68ee"), ForeColor = Color.White, FlatStyle = FlatStyle.Flat,
};
_go.FlatAppearance.BorderSize = 0;
_go.Click += (s, e) => OnGo();
Controls.Add(_go);
_code = new Label
{
Location = new Point(200, 172), Size = new Size(220, 38), Visible = false,
Font = new Font("Consolas", 18f, FontStyle.Bold), ForeColor = Gfx.Hex("#6453d6"), TextAlign = ContentAlignment.MiddleCenter,
BackColor = Gfx.Hex("#f4f1ff"),
};
Controls.Add(_code);
_status = new Label { Location = new Point(20, 222), Size = new Size(400, 66), ForeColor = Gfx.Hex("#636363") };
Controls.Add(_status);
var close = new Button { Text = "닫기", Location = new Point(340, 298), Size = new Size(80, 30), DialogResult = DialogResult.Cancel };
Controls.Add(close);
CancelButton = close;
AcceptButton = _go;
_poll.Tick += (s, e) => OnPoll();
}
private async void OnGo()
{
if (_approveUrl.Length > 0) // 이미 코드를 받았으면 브라우저만 다시
{
OpenApprove();
return;
}
string server;
try { server = Api.NormalizeServer(_server.Text); }
catch (ArgumentException ex)
{
_status.Text = ex.Message;
return;
}
_go.Enabled = false;
_server.Enabled = false;
_status.Text = "연결 요청 중…";
try
{
var r = await _api.StartLink(server, Environment.MachineName);
Server = server;
_pollSecret = r.Poll;
_approveUrl = server + r.ApprovePath;
_expires = DateTime.Now.AddSeconds(r.ExpiresIn > 0 ? r.ExpiresIn : 600);
_code.Text = r.Code;
_code.Visible = true;
_go.Text = "브라우저 다시 열기";
OpenApprove();
_poll.Start();
}
catch (Exception ex)
{
_status.Text = "연결 요청 실패: " + ex.Message;
_server.Enabled = true;
}
finally
{
_go.Enabled = true;
}
}
private void OpenApprove()
{
_status.Text = Browser.Open(_approveUrl)
? "브라우저 화면의 연결 코드가 오른쪽 코드와 같은지 확인하고 [연결]을 누르세요.\n(10분 안에 — 연결되면 이 창은 저절로 닫힙니다.)"
: "브라우저를 열지 못해 주소를 복사했습니다. 브라우저 주소창에 붙여 넣으세요.\n" + _approveUrl;
}
private void Reset(string message)
{
_poll.Stop();
_approveUrl = _pollSecret = "";
_code.Visible = false;
_go.Text = "브라우저에서 연결";
_server.Enabled = true;
_status.Text = message;
}
private async void OnPoll()
{
if (_busy) return;
if (DateTime.Now > _expires)
{
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
return;
}
_busy = true;
try
{
var r = await _api.PollLink(Server, _pollSecret);
if (r.Status == "ok" && r.Token.Length > 0)
{
_poll.Stop();
Token = r.Token;
Email = r.Email;
DialogResult = DialogResult.OK;
Close();
}
else if (r.Status == "expired")
{
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
}
}
catch
{
// 네트워크 잠깐 끊김 — 다음 확인 때 다시
}
finally
{
_busy = false;
}
}
protected override void Dispose(bool disposing)
{
if (disposing) _poll.Dispose();
base.Dispose(disposing);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- DBX 알림(PC 트레이 프로그램). .NET Framework 4.8 — Windows 10(1903+)·11 에 기본 설치돼 있어 런타임 설치 없이
exe 하나로 실행된다. 압축·난독화·자체 압축 해제(백신 오탐 주원인)를 쓰지 않는 평범한 관리 코드 exe. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net48</TargetFramework>
<LangVersion>latest</LangVersion>
<AssemblyName>DBXNotifier</AssemblyName>
<RootNamespace>DbxNotifier</RootNamespace>
<ApplicationIcon>app.ico</ApplicationIcon>
<ApplicationManifest>app.manifest</ApplicationManifest>
<PlatformTarget>AnyCPU</PlatformTarget>
<Prefer32Bit>false</Prefer32Bit>
<Deterministic>true</Deterministic>
<DebugType>none</DebugType>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<!-- 파일 속성(자세히) — 회사·제품·설명·버전이 채워진 exe 가 백신·SmartScreen 평판에 유리 -->
<Version>1.0.0</Version>
<FileVersion>1.0.0.0</FileVersion>
<AssemblyVersion>1.0.0.0</AssemblyVersion>
<Company>DBX</Company>
<Product>DBX 알림</Product>
<AssemblyTitle>DBX 알림</AssemblyTitle>
<Description>DBX ERP 프로젝트 알림(태그·작업 배정)을 화면에 띄우는 트레이 프로그램</Description>
<Copyright>© 2026 DBX</Copyright>
<NeutralLanguage>ko-KR</NeutralLanguage>
</PropertyGroup>
<ItemGroup>
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Security" />
<Reference Include="System.Web.Extensions" />
<EmbeddedResource Include="app.ico" LogicalName="DbxNotifier.app.ico" />
</ItemGroup>
<ItemGroup>
<Compile Remove="tools\**" />
<None Remove="tools\**" />
</ItemGroup>
</Project>
+83
View File
@@ -0,0 +1,83 @@
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>그리기 도우미 — 둥근 사각형, 종 아이콘, 색 섞기, 내장 아이콘.</summary>
internal static class Gfx
{
public static GraphicsPath Round(RectangleF r, float radius)
{
var p = new GraphicsPath();
float d = Math.Min(radius * 2, Math.Min(r.Width, r.Height));
if (d <= 0.5f)
{
p.AddRectangle(r);
return p;
}
p.AddArc(r.X, r.Y, d, d, 180, 90);
p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
p.CloseFigure();
return p;
}
public static Color Mix(Color a, Color b, double t) => Color.FromArgb(
(int)(a.A + (b.A - a.A) * t), (int)(a.R + (b.R - a.R) * t),
(int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t));
public static Color Hex(string hex, int alpha = 255)
{
int v = Convert.ToInt32(hex.TrimStart('#'), 16);
return Color.FromArgb(alpha, (v >> 16) & 255, (v >> 8) & 255, v & 255);
}
/// <summary>울리는 종(웹 팝업 머리의 notifications_active 와 같은 느낌) — 24 격자를 r 에 맞춰 그린다.</summary>
public static void Bell(Graphics g, RectangleF r, Color color)
{
GraphicsState st = g.Save();
g.TranslateTransform(r.X, r.Y);
g.ScaleTransform(r.Width / 24f, r.Height / 24f);
using (var b = new SolidBrush(color))
using (var body = new GraphicsPath())
{
body.AddLine(5f, 17f, 6.6f, 15.2f);
body.AddLine(6.6f, 15.2f, 6.6f, 10.6f);
body.AddBezier(6.6f, 10.6f, 6.6f, 7.2f, 9.0f, 4.9f, 12f, 4.9f);
body.AddBezier(12f, 4.9f, 15.0f, 4.9f, 17.4f, 7.2f, 17.4f, 10.6f);
body.AddLine(17.4f, 10.6f, 17.4f, 15.2f);
body.AddLine(17.4f, 15.2f, 19f, 17f);
body.CloseFigure();
g.FillPath(b, body);
g.FillEllipse(b, 10.1f, 16.7f, 3.8f, 3.8f);
g.FillEllipse(b, 10.9f, 3.3f, 2.2f, 2.2f);
}
using (var pen = new Pen(color, 1.7f) { StartCap = LineCap.Round, EndCap = LineCap.Round })
{
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 198, 40);
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 302, 40);
}
g.Restore(st);
}
/// <summary>exe 에 넣은 app.ico 에서 원하는 크기 아이콘(트레이 = 작은 아이콘 크기).</summary>
public static Icon AppIcon(Size size)
{
using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("DbxNotifier.app.ico"))
return s == null ? SystemIcons.Information : new Icon(s, size);
}
public static Icon TrayIcon() => AppIcon(SystemInformation.SmallIconSize);
public static float SystemScale()
{
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
return Math.Max(1f, g.DpiX / 96f);
}
}
}
+29
View File
@@ -0,0 +1,29 @@
using System;
using System.Threading;
using System.Windows.Forms;
namespace DbxNotifier
{
internal static class Program
{
[STAThread]
private static void Main(string[] args)
{
// 한 사용자 세션에 하나만 — 두 번 실행하면 안내만 하고 끝낸다.
using (var mutex = new Mutex(true, @"Local\DBXNotifier.SingleInstance", out bool created))
{
if (!created)
{
MessageBox.Show("DBX 알림이 이미 실행 중입니다.\n화면 오른쪽 아래 트레이의 종 아이콘을 확인하세요.",
"DBX 알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
bool autostart = Array.IndexOf(args, "--autostart") >= 0;
Application.Run(new TrayApp(autostart));
GC.KeepAlive(mutex);
}
}
}
}
+40
View File
@@ -0,0 +1,40 @@
# DBX 알림 (PC 트레이 프로그램)
ERP 프로젝트에서 **나를 태그**하거나 **작업이 배정**되면, 브라우저가 뒤에 있어도 PC 화면 아래 가운데에
웹 팝업과 같은 모양의 큰 알림 창을 띄운다. 서버 쪽 설명은 `docs/PROJECT_MODULE.md` 6-11.
- 실행 파일 하나(`DBXNotifier.exe`, 약 50KB), 설치 없음, 관리자 권한 불필요
- 실행하면 트레이(오른쪽 아래)에 종 아이콘만 남는다 — 메모리 약 25~30MB(전용), 20초마다 서버 확인
- 대상: Windows 10(1903 이후)·11 — 기본으로 들어 있는 .NET Framework 4.8 로 동작(런타임 설치 없음)
## 사용
1. `DBXNotifier.exe` 실행 → 연결 창에서 [브라우저에서 연결]
2. 브라우저(ERP 로그인 상태)의 `/project/notifier` 화면에서 코드가 같은지 보고 [연결] → 연결 창이 저절로 닫힘
3. 트레이 아이콘 메뉴: 지금 알림 확인 · ERP 수신함 열기 · 알림 소리 · Windows 시작 시 실행 · 연결 해제 · 종료
(왼쪽 클릭 = 알림이 있으면 알림 창, 없으면 수신함)
설정: `%APPDATA%\DBXNotifier\settings.json` — 토큰은 Windows DPAPI(현재 사용자)로 암호화. 다른 PC·사용자로 복사해도 못 쓴다.
연결 해제는 트레이 메뉴 또는 ERP `/project/notifier` 의 [연결 해제](분실 PC 등).
## 빌드
```powershell
powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1 # → desktop\notifier\dist\DBXNotifier.exe
```
.NET SDK(6 이상)가 있으면 된다. `net48` 참조 어셈블리는 빌드 때 NuGet 에서 자동으로 받는다.
아이콘을 바꾸려면 `tools/make_icon.py`(Pillow) 수정 후 실행 → `app.ico`.
서버 내려받기 버튼에 올리기: `docs/DEPLOYMENT.md` "PC 알림 프로그램 마이그레이션 (023)".
## 백신·SmartScreen
오탐을 부르는 방식은 쓰지 않는다: 실행 파일 압축(UPX)·난독화·자체 압축 해제·다른 프로세스 주입·관리자 권한·숨은 다운로드 없음.
평범한 관리 코드 exe 에 회사·제품·버전 정보가 채워져 있고, 통신은 설정한 ERP 주소(HTTPS)로만 한다.
"Windows 시작 시 실행"은 사용자가 고른 경우에만 현재 사용자 Run 키에 등록한다.
그래도 **서명하지 않은 새 exe** 는 인터넷에서 받으면 Windows SmartScreen 이 "알 수 없는 게시자" 경고를 띄울 수 있다
(백신의 바이러스 판정과는 다르다 — [추가 정보] → [실행]). 경고를 없애는 확실한 방법은 **코드 서명 인증서**(OV/EV)로 서명하는 것:
`build.ps1` 이 `DBX_SIGN_PFX`·`DBX_SIGN_PASSWORD` 환경변수가 있으면 서명한다. 회사 백신 관리 콘솔이 있으면 `build.ps1` 이
출력하는 SHA-256 을 허용 목록에 넣어도 된다.
+134
View File
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Script.Serialization;
using Microsoft.Win32;
using System.Windows.Forms;
namespace DbxNotifier
{
/// <summary>
/// 설정 — %APPDATA%\DBXNotifier\settings.json. 연결 토큰은 Windows DPAPI(현재 사용자)로 암호화해 저장하므로
/// 파일을 다른 PC·다른 사용자로 복사해도 쓸 수 없다.
/// </summary>
internal sealed class Settings
{
public const string DefaultServer = "https://dbx.no1king.freeddns.org";
public string Server = DefaultServer;
public string Token = ""; // 원문은 메모리에서만
public long LastSeen = -1; // 이 번호까지는 본 알림(닫기 누른 것). -1 = 처음(지금 최신을 기준으로)
public bool Sound = true;
public string UserName = "";
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("DBXNotifier.v1");
// DBX_NOTIFIER_DIR — 테스트용 설정 폴더(없으면 %APPDATA%\DBXNotifier)
private static string Dir =>
Environment.GetEnvironmentVariable("DBX_NOTIFIER_DIR") is string d && d.Length > 0
? d
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DBXNotifier");
private static string FilePath => Path.Combine(Dir, "settings.json");
public bool Connected => Token.Length > 0;
public static Settings Load()
{
var s = new Settings();
try
{
if (!File.Exists(FilePath)) return s;
var d = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(File.ReadAllText(FilePath, Encoding.UTF8));
if (d == null) return s;
if (d.TryGetValue("server", out var v) && v is string server && server.Length > 0) s.Server = server;
if (d.TryGetValue("last_seen", out v) && v != null) s.LastSeen = Convert.ToInt64(v);
if (d.TryGetValue("sound", out v) && v is bool sound) s.Sound = sound;
if (d.TryGetValue("user_name", out v) && v is string name) s.UserName = name;
if (d.TryGetValue("token", out v) && v is string enc && enc.Length > 0)
{
byte[] raw = ProtectedData.Unprotect(Convert.FromBase64String(enc), Entropy, DataProtectionScope.CurrentUser);
s.Token = Encoding.UTF8.GetString(raw);
}
}
catch
{
// 깨진 설정은 처음 상태로 — 다시 연결하면 된다.
}
return s;
}
public void Save()
{
try
{
Directory.CreateDirectory(Dir);
string enc = Token.Length == 0
? ""
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(Token), Entropy, DataProtectionScope.CurrentUser));
var d = new Dictionary<string, object>
{
["server"] = Server,
["last_seen"] = LastSeen,
["sound"] = Sound,
["user_name"] = UserName,
["token"] = enc,
};
string tmp = FilePath + ".tmp";
File.WriteAllText(tmp, new JavaScriptSerializer().Serialize(d), new UTF8Encoding(false));
if (File.Exists(FilePath)) File.Replace(tmp, FilePath, null);
else File.Move(tmp, FilePath);
}
catch
{
// 저장 실패는 다음 저장 때 다시
}
}
}
/// <summary>Windows 시작 시 실행 — 현재 사용자 Run 키(관리자 권한 불필요). 사용자가 켜고 끈다.</summary>
internal static class AutoStart
{
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string Name = "DBXNotifier";
private static string Command => "\"" + Application.ExecutablePath + "\" --autostart";
public static bool Enabled
{
get
{
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
return k?.GetValue(Name) is string;
}
}
public static void Set(bool on)
{
try
{
using (var k = Registry.CurrentUser.CreateSubKey(RunKey))
{
if (on) k.SetValue(Name, Command);
else k.DeleteValue(Name, false);
}
}
catch
{
// 정책으로 막힌 PC — 메뉴 체크 표시만 그대로
}
}
/// <summary>exe 를 다른 폴더로 옮겼으면 등록된 경로를 지금 위치로.</summary>
public static void RefreshPath()
{
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
{
if (k?.GetValue(Name) is string cur && !string.Equals(cur, Command, StringComparison.OrdinalIgnoreCase))
Set(true);
}
}
}
}
+300
View File
@@ -0,0 +1,300 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Media;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Win32;
namespace DbxNotifier
{
/// <summary>
/// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창.
/// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로,
/// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다.
/// </summary>
internal sealed class TrayApp : ApplicationContext
{
private const int PollMs = 20000;
private readonly Settings _cfg = Settings.Load();
private readonly Api _api = new Api();
private readonly Icon _icon;
private readonly NotifyIcon _tray;
private readonly ContextMenuStrip _menu;
private readonly Timer _timer = new Timer { Interval = PollMs };
private readonly ToolStripMenuItem _miStatus, _miCheck, _miOpen, _miSound, _miAuto, _miConnect;
private readonly List<Alert> _pending = new List<Alert>();
private readonly HashSet<long> _opened = new HashSet<long>();
private AlertForm _popup;
private ConnectForm _connect;
private bool _busy;
private string _problem = "";
public TrayApp(bool autostart)
{
_icon = Gfx.TrayIcon();
_menu = new ContextMenuStrip { Font = new Font("Malgun Gothic", 9f) };
_miStatus = new ToolStripMenuItem("DBX 알림") { Enabled = false };
_miCheck = new ToolStripMenuItem("지금 알림 확인", null, async (s, e) => await Poll(true));
_miOpen = new ToolStripMenuItem("ERP 수신함 열기", null, (s, e) => OpenPath("/project/inbox"));
_miSound = new ToolStripMenuItem("알림 소리", null, (s, e) => { _cfg.Sound = !_cfg.Sound; _cfg.Save(); Sync(); });
_miAuto = new ToolStripMenuItem("Windows 시작 시 실행", null, (s, e) => { AutoStart.Set(!AutoStart.Enabled); Sync(); });
_miConnect = new ToolStripMenuItem("연결…", null, async (s, e) => { if (_cfg.Connected) await Disconnect(); else ShowConnect(); });
var miExit = new ToolStripMenuItem("종료", null, (s, e) => ExitThread());
_menu.Items.AddRange(new ToolStripItem[]
{
_miStatus, new ToolStripSeparator(), _miCheck, _miOpen, new ToolStripSeparator(),
_miSound, _miAuto, _miConnect, new ToolStripSeparator(), miExit,
});
_menu.Opening += (s, e) => Sync();
_tray = new NotifyIcon { Icon = _icon, Text = "DBX 알림", ContextMenuStrip = _menu, Visible = true };
_tray.MouseClick += (s, e) => { if (e.Button == MouseButtons.Left) OnTrayClick(); };
_timer.Tick += async (s, e) => await Poll(false);
SystemEvents.PowerModeChanged += OnPowerModeChanged;
AutoStart.RefreshPath();
Sync();
// 메시지 루프가 돈 뒤에 시작(창·풍선 도움말이 제대로 뜨게)
var boot = new Timer { Interval = 300 };
boot.Tick += async (s, e) =>
{
boot.Stop();
boot.Dispose();
if (_cfg.Connected)
{
_timer.Start();
await Poll(false);
}
else if (autostart)
{
Balloon("DBX 알림 연결이 필요합니다", "트레이의 종 아이콘을 오른쪽 클릭해 [연결…]을 누르세요.");
}
else
{
ShowConnect();
}
};
boot.Start();
}
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
if (e.Mode == PowerModes.Resume) _ = Poll(false); // 절전에서 깨면 바로 확인
}
private async Task Poll(bool manual)
{
if (!_cfg.Connected)
{
if (manual) ShowConnect();
return;
}
if (_busy) return;
_busy = true;
try
{
AlertResult r = await _api.Alerts(_cfg.Server, _cfg.Token, _cfg.LastSeen < 0 ? -1 : _cfg.LastSeen);
_problem = "";
if (r.Name.Length > 0 && r.Name != _cfg.UserName)
{
_cfg.UserName = r.Name;
_cfg.Save();
}
if (_cfg.LastSeen < 0)
{
_cfg.LastSeen = r.LatestId; // 처음 — 지금까지 온 알림은 띄우지 않는다
_cfg.Save();
}
else
{
Apply(r.Alerts);
}
if (manual && _pending.Count == 0) Balloon("새 알림 없음", "확인하지 않은 태그·작업 배정 알림이 없습니다.");
}
catch (ApiException ex) when (ex.Status == 401)
{
ClearConnection();
Balloon("DBX 알림 연결이 해제되었습니다", ex.Message + "\n트레이 아이콘 메뉴의 [연결…]로 다시 연결하세요.");
}
catch (Exception ex)
{
_problem = "서버에 연결할 수 없음 — 다시 시도 중";
if (manual) Balloon("서버에 연결할 수 없습니다", ex.Message);
}
finally
{
_busy = false;
Sync();
}
}
/// <summary>서버의 지금 목록으로 바꾼다 — 새 번호가 있으면 창을 띄우고 소리, 다른 곳에서 읽은 것은 빠진다.</summary>
private void Apply(List<Alert> fresh)
{
fresh = fresh.Where(a => !_opened.Contains(a.Id)).ToList();
var known = new HashSet<long>(_pending.Select(a => a.Id));
bool added = fresh.Any(a => !known.Contains(a.Id));
_pending.Clear();
_pending.AddRange(fresh);
if (_pending.Count == 0)
{
_popup?.HidePopup();
return;
}
if (added)
{
ShowPopup();
if (_cfg.Sound) SystemSounds.Exclamation.Play();
}
else if (_popup != null && _popup.Visible)
{
_popup.SetAlerts(_pending);
}
}
private void ShowPopup()
{
if (_popup == null)
{
_popup = new AlertForm();
_popup.OpenClicked += OpenAlert;
_popup.CloseClicked += CloseAll;
_popup.MoreClicked += () =>
{
OpenPath("/project/inbox");
CloseAll();
};
}
_popup.SetAlerts(_pending);
Sync();
}
private void OpenAlert(Alert a)
{
OpenPath(a.Path);
_opened.Add(a.Id);
_ = MarkRead(a.Id);
_pending.RemoveAll(x => x.Id == a.Id);
if (_pending.Count == 0) CloseAll();
else _popup.SetAlerts(_pending);
Sync();
}
private async Task MarkRead(long id)
{
try { await _api.MarkRead(_cfg.Server, _cfg.Token, id); }
catch { /* 다음에 웹에서 읽어도 된다 */ }
}
/// <summary>[닫기] — 지금 보이는 알림까지 본 것으로(다시 뜨지 않음).</summary>
private void CloseAll()
{
long max = _cfg.LastSeen;
foreach (Alert a in _pending) max = Math.Max(max, a.Id);
foreach (long id in _opened) max = Math.Max(max, id);
if (max != _cfg.LastSeen)
{
_cfg.LastSeen = max;
_cfg.Save();
}
_pending.Clear();
_opened.Clear();
_popup?.HidePopup();
Sync();
}
private void OnTrayClick()
{
if (_pending.Count > 0) ShowPopup();
else if (!_cfg.Connected) ShowConnect();
else OpenPath("/project/inbox");
}
private void OpenPath(string path) => Browser.Open(_cfg.Server + path);
private void ShowConnect()
{
if (_connect != null)
{
_connect.Activate();
return;
}
_connect = new ConnectForm(_api, _cfg.Server, true);
_connect.FormClosed += (s, e) =>
{
ConnectForm c = _connect;
_connect = null;
if (c.DialogResult != DialogResult.OK || c.Token.Length == 0) return;
_cfg.Server = c.Server;
_cfg.Token = c.Token;
_cfg.LastSeen = -1;
_cfg.Save();
AutoStart.Set(c.AutoStartChecked);
_timer.Start();
Balloon("DBX 알림이 연결되었습니다", c.Email + " 님의 태그·작업 배정 알림을 이 PC 화면에 띄웁니다.");
_ = Poll(false);
};
_connect.Show();
_connect.Activate();
}
private async Task Disconnect()
{
if (MessageBox.Show("이 PC 의 DBX 알림 연결을 해제할까요?\n해제하면 알림이 오지 않습니다.", "DBX 알림",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return;
try { await _api.Logout(_cfg.Server, _cfg.Token); }
catch { /* 서버에서도 해제할 수 있다(ERP > Project > PC 알림) */ }
ClearConnection();
}
private void ClearConnection()
{
_timer.Stop();
_cfg.Token = "";
_cfg.LastSeen = -1;
_cfg.UserName = "";
_cfg.Save();
_pending.Clear();
_opened.Clear();
_popup?.HidePopup();
Sync();
}
private void Balloon(string title, string text) => _tray.ShowBalloonTip(6000, title, text, ToolTipIcon.Info);
private void Sync()
{
bool on = _cfg.Connected;
string who = _cfg.UserName.Length > 0 ? _cfg.UserName : "연결됨";
_miStatus.Text = on ? "DBX 알림 — " + who : "DBX 알림 — 연결 안 됨";
if (_problem.Length > 0) _miStatus.Text += " (" + _problem + ")";
_miCheck.Enabled = _miOpen.Enabled = on;
_miSound.Checked = _cfg.Sound;
_miAuto.Checked = AutoStart.Enabled;
_miConnect.Text = on ? "연결 해제" : "연결…";
string tip = !on ? "DBX 알림 — 연결 안 됨"
: _pending.Count > 0 ? "DBX 알림 — 새 알림 " + _pending.Count + "건"
: _problem.Length > 0 ? "DBX 알림 — " + _problem
: "DBX 알림 — 클릭하면 수신함";
_tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
}
protected override void ExitThreadCore()
{
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
_timer.Stop();
_timer.Dispose();
_tray.Visible = false;
_tray.Dispose();
_menu.Dispose();
_popup?.Dispose();
_connect?.Dispose();
_api.Dispose();
_icon.Dispose();
base.ExitThreadCore();
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

+30
View File
@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="DBX.Notifier" type="win32" />
<description>DBX 알림</description>
<!-- 관리자 권한을 요구하지 않는다(현재 사용자 권한으로만 실행). -->
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /><!-- Windows 10 / 11 -->
</application>
</compatibility>
<!-- 화면 배율(125%·150%·200%)에서 글자가 흐리지 않게 — 시스템 DPI 기준으로 직접 그린다. -->
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
</assembly>
+27
View File
@@ -0,0 +1,27 @@
# DBX 알림 빌드 — dist\DBXNotifier.exe 하나를 만든다(.NET SDK 필요, 실행 PC 에는 .NET Framework 4.8 만 있으면 됨).
# powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1
# 코드 서명(선택, 백신·SmartScreen 경고를 줄이는 가장 확실한 방법):
# $env:DBX_SIGN_PFX = 'C:\cert\dbx-codesign.pfx'; $env:DBX_SIGN_PASSWORD = '...' (비밀번호는 저장소에 남기지 않는다)
$ErrorActionPreference = 'Stop'
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Push-Location $here
try {
dotnet build -c Release
if ($LASTEXITCODE -ne 0) { throw "빌드 실패" }
New-Item -ItemType Directory -Force (Join-Path $here 'dist') | Out-Null
$exe = Join-Path $here 'dist\DBXNotifier.exe'
Copy-Item (Join-Path $here 'bin\Release\net48\DBXNotifier.exe') $exe -Force
if ($env:DBX_SIGN_PFX) {
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending | Select-Object -First 1
if (-not $signtool) { throw "signtool.exe 를 찾을 수 없습니다(Windows SDK 설치 필요)." }
& $signtool.FullName sign /fd SHA256 /f $env:DBX_SIGN_PFX /p $env:DBX_SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $exe
if ($LASTEXITCODE -ne 0) { throw "서명 실패" }
}
$f = Get-Item $exe
"{0} {1:N0} KB SHA256 {2}" -f $f.FullName, ($f.Length / 1KB), (Get-FileHash $exe -Algorithm SHA256).Hash
}
finally {
Pop-Location
}
+68
View File
@@ -0,0 +1,68 @@
"""app.ico 생성 — 보라(#7b68ee) 둥근 사각형 위 흰 종(울리는 표시). 크기별로 따로 그려 작은 트레이 크기도 또렷하게.
사용: python desktop/notifier/tools/make_icon.py (Pillow 필요) → desktop/notifier/app.ico
"""
from pathlib import Path
from PIL import Image, ImageDraw
SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256]
SS = 8 # 슈퍼샘플링 배율
def bezier(p0, p1, p2, p3, n=24):
out = []
for i in range(n + 1):
t = i / n
a = (1 - t) ** 3
b = 3 * (1 - t) ** 2 * t
c = 3 * (1 - t) * t ** 2
d = t ** 3
out.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))
return out
def draw(size: int) -> Image.Image:
big = size * SS
k = big / 24.0 # 24 단위 격자
img = Image.new("RGBA", (big, big), (0, 0, 0, 0))
g = ImageDraw.Draw(img)
g.rounded_rectangle([0, 0, big - 1, big - 1], radius=int(5.5 * k), fill=(123, 104, 238, 255))
white = (255, 255, 255, 255)
small = size <= 20 # 아주 작은 크기는 종을 크게, 울림 표시는 생략
def P(x, y):
# 종 중심을 (12, 12.5) 기준으로 확대
s = 1.12 if small else 0.92
return ((12 + (x - 12) * s) * k, (12.6 + (y - 12) * s) * k)
body = [P(5, 17), P(6.6, 15.2), P(6.6, 10.6)]
body += [P(*q) for q in bezier((6.6, 10.6), (6.6, 7.2), (9.0, 4.9), (12, 4.9))[1:]]
body += [P(*q) for q in bezier((12, 4.9), (15.0, 4.9), (17.4, 7.2), (17.4, 10.6))[1:]]
body += [P(17.4, 15.2), P(19, 17)]
g.polygon(body, fill=white)
cx, cy = P(12, 18.6)
r = 1.9 * k * (1.12 if small else 0.92)
g.ellipse([cx - r, cy - r, cx + r, cy + r], fill=white)
kx, ky = P(12, 4.4)
r2 = 1.1 * k * (1.12 if small else 0.92)
g.ellipse([kx - r2, ky - r2, kx + r2, ky + r2], fill=white)
if not small:
w = max(1, int(1.5 * k))
c = P(12, 10.6)
rr = 9.6 * 0.92 * k
box = [c[0] - rr, c[1] - rr, c[0] + rr, c[1] + rr]
g.arc(box, 198, 238, fill=white, width=w)
g.arc(box, 302, 342, fill=white, width=w)
return img.resize((size, size), Image.LANCZOS)
def main() -> None:
out = Path(__file__).resolve().parents[1] / "app.ico"
imgs = [draw(s) for s in SIZES]
imgs[-1].save(out, format="ICO", sizes=[(s, s) for s in SIZES], append_images=imgs[:-1])
print(out)
if __name__ == "__main__":
main()
+18
View File
@@ -125,6 +125,24 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다. 설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
## PC 알림 프로그램 마이그레이션 (023)
023은 `notifier_links`·`notifier_tokens` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 `/project/notifier` 화면은
"마이그레이션 필요" 안내만, PC 알림 API 는 503.
```bash
cd /opt/www/main
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_023_$(date +%Y%m%d%H%M).sql
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_023_notifier.sql
```
내려받기 파일(선택): 개발 PC 에서 `desktop/notifier/build.ps1` 로 만든 `dist/DBXNotifier.exe` 를 서버로 옮긴 뒤 컨테이너 데이터 볼륨에 둔다.
없으면 화면에 "관리자에게 받으세요"만 나온다(공유 드라이브로 나눠 줘도 된다).
```bash
cd /opt/www/main && docker compose exec web mkdir -p /data/notifier && docker compose cp ~/DBXNotifier.exe web:/data/notifier/DBXNotifier.exe
```
## 주간 회의록 회의 완료 마이그레이션 (022) ## 주간 회의록 회의 완료 마이그레이션 (022)
022는 `goal_meetings` 에 `completed_at`·`completed_by` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 [회의 완료] 버튼이 나오지 않고 022는 `goal_meetings` 에 `completed_at`·`completed_by` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 [회의 완료] 버튼이 나오지 않고
+23
View File
@@ -1041,6 +1041,29 @@ SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id
교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다. 교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다.
권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다). 권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다).
## 6-11. PC 알림 프로그램 (마이그레이션 023, 2026-10-08)
웹 큰 팝업(`initTaskAlerts`)은 브라우저 탭이 보일 때만 뜬다. 브라우저가 뒤에 있어도 같은 알림을 PC 화면 위에 크게 띄우는
Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms, exe 하나). 빌드·배포·백신 주의는
`desktop/notifier/README.md`.
- **연결(토큰)**: 브라우저 쿠키를 쓸 수 없어 PC마다 토큰. ① 프로그램 `POST /project/api/notifier/link/start {device}`(로그인
없음 → 화면 코드 `XXXX-XXXX` + poll 비밀값, 10분, 대기 200건 상한 429) → ② 브라우저 `/project/notifier?code=`(로그인 필요,
없으면 `/login?next=`)에서 PC 이름·코드 확인 후 [연결] = `POST .../link/approve {code}` → ③ 프로그램 `POST .../link/poll {poll}`
→ `pending`/`expired`/`ok`(토큰 **한 번만**). `notifier_links`·`notifier_tokens` 에는 poll·토큰 **SHA-256 만** 저장.
PC 쪽 토큰은 Windows DPAPI(현재 사용자)로 암호화해 `%APPDATA%\DBXNotifier\settings.json`.
- **알림**: `GET /project/api/notifier/alerts?after=` (`Authorization: Bearer`) — 웹 `/api/notifications/alerts` 와 같은
`_alerts_payload`(태그·배정, 읽지 않은 것, 지금 볼 수 있는 작업만) + `name`. 토큰마다 **지금** 사용자 레코드·`project` 권한을
다시 확인(해제·권한 회수 = 401 → 프로그램이 연결 끊김 안내). `POST .../alerts/{id}/read`, `POST .../logout`(토큰 해제).
- **프로그램 동작**: 20초마다 확인(절전 해제 시 바로). 처음 연결하면 최신 번호를 기준으로(옛 알림 몰아 띄우지 않음),
새 번호가 오면 마우스가 있는 화면 아래 가운데에 웹과 같은 모양의 큰 창(맨 위, 포커스 안 뺏음, 보라↔주황 깜박임, 최대 6줄 +
"외 N건 더") + 알림 소리. [열기] = 기본 브라우저로 작업 + 읽음, [닫기] = 그 번호까지 본 것으로(PC 설정 `last_seen`).
웹에서 읽은 알림은 다음 확인 때 창에서 빠진다. 웹 팝업의 "본 것"(localStorage)과는 따로다.
- **화면** `/project/notifier`(사이드바 "PC 알림"): 연결 승인 카드, 설치 안내, 내 연결된 PC 목록·[연결 해제]
(`POST /project/api/notifier/devices/{id}/revoke`). 내려받기 `GET /project/notifier/download` = 서버
`DATA_DIR/notifier/DBXNotifier.exe`(컨테이너 `/data/notifier/`) — 파일이 없으면 버튼 대신 "관리자에게 받으세요".
- 023 미적용이면 화면은 안내만, notifier API 는 503.
## 7. 추후 단계 ## 7. 추후 단계
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩, 작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
+44
View File
@@ -0,0 +1,44 @@
-- =====================================================================
-- project_db 마이그레이션 023 — PC 알림 프로그램(DBX 알림) 연결
-- =====================================================================
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
--
-- 왜(2026-10-08 사용자 요청): 웹브라우저가 뒤에 있어도 태그·작업 배정 알림을 PC 화면 위에 크게 띄우는
-- 트레이 프로그램(desktop/notifier). 브라우저 세션(쿠키)을 쓸 수 없으므로 PC마다 연결 토큰을 발급한다.
-- ① 프로그램이 연결 요청(notifier_links: 화면 코드 + 확인용 poll 비밀값) → ② 사용자가 브라우저(로그인 상태)에서
-- 코드를 확인하고 [연결] → ③ 프로그램이 poll 로 토큰을 한 번 받는다(notifier_tokens). 토큰·poll 값은 원문을
-- 저장하지 않고 SHA-256 해시만 저장한다. 연결 해제 = revoked_at.
-- =====================================================================
BEGIN;
CREATE TABLE IF NOT EXISTS notifier_links (
id BIGSERIAL PRIMARY KEY,
code TEXT NOT NULL UNIQUE, -- 화면에 보이는 짧은 코드(예: K7QM-4XPA)
poll_hash TEXT NOT NULL UNIQUE, -- 프로그램만 아는 poll 비밀값의 SHA-256
device_name TEXT NOT NULL DEFAULT '',
email TEXT NULL, -- [연결]을 누른 사용자(승인 전 NULL)
approved_at TIMESTAMPTZ NULL,
consumed_at TIMESTAMPTZ NULL, -- 토큰을 내준 시각(한 번만)
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_notifier_links_expires ON notifier_links (expires_at);
COMMENT ON TABLE notifier_links IS 'PC 알림 프로그램 연결 요청 — 10분 유효, 승인 후 토큰 1회 발급';
CREATE TABLE IF NOT EXISTS notifier_tokens (
id BIGSERIAL PRIMARY KEY,
email TEXT NOT NULL,
token_hash TEXT NOT NULL UNIQUE, -- 토큰 원문의 SHA-256
device_name TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_seen_at TIMESTAMPTZ NULL,
revoked_at TIMESTAMPTZ NULL
);
CREATE INDEX IF NOT EXISTS idx_notifier_tokens_email ON notifier_tokens (email);
COMMENT ON TABLE notifier_tokens IS 'PC 알림 프로그램 토큰 — 사용자·PC 단위, revoked_at 이면 해제';
GRANT SELECT, INSERT, UPDATE, DELETE ON notifier_links, notifier_tokens TO project_app;
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
COMMIT;
SELECT 'project_db 023 notifier ready' AS status;
+128
View File
@@ -0,0 +1,128 @@
"""PC 알림 프로그램 API(023) — 토큰 인증·연결 요청/승인/발급·마이그레이션 미적용 503. DB 없이 가짜 저장소로."""
import importlib
import unittest
from unittest.mock import patch
from fastapi import FastAPI
from fastapi.testclient import TestClient
from psycopg.errors import UndefinedTable
api = importlib.import_module("app.modules.project.router")
ROWS = [
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
]
class FakeStore:
def __init__(self):
self.links = {} # poll → {"code", "email"}
self.tokens = {"good-token": "me@test.local"}
self.read = []
def list_notifications(self, recipient_email, unread_only=False, limit=100):
return ROWS[:limit]
def mark_read(self, notification_id, recipient_email):
self.read.append((notification_id, recipient_email))
def notifier_token_email(self, token):
return self.tokens.get(token)
def notifier_start_link(self, device_name):
self.links["poll-1"] = {"code": "ABCD-EFGH", "email": None, "device": device_name, "used": False}
return {"code": "ABCD-EFGH", "poll": "poll-1", "expires_in": 600}
def notifier_approve_link(self, code, email):
for link in self.links.values():
if link["code"] == code.upper() and link["email"] is None:
link["email"] = email
return True
return False
def notifier_poll_link(self, poll):
link = self.links.get(poll)
if not link or link["used"]:
return {"status": "expired"}
if not link["email"]:
return {"status": "pending"}
link["used"] = True
self.tokens["new-token"] = link["email"]
return {"status": "ok", "token": "new-token", "email": link["email"]}
def notifier_revoke_token(self, token):
self.tokens.pop(token, None)
USER = {"email": "me@test.local", "name": "나"}
class NotifierApiTests(unittest.TestCase):
def setUp(self):
app = FastAPI()
app.include_router(api.router)
self.client = TestClient(app)
self.st = FakeStore()
self.patches = [
patch.object(api, "_db_or_503", return_value=self.st),
patch.object(api, "_visible_notifications", side_effect=lambda st, user, items: items),
patch.object(api, "_user_by_email", side_effect=lambda e: dict(USER) if e == USER["email"] else None),
patch("app.store.has_module", return_value=True),
]
for p in self.patches:
p.start()
def tearDown(self):
for p in self.patches:
p.stop()
def alerts(self, token, qs="?after=0"):
return self.client.get("/project/api/notifier/alerts" + qs, headers={"Authorization": "Bearer " + token})
def test_alerts_with_token_returns_same_payload_as_web_plus_name(self):
res = self.alerts("good-token")
self.assertEqual(res.status_code, 200)
out = res.json()
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
self.assertEqual((out["me"], out["latest_id"], out["name"]), ("me@test.local", 8, "나"))
def test_alerts_rejects_missing_or_unknown_token(self):
self.assertEqual(self.client.get("/project/api/notifier/alerts").status_code, 401)
self.assertEqual(self.alerts("bad").status_code, 401)
def test_alerts_rejects_user_without_project_module(self):
with patch("app.store.has_module", return_value=False):
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_read_marks_only_for_token_owner(self):
res = self.client.post("/project/api/notifier/alerts/8/read", headers={"Authorization": "Bearer good-token"})
self.assertEqual(res.status_code, 200)
self.assertEqual(self.st.read, [(8, "me@test.local")])
def test_link_flow_pending_then_token_once(self):
start = self.client.post("/project/api/notifier/link/start", json={"device": "KING-PC"}).json()
self.assertEqual(start["approve_path"], "/project/notifier?code=ABCD-EFGH")
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "pending")
with patch.object(api, "_require_user", return_value=dict(USER)):
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "abcd-efgh"}).status_code, 200)
self.assertEqual(self.client.post("/project/api/notifier/link/approve", json={"code": "ABCD-EFGH"}).status_code, 404)
got = self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()
self.assertEqual((got["status"], got["token"]), ("ok", "new-token"))
self.assertEqual(self.client.post("/project/api/notifier/link/poll", json={"poll": start["poll"]}).json()["status"], "expired")
self.assertEqual(self.alerts("new-token").status_code, 200)
def test_logout_revokes_token(self):
self.client.post("/project/api/notifier/logout", headers={"Authorization": "Bearer good-token"})
self.assertEqual(self.alerts("good-token").status_code, 401)
def test_missing_migration_is_503(self):
def boom(**_):
raise UndefinedTable("notifier_links")
self.st.notifier_start_link = boom
res = self.client.post("/project/api/notifier/link/start", json={"device": "X"})
self.assertEqual(res.status_code, 503)
if __name__ == "__main__":
unittest.main()