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

Support chat class based #843

Merged
merged 8 commits into from
Nov 16, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
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
5 changes: 2 additions & 3 deletions packages/uiweb/src/lib/components/supportChat/AddressInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
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, userAlice } = 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 });
const user = await userAlice.info();
setUser(user);
};
getUser();
Expand Down
9 changes: 8 additions & 1 deletion 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 Down Expand Up @@ -47,6 +48,7 @@ export type ButtonStyleProps = {
const [toastType, setToastType] = useState<'error' | 'success'>();
const [chats, setChats] = useState<IMessageIPFS[]>([]);
const [accountadd, setAccount] = useState<string | null>(account)
pritipsingh marked this conversation as resolved.
Show resolved Hide resolved
const [userAlice, setUserAlice] = useState<PushAPI | null>(null);
const setChatsSorted = (chats: IMessageIPFS[]) => {
const uniqueChats = [
...new Map(chats.map((item) => [item['timestamp'], item])).values(),
Expand All @@ -58,14 +60,17 @@ export type ButtonStyleProps = {
setChats(uniqueChats);
};
const socketData = useSDKSocket({
account: account,
account: accountadd,
env,
apiKey,
userAlice
});

console.log("chanecing", socketData)
const chatPropsData = {
account : accountadd,
signer,
userAlice,
supportAddress,
greetingMsg,
modalTitle,
Expand All @@ -77,6 +82,8 @@ export type ButtonStyleProps = {
useEffect(() => {
(async () => {
if(signer) {
const userAlice = await PushAPI.initialize(signer, {env: env});
setUserAlice(userAlice)
if (!account) {
const address = await getAddressFromSigner(signer);
setAccount(address);
Expand Down
18 changes: 8 additions & 10 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, userAlice } =
useContext<any>(SupportChatPropsContext);

const {
Expand All @@ -40,15 +39,14 @@ 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 userAlice.chat.send(supportAddress ,{

type: 'Text',
content: message,

});
console.log(sendResponse);
pritipsingh marked this conversation as resolved.
Show resolved Hide resolved

if (typeof sendResponse !== 'string') {
sendResponse.messageContent = message;
Expand Down
42 changes: 31 additions & 11 deletions packages/uiweb/src/lib/components/supportChat/Chats.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import React, { useContext, useState } from 'react';
import styled from 'styled-components';
import { SupportChatMainStateContext, SupportChatPropsContext } from '../../context';
Expand Down Expand Up @@ -30,29 +31,48 @@ 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!);

let date;
let timestamp;

if (typeof msg.timestamp === "string") {
timestamp = parseInt(msg.timestamp);
}else{
timestamp = msg.timestamp
}
const time = new Date(timestamp!);

if (!isNaN(time.getTime())){

const time1 = time.toLocaleTimeString('en-US');
const date = time1.slice(0, -6) + time1.slice(-2);

date = time1.slice(0, -6) + time1.slice(-2);
}

pritipsingh marked this conversation as resolved.
Show resolved Hide resolved

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>
{console.log("woiiii" , msg.messageContent)}
<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}
{console.log("insideee",msg.message?.content)}
<TextMessage>{ msg.message?.content || msg.messageContent}</TextMessage>
{msg.timestamp !== undefined && <TimeStamp>{date}</TimeStamp>}
</ReceivedMessage>
</MessageWrapper>

)}
</>
) : // : msg.messageType === 'Image' ? (
Expand Down
46 changes: 34 additions & 12 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, userAlice, 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,19 +63,34 @@ 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,
userAlice,
pgpPrivateKey: connectedUser.privateKey,
supportAddress,
threadHash: lastThreadHashFetched!,
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, userAlice });
setConnectedUser(user);
setLoading(false);
} catch (err:any) {
Expand All @@ -105,22 +120,29 @@ 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]);

if (message && (supportAddress === pCAIP10ToWallet(message?.from))) {
// const chat = await decryptChat({ message, connectedUser, env });
// socketData.messagesSinceLastConnection.decrypted = true;

setChatsSorted([...chats, message]);
}
}

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

if(socketData.messagesSinceLastConnection){
getUpdatedChats(socketData.messagesSinceLastConnection);
}
}, [socketData.messagesSinceLastConnection]);

useEffect(() => {
getChatCall();
}, [connectedUser]);
}, [connectedUser, env, account,signer, supportAddress ]);

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

return (
<Container theme={theme}>
Expand Down
55 changes: 16 additions & 39 deletions packages/uiweb/src/lib/helpers/chat/chat.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as PushAPI from '@pushprotocol/restapi';
// import * as PushAPI from '@pushprotocol/restapi';
import type { ENV } from '../../config';
import { Constants } from '../../config';
import type {
Expand All @@ -12,15 +12,16 @@ import type { Env, IConnectedUser, IFeeds, IUser } from '@pushprotocol/restapi';
import { isPCAIP, pCAIP10ToWallet, walletToPCAIP10 } from '../address';
import { getData } from './localStorage';
import { ethers } from 'ethers';

import { PushAPI } from '@pushprotocol/restapi';
type HandleOnChatIconClickProps = {
isModalOpen: boolean;
setIsModalOpen: (isModalOpen: boolean) => void;
};

type GetChatsType = {
pgpPrivateKey: string;
pgpPrivateKey?: string;
supportAddress: string;
userAlice: PushAPI;
limit: number;
threadHash?: string;
env?: Env;
Expand All @@ -37,22 +38,12 @@ export const handleOnChatIconClick = ({
export const createUserIfNecessary = async (
options: AccountEnvOptionsType
): Promise<IConnectedUser> => {
const { account, signer, env = Constants.ENV.PROD } = options || {};
let connectedUser = await PushAPI.user.get({ account: account, env });
if (!connectedUser?.encryptedPrivateKey) {
connectedUser = await PushAPI.user.create({
account: account,
signer: signer,
env,
});
}
const decryptedPrivateKey = await PushAPI.chat.decryptPGPKey({
encryptedPGPPrivateKey: connectedUser.encryptedPrivateKey,
account,
signer,
env,
});
return { ...connectedUser, privateKey: decryptedPrivateKey };
const { account, signer, env = Constants.ENV.PROD, userAlice } = options || {};
const connectedUser = await userAlice.info();



return { ...connectedUser, privateKey: connectedUser.encryptedPrivateKey };
};

type GetChatsResponseType = {
Expand All @@ -68,35 +59,21 @@ export const getChats = async (
account,
pgpPrivateKey,
supportAddress,
userAlice,
threadHash = null,
limit = 40,
env = Constants.ENV.PROD,
} = options || {};
let threadhash: any = threadHash;
if (!threadhash) {
threadhash = await PushAPI.chat.conversationHash({
account: account,
conversationId: supportAddress,
env,
});
threadhash = threadhash.threadHash;
}


if (threadhash) {
const chats = await PushAPI.chat.history({
account: account,
pgpPrivateKey: pgpPrivateKey,
threadhash: threadhash,
toDecrypt: true,
limit: limit,
env,
});
const chats = await userAlice?.chat.history(
supportAddress
);

const lastThreadHash = chats[chats.length - 1]?.link;
const lastListPresent = chats.length > 0 ? true : false;
return { chatsResponse: chats, lastThreadHash, lastListPresent };
}
return { chatsResponse: [], lastThreadHash: null, lastListPresent: false };

};

type DecrypteChatType = {
Expand Down
Loading