using System.Net.Http; using System.Text; using System.Text.Json; using System.Windows; using AutoShutdown.Models; namespace AutoShutdown.Services; internal sealed class NotificationService { private static readonly HttpClient HttpClient = new(); private NotificationSettings _settings; public NotificationService(NotificationSettings settings) { _settings = settings; } public void UpdateSettings(NotificationSettings settings) { _settings = settings; } public async Task NotifyAsync(Window owner, string title, string body, MessageBoxImage image = MessageBoxImage.Information) { if (_settings.Mode == NotificationMode.OmniNotify) { await TrySendToOmniNotifyAsync(title, body); return; } System.Windows.MessageBox.Show(owner, body, title, MessageBoxButton.OK, image); } public Task NotifyAsync(string title, string body) { return _settings.Mode == NotificationMode.OmniNotify ? TrySendToOmniNotifyAsync(title, body) : Task.CompletedTask; } public async Task TestOmniNotifyAsync(NotificationSettings settings) { var oldSettings = _settings; try { _settings = settings; await SendToOmniNotifyAsync("AutoShutdown 测试消息", "OmniNotify 适配已连接。"); return true; } catch { return false; } finally { _settings = oldSettings; } } private async Task SendToOmniNotifyAsync(string title, string body) { if (!Uri.TryCreate(_settings.OmniNotifyEndpoint, UriKind.Absolute, out var endpoint)) { return; } var payload = JsonSerializer.Serialize(new { channel = string.IsNullOrWhiteSpace(_settings.Channel) ? "default" : _settings.Channel.Trim(), title, body }); using var content = new StringContent(payload, Encoding.UTF8, "application/json"); using var response = await HttpClient.PostAsync(endpoint, content); response.EnsureSuccessStatusCode(); } private async Task TrySendToOmniNotifyAsync(string title, string body) { try { await SendToOmniNotifyAsync(title, body); } catch { // OmniNotify 适配模式下不再弹窗打扰用户,发送失败只静默跳过。 } } }