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.

133 lines
5.1 KiB

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