Actions: TypeScript

Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
environments/review-develop-3zknud/deployments/332^2
marcin mikołajczak 2022-06-13 23:23:49 +02:00
rodzic aec85d6db7
commit 3a09a91dd7
5 zmienionych plików z 99 dodań i 100 usunięć

Wyświetl plik

@ -7,6 +7,8 @@ import {
setAlerts, setAlerts,
} from './setter'; } from './setter';
import type { AppDispatch } from 'soapbox/store';
export { export {
SET_BROWSER_SUPPORT, SET_BROWSER_SUPPORT,
SET_SUBSCRIPTION, SET_SUBSCRIPTION,
@ -15,9 +17,8 @@ export {
register, register,
}; };
export function changeAlerts(path, value) { export const changeAlerts = (path: Array<string>, value: any) =>
return dispatch => { (dispatch: AppDispatch) => {
dispatch(setAlerts(path, value)); dispatch(setAlerts(path, value));
dispatch(saveSettings()); dispatch(saveSettings() as any);
}; };
}

Wyświetl plik

@ -1,12 +1,15 @@
import { createPushSubsription, updatePushSubscription } from 'soapbox/actions/push_subscriptions'; import { createPushSubscription, updatePushSubscription } from 'soapbox/actions/push_subscriptions';
import { pushNotificationsSetting } from 'soapbox/settings'; import { pushNotificationsSetting } from 'soapbox/settings';
import { getVapidKey } from 'soapbox/utils/auth'; import { getVapidKey } from 'soapbox/utils/auth';
import { decode as decodeBase64 } from 'soapbox/utils/base64'; import { decode as decodeBase64 } from 'soapbox/utils/base64';
import { setBrowserSupport, setSubscription, clearSubscription } from './setter'; import { setBrowserSupport, setSubscription, clearSubscription } from './setter';
import type { AppDispatch, RootState } from 'soapbox/store';
import type { Me } from 'soapbox/types/soapbox';
// Taken from https://www.npmjs.com/package/web-push // Taken from https://www.npmjs.com/package/web-push
const urlBase64ToUint8Array = (base64String) => { const urlBase64ToUint8Array = (base64String: string) => {
const padding = '='.repeat((4 - base64String.length % 4) % 4); const padding = '='.repeat((4 - base64String.length % 4) % 4);
const base64 = (base64String + padding) const base64 = (base64String + padding)
.replace(/\-/g, '+') .replace(/\-/g, '+')
@ -17,22 +20,25 @@ const urlBase64ToUint8Array = (base64String) => {
const getRegistration = () => navigator.serviceWorker.ready; const getRegistration = () => navigator.serviceWorker.ready;
const getPushSubscription = (registration) => const getPushSubscription = (registration: ServiceWorkerRegistration) =>
registration.pushManager.getSubscription() registration.pushManager.getSubscription()
.then(subscription => ({ registration, subscription })); .then(subscription => ({ registration, subscription }));
const subscribe = (registration, getState) => const subscribe = (registration: ServiceWorkerRegistration, getState: () => RootState) =>
registration.pushManager.subscribe({ registration.pushManager.subscribe({
userVisibleOnly: true, userVisibleOnly: true,
applicationServerKey: urlBase64ToUint8Array(getVapidKey(getState())), applicationServerKey: urlBase64ToUint8Array(getVapidKey(getState())),
}); });
const unsubscribe = ({ registration, subscription }) => const unsubscribe = ({ registration, subscription }: {
subscription ? subscription.unsubscribe().then(() => registration) : registration; registration: ServiceWorkerRegistration,
subscription: PushSubscription | null,
}) =>
subscription ? subscription.unsubscribe().then(() => registration) : new Promise<ServiceWorkerRegistration>(r => r(registration));
const sendSubscriptionToBackend = (subscription, me) => { const sendSubscriptionToBackend = (subscription: PushSubscription, me: Me) =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const alerts = getState().getIn(['push_notifications', 'alerts']).toJS(); const alerts = getState().push_notifications.get('alerts').toJS();
const params = { subscription, data: { alerts } }; const params = { subscription, data: { alerts } };
if (me) { if (me) {
@ -42,16 +48,15 @@ const sendSubscriptionToBackend = (subscription, me) => {
} }
} }
return dispatch(createPushSubsription(params)); return dispatch(createPushSubscription(params) as any);
}; };
};
// Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload // Last one checks for payload support: https://web-push-book.gauntface.com/chapter-06/01-non-standards-browsers/#no-payload
const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype); const supportsPushNotifications = ('serviceWorker' in navigator && 'PushManager' in window && 'getKey' in PushSubscription.prototype);
export function register() { export const register = () =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const me = getState().get('me'); const me = getState().me;
const vapidKey = getVapidKey(getState()); const vapidKey = getVapidKey(getState());
dispatch(setBrowserSupport(supportsPushNotifications)); dispatch(setBrowserSupport(supportsPushNotifications));
@ -68,35 +73,39 @@ export function register() {
getRegistration() getRegistration()
.then(getPushSubscription) .then(getPushSubscription)
.then(({ registration, subscription }) => { // @ts-ignore
.then(({ registration, subscription }: {
registration: ServiceWorkerRegistration,
subscription: PushSubscription | null,
}) => {
if (subscription !== null) { if (subscription !== null) {
// We have a subscription, check if it is still valid // We have a subscription, check if it is still valid
const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey)).toString(); const currentServerKey = (new Uint8Array(subscription.options.applicationServerKey!)).toString();
const subscriptionServerKey = urlBase64ToUint8Array(vapidKey).toString(); const subscriptionServerKey = urlBase64ToUint8Array(vapidKey).toString();
const serverEndpoint = getState().getIn(['push_notifications', 'subscription', 'endpoint']); const serverEndpoint = getState().push_notifications.getIn(['subscription', 'endpoint']);
// If the VAPID public key did not change and the endpoint corresponds // If the VAPID public key did not change and the endpoint corresponds
// to the endpoint saved in the backend, the subscription is valid // to the endpoint saved in the backend, the subscription is valid
if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) { if (subscriptionServerKey === currentServerKey && subscription.endpoint === serverEndpoint) {
return subscription; return { subscription };
} else { } else {
// Something went wrong, try to subscribe again // Something went wrong, try to subscribe again
return unsubscribe({ registration, subscription }).then(registration => { return unsubscribe({ registration, subscription }).then((registration: ServiceWorkerRegistration) => {
return subscribe(registration, getState); return subscribe(registration, getState);
}).then( }).then(
subscription => dispatch(sendSubscriptionToBackend(subscription, me))); (subscription: PushSubscription) => dispatch(sendSubscriptionToBackend(subscription, me) as any));
} }
} }
// No subscription, try to subscribe // No subscription, try to subscribe
return subscribe(registration, getState) return subscribe(registration, getState)
.then(subscription => dispatch(sendSubscriptionToBackend(subscription, me))); .then(subscription => dispatch(sendSubscriptionToBackend(subscription, me) as any));
}) })
.then(subscription => { .then(({ subscription }: { subscription: PushSubscription | Record<string, any> }) => {
// If we got a PushSubscription (and not a subscription object from the backend) // If we got a PushSubscription (and not a subscription object from the backend)
// it means that the backend subscription is valid (and was set during hydration) // it means that the backend subscription is valid (and was set during hydration)
if (!(subscription instanceof PushSubscription)) { if (!(subscription instanceof PushSubscription)) {
dispatch(setSubscription(subscription)); dispatch(setSubscription(subscription as PushSubscription));
if (me) { if (me) {
pushNotificationsSetting.set(me, { alerts: subscription.alerts }); pushNotificationsSetting.set(me, { alerts: subscription.alerts });
} }
@ -123,14 +132,13 @@ export function register() {
}) })
.catch(console.warn); .catch(console.warn);
}; };
}
export function saveSettings() { export const saveSettings = () =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => RootState) => {
const state = getState().get('push_notifications'); const state = getState().push_notifications;
const alerts = state.get('alerts'); const alerts = state.get('alerts');
const data = { alerts }; const data = { alerts };
const me = getState().get('me'); const me = getState().me;
return dispatch(updatePushSubscription({ data })).then(() => { return dispatch(updatePushSubscription({ data })).then(() => {
if (me) { if (me) {
@ -138,4 +146,3 @@ export function saveSettings() {
} }
}).catch(console.warn); }).catch(console.warn);
}; };
}

