diff --git a/App.xaml.cs b/App.xaml.cs
index 81c3a96..2bf7de7 100644
--- a/App.xaml.cs
+++ b/App.xaml.cs
@@ -16,6 +16,7 @@ public partial class App : Application
private Services.GotifyApiService? _apiService;
private Services.GotifyWebSocketService? _webSocketService;
private Services.NotificationService? _notificationService;
+ private Services.ApplicationCache? _appCache;
private Tray.TrayIconService? _trayService;
private MainWindow? _mainWindow;
@@ -37,6 +38,7 @@ public partial class App : Application
_stateService = new Services.StateService(_logger);
_apiService = new Services.GotifyApiService(config, _logger);
_notificationService = new Services.NotificationService(config, _logger);
+ _appCache = new Services.ApplicationCache(_apiService, _logger);
try
{
@@ -74,13 +76,17 @@ public partial class App : Application
_logger,
_trayService,
_webSocketService,
- _apiService);
+ _apiService,
+ _appCache);
if (config.Startup.Enabled)
{
Utils.StartupManager.EnableCurrentUserStartup(_logger);
}
+ // 后台异步拉一次应用列表,不阻塞启动
+ _ = _appCache.RefreshAsync();
+
await _webSocketService.StartAsync();
}
diff --git a/Converters/ValueConverters.cs b/Converters/ValueConverters.cs
new file mode 100644
index 0000000..93f2aa8
--- /dev/null
+++ b/Converters/ValueConverters.cs
@@ -0,0 +1,78 @@
+using System.Globalization;
+using System.Windows;
+using System.Windows.Data;
+using System.Windows.Media;
+
+// 双开 WPF + WinForms 时,Color 在两个命名空间都有,固定走 WPF 的。
+using Color = System.Windows.Media.Color;
+
+namespace WindowsGotify;
+
+public sealed class PriorityToBrushConverter : IValueConverter
+{
+ public object Convert(object value, Type targetType, object? parameter, CultureInfo culture)
+ {
+ if (parameter is string p && p == "hideIfEmpty" && value is string s)
+ {
+ return string.IsNullOrWhiteSpace(s) || s == "(无标题)" ? Visibility.Collapsed : Visibility.Visible;
+ }
+
+ if (value is int p1)
+ {
+ return p1 switch
+ {
+ >= 8 => new SolidColorBrush(Color.FromRgb(0xD1, 0x34, 0x38)), // 紧急 - 红
+ >= 5 => new SolidColorBrush(Color.FromRgb(0xCA, 0x50, 0x10)), // 重要 - 橙
+ >= 1 => new SolidColorBrush(Color.FromRgb(0x4A, 0x55, 0x68)), // 一般 - 灰蓝
+ _ => new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88)) // 静默 - 浅灰
+ };
+ }
+ return new SolidColorBrush(Colors.Gray);
+ }
+
+ public object ConvertBack(object value, Type targetType, object? parameter, CultureInfo culture)
+ => throw new NotSupportedException();
+}
+
+///
+/// 应用名 → 稳定颜色(用名字的 hash 决定 hue),让每个应用在历史里视觉上可区分。
+///
+public sealed class AppNameToBrushConverter : IValueConverter
+{
+ public object Convert(object value, Type targetType, object? parameter, CultureInfo culture)
+ {
+ var name = value as string ?? "";
+ if (string.IsNullOrWhiteSpace(name)) return new SolidColorBrush(Color.FromRgb(0x55, 0x55, 0x55));
+
+ // 简单 FNV-1a 32-bit hash → hue 0..360
+ uint hash = 2166136261u;
+ foreach (var c in name)
+ {
+ hash ^= c;
+ hash *= 16777619u;
+ }
+ var hue = hash % 360;
+ return new SolidColorBrush(HsvToColor(hue, 0.55, 0.75));
+ }
+
+ private static Color HsvToColor(double hue, double sat, double val)
+ {
+ var c = val * sat;
+ var x = c * (1 - Math.Abs((hue / 60) % 2 - 1));
+ var m = val - c;
+ double r, g, b;
+ if (hue < 60) { r = c; g = x; b = 0; }
+ else if (hue < 120) { r = x; g = c; b = 0; }
+ else if (hue < 180) { r = 0; g = c; b = x; }
+ else if (hue < 240) { r = 0; g = x; b = c; }
+ else if (hue < 300) { r = x; g = 0; b = c; }
+ else { r = c; g = 0; b = x; }
+ return Color.FromRgb(
+ (byte)Math.Round((r + m) * 255),
+ (byte)Math.Round((g + m) * 255),
+ (byte)Math.Round((b + m) * 255));
+ }
+
+ public object ConvertBack(object value, Type targetType, object? parameter, CultureInfo culture)
+ => throw new NotSupportedException();
+}
diff --git a/MainWindow.xaml b/MainWindow.xaml
index 79bbe31..fcbb6d6 100644
--- a/MainWindow.xaml
+++ b/MainWindow.xaml
@@ -1,14 +1,92 @@
+ Width="1100"
+ Height="720"
+ MinWidth="900"
+ MinHeight="560"
+ WindowStartupLocation="CenterScreen"
+ Background="#FAFAFA">
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -17,109 +95,244 @@
-
-
+
+
-
+ FontSize="24"
+ FontWeight="Bold"
+ Foreground="#222" />
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ Padding="12"
+ Margin="0,0,0,8">
+
+
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/MainWindow.xaml.cs b/MainWindow.xaml.cs
index 5e75b7e..7308ad6 100644
--- a/MainWindow.xaml.cs
+++ b/MainWindow.xaml.cs
@@ -2,12 +2,17 @@ using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
using WindowsGotify.Models;
using WindowsGotify.Services;
using WindowsGotify.Tray;
-// 双开 WPF + WinForms 时,MessageBox 在两个命名空间都有,用别名强制走 WPF 的。
+// 双开 WPF + WinForms 时,这几个类型两个命名空间都有,固定走 WPF 的。
using MessageBox = System.Windows.MessageBox;
+using Color = System.Windows.Media.Color;
+using Brush = System.Windows.Media.Brush;
+using Brushes = System.Windows.Media.Brushes;
namespace WindowsGotify;
@@ -21,6 +26,7 @@ public partial class MainWindow : Window
private TrayIconService? _tray;
private GotifyWebSocketService? _webSocket;
private GotifyApiService? _apiService;
+ private ApplicationCache? _appCache;
private readonly ObservableCollection _history = new();
@@ -42,7 +48,8 @@ public partial class MainWindow : Window
Logger logger,
TrayIconService tray,
GotifyWebSocketService webSocket,
- GotifyApiService apiService)
+ GotifyApiService apiService,
+ ApplicationCache appCache)
{
_config = config;
_configService = configService;
@@ -50,14 +57,29 @@ public partial class MainWindow : Window
_tray = tray;
_webSocket = webSocket;
_apiService = apiService;
+ _appCache = appCache;
UrlTextBox.Text = config.Gotify.Url;
TokenBox.Password = config.Gotify.ClientToken;
- StatusText.Text = "状态:等待连接";
+ UpdateAppCount();
+ SetStatus("等待连接", StatusKind.Pending);
UpdateHistoryCount();
// 实时消息追加到历史
_webSocket.MessageReceived += OnLiveMessage;
+
+ // 应用缓存更新时,刷新已加载消息的 AppName
+ if (_appCache != null)
+ {
+ _appCache.Updated += (_, _) => Dispatcher.Invoke(() =>
+ {
+ UpdateAppCount();
+ // 已存在的消息重新解析 AppName(缓存里可能新增了之前缺失的应用)
+ foreach (var m in _history) m.AppName = _appCache.GetName(m.AppId);
+ // 详情面板如果当前选中的,刷新
+ if (HistoryList.SelectedItem is GotifyMessage sel) RenderDetail(sel);
+ });
+ }
}
public void ShowFromTray()
@@ -65,13 +87,14 @@ public partial class MainWindow : Window
Show();
WindowState = WindowState.Normal;
Activate();
- // 每次打开都拉一次最新历史,确保和远端同步
+ // 每次打开都拉一次最新历史和应用,确保和远端同步
_ = LoadHistoryAsync();
+ _ = RefreshAppsAsync(silent: true);
}
private void OnLiveMessage(GotifyMessage msg)
{
- // WebSocket 回调可能在非 UI 线程,切回 UI 线程
+ Enrich(msg);
Dispatcher.Invoke(() =>
{
_history.Insert(0, msg);
@@ -80,6 +103,18 @@ public partial class MainWindow : Window
});
}
+ ///
+ /// 拿到一条消息后,补 AppName(从缓存查),返回原对象。
+ ///
+ private GotifyMessage Enrich(GotifyMessage msg)
+ {
+ if (_appCache != null && string.IsNullOrEmpty(msg.AppName))
+ {
+ msg.AppName = _appCache.GetName(msg.AppId);
+ }
+ return msg;
+ }
+
private void TrimHistory()
{
while (_history.Count > MaxHistoryInUi)
@@ -90,7 +125,27 @@ public partial class MainWindow : Window
private void UpdateHistoryCount()
{
- HistoryCountText.Text = $"共 {_history.Count} 条(本地缓存上限 {MaxHistoryInUi})";
+ HistoryCountText.Text = $"共 {_history.Count} 条";
+ }
+
+ private void UpdateAppCount()
+ {
+ if (_appCache == null) { AppCountText.Text = " · 应用:?"; return; }
+ var n = _appCache.Count;
+ AppCountText.Text = n == 0 ? " · 应用:0(未拉取)" : $" · 应用:{n}";
+ }
+
+ private enum StatusKind { Pending, Connected, Error, Info }
+ private void SetStatus(string text, StatusKind kind)
+ {
+ StatusText.Text = $"状态:{text}";
+ StatusDot.Fill = kind switch
+ {
+ StatusKind.Connected => new SolidColorBrush(Color.FromRgb(0x10, 0x81, 0x16)),
+ StatusKind.Error => new SolidColorBrush(Color.FromRgb(0xD1, 0x34, 0x38)),
+ StatusKind.Pending => new SolidColorBrush(Color.FromRgb(0xCA, 0x50, 0x10)),
+ _ => new SolidColorBrush(Color.FromRgb(0x88, 0x88, 0x88))
+ };
}
private async Task LoadHistoryAsync()
@@ -98,58 +153,122 @@ public partial class MainWindow : Window
if (_apiService is null || _config is null) return;
if (string.IsNullOrWhiteSpace(_config.Gotify.ClientToken))
{
- StatusText.Text = "状态:未配置 Client Token,无法拉取历史";
+ SetStatus("未配置 Client Token,无法拉取历史", StatusKind.Error);
return;
}
try
{
- StatusText.Text = "状态:正在拉取历史...";
+ SetStatus("正在拉取历史...", StatusKind.Pending);
var limit = Math.Clamp(_config.History.ViewerLimit, 1, 100);
var messages = await _apiService.GetRecentMessagesAsync(limit, CancellationToken.None);
+ foreach (var m in messages) Enrich(m);
- // 用清空 + 批量 Insert 让 UI 一次性刷新,避免多次 CollectionChanged
_history.Clear();
- foreach (var m in messages)
- {
- _history.Add(m);
- }
+ foreach (var m in messages) _history.Add(m);
UpdateHistoryCount();
- StatusText.Text = $"状态:已加载 {messages.Count} 条历史消息";
+ SetStatus($"已加载 {messages.Count} 条历史消息", StatusKind.Connected);
_logger?.Info($"History loaded. count={messages.Count}");
}
catch (Exception ex)
{
_logger?.Error("Load history failed.", ex);
- StatusText.Text = $"状态:拉取历史失败 - {ex.Message}";
+ SetStatus($"拉取历史失败 - {ex.Message}", StatusKind.Error);
}
}
+ private async Task RefreshAppsAsync(bool silent = false)
+ {
+ if (_appCache is null) return;
+ if (_config is null || string.IsNullOrWhiteSpace(_config.Gotify.ClientToken))
+ {
+ if (!silent) SetStatus("未配置 Client Token,无法拉取应用", StatusKind.Error);
+ return;
+ }
+ try
+ {
+ if (!silent) SetStatus("正在拉取应用列表...", StatusKind.Pending);
+ await _appCache.RefreshAsync();
+ UpdateAppCount();
+ if (!silent) SetStatus($"已加载 {_appCache.Count} 个应用", StatusKind.Connected);
+ }
+ catch (Exception ex)
+ {
+ _logger?.Error("Refresh applications failed.", ex);
+ if (!silent) SetStatus($"拉取应用失败 - {ex.Message}", StatusKind.Error);
+ }
+ }
+
+ private async void RefreshAppsButton_Click(object sender, RoutedEventArgs e)
+ {
+ await RefreshAppsAsync();
+ }
+
private async void RefreshButton_Click(object sender, RoutedEventArgs e)
{
await LoadHistoryAsync();
}
- private void HistoryList_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
+ private void HistoryList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
- if (HistoryList.SelectedItem is not GotifyMessage msg) return;
- var url = msg.ClickUrl;
- if (string.IsNullOrWhiteSpace(url)) return;
-
- try
+ if (HistoryList.SelectedItem is GotifyMessage msg)
{
- Process.Start(new ProcessStartInfo
- {
- FileName = url,
- UseShellExecute = true
- });
- _logger?.Info($"Opened click url. id={msg.Id}, url={url}");
+ RenderDetail(msg);
}
- catch (Exception ex)
+ else
{
- _logger?.Error("Failed to open click url.", ex);
- MessageBox.Show($"无法打开链接:{ex.Message}", "Windows Gotify",
- MessageBoxButton.OK, MessageBoxImage.Warning);
+ DetailPanel.Visibility = Visibility.Collapsed;
+ DetailEmptyHint.Visibility = Visibility.Visible;
+ }
+ }
+
+ private void RenderDetail(GotifyMessage msg)
+ {
+ DetailEmptyHint.Visibility = Visibility.Collapsed;
+ DetailPanel.Visibility = Visibility.Visible;
+
+ DetailAppName.Text = string.IsNullOrWhiteSpace(msg.AppName) ? msg.TitleDisplay : msg.AppName;
+ DetailAppName.Foreground = (Brush)(new AppNameToBrushConverter().Convert(msg.AppName, typeof(Brush), null, System.Globalization.CultureInfo.CurrentCulture) ?? Brushes.Black);
+
+ var app = _appCache?.Get(msg.AppId);
+ DetailAppDesc.Text = app?.Description ?? "(无应用描述)";
+ DetailAppDesc.Visibility = string.IsNullOrWhiteSpace(app?.Description) ? Visibility.Collapsed : Visibility.Visible;
+
+ DetailPriority.Text = $"{msg.PriorityDisplay} ({(msg.Priority >= 8 ? "紧急-告警音" : msg.Priority >= 5 ? "重要" : "一般")})";
+ DetailDate.Text = msg.Date.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
+ DetailTitle.Text = msg.TitleDisplay;
+ DetailAppId.Text = msg.AppId.ToString();
+ DetailMessage.Text = msg.Message ?? "";
+
+ var url = msg.ClickUrl;
+ if (!string.IsNullOrWhiteSpace(url))
+ {
+ DetailUrl.Text = url;
+ DetailUrl.Tag = url;
+ DetailUrlLabel.Visibility = Visibility.Visible;
+ DetailUrl.Visibility = Visibility.Visible;
+ }
+ else
+ {
+ DetailUrlLabel.Visibility = Visibility.Collapsed;
+ DetailUrl.Visibility = Visibility.Collapsed;
+ }
+ }
+
+ private void DetailUrl_Click(object sender, MouseButtonEventArgs e)
+ {
+ if (DetailUrl.Tag is string url && !string.IsNullOrWhiteSpace(url))
+ {
+ try
+ {
+ Process.Start(new ProcessStartInfo { FileName = url, UseShellExecute = true });
+ }
+ catch (Exception ex)
+ {
+ _logger?.Error("Failed to open click url.", ex);
+ MessageBox.Show($"无法打开链接:{ex.Message}", "Windows Gotify",
+ MessageBoxButton.OK, MessageBoxImage.Warning);
+ }
}
}
@@ -180,6 +299,9 @@ public partial class MainWindow : Window
await _configService.SaveAsync(_config);
_webSocket?.RequestReconnect();
+ // URL/Token 变了,重新拉应用和历史
+ _ = RefreshAppsAsync(silent: true);
+ await LoadHistoryAsync();
MessageBox.Show("配置已保存,正在重新连接。", "Windows Gotify",
MessageBoxButton.OK, MessageBoxImage.Information);
diff --git a/Models/GotifyApplication.cs b/Models/GotifyApplication.cs
new file mode 100644
index 0000000..a551d83
--- /dev/null
+++ b/Models/GotifyApplication.cs
@@ -0,0 +1,24 @@
+using System.Text.Json.Serialization;
+
+namespace WindowsGotify.Models;
+
+public sealed class GotifyApplication
+{
+ [JsonPropertyName("id")]
+ public long Id { get; set; }
+
+ [JsonPropertyName("name")]
+ public string Name { get; set; } = "";
+
+ [JsonPropertyName("description")]
+ public string? Description { get; set; }
+
+ [JsonPropertyName("defaultPriority")]
+ public int DefaultPriority { get; set; }
+
+ [JsonPropertyName("createdAt")]
+ public DateTimeOffset? CreatedAt { get; set; }
+
+ [JsonPropertyName("internal")]
+ public bool Internal { get; set; }
+}
diff --git a/Models/GotifyMessage.cs b/Models/GotifyMessage.cs
index 8b0ef9b..8f81ca3 100644
--- a/Models/GotifyMessage.cs
+++ b/Models/GotifyMessage.cs
@@ -26,9 +26,15 @@ public sealed class GotifyMessage
[JsonPropertyName("extras")]
public Dictionary? Extras { get; set; }
+ ///
+ /// 由 UI 在加入历史列表前,从 ApplicationCache 解析填入;不会从 JSON 反序列化。
+ ///
+ [JsonIgnore]
+ public string AppName { get; set; } = "";
+
[JsonIgnore]
public string TitleDisplay =>
- string.IsNullOrWhiteSpace(Title) ? $"(App {AppId})" : Title!;
+ string.IsNullOrWhiteSpace(Title) ? "(无标题)" : Title!;
[JsonIgnore]
public string DateDisplay =>
diff --git a/Services/ApplicationCache.cs b/Services/ApplicationCache.cs
new file mode 100644
index 0000000..519565b
--- /dev/null
+++ b/Services/ApplicationCache.cs
@@ -0,0 +1,59 @@
+using System.Collections.Concurrent;
+using WindowsGotify.Models;
+
+namespace WindowsGotify.Services;
+
+///
+/// 缓存 Gotify Applications 列表(从 GET /application 拉取),供 UI 用来把消息的 AppId 解析为可读应用名。
+///
+public sealed class ApplicationCache
+{
+ private readonly ConcurrentDictionary _apps = new();
+ private readonly GotifyApiService _api;
+ private readonly Logger _logger;
+ private DateTimeOffset _lastFetchedAt = DateTimeOffset.MinValue;
+
+ public ApplicationCache(GotifyApiService api, Logger logger)
+ {
+ _api = api;
+ _logger = logger;
+ }
+
+ public int Count => _apps.Count;
+
+ public event EventHandler? Updated;
+
+ ///
+ /// 拉一次最新的应用列表。失败抛异常,调用方决定怎么处理(忽略 / 重试 / 提示)。
+ ///
+ public async Task RefreshAsync(CancellationToken ct = default)
+ {
+ var list = await _api.GetApplicationsAsync(ct);
+ _apps.Clear();
+ foreach (var app in list)
+ {
+ _apps[app.Id] = app;
+ }
+ _lastFetchedAt = DateTimeOffset.UtcNow;
+ _logger.Info($"ApplicationCache refreshed. count={list.Count}");
+ Updated?.Invoke(this, EventArgs.Empty);
+ }
+
+ ///
+ /// 把 appId 解析为应用名。缓存里没有就回退 "App {id}"。
+ ///
+ public string GetName(long appId)
+ {
+ return _apps.TryGetValue(appId, out var app) && !string.IsNullOrWhiteSpace(app.Name)
+ ? app.Name
+ : $"App {appId}";
+ }
+
+ public GotifyApplication? Get(long appId)
+ {
+ _apps.TryGetValue(appId, out var app);
+ return app;
+ }
+
+ public DateTimeOffset LastFetchedAt => _lastFetchedAt;
+}
diff --git a/Services/GotifyApiService.cs b/Services/GotifyApiService.cs
index cf33c96..5df9a3b 100644
--- a/Services/GotifyApiService.cs
+++ b/Services/GotifyApiService.cs
@@ -90,4 +90,19 @@ public sealed class GotifyApiService
// Gotify 的 since=0 行为:返回数据库里所有消息中的 limit 条;按 id 降序再取一次保证正确
return list.OrderByDescending(m => m.Id).Take(Math.Clamp(limit, 1, 100)).ToList();
}
+
+ ///
+ /// 拉取所有 Gotify Application,供 UI 用来把消息 AppId 解析为应用名。
+ ///
+ public async Task> GetApplicationsAsync(CancellationToken ct)
+ {
+ SyncAuthHeaders();
+ var path = "application?limit=999";
+ using var response = await _httpClient.GetAsync(BuildUri(path), ct);
+ response.EnsureSuccessStatusCode();
+
+ await using var stream = await response.Content.ReadAsStreamAsync(ct);
+ var list = await JsonSerializer.DeserializeAsync>(stream, cancellationToken: ct);
+ return list ?? new List();
+ }
}