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 { /// /// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창. /// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로, /// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다. /// 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 _pending = new List(); private readonly HashSet _opened = new HashSet(); 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(); } } /// 서버의 지금 목록으로 바꾼다 — 새 번호가 있으면 창을 띄우고 소리, 다른 곳에서 읽은 것은 빠진다. private void Apply(List fresh) { fresh = fresh.Where(a => !_opened.Contains(a.Id)).ToList(); var known = new HashSet(_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 { /* 다음에 웹에서 읽어도 된다 */ } } /// [닫기] — 지금 보이는 알림까지 본 것으로(다시 뜨지 않음). 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(); } } }