Wyświetl plik

@ -1,34 +0,0 @@
export const SET_BROWSER_SUPPORT = 'PUSH_NOTIFICATIONS_SET_BROWSER_SUPPORT';
export const SET_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_SET_SUBSCRIPTION';
export const CLEAR_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_CLEAR_SUBSCRIPTION';
export const SET_ALERTS = 'PUSH_NOTIFICATIONS_SET_ALERTS';
export function setBrowserSupport(value) {
return {
type: SET_BROWSER_SUPPORT,
value,
};
}
export function setSubscription(subscription) {
return {
type: SET_SUBSCRIPTION,
subscription,
};
}
export function clearSubscription() {
return {
type: CLEAR_SUBSCRIPTION,
};
}
export function setAlerts(path, value) {
return dispatch => {
dispatch({
type: SET_ALERTS,
path,
value,
});
};
}

Wyświetl plik

@ -0,0 +1,28 @@
import type { AnyAction } from 'redux';
export const SET_BROWSER_SUPPORT = 'PUSH_NOTIFICATIONS_SET_BROWSER_SUPPORT';
export const SET_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_SET_SUBSCRIPTION';
export const CLEAR_SUBSCRIPTION = 'PUSH_NOTIFICATIONS_CLEAR_SUBSCRIPTION';
export const SET_ALERTS = 'PUSH_NOTIFICATIONS_SET_ALERTS';
export const setBrowserSupport = (value: boolean) => ({
type: SET_BROWSER_SUPPORT,
value,
});
export const setSubscription = (subscription: PushSubscription) => ({
type: SET_SUBSCRIPTION,
subscription,
});
export const clearSubscription = () => ({
type: CLEAR_SUBSCRIPTION,
});
export const setAlerts = (path: Array<string>, value: any) =>
(dispatch: React.Dispatch<AnyAction>) =>
dispatch({
type: SET_ALERTS,
path,
value,
});

