Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Class sdk #1327

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"@pushprotocol/ledgerlive": "latest",
"@pushprotocol/restapi": "1.4.38",
"@pushprotocol/socket": "0.5.3",
"@pushprotocol/uiweb": "1.1.19",
"@pushprotocol/uiweb": "1.1.20",
"@reduxjs/toolkit": "^1.7.1",
"@testing-library/dom": "^9.0.1",
"@testing-library/jest-dom": "^4.2.4",
Expand Down
197 changes: 73 additions & 124 deletions src/components/chat/w2wChat/chatBox/ChatBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
import { ethers } from 'ethers';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

import { ChatViewList, MessageInput } from '@pushprotocol/uiweb';
// External Packages
import MuiAlert, { AlertProps } from '@mui/material/Alert';
import Snackbar from '@mui/material/Snackbar';
import * as PushAPI from '@pushprotocol/restapi';
import { VideoCallStatus } from '@pushprotocol/restapi';
import 'font-awesome/css/font-awesome.min.css';
import { CID } from 'ipfs-http-client';
import { BsDashLg } from 'react-icons/bs';
Expand Down Expand Up @@ -97,9 +97,9 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
const [isGroup, setIsGroup] = useState<boolean>(false);
const [showGroupInfo, setShowGroupInfo] = useState<boolean>(false);
const groupInfoRef = useRef<HTMLInputElement>(null);
const { connectedUser, setConnectedUser, createUserIfNecessary } = useContext(ChatUserContext);
const { connectedUser, setConnectedUser, createUserIfNecessary, pushUser } = useContext(ChatUserContext);
const { videoObject } = useContext(VideoCallContext);

