logo

mastofe

My custom branche(s) on git.pleroma.social/pleroma/mastofe git clone https://hacktivis.me/git/mastofe.git

registerer.js (5605B)


  1. import api from '../../api';
  2. import { pushNotificationsSetting } from '../../settings';
  3. import { setBrowserSupport, setSubscription, clearSubscription } from './setter';
  4. import { me } from '../../initial_state';
  5. // Taken from https://www.npmjs.com/package/web-push
  6. const urlBase64ToUint8Array = (base64String) => {
  7. const padding = '='.repeat((4 - base64String.length % 4) % 4);
  8. const base64 = (base64String + padding)
  9. .replace(/\-/g, '+')
  10. .replace(/_/g, '/');
  11. const rawData = window.atob(base64);
  12. const outputArray = new Uint8Array(rawData.length);
  13. for (let i = 0; i < rawData.length; ++i) {
  14. outputArray[i] = rawData.charCodeAt(i);
  15. }
  16. return outputArray;
  17. };
  18. const getApplicationServerKey = () => {
  19. const k = document.querySelector('[name="applicationServerKey"]');
  20. return k === null ? '' : k.getAttribute('content');
  21. }
  22. const getRegistration = () => navigator.serviceWorker.ready;
  23. const getPushSubscription = (registration) =>
  24. registration.pushManager.getSubscription()
  25. .then(subscription => ({ registration, subscription }));
  26. const subscribe = (registration) =>
  27. registration.pushManager.subscribe({
  28. userVisibleOnly: true,
  29. applicationServerKey: urlBase64ToUint8Array(getApplicationServerKey()),
  30. });
  31. const unsubscribe = ({ registration, subscription }) =>
  32. subscription ? subscription.unsubscribe().then(() => registration) : registration;
  33. const sendSubscriptionToBackend = (getState, subscription) => {
  34. const params = { subscription };
  35. if (me) {
  36. const data = pushNotificationsSetting.get(me);
  37. if (data) {
  38. params.data = data;
  39. }
  40. }
  41. return api(getState).post('/api/web/push_subscriptions', params).then(response => response.data);
  42. };
  43. // Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload
  44. const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype);
  45. export function register () {
  46. return (dispatch, getState) => {
  47. dispatch(setBrowserSupport(supportsPushNotifications));
  48. if (me && !pushNotificationsSetting.get(me)) {
  49. const alerts = getState().getIn(['push_notifications', 'alerts']);
  50. if (alerts) {
  51. pushNotificationsSetting.set(me, { alerts: alerts });
  52. }
  53. }
  54. if (supportsPushNotifications) {
  55. if (!getApplicationServerKey()) {
  56. console.error('The VAPID public key is not set. You will not be able to receive Web Push Notifications.');
  57. return;
  58. }
  59. getRegistration()
  60. .then(getPushSubscription)
  61. .then(({ registration, subscription }) => {
  62. if (subscription !== null) {
  63. // We have a subscription, check if it is still valid
  64. const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString();
  65. const subscriptionServerKey = urlBase64ToUint8Array(getApplicationServerKey()).toString();
  66. const serverEndpoint = getState().getIn(['push_notifications', 'subscription', 'endpoint']);
  67. // If the VAPID public key did not change and the endpoint corresponds
  68. // to the endpoint saved in the backend, the subscription is valid
  69. if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) {
  70. return subscription;
  71. } else {
  72. // Something went wrong, try to subscribe again
  73. return unsubscribe({ registration, subscription }).then(subscribe).then(
  74. subscription => sendSubscriptionToBackend(getState, subscription));
  75. }
  76. }
  77. // No subscription, try to subscribe
  78. return subscribe(registration).then(
  79. subscription => sendSubscriptionToBackend(getState, subscription));
  80. })
  81. .then(subscription => {
  82. // If we got a PushSubscription (and not a subscription object from the backend)
  83. // it means that the backend subscription is valid (and was set during hydration)
  84. if (!(subscription instanceof PushSubscription)) {
  85. dispatch(setSubscription(subscription));
  86. if (me) {
  87. pushNotificationsSetting.set(me, { alerts: subscription.alerts });
  88. }
  89. }
  90. })
  91. .catch(error => {
  92. if (error.code === 20 && error.name === 'AbortError') {
  93. console.warn('Your browser supports Web Push Notifications, but does not seem to implement the VAPID protocol.');
  94. } else if (error.code === 5 && error.name === 'InvalidCharacterError') {
  95. console.error('The VAPID public key seems to be invalid:', getApplicationServerKey());
  96. }
  97. // Clear alerts and hide UI settings
  98. dispatch(clearSubscription());
  99. if (me) {
  100. pushNotificationsSetting.remove(me);
  101. }
  102. return getRegistration()
  103. .then(getPushSubscription)
  104. .then(unsubscribe);
  105. })
  106. .catch(console.warn);
  107. } else {
  108. console.warn('Your browser does not support Web Push Notifications.');
  109. }
  110. };
  111. }
  112. export function saveSettings() {
  113. return (_, getState) => {
  114. const state = getState().get('push_notifications');
  115. const subscription = state.get('subscription');
  116. const alerts = state.get('alerts');
  117. const data = { alerts };
  118. api(getState).put(`/api/web/push_subscriptions/${subscription.get('id')}`, {
  119. data,
  120. }).then(() => {
  121. if (me) {
  122. pushNotificationsSetting.set(me, data);
  123. }
  124. }).catch(console.warn);
  125. };
  126. }