using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using GsDChat.Core.Models; using GsDChat.Core.Security; using GsDChat.Server.Configuration; using GsDChat.Server.Data; namespace GsDChat.Server.Services; public class WebPushNotificationPayload { public string Title { get; set; } = string.Empty; public string Body { get; set; } = string.Empty; public string ChannelId { get; set; } = string.Empty; public string ChannelName { get; set; } = string.Empty; public string Category { get; set; } = string.Empty; public string ItemId { get; set; } = string.Empty; public string SenderUsername { get; set; } = string.Empty; public string Timestamp { get; set; } = string.Empty; } public class WebPushService : IDisposable { private static readonly JsonSerializerOptions s_jsonOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; private readonly ChatDatabase _db; private readonly ServerOptions _options; private readonly ILogger _logger; private readonly HttpClient _httpClient; public WebPushService( ChatDatabase db, ServerOptions options, ILogger logger, HttpMessageHandler? customHandler = null) { _db = db; _options = options; _logger = logger; if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey)) { var (pub, priv) = WebPushCrypto.GenerateVapidKeys(); _options.VapidPublicKey = pub; _options.VapidPrivateKey = priv; } _httpClient = customHandler != null ? new HttpClient(customHandler) { Timeout = TimeSpan.FromSeconds(10) } : new HttpClient { Timeout = TimeSpan.FromSeconds(10) }; } public string VapidPublicKey => _options.VapidPublicKey ?? string.Empty; public static WebPushNotificationPayload BuildNotificationPayload(InboxItem item, string serverName) { string sender = string.IsNullOrWhiteSpace(item.SenderUsername) ? "System" : item.SenderUsername; string chName = string.IsNullOrWhiteSpace(item.ChannelName) ? "chat" : item.ChannelName; string title = item.Category switch { InboxCategories.Mention => $"@{sender} mentioned you in {(item.ChannelType == ChannelTypes.Channel ? "#" + chName : chName)}", InboxCategories.Announcement => $"📢 Announcement from @{sender}", InboxCategories.DirectMessage => $"Direct Message from @{sender}", InboxCategories.GroupMessage => $"@{sender} in [Group] {chName}", InboxCategories.GroupInvite => $"Group Chat Invitation: {chName}", _ => $"@{sender} in #{chName}" }; bool isEncrypted = item.IsEncrypted || E2eeCrypto.IsEncryptedPayload(item.ContentPreview); string body; if (isEncrypted) { body = $"🔒 New encrypted message from @{sender}"; } else { string raw = item.ContentPreview ?? string.Empty; body = raw.Length > 180 ? raw[..177] + "..." : raw; } return new WebPushNotificationPayload { Title = title, Body = body, ChannelId = item.ChannelId, ChannelName = chName, Category = item.Category, ItemId = item.Id, SenderUsername = sender, Timestamp = item.CreatedAt.ToString("O") }; } public async Task SendPushForInboxItemAsync(InboxItem item, InboxPreferences? prefs = null, CancellationToken ct = default) { try { var effectivePrefs = prefs ?? await _db.GetInboxPreferencesAsync(item.UserId); if (!effectivePrefs.PushNotificationsEnabled) { return; } var subscriptions = await _db.GetPushSubscriptionsForUserAsync(item.UserId); if (subscriptions.Count == 0) { return; } var payload = BuildNotificationPayload(item, _options.ServerName); byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions); var sendTasks = new List(subscriptions.Count); foreach (var sub in subscriptions) { sendTasks.Add(DeliverToSubscriptionAsync(sub, jsonBytes, ct)); } await Task.WhenAll(sendTasks); } catch (Exception ex) { SafeLogger.LogWarning(_logger, "Error sending Web Push notifications for user {UserId}: {Msg}", item.UserId, ex.Message); } } public async Task SendTestPushAsync(string userId, string username, CancellationToken ct = default) { var subscriptions = await _db.GetPushSubscriptionsForUserAsync(userId); if (subscriptions.Count == 0) { return false; } var payload = new WebPushNotificationPayload { Title = $"{_options.ServerName} Push Active", Body = $"Push notifications are configured for @{username}!", ChannelId = string.Empty, ChannelName = "inbox", Category = InboxCategories.Announcement, ItemId = Guid.NewGuid().ToString("N"), SenderUsername = "System", Timestamp = DateTime.UtcNow.ToString("O") }; byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(payload, s_jsonOptions); foreach (var sub in subscriptions) { await DeliverToSubscriptionAsync(sub, jsonBytes, ct); } return true; } private async Task DeliverToSubscriptionAsync(PushSubscriptionRecord sub, byte[] plaintextBytes, CancellationToken ct) { if (string.IsNullOrWhiteSpace(_options.VapidPublicKey) || string.IsNullOrWhiteSpace(_options.VapidPrivateKey)) { return; } try { byte[] encrypted = WebPushCrypto.EncryptPayload(plaintextBytes, sub.P256dh, sub.Auth); string vapidHeader = WebPushCrypto.CreateVapidAuthorizationHeader( sub.Endpoint, _options.VapidSubject, _options.VapidPublicKey, _options.VapidPrivateKey); using var request = new HttpRequestMessage(HttpMethod.Post, sub.Endpoint); request.Headers.TryAddWithoutValidation("Authorization", vapidHeader); request.Headers.TryAddWithoutValidation("Crypto-Key", $"p256ecdsa={_options.VapidPublicKey}"); request.Headers.TryAddWithoutValidation("TTL", "86400"); request.Headers.TryAddWithoutValidation("Urgency", "high"); var content = new ByteArrayContent(encrypted); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); content.Headers.ContentEncoding.Add("aes128gcm"); request.Content = content; using var response = await _httpClient.SendAsync(request, ct); if (response.StatusCode == HttpStatusCode.Gone || response.StatusCode == HttpStatusCode.NotFound) { await _db.RemovePushSubscriptionByEndpointAsync(sub.Endpoint); } } catch (Exception ex) { SafeLogger.LogDebug(_logger, "Web Push delivery failed for endpoint: {Msg}", ex.Message); } } public void Dispose() { _httpClient.Dispose(); } }