const [chatId, setChatId] = useState("");
const listInnerRef = useRef<HTMLDivElement>(null);
const topRef = useRef<HTMLDivElement>(null);
const bottomRef = useRef<HTMLDivElement>(null);
Expand All @@ -114,6 +114,17 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {

useClickAway(groupInfoRef, () => setShowGroupInfo(false));


useEffect(() => {
if(currentChat?.groupInformation){
setChatId(currentChat?.groupInformation?.chatId)
}else{
setChatId(currentChat?.did);
}



},[currentChat])
//resolve web3 names
useResolveWeb3Name(!isGroup ? currentChat?.wallets?.split(',')[0].toString() : null);

Expand Down Expand Up @@ -174,38 +185,26 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
if (wasLastListPresentProp && !lastThreadHashFetchedProp) return;
setChatsLoading(true);
// scrollToNext();
const { chatsResponse, lastThreadHash, lastListPresent } = await getChats({
const { chatsResponse, lastListPresent } = await getChats({
account,
pgpPrivateKey: connectedUser.privateKey,
pushUser,
chatId: currentChat?.did || currentChat?.groupInformation?.chatId,
threadHash: lastThreadHashFetchedProp!,
limit: chatsFetchedLimit,
});

console.log("my chat" ,chatsResponse);
// remove this custom decryption after SDK issue is resolved in future
const promiseArrToDecryptMsg = [];
chatsResponse.forEach((chat) =>
promiseArrToDecryptMsg.push(
w2wHelper.decryptMessages({
savedMsg: chat,
connectedUser,
account,
currentChat,
inbox,
})
)
);
const decryptedMsgArr = await Promise.all(promiseArrToDecryptMsg);
decryptedMsgArr.sort((a, b) => {
return a.timestamp! > b.timestamp! ? 1 : -1;
});



setMessages([...decryptedMsgArr, ...messagesProp]);
setLastThreadHashFetched(lastThreadHash);
setMessages([...chatsResponse]);
// setLastThreadHashFetched(lastThreadHash);
setWasLastListPresent(lastListPresent);
setChatsLoading(false);
};



useEffect(() => {
setWasLastListPresent(false);
setLastThreadHashFetched(null);
Expand Down Expand Up @@ -240,8 +239,14 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
if (currentChat?.wallets) return caip10ToWallet(currentChat?.wallets?.split(',')[0].toString());
};

useEffect(() => {
const test = async () => {
console.log("my userr", await pushUser.chat.list("CHATS"))
}
test();
},[pushUser])
const fetchInboxApi = async (): Promise<Feeds> => {
const inboxes: Feeds[] = await fetchInbox({connectedUser});
const inboxes: Feeds[] = await fetchInbox({connectedUser, pushUser});
setInbox(inboxes);
return inboxes?.find((x) => x.wallets.split(':')[1]?.toLowerCase() === currentChat.wallets.split(':')[1]?.toLowerCase());
};
Expand All @@ -261,14 +266,11 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
createdUser = await createUserIfNecessary();
}
const signer = await provider.getSigner();
let receiverAddress= isGroup ? currentChat.groupInformation?.chatId : currentChat?.wallets

const sendResponse = await PushAPI.chat.send({
messageContent: message,
messageType: messageType,
receiverAddress: isGroup ? currentChat.groupInformation?.chatId : currentChat?.wallets,
signer: signer!,
pgpPrivateKey: connectedUser?.privateKey || createdUser?.privateKey,
env: appConfig.appEnv,
const sendResponse = await pushUser.chat.send(receiverAddress,{
content:message,
type: messageType,
});

if (typeof sendResponse !== 'string') {
Expand Down Expand Up @@ -313,11 +315,12 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
setLoading(true);
// If the user is not registered in the protocol yet, his did will be his wallet address
const didOrWallet: string = connectedUser.wallets.split(':')[1];
let intents = await PushAPI.chat.requests({ account: didOrWallet!, env: appConfig.appEnv, toDecrypt: true, pgpPrivateKey:connectedUser.privateKey });
let intents = await pushUser.chat.list('REQUESTS')
setReceivedIntents(intents);
setLoading(false);
}

console.log("requestsss" , receivedIntents);
async function ApproveIntent(status: string): Promise<void> {
setMessageBeingSent(true);
let updatedIntent: any;
Expand All @@ -326,14 +329,9 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
if (!connectedUser.publicKey) {
createdUser = await createUserIfNecessary();
}
const signer = await provider.getSigner();
updatedIntent = await PushAPI.chat.approve({
status: 'Approved',
signer: signer!,
senderAddress: isGroup ? currentChat.groupInformation?.chatId : currentChat.intentSentBy,
pgpPrivateKey: connectedUser?.privateKey || createdUser?.privateKey,
env: appConfig.appEnv,
});
let senderAddress= isGroup ? currentChat.groupInformation?.chatId : currentChat.intentSentBy,

updatedIntent = await pushUser.chat.accept(senderAddress);

let activeChat = currentChat;
activeChat.intent = updatedIntent.data;
Expand Down Expand Up @@ -388,24 +386,22 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
!currentChat.intent?.toLowerCase().includes(currentChat.wallets.split(':')[1]?.toLowerCase())
) {
let createdUser;
if (!connectedUser.publicKey) {
if (!connectedUser.privateKey) {
createdUser = await createUserIfNecessary();
}
const signer = await provider.getSigner();
const sendResponse = await PushAPI.chat.send({
messageContent: message,
messageType: messageType,
receiverAddress: currentChat?.wallets.split(':')[1],
signer: signer!,
pgpPrivateKey: connectedUser.privateKey || createdUser?.privateKey,
env: appConfig.appEnv,
let receiverAddress= currentChat?.wallets.split(':')[1]

const sendResponse = await pushUser.chat.send(receiverAddress,{
content: message,
type: messageType,
});

if (typeof sendResponse !== 'string') {
// We store the message in state decrypted so we display to the user the intent message
sendResponse.messageContent = message;
setNewMessage('');
let result = await fetchInboxApi();
console.log("newww", result)
result.msg.messageContent = message;
setChat(result);
chatBoxToast.showMessageToast({
Expand Down Expand Up @@ -457,7 +453,7 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
return produce(oldData, (draft) => {
draft.local.address = account;
draft.incoming[0].address = caip10ToWallet(currentChat.wallets.toString());
draft.incoming[0].status = PushAPI.VideoCallStatus.INITIALIZED;
draft.incoming[0].status = VideoCallStatus.INITIALIZED;
draft.meta.chatId = currentChat.chatId;
});
});
Expand Down Expand Up @@ -645,87 +641,33 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
>
{/* style={{overflow: "scroll",backgroundColor:'red'}} */}
{/* <CustomScrollContent initialScrollBehavior="smooth"> */}
{Loading ? (
<SpinnerWrapper>
<LoaderSpinner
type={LOADER_TYPE.SEAMLESS}
spinnerSize={40}
/>
</SpinnerWrapper>
) : (
<>
{chatsLoading && (
<SpinnerWrapper height="35px">
<LoaderSpinner
type={LOADER_TYPE.SEAMLESS}
spinnerSize={40}
/>
</SpinnerWrapper>
)}
<>
<div ref={topRef}>
{messages?.map((msg, i) => {
//const isLast = i === messages.length - 1
//const noTail = !isLast && messages[i + 1]?.fromDID === msg.fromDID

showTime = false;
if (i >= 0) {
const duration = new Date(messages[i]?.timestamp);
const dateString = duration.toDateString();
if (dateString !== time || i === 0) {
showTime = true;
time = dateString;
}
}
return (
<div key={i}>
{!showTime ? null : (
<HeaderMessage
index={i}
time={time}
isGroup={isGroup}
/>
)}
<Chats
msg={
(!currentChat?.groupInformation?.isPublic && checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser, isGroup }))
? ''
: msg
}
caip10={walletToCAIP10({ account: account! })}
messageBeingSent={messageBeingSent}
isGroup={isGroup}
/>

</div>
);
})}
<ChatViewList chatId={chatId} limit={10}/>

</div>
<HeaderMessage
messages={messages}
isGroup={isGroup}
/>

{checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser, isGroup }) && (
<Chats
msg={{
...messages[0],
messageContent: getIntentMessage(currentChat, isGroup),
messageType: 'Intent',
}}
caip10={walletToCAIP10({ account: account! })}
messageBeingSent={messageBeingSent}
ApproveIntent={() => ApproveIntent('Approved')}
isGroup={isGroup}
/>
<ChatViewList chatId={chatId} limit={10}/>
)}
</>
)}

{/* </CustomScrollContent> */}
<div ref={bottomRef}></div>
</MessageContainer>

{checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser,isGroup }) ? null : (
{checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser,isGroup }) ?
<MessageInputWrapper >
<MessageInput chatId={chatId} />
</MessageInputWrapper>
: (
<>
<Typebar

<MessageInputWrapper >
<MessageInput chatId={chatId} />
</MessageInputWrapper>

{/* <Typebar
messageBeingSent={messageBeingSent}
setNewMessage={setNewMessage}
newMessage={newMessage}
Expand All @@ -736,7 +678,7 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => {
setSnackbarText={setSnackbarText}
isJoinGroup = {(!checkIfChatExist({ chats:inbox, currentChat, connectedUser,isGroup }) && isGroup)}
approveIntent= {ApproveIntent}
/>
/> */}
</>
)}
</>
Expand All @@ -751,6 +693,13 @@ const SpinnerWrapper = styled.div`
height: ${(props) => props.height || '90px'};
`;

const MessageInputWrapper = styled.div`
margin-top: auto;
margin-botton: 0;
width: 100%;
z-index: 99;
`

const MessageContainer = styled(ItemVV2)`
align-items: unset;
display: block;
Expand Down
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 @@ -7,7 +7,7 @@ import { TwitterTweetEmbed } from 'react-twitter-embed';
import styled from 'styled-components';

// Internal Components
import * as PushAPI from '@pushprotocol/restapi';
import {PushAPI} from '@pushprotocol/restapi';
import LoaderSpinner, { LOADER_TYPE } from 'components/reusables/loaders/LoaderSpinner';
import { ImageV2, ItemHV2, ItemVV2, SpanV2 } from 'components/reusables/SharedStylingV2';
import { shortenText } from 'helpers/UtilityHelper';
Expand Down Expand Up @@ -35,9 +35,10 @@ interface ChatProps {
messageBeingSent: boolean;
ApproveIntent?: Function;
isGroup?: boolean;
pushUser: PushAPI;
}

export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, isGroup }: ChatProps) {
export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, isGroup, pushUser }: ChatProps) {
const { currentChat }: ContextType = useContext<ContextType>(Context);
const { web3NameList }: AppContextType = useContext(AppContext);
const [showImageModal, setShowImageModal] = useState<boolean>(false);
Expand All @@ -63,8 +64,8 @@ export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, is
setProfilePicture(member.image);
} else {
// console.log(msg)
let user = await PushAPI.user.get({ account: msg.fromCAIP10, env: appConfig.appEnv });
setProfilePicture(user.profilePicture);
let user = await pushUser.info();
setProfilePicture(user.profile.picture);
}
};

Expand Down
Loading
Loading