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:
@@ -0,0 +1,3 @@
|
||||
bin/
|
||||
obj/
|
||||
dist/
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 { });
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 을 허용 목록에 넣어도 된다.
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 |
@@ -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>
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user