Wyświetl plik

@ -16,47 +16,44 @@ export const PUSH_SUBSCRIPTION_DELETE_REQUEST = 'PUSH_SUBSCRIPTION_DELETE_REQUES
export const PUSH_SUBSCRIPTION_DELETE_SUCCESS = 'PUSH_SUBSCRIPTION_DELETE_SUCCESS'; export const PUSH_SUBSCRIPTION_DELETE_SUCCESS = 'PUSH_SUBSCRIPTION_DELETE_SUCCESS';
export const PUSH_SUBSCRIPTION_DELETE_FAIL = 'PUSH_SUBSCRIPTION_DELETE_FAIL'; export const PUSH_SUBSCRIPTION_DELETE_FAIL = 'PUSH_SUBSCRIPTION_DELETE_FAIL';
export function createPushSubsription(params) { import type { AppDispatch, RootState } from 'soapbox/store';
return (dispatch, getState) => {
export const createPushSubscription = (params: Record<string, any>) =>
(dispatch: AppDispatch, getState: () => RootState) => {
dispatch({ type: PUSH_SUBSCRIPTION_CREATE_REQUEST, params }); dispatch({ type: PUSH_SUBSCRIPTION_CREATE_REQUEST, params });
return api(getState).post('/api/v1/push/subscription', params).then(({ data: subscription }) => { return api(getState).post('/api/v1/push/subscription', params).then(({ data: subscription }) =>
dispatch({ type: PUSH_SUBSCRIPTION_CREATE_SUCCESS, params, subscription }); dispatch({ type: PUSH_SUBSCRIPTION_CREATE_SUCCESS, params, subscription }),
return subscription; ).catch(error =>
}).catch(error => { dispatch({ type: PUSH_SUBSCRIPTION_CREATE_FAIL, params, error }),
dispatch({ type: PUSH_SUBSCRIPTION_CREATE_FAIL, params, error }); );
});
}; };
}
export function fetchPushSubsription() { export const fetchPushSubscription = () =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => RootState) => {
dispatch({ type: PUSH_SUBSCRIPTION_FETCH_REQUEST }); dispatch({ type: PUSH_SUBSCRIPTION_FETCH_REQUEST });
return api(getState).get('/api/v1/push/subscription').then(({ data: subscription }) => { return api(getState).get('/api/v1/push/subscription').then(({ data: subscription }) =>
dispatch({ type: PUSH_SUBSCRIPTION_FETCH_SUCCESS, subscription }); dispatch({ type: PUSH_SUBSCRIPTION_FETCH_SUCCESS, subscription }),
}).catch(error => { ).catch(error =>
dispatch({ type: PUSH_SUBSCRIPTION_FETCH_FAIL, error }); dispatch({ type: PUSH_SUBSCRIPTION_FETCH_FAIL, error }),
}); );
}; };
}
export function updatePushSubscription(params) { export const updatePushSubscription = (params: Record<string, any>) =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => any) => {
dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_REQUEST, params }); dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_REQUEST, params });
return api(getState).put('/api/v1/push/subscription', params).then(({ data: subscription }) => { return api(getState).put('/api/v1/push/subscription', params).then(({ data: subscription }) =>
dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_SUCCESS, params, subscription }); dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_SUCCESS, params, subscription }),
}).catch(error => { ).catch(error =>
dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_FAIL, params, error }); dispatch({ type: PUSH_SUBSCRIPTION_UPDATE_FAIL, params, error }),
}); );
}; };
}
export function deletePushSubsription() { export const deletePushSubscription = () =>
return (dispatch, getState) => { (dispatch: AppDispatch, getState: () => RootState) => {
dispatch({ type: PUSH_SUBSCRIPTION_DELETE_REQUEST }); dispatch({ type: PUSH_SUBSCRIPTION_DELETE_REQUEST });
return api(getState).delete('/api/v1/push/subscription').then(() => { return api(getState).delete('/api/v1/push/subscription').then(() =>
dispatch({ type: PUSH_SUBSCRIPTION_DELETE_SUCCESS }); dispatch({ type: PUSH_SUBSCRIPTION_DELETE_SUCCESS }),
}).catch(error => { ).catch(error =>
dispatch({ type: PUSH_SUBSCRIPTION_DELETE_FAIL, error }); dispatch({ type: PUSH_SUBSCRIPTION_DELETE_FAIL, error }),
}); );
}; };
}