From dcccc67d3e22651c871a0585b220ade70620a388 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 31 Oct 2026 16:10:32 +0300 Subject: [PATCH] feat(web): add WhatsApp Web-style background push notifications, onboarding banner, and deep-linking --- src/GsDChat.Server/Services/WebPushService.cs | 1 + src/GsDChat.Server/wwwroot/app.css | 66 ++++++++++ src/GsDChat.Server/wwwroot/app.js | 124 +++++++++++++++--- src/GsDChat.Server/wwwroot/icon.svg | 8 ++ src/GsDChat.Server/wwwroot/index.html | 15 +++ src/GsDChat.Server/wwwroot/manifest.json | 13 +- src/GsDChat.Server/wwwroot/sw.js | 32 +++-- tests/GsDChat.Tests/WebClientStaticTests.cs | 23 ++++ 8 files changed, 248 insertions(+), 34 deletions(-) create mode 100644 src/GsDChat.Server/wwwroot/icon.svg diff --git a/src/GsDChat.Server/Services/WebPushService.cs b/src/GsDChat.Server/Services/WebPushService.cs index 8731e2c..c7d00a3 100644 --- a/src/GsDChat.Server/Services/WebPushService.cs +++ b/src/GsDChat.Server/Services/WebPushService.cs @@ -182,6 +182,7 @@ public class WebPushService : IDisposable 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"); diff --git a/src/GsDChat.Server/wwwroot/app.css b/src/GsDChat.Server/wwwroot/app.css index 8f0bfb6..dc87854 100644 --- a/src/GsDChat.Server/wwwroot/app.css +++ b/src/GsDChat.Server/wwwroot/app.css @@ -228,6 +228,72 @@ html, body { text-transform: uppercase; } +/* ========================================================================== + WhatsApp Web Style Desktop Notification Banner + ========================================================================== */ + +.notif-banner { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 8px 16px; + background-color: var(--ctp-mantle); + border-bottom: 1px solid var(--ctp-mauve); + color: var(--ctp-text); + font-family: var(--font-mono); + font-size: 0.84rem; + flex-shrink: 0; +} + +.notif-banner-icon { + font-size: 1.2rem; + color: var(--ctp-mauve); + line-height: 1; +} + +.notif-banner-body { + display: flex; + flex-direction: column; + flex: 1; + min-width: 0; + gap: 2px; +} + +.notif-banner-title { + font-weight: 700; + color: var(--ctp-mauve); + font-size: 0.86rem; +} + +.notif-banner-desc { + font-size: 0.76rem; + color: var(--ctp-subtext0); +} + +.notif-banner-actions { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; +} + +.notif-banner-dismiss { + background: transparent; + border: 1px solid transparent; + color: var(--ctp-overlay0); + font-family: var(--font-mono); + font-size: 1rem; + cursor: pointer; + padding: 2px 6px; + transition: color 0.1s, border-color 0.1s; +} + +.notif-banner-dismiss:hover { + color: var(--ctp-red); + border-color: var(--ctp-red); +} + /* ========================================================================== Main Content Views ========================================================================== */ diff --git a/src/GsDChat.Server/wwwroot/app.js b/src/GsDChat.Server/wwwroot/app.js index ddabb4c..24bdbef 100644 --- a/src/GsDChat.Server/wwwroot/app.js +++ b/src/GsDChat.Server/wwwroot/app.js @@ -50,6 +50,10 @@ tabViews: document.querySelectorAll('.tab-view'), currentUsername: document.getElementById('currentUsername'), currentUserRole: document.getElementById('currentUserRole'), + headerPushBtn: document.getElementById('headerPushBtn'), + desktopNotifBanner: document.getElementById('desktopNotifBanner'), + bannerEnablePushBtn: document.getElementById('bannerEnablePushBtn'), + bannerDismissBtn: document.getElementById('bannerDismissBtn'), e2eeVaultBtn: document.getElementById('e2eeVaultBtn'), logoutBtn: document.getElementById('logoutBtn'), userBadge: document.getElementById('userBadge'), @@ -644,7 +648,10 @@ } async function initServiceWorkerAndPush() { - if (!('serviceWorker' in navigator)) return; + if (!('serviceWorker' in navigator)) { + updateDesktopNotifBanner(); + return; + } try { const reg = await navigator.serviceWorker.register('/sw.js'); state.swRegistration = reg; @@ -667,13 +674,64 @@ if (reg.pushManager) { const existingSub = await reg.pushManager.getSubscription(); state.pushSubscribed = !!existingSub; - updateInboxPreferencesUI(); if (existingSub && state.token) { await syncSubscriptionToServer(existingSub); + } else if (!existingSub && 'Notification' in window && Notification.permission === 'granted' && state.token) { + // If browser has already granted permission, auto-subscribe seamlessly like WhatsApp Web + await subscribeWebPush(false); } } } catch (err) { console.warn('Service Worker registration skipped or failed:', err); + } finally { + updateDesktopNotifBanner(); + updateInboxPreferencesUI(); + } + } + + function updateDesktopNotifBanner() { + initElements(); + const hasPushApi = ('Notification' in window) && ('serviceWorker' in navigator); + + if (el.headerPushBtn) { + if (!hasPushApi) { + el.headerPushBtn.style.display = 'none'; + } else { + el.headerPushBtn.style.display = ''; + if (Notification.permission === 'granted') { + if (state.pushSubscribed) { + el.headerPushBtn.textContent = '[🔔 Push: ON]'; + el.headerPushBtn.className = 'btn btn-sm btn-primary'; + el.headerPushBtn.title = 'Background Web Push is active (click to disable)'; + } else { + el.headerPushBtn.textContent = '[🔔 Enable Push]'; + el.headerPushBtn.className = 'btn btn-sm btn-outline-primary'; + el.headerPushBtn.title = 'Click to activate background Web Push'; + } + } else if (Notification.permission === 'denied') { + el.headerPushBtn.textContent = '[🔕 Push: Blocked]'; + el.headerPushBtn.className = 'btn btn-sm btn-secondary'; + el.headerPushBtn.title = 'Notifications are blocked in browser site permissions'; + } else { + el.headerPushBtn.textContent = '[🔔 Enable Push]'; + el.headerPushBtn.className = 'btn btn-sm btn-outline-primary'; + el.headerPushBtn.title = 'Enable background Web Push notifications'; + } + } + } + + if (!el.desktopNotifBanner) return; + + if (!hasPushApi || !state.token || Notification.permission === 'granted' || Notification.permission === 'denied') { + el.desktopNotifBanner.style.display = 'none'; + return; + } + + const dismissed = localStorage.getItem('gsdchat_dismiss_push_banner') === 'true'; + if (dismissed) { + el.desktopNotifBanner.style.display = 'none'; + } else { + el.desktopNotifBanner.style.display = 'flex'; } } @@ -733,16 +791,17 @@ if (state.pushSubscribed) { await unsubscribeWebPush(); } else { - await subscribeWebPush(); + await subscribeWebPush(true); } } - async function subscribeWebPush() { + async function subscribeWebPush(interactive = true) { try { if ('Notification' in window) { const perm = await Notification.requestPermission(); if (perm !== 'granted') { - showToast('Notification permission denied by browser.'); + if (interactive) showToast('Notification permission denied by browser.'); + updateDesktopNotifBanner(); return; } } @@ -754,33 +813,40 @@ const vapidKey = await fetchVapidPublicKey(); if (!vapidKey) { - showToast('Server VAPID public key is unavailable.'); + if (interactive) showToast('Server VAPID public key is unavailable.'); return; } - const sub = await state.swRegistration.pushManager.subscribe({ - userVisibleOnly: true, - applicationServerKey: urlBase64ToUint8Array(vapidKey) - }); + let sub = await state.swRegistration.pushManager.getSubscription(); + if (!sub) { + sub = await state.swRegistration.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: urlBase64ToUint8Array(vapidKey) + }); + } const ok = await syncSubscriptionToServer(sub); if (ok) { state.pushSubscribed = true; state.inboxPreferences.pushNotificationsEnabled = true; - sendEnvelope('UPDATE_INBOX_PREFERENCES', { - mentionsEnabled: state.inboxPreferences.mentionsEnabled, - announcementsEnabled: state.inboxPreferences.announcementsEnabled, - directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, - followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, - pushNotificationsEnabled: true - }); + if (state.socket && state.socket.readyState === WebSocket.OPEN) { + sendEnvelope('UPDATE_INBOX_PREFERENCES', { + mentionsEnabled: state.inboxPreferences.mentionsEnabled, + announcementsEnabled: state.inboxPreferences.announcementsEnabled, + directMessagesEnabled: state.inboxPreferences.directMessagesEnabled, + followedChannelsEnabled: state.inboxPreferences.followedChannelsEnabled, + pushNotificationsEnabled: true + }); + } updateInboxPreferencesUI(); + updateDesktopNotifBanner(); showToast('🔔 Background Web Push notifications enabled on this browser!'); } else { - showToast('Failed to register Web Push subscription with server.'); + if (interactive) showToast('Failed to register Web Push subscription with server.'); } } catch (err) { - showToast(`Web Push setup failed: ${err.message || err}`); + if (interactive) showToast(`Web Push setup failed: ${err.message || err}`); + updateDesktopNotifBanner(); } } @@ -807,6 +873,7 @@ } state.pushSubscribed = false; updateInboxPreferencesUI(); + updateDesktopNotifBanner(); showToast('🔕 Web Push notifications disabled on this browser.'); } catch (err) { showToast(`Unsubscribe error: ${err.message || err}`); @@ -1004,6 +1071,8 @@ updateSettingsBadges(); hideAuthModal(); connectWebSocket(); + initServiceWorkerAndPush(); + updateDesktopNotifBanner(); } catch (err) { el.authError.textContent = 'Connection error. Please try again.'; } finally { @@ -1146,7 +1215,8 @@ sendInboxAction('mark_read', deepInboxItem); } if (deepChannel && getConversationById(deepChannel)) { - state.activeChannelId = deepChannel; + joinChannel(deepChannel); + switchTab('chat'); window.history.replaceState({}, document.title, window.location.pathname); } } catch { @@ -1426,6 +1496,7 @@ el.toggleWebPushBtn.textContent = activePush ? '[🔔 Web Push: ON]' : '[🔕 Enable Web Push]'; el.toggleWebPushBtn.className = activePush ? 'btn btn-sm btn-primary' : 'btn btn-sm btn-secondary'; } + updateDesktopNotifBanner(); } function renderInbox() { @@ -2609,6 +2680,7 @@ if (state.socket) state.socket.close(); hideE2eeModal(); updateUserUI(); + updateDesktopNotifBanner(); showAuthModal(); } @@ -2690,6 +2762,18 @@ if (el.toggleWebPushBtn) { el.toggleWebPushBtn.addEventListener('click', toggleWebPushSubscription); } + if (el.headerPushBtn) { + el.headerPushBtn.addEventListener('click', toggleWebPushSubscription); + } + if (el.bannerEnablePushBtn) { + el.bannerEnablePushBtn.addEventListener('click', () => subscribeWebPush(false)); + } + if (el.bannerDismissBtn) { + el.bannerDismissBtn.addEventListener('click', () => { + localStorage.setItem('gsdchat_dismiss_push_banner', 'true'); + if (el.desktopNotifBanner) el.desktopNotifBanner.style.display = 'none'; + }); + } if (el.testWebPushBtn) { el.testWebPushBtn.addEventListener('click', sendTestWebPush); } diff --git a/src/GsDChat.Server/wwwroot/icon.svg b/src/GsDChat.Server/wwwroot/icon.svg new file mode 100644 index 0000000..e6606e7 --- /dev/null +++ b/src/GsDChat.Server/wwwroot/icon.svg @@ -0,0 +1,8 @@ + + GsDChat + + + + + + diff --git a/src/GsDChat.Server/wwwroot/index.html b/src/GsDChat.Server/wwwroot/index.html index d9c7aa3..aee774d 100644 --- a/src/GsDChat.Server/wwwroot/index.html +++ b/src/GsDChat.Server/wwwroot/index.html @@ -6,6 +6,7 @@ GsDChat - Web Client + @@ -58,11 +59,25 @@ + + + +
diff --git a/src/GsDChat.Server/wwwroot/manifest.json b/src/GsDChat.Server/wwwroot/manifest.json index 8f2fb3b..4bebc65 100644 --- a/src/GsDChat.Server/wwwroot/manifest.json +++ b/src/GsDChat.Server/wwwroot/manifest.json @@ -4,7 +4,14 @@ "description": "High-performance terminal-inspired hybrid chat with End-to-End Encryption, Inbox, and Web Push Notifications.", "start_url": "/", "display": "standalone", - "background_color": "#0d1117", - "theme_color": "#00d4ff", - "icons": [] + "background_color": "#11111b", + "theme_color": "#cba6f7", + "icons": [ + { + "src": "/icon.svg", + "sizes": "192x192 512x512", + "type": "image/svg+xml", + "purpose": "any maskable" + } + ] } diff --git a/src/GsDChat.Server/wwwroot/sw.js b/src/GsDChat.Server/wwwroot/sw.js index decab58..90859dd 100644 --- a/src/GsDChat.Server/wwwroot/sw.js +++ b/src/GsDChat.Server/wwwroot/sw.js @@ -1,5 +1,6 @@ // ============================================================================ // GsDChat Service Worker (Web Push Notifications & Background Deep-Linking) +// Functions like WhatsApp Web: delivers notifications even when app is closed. // ============================================================================ self.addEventListener('install', (event) => { @@ -43,15 +44,15 @@ self.addEventListener('push', (event) => { // Check if any open client window is currently focused in the foreground let focusedClient = null; for (const client of windowClients) { - if (client.focused || client.visibilityState === 'visible') { + if (client.focused) { focusedClient = client; break; } } - if (focusedClient && focusedClient.focused) { - // Suppress duplicate OS popup if the user is actively focused on the app; - // notify the foreground window so it can play an indicator if desired. + if (focusedClient) { + // Suppress duplicate OS popup if user is actively focused on the chat window; + // notify the foreground window so it can update badges/chime if desired. focusedClient.postMessage({ type: 'PUSH_RECEIVED_FOREGROUND', payload: payload @@ -63,12 +64,20 @@ self.addEventListener('push', (event) => { ? `gsdchat-${payload.category || 'notif'}-${payload.channelId}` : `gsdchat-item-${payload.itemId || Date.now()}`; - await self.registration.showNotification(payload.title || 'GsDChat', { - body: payload.body || 'New activity in GsDChat', + const notificationOptions = { + body: payload.body || 'New message in GsDChat', + icon: '/icon.svg', + badge: '/icon.svg', tag: tag, renotify: true, - data: payload - }); + vibrate: [200, 100, 200], + data: payload, + actions: [ + { action: 'open', title: 'Open Chat' } + ] + }; + + await self.registration.showNotification(payload.title || 'GsDChat', notificationOptions); })()); }); @@ -76,6 +85,10 @@ self.addEventListener('notificationclick', (event) => { event.notification.close(); const data = event.notification.data || {}; + const targetUrl = data.channelId + ? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}` + : '/'; + event.waitUntil((async () => { const windowClients = await self.clients.matchAll({ type: 'window', @@ -95,9 +108,6 @@ self.addEventListener('notificationclick', (event) => { } if (self.clients.openWindow) { - const targetUrl = data.channelId - ? `/?channel=${encodeURIComponent(data.channelId)}&inboxItem=${encodeURIComponent(data.itemId || '')}` - : '/'; await self.clients.openWindow(targetUrl); } })()); diff --git a/tests/GsDChat.Tests/WebClientStaticTests.cs b/tests/GsDChat.Tests/WebClientStaticTests.cs index 4f9d65f..0be95e7 100644 --- a/tests/GsDChat.Tests/WebClientStaticTests.cs +++ b/tests/GsDChat.Tests/WebClientStaticTests.cs @@ -109,6 +109,10 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("id=\"navTabInbox\"", html); Assert.Contains("id=\"inboxUnreadBadge\"", html); Assert.Contains("id=\"toggleWebPushBtn\"", html); + Assert.Contains("id=\"desktopNotifBanner\"", html); + Assert.Contains("id=\"bannerEnablePushBtn\"", html); + Assert.Contains("id=\"headerPushBtn\"", html); + Assert.Contains("rel=\"icon\"", html); } [Fact] @@ -125,6 +129,7 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains(".conv-security-badge", css); Assert.Contains(".inbox-item", css); Assert.Contains(".inbox-badge", css); + Assert.Contains(".notif-banner", css); } [Fact] @@ -146,6 +151,8 @@ public class WebClientStaticTests : IAsyncLifetime Assert.Contains("INBOX_SYNC", js); Assert.Contains("INBOX_NEW_ITEM", js); Assert.Contains("subscribeWebPush", js); + Assert.Contains("updateDesktopNotifBanner", js); + Assert.Contains("initServiceWorkerAndPush", js); } [Fact] @@ -158,10 +165,26 @@ public class WebClientStaticTests : IAsyncLifetime string swJs = await swRes.Content.ReadAsStringAsync(); Assert.Contains("showNotification", swJs); Assert.Contains("notificationclick", swJs); + Assert.Contains("/icon.svg", swJs); + Assert.Contains("renotify: true", swJs); var manifestRes = await _httpClient.GetAsync("/manifest.json"); Assert.True(manifestRes.IsSuccessStatusCode); string manifestJson = await manifestRes.Content.ReadAsStringAsync(); Assert.Contains("GsDChat", manifestJson); + Assert.Contains("icons", manifestJson); + Assert.Contains("/icon.svg", manifestJson); + } + + [Fact] + public async Task GetIconSvg_ShouldServeValidSvg() + { + Assert.NotNull(_httpClient); + + var iconRes = await _httpClient.GetAsync("/icon.svg"); + Assert.True(iconRes.IsSuccessStatusCode); + string svg = await iconRes.Content.ReadAsStringAsync(); + Assert.Contains("