Skip to content

Commit

Permalink
Merge pull request #1270 from ethereum-push-notification-service/refa…
Browse files Browse the repository at this point in the history
…ctor/settings-integration

Integrated new api and notif settings backend
  • Loading branch information
0xNilesh authored Oct 10, 2023
2 parents 9101023 + d5d791e commit 829d009
Show file tree
Hide file tree
Showing 19 changed files with 1,136 additions and 425 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
"@mui/lab": "^5.0.0-alpha.72",
"@mui/material": "^5.5.0",
"@pushprotocol/ledgerlive": "latest",
"@pushprotocol/restapi": "0.0.1-alpha.45",
"@pushprotocol/restapi": "0.0.1-alpha.48",
"@pushprotocol/socket": "latest",
"@pushprotocol/uiweb": "1.1.14",
"@pushprotocol/uiweb": "0.0.1-alpha.17",
"@reduxjs/toolkit": "^1.7.1",
"@testing-library/dom": "^9.0.1",
"@testing-library/jest-dom": "^4.2.4",
Expand Down
18 changes: 3 additions & 15 deletions src/components/ChannelDetails.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export default function ChannelDetails({ isChannelExpired, setIsChannelExpired,
canVerify,
aliasDetails: { isAliasVerified, aliasAddrFromContract },
} = useSelector((state) => state.admin);
const { channelSettings } = useSelector((state) => state.channels);

const { CHANNEL_ACTIVE_STATE, CHANNNEL_DEACTIVATED_STATE } = useSelector((state) => state.channels);
const { processingState } = useSelector((state) => state.channelCreation);
Expand Down Expand Up @@ -142,19 +143,6 @@ export default function ChannelDetails({ isChannelExpired, setIsChannelExpired,
}
}, [account]);

const channelSettings = useMemo(() => {
if (delegatees) {
const delegatee = delegatees.find(({ channel }) => channel === channelAddress);
if (delegatee) {
const { channel_settings } = delegatee;
if (channel_settings !== null) {
return JSON.parse(channel_settings);
}
}
}
return [];
}, [delegatees, channelAddress]);

