Files
dbx-main/desktop/notifier/Api.cs
T
king 06af036f86 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>
2026-10-08 10:21:58 +09:00

165 lines
7.2 KiB
C#

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 { });
}
}