Skip to content

Commit

Permalink
Socket & pagination (#966)
Browse files Browse the repository at this point in the history
* added socket connection

* fixing in messageFeed

* Added pagination feature

* bottom scroll

* pagination fix

* scroll in view

* fix scroll

* Removed horizontal scroll and some other issues

* socket changes

* removed checkConnectedUser

* added group events

* fixed sockets bugs

* fixed import error

---------

Co-authored-by: Nilesh Gupta <guptanilesh2312@gmail.com>
Co-authored-by: corlard3y <corlardey@gmail.com>
  • Loading branch information
3 people authored Mar 22, 2023
1 parent 7588145 commit 98462fe
Show file tree
Hide file tree
Showing 18 changed files with 401 additions and 243 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"@mui/material": "^5.5.0",
"@pushprotocol/ledgerlive": "0.0.1",
"@pushprotocol/restapi": "0.8.0",
"@pushprotocol/socket": "0.3.0",
"@pushprotocol/socket": "0.4.2",
"@pushprotocol/uiweb": "0.5.0",
"@reduxjs/toolkit": "^1.7.1",
"@testing-library/dom": "^9.0.1",
Expand Down
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export default function App() {

// enable socket notifications
useSDKSocket({ account, chainId, env: appConfig.appEnv });

const toggleDarkMode = () => {
setDarkMode(!darkMode);
};
Expand Down
260 changes: 148 additions & 112 deletions src/components/chat/w2wChat/chatBox/ChatBox.tsx

Large diffs are not rendered by default.

9 changes: 5 additions & 4 deletions src/components/chat/w2wChat/chats/Chats.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,10 @@ export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, is
const getProfilePicture = async() =>{
let member = getMemberDetails(currentChat,msg?.fromCAIP10);
if(member){
setProfilePicture(member.image);
setProfilePicture(member.image);
}
else {
console.log(msg)
let user = await PushAPI.user.get({account:msg.fromCAIP10,env:appConfig.appEnv});
setProfilePicture(user.profilePicture);
}
Expand All @@ -63,7 +64,7 @@ export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, is
useEffect(() => {
if(isGroup && msg && msg.messageType !== 'Intent')
getProfilePicture();
})
}, []);

return (
<>
Expand Down Expand Up @@ -372,7 +373,7 @@ const MessageText = styled(SpanV2)`
const ReceivedMessage = styled.div`
box-sizing: border-box;
position: relative;
left: ${(props) => props.left || '34px'};
margin-left: ${(props) => props.left || '34px'};
max-width: 419px;
padding: ${(props: any): string => props.padding || '5px 11px 10px 15px'};
background: ${(props: any): string => props.color || '#ffffff'};
Expand All @@ -394,7 +395,7 @@ const IntentMessage = styled(ReceivedMessage)`
const SenderMessage = styled.div`
box-sizing: border-box;
position: relative;
right: 34px;
margin-right: 34px;
max-width: 419px;
text-align: left;
padding: ${(props: any): string => props.padding || '11px 11px 5px 15px'};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const ReceivedMessageWrapper = (props): JSX.Element => {
>
<ItemHV2
position="relative"
left={props?.isGroup ? '34px' : '0px'}
margin={props?.isGroup ? '0 0 0 34px' : '0px'}
>
{props?.isGroup && props?.profilePicture && props.msgType !== 'Intent' && (
<ItemVV2
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => {
...currentChat?.groupInformation?.members,
...currentChat?.groupInformation?.pendingMembers,
]);
const newAdminList = getUpdatedAdminList(currentChat, selectedMemeberAddress, false);
const newAdminList = getUpdatedAdminList(currentChat?.groupInformation, selectedMemeberAddress, false);
try {
const { updateResponse, updatedCurrentChat } = await updateGroup({
currentChat,
Expand Down Expand Up @@ -122,7 +122,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => {
...currentChat?.groupInformation?.members,
...currentChat?.groupInformation?.pendingMembers,
]);
const newAdminList = getUpdatedAdminList(currentChat, selectedMemeberAddress, true);
const newAdminList = getUpdatedAdminList(currentChat?.groupInformation, selectedMemeberAddress, true);
try {
const { updateResponse, updatedCurrentChat } = await updateGroup({
currentChat,
Expand Down
54 changes: 17 additions & 37 deletions src/components/chat/w2wChat/messageFeed/MessageFeed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
import React, { useContext, useEffect, useState } from 'react';

// External Packages
import { useQuery } from 'react-query';
import styled, { useTheme } from 'styled-components';
import { MdError } from 'react-icons/md';
import { ethers } from 'ethers';
Expand Down Expand Up @@ -60,7 +59,7 @@ const MessageFeed = (props: MessageFeedProps): JSX.Element => {

const getInbox = async (): Promise<Feeds[]> => {
const getInbox = await intitializeDb<string>('Read', 'Inbox', walletToCAIP10({ account }), '', 'did');
if (getInbox !== undefined) {
if (getInbox !== undefined && !inbox.length) {
let inboxes: Feeds[] = getInbox.body;
inboxes = await decryptFeeds({ feeds: inboxes, connectedUser });
if (JSON.stringify(feeds) !== JSON.stringify(inboxes))
Expand All @@ -69,19 +68,16 @@ const MessageFeed = (props: MessageFeedProps): JSX.Element => {
setInbox(inboxes);
}
return inboxes;
} else {
let inboxes: Feeds[] = await fetchInboxApi();
return inboxes;
}
}
};
const fetchInboxApi = async (): Promise<Feeds[]> => {
try {
const inboxes:Feeds[] = await fetchInbox(connectedUser);
if (JSON.stringify(feeds) !== JSON.stringify(inboxes)) {
if (JSON.stringify(feeds) !== JSON.stringify(inbox)){
setFeeds(inboxes);
setInbox(inboxes);
if(checkIfGroup(currentChat)){
if(JSON.stringify(currentChat?.groupInformation?.members) !== JSON.stringify(inboxes[selectedChatSnap]?.groupInformation?.members))
if(currentChat?.groupInformation?.members?.length !== inboxes[selectedChatSnap]?.groupInformation?.members?.length)
setChat(inboxes[selectedChatSnap]);
}
}
Expand All @@ -104,40 +100,24 @@ const MessageFeed = (props: MessageFeedProps): JSX.Element => {
setShowError(true);
}
};
useQuery('inbox', getInbox, {
enabled: !props.hasUserBeenSearched && stopApi,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchIntervalInBackground: false,
suspense: false,
onError: () => {
setStopApi(false);
},
retry: 3,
refetchInterval: 1000 * 5,
retryDelay: 1000 * 5,
});

useQuery('fetchInboxApi', fetchInboxApi, {
enabled: !props.hasUserBeenSearched && stopApi,
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchIntervalInBackground: false,
suspense: false,
onError: () => {
setStopApi(false);
},
retry: 3,
refetchInterval: 1000 * 5,
retryDelay: 1000 * 5,
});

const updateInbox = async (): Promise<void> => {
await getInbox();
fetchInboxApi();

setMessagesLoading(false);
};

useEffect(() => {
setFeeds(inbox);
},[inbox]);


useEffect(() => {
if(!props.hasUserBeenSearched)
updateInbox();
},[]);

useEffect(() => {
if (!props.hasUserBeenSearched) {
updateInbox();
Expand Down
17 changes: 5 additions & 12 deletions src/contexts/ChatUserContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,11 @@ const ChatUserContextProvider = (props) => {
if (user.wallets.includes(',') || !user.wallets.includes(caip10)) {
throw Error('Invalid user');
}

const privateKeyArmored: string = await CryptoHelper.decryptWithWalletRPCMethod(
library.provider,
user.encryptedPrivateKey,
account
);
const _signer = await library.getSigner();
const privateKeyArmored: string = await PushAPI.chat.decryptPGPKey({
encryptedPGPPrivateKey: user.encryptedPrivateKey,
signer: _signer
});
setPgpPvtKey(privateKeyArmored);
connectedUser = { ...user, privateKey: privateKeyArmored };
} else {
Expand Down Expand Up @@ -91,7 +90,6 @@ const ChatUserContextProvider = (props) => {
});
await new Promise((r) => setTimeout(r, 200));

// const keyPairs = await generateKeyPair();
setBlockedLoading({
enabled: true,
title: 'Step 2/4: Encrypting your keys',
Expand All @@ -100,11 +98,6 @@ const ChatUserContextProvider = (props) => {
progressNotice: 'Please sign the transaction to continue. Steady lads, chat is almost ready!',
});

// const walletPublicKey = await CryptoHelper.getPublicKey(account);
// const encryptedPrivateKey = CryptoHelper.encryptWithRPCEncryptionPublicKeyReturnRawData(
// keyPairs.privateKeyArmored,
// walletPublicKey
// );
const signer = await library.getSigner();
await PushNodeClient.createUser({
signer: signer
Expand Down
3 changes: 1 addition & 2 deletions src/helpers/w2w/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,6 @@ export interface IDecryptMessage {
savedMsg: MessageIPFSWithCID;
connectedUser: ConnectedUser;
account: string;
chainId: number;
currentChat: Feeds;
inbox: Feeds[];
}
Expand All @@ -133,7 +132,7 @@ export const decryptMessages = async ({
if (savedMsg.fromCAIP10 === walletToCAIP10({ account })) {
signatureValidationPubliKey = connectedUser.publicKey;
} else {
if (!currentChat.publicKey) {
if (!currentChat?.publicKey) {
if (checkIfGroup(currentChat)) {
const member = getMemberDetails(currentChat, currentChat?.msg?.fromCAIP10);
signatureValidationPubliKey = member ? member.publicKey : '';
Expand Down
7 changes: 7 additions & 0 deletions src/helpers/w2w/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,4 +168,11 @@ export const fetchInbox = async (connectedUser):Promise<Feeds[]>=> {
await intitializeDb<Feeds[]>('Insert', 'Inbox', walletToCAIP10({ account: connectedUser.wallets! }), inboxes, 'did');
inboxes = await w2wHelper.decryptFeeds({ feeds: inboxes, connectedUser: connectedUser });
return inboxes
};

export const fetchIntent = async (connectedUser): Promise<Feeds[]> => {
let intents = await PushAPI.chat.requests({account:connectedUser.wallets.split(':')[1],env:appConfig.appEnv, toDecrypt:false});
await intitializeDb<Feeds[]>('Insert', 'Intent', w2wHelper.walletToCAIP10({ account: connectedUser.wallets }),intents, 'did');
intents = await w2wHelper.decryptFeeds({ feeds: intents, connectedUser });
return intents;
};
34 changes: 30 additions & 4 deletions src/hooks/useSDKSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,30 @@ import { createSocketConnection, EVENTS } from '@pushprotocol/socket';
import { showNotifcationToast } from 'components/reusables/toasts/toastController';
import { VideoCallContext } from 'contexts/VideoCallContext';
import { convertAddressToAddrCaip } from '../helpers/CaipHelper';
import { ENV } from '@pushprotocol/restapi/src/lib/constants';


// Types
export type SDKSocketHookOptions = {
account?: string | null;
env?: string;
env?: ENV;
chainId?: number;
socketType?: 'chat' | 'notification',
};

export const useSDKSocket = ({ account, env, chainId }: SDKSocketHookOptions) => {
export const useSDKSocket = ({ account, env, chainId,socketType }: SDKSocketHookOptions) => {
const [epnsSDKSocket, setEpnsSDKSocket] = useState<any>(null);
const [isSDKSocketConnected, setIsSDKSocketConnected] = useState(epnsSDKSocket?.connected);
const [messagesSinceLastConnection, setMessagesSinceLastConnection] = useState<any>('');
const [groupInformationSinceLastConnection, setGroupInformationSinceLastConnection] = useState<any>('');
const { incomingCall, acceptCall } = useContext(VideoCallContext);

const addSocketEvents = () => {
epnsSDKSocket?.on(EVENTS.CONNECT, () => {
setIsSDKSocketConnected(true);
});

epnsSDKSocket?.on(EVENTS.DISCONNECT, () => {

setIsSDKSocketConnected(false);
});

Expand Down Expand Up @@ -55,12 +60,30 @@ export const useSDKSocket = ({ account, env, chainId }: SDKSocketHookOptions) =>
console.error('DAPP Error while diplaying received Notification: ', e);
}
});

epnsSDKSocket?.on(EVENTS.CHAT_RECEIVED_MESSAGE, (chat: any) => {
/**
* We receive a 1 message.
*/
setMessagesSinceLastConnection(chat);
});

//change this event name once sdk is published
epnsSDKSocket?.on(EVENTS.CHAT_GROUPS, (groupInfo: any) => {
/**
* We receive a group creation or updated event.
*/
console.log(groupInfo)
setGroupInformationSinceLastConnection(groupInfo);
});
};

const removeSocketEvents = () => {
epnsSDKSocket?.off(EVENTS.CONNECT);
epnsSDKSocket?.off(EVENTS.DISCONNECT);
epnsSDKSocket?.off(EVENTS.USER_FEEDS);
epnsSDKSocket?.off(EVENTS.CHAT_GROUPS);
epnsSDKSocket?.off(EVENTS.CHAT_RECEIVED_MESSAGE);
};

useEffect(() => {
Expand Down Expand Up @@ -88,7 +111,8 @@ export const useSDKSocket = ({ account, env, chainId }: SDKSocketHookOptions) =>

// this is auto-connect on instantiation
const connectionObject = createSocketConnection({
user: convertAddressToAddrCaip(account, chainId),
user: socketType == 'chat'?account:convertAddressToAddrCaip(account, chainId),
socketType,
env,
});
setEpnsSDKSocket(connectionObject);
Expand All @@ -98,5 +122,7 @@ export const useSDKSocket = ({ account, env, chainId }: SDKSocketHookOptions) =>
return {
epnsSDKSocket,
isSDKSocketConnected,
messagesSinceLastConnection,
groupInformationSinceLastConnection,
};
};
Loading

0 comments on commit 98462fe

Please sign in to comment.