const removeDelegate = (walletAddress) => {
return epnsCommWriteProvider.removeDelegate(walletAddress);
};
Expand Down Expand Up @@ -335,7 +323,7 @@ export default function ChannelDetails({ isChannelExpired, setIsChannelExpired,
<ChannelInfoList
account={account}
isAddress={false}
items={channelSettings}
items={channelSettings[account]}
isLoading={false}
onClickEmptyListButton={navigateToNotifSettings}
emptyListButtonTitle='Add Setting'
Expand Down Expand Up @@ -624,4 +612,4 @@ const DelegateContainer = styled(Item)`
border-radius: 20px;
border: 1px solid;
border-color: ${(props) => props.theme.default.borderColor};
`;
`;
7 changes: 7 additions & 0 deletions src/components/InitState.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
setUserChannelDetails,
} from 'redux/slices/adminSlice';
import { setProcessingState } from 'redux/slices/channelCreationSlice';
import { updateBulkChannelSettings } from 'redux/slices/channelSlice';
import { setPushAdmin } from 'redux/slices/contractSlice';
import { getChannelsSearch, getUserDelegations } from 'services';
import * as PushAPI from '@pushprotocol/restapi';
Expand Down Expand Up @@ -175,6 +176,12 @@ const InitState = () => {
}
const channelInformation = await Promise.all(channelInformationPromise);
dispatch(setDelegatees(channelInformation));
// get channel settings of all the channels
const channelSettings = {};
for (const channel of channelInformation) {
channelSettings[channel.channel] = channel.channel_settings ? JSON.parse(channel.channel_settings) : [];
}
dispatch(updateBulkChannelSettings(channelSettings));
} else {
dispatch(setDelegatees([]));
}
Expand Down
225 changes: 29 additions & 196 deletions src/components/ViewChannelItem.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// React + Web3 Essentials
import React, { useEffect } from 'react';
import React, { useEffect, useMemo } from 'react';

// External Packages
import Skeleton from '@yisheng90/react-loading';
Expand All @@ -11,6 +11,7 @@ import { toast as toaster } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.min.css';
import styled, { css, useTheme } from 'styled-components';
import axios from 'axios';
import { cloneDeep } from 'lodash';

// Internal Compoonents
import * as PushAPI from '@pushprotocol/restapi';
Expand All @@ -19,7 +20,7 @@ import MetaInfoDisplayer from 'components/MetaInfoDisplayer';
import LoaderSpinner, { LOADER_TYPE } from 'components/reusables/loaders/LoaderSpinner';
import { convertAddressToAddrCaip } from 'helpers/CaipHelper';
import useToast from 'hooks/useToast';
import { cacheChannelInfo, updateSubscriptionStatus } from 'redux/slices/channelSlice';
import { cacheChannelInfo } from 'redux/slices/channelSlice';
import { addNewWelcomeNotif, incrementStepIndex } from 'redux/slices/userJourneySlice';
import ChannelTutorial, { isChannelTutorialized } from 'segments/ChannelTutorial';
import NotificationToast from '../primaries/NotificationToast';
Expand Down Expand Up @@ -51,7 +52,7 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {
(state) => state.contracts
);
const { canVerify } = useSelector((state) => state.admin);
const { channelsCache, CHANNEL_BLACKLIST, subscriptionStatus } = useSelector((state) => state.channels);
const { channelsCache, CHANNEL_BLACKLIST, subscriptionStatus, userSettings: currentUserSettings } = useSelector((state) => state.channels);
const { account, provider, chainId } = useAccount();

const onCoreNetwork = chainId === appConfig.coreContractChain;
Expand Down Expand Up @@ -186,11 +187,9 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {

const generalToast = useToast();

// to subscribe
const subscribe = async () => {
console.log('click executed');
subscribeAction(false);
};
const userSettings = useMemo(() => {
return cloneDeep(currentUserSettings);
}, [currentUserSettings]);

const formatAddress = (addressText) => {
return addressText.length > 40 ? `${shortenText(addressText, 4, 6)}` : addressText;
Expand Down Expand Up @@ -325,125 +324,6 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {
});
};

const subscribeToast = useToast();
const subscribeAction = async () => {
setTxInProgress(true);
try {
let channelAddress = channelObject.channel;
if (!onCoreNetwork) {
channelAddress = channelObject.alias_address;
}

subscribeToast.showLoaderToast({ loaderMessage: 'Waiting for Confirmation...' });

if (run) {
const type = {
Subscribe: [
{ name: 'channel', type: 'address' },
{ name: 'subscriber', type: 'address' },
{ name: 'action', type: 'string' },
],
};

const message = {
channel: channelAddress,
subscriber: account,
action: 'Subscribe',
};

await provider.getSigner(account)._signTypedData(EPNS_DOMAIN, type, message);

console.log('in run');
subscribeToast.showMessageToast({
toastTitle: 'Success',
toastMessage: 'Successfully opted into channel !',
toastType: 'SUCCESS',
getToastIcon: (size) => (
<MdCheckCircle
size={size}
color="green"
/>
),
});

dispatch(
addNewWelcomeNotif({
cta: '',
title: channelObject.info,
message: `Welcome to ${channelObject.name} Channel. From now onwards, you'll be getting notifications from this channel`,
icon: channelIcon,
url: channelObject.url,
sid: '',
app: channelObject.name,
image: '',
})
);
setTxInProgress(false);
setSubscribed(true);
if (stepIndex === 5) {
console.log('this is working');
dispatch(incrementStepIndex());
}
return;
}

const _signer = await provider.getSigner(account);
await PushAPI.channels.subscribe({
signer: _signer,
channelAddress: convertAddressToAddrCaip(channelAddress, chainId), // channel address in CAIP
userAddress: convertAddressToAddrCaip(account, chainId), // user address in CAIP
onSuccess: () => {
dispatch(updateSubscriptionStatus({ channelAddress: channelObject.channel, status: true }));
setSubscribed(true);
setSubscriberCount(subscriberCount + 1);

subscribeToast.showMessageToast({
toastTitle: 'Success',
toastMessage: 'Successfully opted into channel !',
toastType: 'SUCCESS',
getToastIcon: (size) => (
<MdCheckCircle
size={size}
color="green"
/>
),
});
},
onError: () => {
console.error('opt in error');
subscribeToast.showMessageToast({
toastTitle: 'Error',
toastMessage: `There was an error opting into channel`,
toastType: 'ERROR',
getToastIcon: (size) => (
<MdError
size={size}
color="red"
/>
),
});
},
env: appConfig.pushNodesEnv,
});
} catch (err) {
subscribeToast.showMessageToast({
toastTitle: 'Error',
toastMessage: `There was an error opting into channel ( ${err.message} )`,
toastType: 'ERROR',
getToastIcon: (size) => (
<MdError
size={size}
color="red"
/>
),
});

console.log(err);
} finally {
setTxInProgress(false);
}
};

