From 73fbe89a4b4e545796e9cc6aae707de0a4eed3a1 Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Wed, 25 Oct 2023 18:58:33 +0300 Subject: initial work on showing notifications through serviceworkers --- .../desktop_notification_utils.js | 7 +- src/services/push/push.js | 111 ------------------ src/services/sw/sw.js | 124 +++++++++++++++++++++ 3 files changed, 127 insertions(+), 115 deletions(-) delete mode 100644 src/services/push/push.js create mode 100644 src/services/sw/sw.js (limited to 'src/services') diff --git a/src/services/desktop_notification_utils/desktop_notification_utils.js b/src/services/desktop_notification_utils/desktop_notification_utils.js index b84a1f75..c31a1030 100644 --- a/src/services/desktop_notification_utils/desktop_notification_utils.js +++ b/src/services/desktop_notification_utils/desktop_notification_utils.js @@ -1,9 +1,8 @@ +import { showDesktopNotification as swDesktopNotification } from '../sw/sw.js' + export const showDesktopNotification = (rootState, desktopNotificationOpts) => { if (!('Notification' in window && window.Notification.permission === 'granted')) return if (rootState.statuses.notifications.desktopNotificationSilence) { return } - const desktopNotification = new window.Notification(desktopNotificationOpts.title, desktopNotificationOpts) - // Chrome is known for not closing notifications automatically - // according to MDN, anyway. - setTimeout(desktopNotification.close.bind(desktopNotification), 5000) + swDesktopNotification(desktopNotificationOpts) } diff --git a/src/services/push/push.js b/src/services/push/push.js deleted file mode 100644 index 1787ac36..00000000 --- a/src/services/push/push.js +++ /dev/null @@ -1,111 +0,0 @@ -import runtime from 'serviceworker-webpack5-plugin/lib/runtime' - -function urlBase64ToUint8Array (base64String) { - const padding = '='.repeat((4 - base64String.length % 4) % 4) - const base64 = (base64String + padding) - .replace(/-/g, '+') - .replace(/_/g, '/') - - const rawData = window.atob(base64) - return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0))) -} - -function isPushSupported () { - return 'serviceWorker' in navigator && 'PushManager' in window -} - -function getOrCreateServiceWorker () { - return runtime.register() - .catch((err) => console.error('Unable to get or create a service worker.', err)) -} - -function subscribePush (registration, isEnabled, vapidPublicKey) { - if (!isEnabled) return Promise.reject(new Error('Web Push is disabled in config')) - if (!vapidPublicKey) return Promise.reject(new Error('VAPID public key is not found')) - - const subscribeOptions = { - userVisibleOnly: true, - applicationServerKey: urlBase64ToUint8Array(vapidPublicKey) - } - return registration.pushManager.subscribe(subscribeOptions) -} - -function unsubscribePush (registration) { - return registration.pushManager.getSubscription() - .then((subscribtion) => { - if (subscribtion === null) { return } - return subscribtion.unsubscribe() - }) -} - -function deleteSubscriptionFromBackEnd (token) { - return window.fetch('/api/v1/push/subscription/', { - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - } - }).then((response) => { - if (!response.ok) throw new Error('Bad status code from server.') - return response - }) -} - -function sendSubscriptionToBackEnd (subscription, token, notificationVisibility) { - return window.fetch('/api/v1/push/subscription/', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}` - }, - body: JSON.stringify({ - subscription, - data: { - alerts: { - follow: notificationVisibility.follows, - favourite: notificationVisibility.likes, - mention: notificationVisibility.mentions, - reblog: notificationVisibility.repeats, - move: notificationVisibility.moves - } - } - }) - }).then((response) => { - if (!response.ok) throw new Error('Bad status code from server.') - return response.json() - }).then((responseData) => { - if (!responseData.id) throw new Error('Bad response from server.') - return responseData - }) -} - -export function registerPushNotifications (isEnabled, vapidPublicKey, token, notificationVisibility) { - if (isPushSupported()) { - getOrCreateServiceWorker() - .then((registration) => subscribePush(registration, isEnabled, vapidPublicKey)) - .then((subscription) => sendSubscriptionToBackEnd(subscription, token, notificationVisibility)) - .catch((e) => console.warn(`Failed to setup Web Push Notifications: ${e.message}`)) - } -} - -export function unregisterPushNotifications (token) { - if (isPushSupported()) { - Promise.all([ - deleteSubscriptionFromBackEnd(token), - getOrCreateServiceWorker() - .then((registration) => { - return unsubscribePush(registration).then((result) => [registration, result]) - }) - .then(([registration, unsubResult]) => { - if (!unsubResult) { - console.warn('Push subscription cancellation wasn\'t successful, killing SW anyway...') - } - return registration.unregister().then((result) => { - if (!result) { - console.warn('Failed to kill SW') - } - }) - }) - ]).catch((e) => console.warn(`Failed to disable Web Push Notifications: ${e.message}`)) - } -} diff --git a/src/services/sw/sw.js b/src/services/sw/sw.js new file mode 100644 index 00000000..b13c9a1b --- /dev/null +++ b/src/services/sw/sw.js @@ -0,0 +1,124 @@ +import runtime from 'serviceworker-webpack5-plugin/lib/runtime' + +function urlBase64ToUint8Array (base64String) { + const padding = '='.repeat((4 - base64String.length % 4) % 4) + const base64 = (base64String + padding) + .replace(/-/g, '+') + .replace(/_/g, '/') + + const rawData = window.atob(base64) + return Uint8Array.from([...rawData].map((char) => char.charCodeAt(0))) +} + +function isSWSupported () { + return 'serviceWorker' in navigator +} + +function isPushSupported () { + return 'PushManager' in window +} + +function getOrCreateServiceWorker () { + return runtime.register() + .catch((err) => console.error('Unable to get or create a service worker.', err)) +} + +function subscribePush (registration, isEnabled, vapidPublicKey) { + if (!isEnabled) return Promise.reject(new Error('Web Push is disabled in config')) + if (!vapidPublicKey) return Promise.reject(new Error('VAPID public key is not found')) + + const subscribeOptions = { + userVisibleOnly: true, + applicationServerKey: urlBase64ToUint8Array(vapidPublicKey) + } + return registration.pushManager.subscribe(subscribeOptions) +} + +function unsubscribePush (registration) { + return registration.pushManager.getSubscription() + .then((subscribtion) => { + if (subscribtion === null) { return } + return subscribtion.unsubscribe() + }) +} + +function deleteSubscriptionFromBackEnd (token) { + return fetch('/api/v1/push/subscription/', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + } + }).then((response) => { + if (!response.ok) throw new Error('Bad status code from server.') + return response + }) +} + +function sendSubscriptionToBackEnd (subscription, token, notificationVisibility) { + return window.fetch('/api/v1/push/subscription/', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}` + }, + body: JSON.stringify({ + subscription, + data: { + alerts: { + follow: notificationVisibility.follows, + favourite: notificationVisibility.likes, + mention: notificationVisibility.mentions, + reblog: notificationVisibility.repeats, + move: notificationVisibility.moves + } + } + }) + }).then((response) => { + if (!response.ok) throw new Error('Bad status code from server.') + return response.json() + }).then((responseData) => { + if (!responseData.id) throw new Error('Bad response from server.') + return responseData + }) +} +export function initServiceWorker () { + if (!isSWSupported()) return + getOrCreateServiceWorker() +} + +export async function showDesktopNotification (content) { + const { active: sw } = await window.navigator.serviceWorker.getRegistration() + sw.postMessage({ type: 'desktopNotification', content }) +} + +export async function updateFocus () { + const { active: sw } = await window.navigator.serviceWorker.getRegistration() + sw.postMessage({ type: 'updateFocus' }) +} + +export function registerPushNotifications (isEnabled, vapidPublicKey, token, notificationVisibility) { + if (isPushSupported()) { + getOrCreateServiceWorker() + .then((registration) => subscribePush(registration, isEnabled, vapidPublicKey)) + .then((subscription) => sendSubscriptionToBackEnd(subscription, token, notificationVisibility)) + .catch((e) => console.warn(`Failed to setup Web Push Notifications: ${e.message}`)) + } +} + +export function unregisterPushNotifications (token) { + if (isPushSupported()) { + Promise.all([ + deleteSubscriptionFromBackEnd(token), + getOrCreateServiceWorker() + .then((registration) => { + return unsubscribePush(registration).then((result) => [registration, result]) + }) + .then(([registration, unsubResult]) => { + if (!unsubResult) { + console.warn('Push subscription cancellation wasn\'t successful') + } + }) + ]).catch((e) => console.warn(`Failed to disable Web Push Notifications: ${e.message}`)) + } +} -- cgit v1.2.3-70-g09d2