From ceab1c9fdfb78e981d2ce576b49da8fe64e89ddf Mon Sep 17 00:00:00 2001 From: Rafael dos Santos Silva Date: Mon, 8 Feb 2021 12:09:52 -0300 Subject: [PATCH] FEATURE: Handle user agent push subscription change events (#11994) A user browser may rotate a user subscription endpoint/keys anytime. Currently, Discourse will receive a 4XX response while trying to deliver a push notification and silently unsubscribe the device. With this change, we will gracefully handle desativating the old subscription and the replacement creation with the need for the user to resubscribe manually every time it breaks. https://meta.discourse.org/t/-/125179?u=falco --- app/assets/javascripts/service-worker.js.erb | 30 +++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/app/assets/javascripts/service-worker.js.erb b/app/assets/javascripts/service-worker.js.erb index 9efd286b7c..e5f53f34b4 100644 --- a/app/assets/javascripts/service-worker.js.erb +++ b/app/assets/javascripts/service-worker.js.erb @@ -186,7 +186,35 @@ self.addEventListener('notificationclick', function(event) { self.addEventListener('message', function(event) { if('lastAction' in event.data){ lastAction = event.data.lastAction; - }}); + } +}); + +self.addEventListener('pushsubscriptionchange', function(event) { + event.waitUntil( + Promise.all( + fetch('<%= Discourse.base_url %>/push_notifications/subscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, + body: new URLSearchParams({ + "subscription[endpoint]": event.newSubscription.endpoint, + "subscription[keys][auth]": event.newSubscription.toJSON().keys.auth, + "subscription[keys][p256dh]": event.newSubscription.toJSON().keys.p256dh, + "send_confirmation": false + }) + }), + fetch('<%= Discourse.base_url %>/push_notifications/unsubscribe', { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, + body: new URLSearchParams({ + "subscription[endpoint]": event.oldSubscription.endpoint, + "subscription[keys][auth]": event.oldSubscription.toJSON().keys.auth, + "subscription[keys][p256dh]": event.oldSubscription.toJSON().keys.p256dh + }) + }) + ) + ); +}); + <% DiscoursePluginRegistry.service_workers.each do |js| %> <%=raw "#{File.read(js)}" %> <% end %>