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.

142 lines
5.3 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 (supportsPushNotifications) {
  46. if (!getApplicationServerKey()) {
  47. console.error('The VAPID public key is not set. You will not be able to receive Web Push Notifications.');
  48. return;
  49. }
  50. getRegistration()
  51. .then(getPushSubscription)
  52. .then(({ registration, subscription }) => {
  53. if (subscription !== null) {
  54. // We have a subscription, check if it is still valid
  55. const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString();
  56. const subscriptionServerKey = urlBase64ToUint8Array(getApplicationServerKey()).toString();
  57. const serverEndpoint = getState().getIn(['push_notifications', 'subscription', 'endpoint']);
  58. // If the VAPID public key did not change and the endpoint corresponds
  59. // to the endpoint saved in the backend, the subscription is valid
  60. if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) {
  61. return subscription;
  62. } else {
  63. // Something went wrong, try to subscribe again
  64. return unsubscribe({ registration, subscription }).then(subscribe).then(
  65. subscription => sendSubscriptionToBackend(getState, subscription, me));
  66. }
  67. }
  68. // No subscription, try to subscribe
  69. return subscribe(registration).then(
  70. subscription => sendSubscriptionToBackend(getState, subscription, me));
  71. })
  72. .then(subscription => {
  73. // If we got a PushSubscription (and not a subscription object from the backend)
  74. // it means that the backend subscription is valid (and was set during hydration)
  75. if (!(subscription instanceof PushSubscription)) {
  76. dispatch(setSubscription(subscription));
  77. if (me) {
  78. pushNotificationsSetting.set(me, { alerts: subscription.alerts });
  79. }
  80. }
  81. })
  82. .catch(error => {
  83. if (error.code === 20 && error.name === 'AbortError') {
  84. console.warn('Your browser supports Web Push Notifications, but does not seem to implement the VAPID protocol.');
  85. } else if (error.code === 5 && error.name === 'InvalidCharacterError') {
  86. console.error('The VAPID public key seems to be invalid:', getApplicationServerKey());
  87. }
  88. // Clear alerts and hide UI settings
  89. dispatch(clearSubscription());
  90. if (me) {
  91. pushNotificationsSetting.remove(me);
  92. }
  93. try {
  94. getRegistration()
  95. .then(getPushSubscription)
  96. .then(unsubscribe);
  97. } catch (e) {
  98. }
  99. });
  100. } else {
  101. console.warn('Your browser does not support Web Push Notifications.');
  102. }
  103. };
  104. }
  105. export function saveSettings() {
  106. return (_, getState) => {
  107. const state = getState().get('push_notifications');
  108. const subscription = state.get('subscription');
  109. const alerts = state.get('alerts');
  110. const data = { alerts };
  111. api(getState).put(`/api/web/push_subscriptions/${subscription.get('id')}`, {
  112. data,
  113. }).then(() => {
  114. const me = getState().getIn(['meta', 'me']);
  115. if (me) {
  116. pushNotificationsSetting.set(me, data);
  117. }
  118. });
  119. };
  120. }