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.

149 lines
5.5 KiB

  1. import api from 'flavours/glitch/util/api';
  2. import { pushNotificationsSetting } from 'flavours/glitch/util/settings';
  3. import { setBrowserSupport, setSubscription, clearSubscription } from './setter';
  4. // Taken from https://www.npmjs.com/package/web-push
  5. const urlBase64ToUint8Array = (base64String) => {
  6. const padding = '='.repeat((4 - base64String.length % 4) % 4);
  7. const base64 = (base64String + padding)
  8. .replace(/\-/g, '+')
  9. .replace(/_/g, '/');
  10. const rawData = window.atob(base64);
  11. const outputArray = new Uint8Array(rawData.length);
  12. for (let i = 0; i < rawData.length; ++i) {
  13. outputArray[i] = rawData.charCodeAt(i);
  14. }
  15. return outputArray;
  16. };
  17. const getApplicationServerKey = () => document.querySelector('[name="applicationServerKey"]').getAttribute('content');
  18. const getRegistration = () => navigator.serviceWorker.ready;
  19. const getPushSubscription = (registration) =>
  20. registration.pushManager.getSubscription()
  21. .then(subscription => ({ registration, subscription }));
  22. const subscribe = (registration) =>
  23. registration.pushManager.subscribe({
  24. userVisibleOnly: true,
  25. applicationServerKey: urlBase64ToUint8Array(getApplicationServerKey()),
  26. });
  27. const unsubscribe = ({ registration, subscription }) =>
  28. subscription ? subscription.unsubscribe().then(() => registration) : registration;
  29. const sendSubscriptionToBackend = (getState, subscription, me) => {
  30. const params = { subscription };
  31. if (me) {
  32. const data = pushNotificationsSetting.get(me);
  33. if (data) {
  34. params.data = data;
  35. }
  36. }
  37. return api(getState).post('/api/web/push_subscriptions', params).then(response => response.data);
  38. };
  39. // Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload
  40. const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype);
  41. export function register () {
  42. return (dispatch, getState) => {
  43. dispatch(setBrowserSupport(supportsPushNotifications));
  44. const me = getState().getIn(['meta', 'me']);
  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, me));
  72. }
  73. }
  74. // No subscription, try to subscribe
  75. return subscribe(registration).then(
  76. subscription => sendSubscriptionToBackend(getState, subscription, me));
  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. try {
  100. getRegistration()
  101. .then(getPushSubscription)
  102. .then(unsubscribe);
  103. } catch (e) {
  104. }
  105. });
  106. } else {
  107. console.warn('Your browser does not support Web Push Notifications.');
  108. }
  109. };
  110. }
  111. export function saveSettings() {
  112. return (_, getState) => {
  113. const state = getState().get('push_notifications');
  114. const subscription = state.get('subscription');
  115. const alerts = state.get('alerts');
  116. const data = { alerts };
  117. api(getState).put(`/api/web/push_subscriptions/${subscription.get('id')}`, {
  118. data,
  119. }).then(() => {
  120. const me = getState().getIn(['meta', 'me']);
  121. if (me) {
  122. pushNotificationsSetting.set(me, data);
  123. }
  124. });
  125. };
  126. }