const copyToClipboard = (address) => {
let hostname = window.location.hostname;
// if we are on localhost, attach the port
Expand All @@ -464,73 +344,6 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {
}
};

const unsubscribeToast = useToast();
const unsubscribeAction = async () => {
try {
let channelAddress = channelObject.channel;
if (!onCoreNetwork) {
channelAddress = channelObject.alias_address;
}

unsubscribeToast.showLoaderToast({ loaderMessage: 'Waiting for Confirmation...' });

const _signer = await provider.getSigner(account);
await PushAPI.channels.unsubscribe({
signer: _signer,
channelAddress: convertAddressToAddrCaip(channelAddress, chainId), // channel address in CAIP
userAddress: convertAddressToAddrCaip(account, chainId), // user address in CAIP
onSuccess: () => {
dispatch(updateSubscriptionStatus({ channelAddress: channelObject.channel, status: false }));
setSubscribed(false);
setSubscriberCount(subscriberCount - 1);

unsubscribeToast.showMessageToast({
toastTitle: 'Success',
toastMessage: 'Successfully opted out of channel !',
toastType: 'SUCCESS',
getToastIcon: (size) => (
<MdCheckCircle
size={size}
color="green"
/>
),
});
},
onError: () => {
console.error('opt out error');
unsubscribeToast.showMessageToast({
toastTitle: 'Error',
toastMessage: `There was an error opting out of channel`,
toastType: 'ERROR',
getToastIcon: (size) => (
<MdError
size={size}
color="red"
/>
),
});
},
env: appConfig.pushNodesEnv,
});
} catch (err) {
unsubscribeToast.showMessageToast({
toastTitle: 'Error',
toastMessage: `There was an error opting out of channel ( ${err.message} )`,
toastType: 'ERROR',
getToastIcon: (size) => (
<MdError
size={size}
color="red"
/>
),
});

console.log(err);
} finally {
setTxInProgress(false);
}
};

const correctChannelTitleLink = () => {
const channelLink = CTA_OVERRIDE_CACHE[channelObject.channel] || channelObject.url;
if (/(?:http|https):\/\//i.test(channelLink)) {
Expand Down Expand Up @@ -1041,7 +854,14 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {
<>
{isOwner && <OwnerButton disabled>Owner</OwnerButton>}
{!isOwner && (
<OptinNotifSettingDropdown>
<OptinNotifSettingDropdown
channelDetail={channelObject}
setLoading={setTxInProgress}
onSuccessOptin={() => {
setSubscribed(true);
setSubscriberCount((prevSubscriberCount) => prevSubscriberCount + 1)
}}
>
<SubscribeButton
onClick={() => {}}
disabled={txInProgress}
Expand All @@ -1066,7 +886,17 @@ function ViewChannelItem({ channelObjectProp, loadTeaser, playTeaser }) {
<>
{isOwner && <OwnerButton disabled>Owner</OwnerButton>}
{!isOwner && (
<ManageNotifSettingDropdown centerOnMobile={true}>
<ManageNotifSettingDropdown
centerOnMobile={true}
channelDetail={channelObject}
setSubscribed={setSubscribed}
userSetting={userSettings[channelObject.channel]}
setSubscriberCount={setSubscriberCount}
onSuccessOptout={() => {
setSubscribed(false);
setSubscriberCount((prevSubscriberCount) => prevSubscriberCount - 1)
}}
>
<UnsubscribeButton
onClick={() => {}}
disabled={txInProgress}
Expand Down Expand Up @@ -1532,6 +1362,9 @@ const UnsubscribeButton = styled(ChannelActionButton)`

const OwnerButton = styled(ChannelActionButton)`
background: #35c5f3;
border-radius: 8px;
min-height: 36px;
min-width: 108px;
`;

const Toaster = styled.div`
Expand Down
Loading

0 comments on commit 829d009

Please sign in to comment.