The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

146 lines
5.4 KiB

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