Skip to content

Commit

Permalink
Support chat class based (#843)
Browse files Browse the repository at this point in the history
* fix: changes-suppport chat

* fix: new stream added

* fix: removed unn consolelogs

* fix: requested changed

* fix: fixed minor issues

* fix: socket connection

* fix: timestamp helper created, removed extra code

* fix: changed userAlice to pushUser

---------

Co-authored-by: Monalisha Mishra <[email protected]>
  • Loading branch information
pritipsingh and mishramonalisha76 authored Nov 16, 2023
1 parent 61979e5 commit b364cee
Show file tree
Hide file tree
Showing 10 changed files with 212 additions and 128 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export const ChatSupportTest = () => {
<SupportChat

signer={librarySigner}
supportAddress="0x6F7919412318E65109c5698bd0E640fc33DE2337"
supportAddress="0x99A08ac6254dcf7ccc37CeC662aeba8eFA666666"
apiKey="tAWEnggQ9Z.UaDBNjrvlJZx3giBTIQDcT8bKQo1O1518uF1Tea7rPwfzXv2ouV5rX9ViwgJUrXm"
env={env}
greetingMsg="How can i help you?"
Expand Down
10 changes: 6 additions & 4 deletions packages/uiweb/src/lib/components/supportChat/AddressInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
import React, { useContext, useEffect, useState } from 'react';
import styled from 'styled-components';
import { SupportChatPropsContext } from '../../context';
import * as PushAPI from '@pushprotocol/restapi';
import { Constants } from '../../config';
import { copyToClipboard, pCAIP10ToWallet } from '../../helpers';
import { CopySvg } from '../../icons/CopySvg';

export const AddressInfo: React.FC = () => {
const { supportAddress, env, theme } = useContext<any>(SupportChatPropsContext);
const { supportAddress, env, theme, pushUser } = useContext<any>(SupportChatPropsContext);
const [ensName, setEnsName] = useState<string>('');
const [user, setUser] = useState<any>({});
const [isCopied, setIsCopied] = useState<boolean>(false);
const walletAddress = pCAIP10ToWallet(supportAddress);

useEffect(() => {
const getUser = async () => {
const user = await PushAPI.user.get({ account: walletAddress, env });
if(pushUser){
const user = await pushUser.info();
setUser(user);
}

};
getUser();
}, [supportAddress]);
}, [supportAddress, pushUser]);

return (
<Container theme={theme}>
Expand Down
41 changes: 36 additions & 5 deletions packages/uiweb/src/lib/components/supportChat/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useEffect, useState } from 'react';
import { PushAPI } from '@pushprotocol/restapi';
import { ChatIcon } from '../../icons/ChatIcon';
import { Modal } from './Modal';
import styled from 'styled-components';
Expand All @@ -14,6 +15,7 @@ import { Constants, lightTheme } from '../../config';
import { useSDKSocket } from '../../hooks/useSDKSocket';
import { Div } from '../reusables/sharedStyling';
import { getAddressFromSigner } from '../../helpers';
import { sign } from 'crypto';
export type ChatProps = {
account?: string;
signer: SignerType;
Expand Down Expand Up @@ -46,26 +48,39 @@ export type ButtonStyleProps = {
const [toastMessage, setToastMessage] = useState<string>('');
const [toastType, setToastType] = useState<'error' | 'success'>();
const [chats, setChats] = useState<IMessageIPFS[]>([]);
const [accountadd, setAccount] = useState<string | null>(account)
const [accountadd, setAccountadd] = useState<string | null>(account)
const [pushUser, setPushUser] = useState<PushAPI | null>(null);
const setChatsSorted = (chats: IMessageIPFS[]) => {

const chatsWithNumericTimestamps = chats.map(item => ({
...item,
timestamp: typeof item.timestamp === 'string' ? parseInt(item.timestamp) : item.timestamp
}));

const uniqueChats = [
...new Map(chats.map((item) => [item['timestamp'], item])).values(),
...new Map(chatsWithNumericTimestamps.map((item) => [item.timestamp, item])).values(),
];

uniqueChats.sort((a, b) => {

return a.timestamp! > b.timestamp! ? 1 : -1;
});
setChats(uniqueChats);
};
const socketData = useSDKSocket({
account: account,
account: accountadd,
env,
apiKey,
pushUser: pushUser!,
supportAddress,
signer
});


const chatPropsData = {
account : accountadd,
signer,
pushUser,
supportAddress,
greetingMsg,
modalTitle,
Expand All @@ -74,21 +89,37 @@ export type ButtonStyleProps = {
env,
};



useEffect(() => {
(async () => {
if(signer) {
if (!account) {
const address = await getAddressFromSigner(signer);
setAccount(address);
setAccountadd(address);

}
else{
setAccount(account);
setAccountadd(account);

}

}
})();
},[signer])

useEffect(() => {
(
async() =>{
if(Object.keys(signer || {}).length && accountadd){
const pushUser = await PushAPI.initialize(signer!, {env: env , account:accountadd!});
setPushUser(pushUser)
}
}
)()

},[signer, accountadd])

useEffect(() => {
setChats([]);
setConnectedUser(null);
Expand Down
31 changes: 18 additions & 13 deletions packages/uiweb/src/lib/components/supportChat/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { SendIconSvg } from '../../icons/SendIconSvg';
import SmileyIcon from '../../icons/smiley.svg';
import AttachmentIcon from '../../icons/attachment.svg';
import styled from 'styled-components';
import * as PushAPI from '@pushprotocol/restapi';
import { SupportChatMainStateContext, SupportChatPropsContext } from '../../context';
import { Spinner } from './spinner/Spinner';
// import Picker from 'emoji-picker-react';
Expand All @@ -14,7 +13,7 @@ export const ChatInput: React.FC = () => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [filesUploading, setFileUploading] = useState<boolean>(false);
const [loading, setLoading] = useState<boolean>(false);
const { account, env, supportAddress, apiKey, theme } =
const { account, env, supportAddress, apiKey, theme, pushUser } =
useContext<any>(SupportChatPropsContext);

const {
Expand All @@ -40,22 +39,28 @@ export const ChatInput: React.FC = () => {
e.preventDefault();
setLoading(true);
if (message.trim() !== '' && connectedUser) {
const sendResponse = await PushAPI.chat.send({
messageContent: message,
messageType: 'Text',
receiverAddress: supportAddress,
account: account,
pgpPrivateKey: connectedUser?.privateKey,
apiKey,
env,

const sendResponse = await pushUser.chat.send(supportAddress ,{

type: 'Text',
content: message,

});

if (!sendResponse) {
setToastMessage(sendResponse);
setToastType('error');
setLoading(false);

}

if (typeof sendResponse !== 'string') {
sendResponse.messageContent = message;
setChatsSorted([...chats, sendResponse]);
// sendResponse.messageContent = message;
// setChatsSorted([...chats, sendResponse]);
setMessage('');
setLoading(false);
} else {
}
else {
setToastMessage(sendResponse);
setToastType('error');
setLoading(false);
Expand Down
32 changes: 20 additions & 12 deletions packages/uiweb/src/lib/components/supportChat/Chats.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@

import React, { useContext, useState } from 'react';
import styled from 'styled-components';
import { SupportChatMainStateContext, SupportChatPropsContext } from '../../context';
import type { IMessageIPFS } from '../../types';
import { formatTime } from '../../helpers/timestamp';

type ChatsPropType = {
msg: IMessageIPFS;
Expand Down Expand Up @@ -30,29 +32,35 @@ export const Chats: React.FC<ChatsPropType> = ({
const { connectedUser } = useContext<any>(SupportChatMainStateContext);
const [showImageModal, setShowImageModal] = useState<boolean>(false);
const [imageUrl, setImageUrl] = useState<string>('');
const time: Date = new Date(msg.timestamp!);
const time1 = time.toLocaleTimeString('en-US');
const date = time1.slice(0, -6) + time1.slice(-2);


const date = formatTime(msg.timestamp)



return (
<Container>
<>
{msg.messageType === 'Text' ? (
{msg.messageType === 'Text' || msg.message?.type ? (
<>
{msg.fromCAIP10 === caip10 ? (
{(msg.fromCAIP10 === caip10 || msg.from === caip10 ) ? (
<MessageWrapper align="row-reverse">
<SenderMessage theme={theme}>
<TextMessage>{msg.messageContent}</TextMessage>

<TextMessage>{msg.messageContent || msg.message?.content}</TextMessage>
{msg.timestamp !== undefined && <TimeStamp>{date}</TimeStamp>}
</SenderMessage>
</MessageWrapper>
) : (
<MessageWrapper align="row">
<ReceivedMessage theme={theme}>
{msg?.icon && msg.icon}
<TextMessage>{msg.messageContent}</TextMessage>
{msg.timestamp !== undefined && <TimeStamp>{date}</TimeStamp>}
</ReceivedMessage>
</MessageWrapper>
<ReceivedMessage theme={theme}>
{msg?.icon && msg.icon}

<TextMessage>{ msg.message?.content || msg.messageContent}</TextMessage>
{msg.timestamp !== undefined && <TimeStamp>{date}</TimeStamp>}
</ReceivedMessage>
</MessageWrapper>

)}
</>
) : // : msg.messageType === 'Image' ? (
Expand Down
53 changes: 35 additions & 18 deletions packages/uiweb/src/lib/components/supportChat/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const Modal: React.FC = () => {
string | null
>(null);
const [wasLastListPresent, setWasLastListPresent] = useState<boolean>(false);
const { supportAddress, env, account, signer, greetingMsg, theme } =
const { supportAddress, pushUser, env, account, signer, greetingMsg, theme } =
useContext<any>(SupportChatPropsContext);
const {
chats,
Expand All @@ -42,7 +42,7 @@ export const Modal: React.FC = () => {
setToastType,
socketData
} = useContext<any>(SupportChatMainStateContext);
const listInnerRef = useChatScroll(chats.length);
const listInnerRef = useChatScroll(0);

const greetingMsgObject = {
fromDID: walletToPCAIP10(supportAddress),
Expand All @@ -63,20 +63,35 @@ export const Modal: React.FC = () => {
if (listInnerRef.current) {
const { scrollTop } = listInnerRef.current;
if (scrollTop === 0) {
// This will be triggered after hitting the first element.
// pagination
const content = listInnerRef.current;
const curScrollPos = content.scrollTop;
const oldScroll = content.scrollHeight - content.clientHeight;

getChatCall();

const newScroll = content.scrollHeight - content.clientHeight;
content.scrollTop = curScrollPos + (newScroll - oldScroll);
}
}
};
const scrollToBottom = () => {
setTimeout(()=>{
if (listInnerRef.current) {
listInnerRef.current.scrollTop = listInnerRef.current.scrollHeight +100;

}
},0)

};

const getChatCall = async () => {
if (!connectedUser) return;
if (wasLastListPresent && !lastThreadHashFetched) return;
setLoading(true);
const { chatsResponse, lastThreadHash, lastListPresent } = await getChats({
account,
pgpPrivateKey: connectedUser.privateKey,
pushUser,
// pgpPrivateKey: connectedUser.privateKey,
supportAddress,
threadHash: lastThreadHashFetched!,
limit: chatsFetchedLimit,
Expand All @@ -94,7 +109,7 @@ export const Modal: React.FC = () => {
if (!socketData.epnsSDKSocket?.connected) {
socketData.epnsSDKSocket?.connect();
}
const user = await createUserIfNecessary({ account, signer, env });
const user = await createUserIfNecessary({ account, signer, env, pushUser });
setConnectedUser(user);
setLoading(false);
} catch (err:any) {
Expand All @@ -104,23 +119,25 @@ export const Modal: React.FC = () => {
}
};

const getUpdatedChats = async (message:IMessageIPFS) =>{
if (message && (supportAddress === pCAIP10ToWallet(message?.fromCAIP10))) {
const chat = await decryptChat({ message, connectedUser, env });
socketData.messagesSinceLastConnection.decrypted = true;
setChatsSorted([...chats, chat]);
}
}


useEffect(() => {
if(socketData.messagesSinceLastConnection && !socketData.messagesSinceLastConnection.decrypted){
getUpdatedChats(socketData.messagesSinceLastConnection);
}

if(socketData.messagesSinceLastConnection){
const message: IMessageIPFS = socketData.messagesSinceLastConnection
if (message ) {
setChatsSorted([...chats, message]);
}}
}, [socketData.messagesSinceLastConnection]);

useEffect(() => {

getChatCall();
}, [connectedUser]);
}, [connectedUser, env, account,signer, supportAddress, pushUser]);

useEffect(() => {
scrollToBottom();
}, [connectedUser, env, account, socketData]);


return (
<Container theme={theme}>
Expand Down
Loading

0 comments on commit b364cee

Please sign in to comment.