From 3af1ca5ff395ed1935fb0962927568ba6009acc9 Mon Sep 17 00:00:00 2001 From: KlausMikhaelson Date: Thu, 16 Nov 2023 05:54:51 -0600 Subject: [PATCH 1/6] feat: changed all the old apis in chat to class component ones --- .husky/pre-commit | 2 +- .../src/app/ChatUITest/ChatViewComponent.tsx | 6 +- .../chat/ChatViewBubble/ChatViewBubble.tsx | 13 +- .../ChatViewList/ApproveRequestBubble.tsx | 10 +- .../chat/ChatViewList/ChatViewList.tsx | 150 +++++++++--------- .../chat/ConnectButton/ConnectButton.tsx | 31 +++- .../chat/MessageInput/MessageInput.tsx | 41 ++--- packages/uiweb/src/lib/context/chatContext.ts | 8 +- .../lib/dataProviders/ChatDataProvider.tsx | 54 ++----- packages/uiweb/src/lib/helpers/chat/chat.ts | 13 +- packages/uiweb/src/lib/helpers/timestamp.ts | 15 ++ .../lib/hooks/chat/useApproveChatRequest.ts | 13 +- .../uiweb/src/lib/hooks/chat/useFetchChat.ts | 20 +-- .../lib/hooks/chat/useFetchHistoryMessages.ts | 29 ++-- .../src/lib/hooks/chat/usePushChatSocket.ts | 134 ++++++++-------- .../src/lib/hooks/chat/usePushSendMessage.ts | 22 ++- .../uiweb/src/lib/hooks/useGetChatProfile.ts | 33 ++-- packages/uiweb/yarn.lock | 23 +++ 18 files changed, 320 insertions(+), 297 deletions(-) create mode 100644 packages/uiweb/src/lib/helpers/timestamp.ts diff --git a/.husky/pre-commit b/.husky/pre-commit index 8a79c3470..2665d0376 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -4,4 +4,4 @@ echo "\nRunning GIT hooks..." yarn cleanbuild yarn nx affected --target=lint -#yarn nx affected --target=test \ No newline at end of file +yarn nx affected --target=test \ No newline at end of file diff --git a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx index 93b49170c..82e854cce 100644 --- a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx +++ b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx @@ -13,13 +13,13 @@ const ChatViewComponentTest = () => { return (

Chat UI Test page

- {console.log('in close')}} /> + {/* {console.log('in close')}} /> */} - {console.log('in close')}} modalBackground={MODAL_BACKGROUND_TYPE.OVERLAY} modalPositionType={MODAL_POSITION_TYPE.RELATIVE}/> + {/* {console.log('in close')}} modalBackground={MODAL_BACKGROUND_TYPE.OVERLAY} modalPositionType={MODAL_POSITION_TYPE.RELATIVE}/> */} console.log("BOIIII RETURNNNSSSSS")} - chatId='4ac5ab85c9c3d57adbdf2dba79357e56b2f9ef0256befe750d9f93af78d2ca68' + chatId='a5dad31b20c9aaf761221b57f6f0ab96b03a456525159378388e896475b1f943' limit={10} isConnected={true} groupInfoModalBackground={MODAL_BACKGROUND_TYPE.OVERLAY} diff --git a/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx b/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx index e7a672dbb..55973f0d7 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx @@ -25,13 +25,14 @@ import { pCAIP10ToWallet, shortenText, } from '../../../helpers'; +import { formatTime } from '../../../helpers/timestamp'; const SenderMessageAddress = ({ chat }: { chat: IMessagePayload }) => { const { account } = useContext(ChatDataContext); const theme = useContext(ThemeContext); return ( <> - {chat.fromCAIP10.split(':')[1] !== account && ( + {(chat.fromDID).split(':')[1] !== account && ( { const [pfp, setPfp] = useState(''); const getUserPfp = async () => { const pfp = await getPfp({ - account: chat.fromCAIP10.split(':')[1], + account: chat.fromDID.split(':')[1], env: env, }); if (pfp) { @@ -62,10 +63,10 @@ const SenderMessageProfilePicture = ({ chat }: { chat: IMessagePayload }) => { }; useEffect(() => { getUserPfp(); - }, [account, chat.fromCAIP10]); + }, [account, chat.fromDID]); return (
- {chat.fromCAIP10.split(':')[1] !== account && ( + {(chat.fromDID || chat.fromDID).split(':')[1] !== account && (
{pfp && ( { const theme = useContext(ThemeContext); - const time = moment(chat.timestamp).format('hh:mm a'); + const time = formatTime(chat.timestamp) return (
(false); useEffect(() => { - if (decryptedMessagePayload.toDID.split(':')[0] === 'eip155') { + if ((decryptedMessagePayload.toDID).split(':')[0] === 'eip155') { if (isGroup) { setIsGroup(false); } diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx index 140d7abc5..e7f488a0d 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx @@ -26,7 +26,7 @@ export const ApproveRequestBubble = ({ chatId, setChatFeed, }: IApproveRequestBubbleProps) => { - const { pgpPrivateKey } = useChatData(); + const { pgpPrivateKey, alias } = useChatData(); const ApproveRequestText = { GROUP: `You were invited to the group ${chatFeed?.groupInformation?.groupName}. Please accept to continue messaging in this group.`, @@ -39,13 +39,7 @@ export const ApproveRequestBubble = ({ const handleApproveChatRequest = async () => { try { - if (!pgpPrivateKey) { - return; - } - - const response = await approveChatRequest({ - chatId, - }); + const response = await alias.chat.accept(chatId); if (response) { const updatedChatFeed = { ...(chatFeed as IFeeds) }; updatedChatFeed.intent = response; diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx index 451df1678..a6662cfb9 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx @@ -33,6 +33,7 @@ import useGetGroup from '../../../hooks/chat/useGetGroup'; import useGetChatProfile from '../../../hooks/useGetChatProfile'; import useFetchChat from '../../../hooks/chat/useFetchChat'; import { ApproveRequestBubble } from './ApproveRequestBubble'; +import { formatTime } from '../../../helpers/timestamp'; /** * @interface IThemeProps @@ -51,7 +52,7 @@ export const ChatViewList: React.FC = ( options: IChatViewListProps ) => { const { chatId, limit = chatLimit, chatFilterList = [] } = options || {}; - const { pgpPrivateKey, account, connectedProfile, setConnectedProfile } = + const { pgpPrivateKey, account, connectedProfile, setConnectedProfile, signer, alias, setAlias } = useChatData(); const [chatFeed, setChatFeed] = useState({} as IFeeds); const [chatStatusText, setChatStatusText] = useState(''); @@ -76,15 +77,6 @@ export const ChatViewList: React.FC = ( setChatStatusText(''); }, [chatId, account, env]); - useEffect(() => { - (async () => { - if (!connectedProfile && account) { - const user = await fetchChatProfile({ profileId: account!, env }); - if (user) setConnectedProfile(user); - } - })(); - }, [account]); - useEffect(() => { setMessages(undefined); setConversationHash(undefined); @@ -93,44 +85,49 @@ export const ChatViewList: React.FC = ( //need to make a common method for fetching chatFeed to ruse in messageInput useEffect(() => { (async () => { - if (!account && !env) return; - const chat = await fetchChat({ chatId }); - if (Object.keys(chat || {}).length) { - setConversationHash(chat?.threadhash as string); - setChatFeed(chat as IFeeds); - } - else { - let newChatFeed; - let group; - const result = await getNewChatUser({ - searchText: chatId, - fetchChatProfile, - env, - }); - if (result) { - newChatFeed = getDefaultFeedObject({ user: result }); + if (alias) { + // console.log('chatss'); + // console.log(account, env, 'chatss') + const chat = await fetchChat(); + // console.log(chat, 'chatss calling main', alias) + if (chat) { + setConversationHash(chat?.threadhash as string); + setChatFeed(chat as IFeeds); } else { - group = await getGroup({ searchText: chatId }); - if (group) { - newChatFeed = getDefaultFeedObject({ groupInformation: group }); + console.log('chatss calling elsez') + let newChatFeed; + let group; + const result = await getNewChatUser({ + searchText: chatId, + fetchChatProfile, + env, + }); + if (result) { + newChatFeed = getDefaultFeedObject({ user: result }); + } else { + group = await getGroup({ searchText: chatId }); + if (group) { + newChatFeed = getDefaultFeedObject({ groupInformation: group }); + } } - } - if (newChatFeed) { - if (!newChatFeed?.groupInformation) { - setChatStatusText(ChatStatus.FIRST_CHAT); + if (newChatFeed) { + if (!newChatFeed?.groupInformation) { + setChatStatusText(ChatStatus.FIRST_CHAT); + } + setConversationHash(newChatFeed.threadhash as string); + setChatFeed(newChatFeed); + } else { + setChatStatusText(ChatStatus.INVALID_CHAT); } - setConversationHash(newChatFeed.threadhash as string); - setChatFeed(newChatFeed); - } else { - setChatStatusText(ChatStatus.INVALID_CHAT); } + setLoading(false); } - setLoading(false); })(); - }, [chatId, pgpPrivateKey, account, env]); + }, [chatId, pgpPrivateKey, account, env, alias]); //moniters socket changes useEffect(() => { + console.log('messagesSinceLastConnection', account, messagesSinceLastConnection, checkIfSameChat(messagesSinceLastConnection, account!, chatId)) if (checkIfSameChat(messagesSinceLastConnection, account!, chatId)) { const updatedChatFeed = chatFeed; updatedChatFeed.msg = messagesSinceLastConnection; @@ -138,9 +135,10 @@ export const ChatViewList: React.FC = ( setFilteredMessages([ messagesSinceLastConnection, ] as IMessageIPFSWithCID[]); - + setConversationHash(messagesSinceLastConnection.cid); } else { + console.log('messagesSinceLastConnection in group') const newChatViewList = appendUniqueMessages( messages as Messagetype, [messagesSinceLastConnection], @@ -168,12 +166,12 @@ export const ChatViewList: React.FC = ( }, [groupInformationSinceLastConnection]); useEffect(() => { - if (conversationHash) { + // if (conversationHash) { (async function () { await getMessagesCall(); })(); - } - }, [conversationHash, pgpPrivateKey, account, env,chatFeed]); + // } + }, [conversationHash, pgpPrivateKey, account, env, chatFeed, alias]); useEffect(() => { scrollToBottom(); @@ -191,10 +189,11 @@ export const ChatViewList: React.FC = ( } }, [messages]); - useEffect(()=>{ + console.log('chatHistory') - if(chatFeed && !chatFeed?.groupInformation?.isPublic && account) - { + useEffect(() => { + + if (chatFeed && !chatFeed?.groupInformation?.isPublic && account) { chatFeed?.groupInformation?.members.forEach((acc) => { if ( acc.wallet.toLowerCase() === walletToPCAIP10(account!).toLowerCase() @@ -203,17 +202,17 @@ export const ChatViewList: React.FC = ( } }); } - },[account,chatFeed]) + }, [account, chatFeed]) //methods const scrollToBottom = () => { - setTimeout(()=>{ + setTimeout(() => { if (listInnerRef.current) { - listInnerRef.current.scrollTop = listInnerRef.current.scrollHeight +100; + listInnerRef.current.scrollTop = listInnerRef.current.scrollHeight + 100; } - },0) - + }, 0) + }; const onScroll = async () => { @@ -233,23 +232,17 @@ export const ChatViewList: React.FC = ( }; const getMessagesCall = async () => { - let threadHash = null; - if (!messages) { - threadHash = conversationHash; - } else { - threadHash = messages?.lastThreadHash; - } - - if ( - threadHash && - ((account && pgpPrivateKey&& chatFeed && !chatFeed?.groupInformation) || - (chatFeed && chatFeed?.groupInformation)) - ) { - - const chatHistory = await historyMessages({ - limit: limit, - threadHash, - }); + // if (!messages) { + // threadHash = conversationHash; + // } else { + // threadHash = messages?.lastThreadHash; + // } + + if (alias && chatId) { + console.log('chatHistory') + + const chatHistory = await historyMessages({chatId}); + console.log(chatHistory, 'chatHistory') if (chatHistory?.length) { if (Object.keys(messages || {}) && messages?.messages.length) { const newChatViewList = appendUniqueMessages( @@ -279,7 +272,7 @@ export const ChatViewList: React.FC = ( } }; - const ifBlurChat = () =>{ + const ifBlurChat = () => { return !!( chatFeed && chatFeed?.groupInformation && @@ -293,7 +286,7 @@ export const ChatViewList: React.FC = ( dateNum: string; }; const renderDate = ({ chat, dateNum }: RenderDataType) => { - const timestampDate = dateToFromNowDaily(chat.timestamp as number); + const timestampDate = formatTime(chat.timestamp); dates.add(dateNum); return ( = ( {!loading && ( <> {chatFeed && - (chatFeed.publicKey || - (chatFeed?.groupInformation && - !chatFeed?.groupInformation?.isPublic)) ? ( + (chatFeed.publicKey || + (chatFeed?.groupInformation && + !chatFeed?.groupInformation?.isPublic)) ? ( ) : ( = ( {messages?.messages && messages?.messages?.map( (chat: IMessageIPFS, index: number) => { - const dateNum = moment(chat.timestamp).format('L'); + const dateNum = formatTime(chat.timestamp); const position = pCAIP10ToWallet(chat.fromDID).toLowerCase() !== - account?.toLowerCase() + account?.toLowerCase() ? 0 : 1; return ( <> {dates.has(dateNum) ? null - : renderDate({ chat, dateNum })} + : dateNum ? renderDate({ chat, dateNum }) : null}
= ( {chatFeed && account && checkIfIntent({ - chat: chatFeed as IFeeds, + chat: chatFeed as any, account: account!, }) && ( = ( }; //styles -const ChatViewListCard = styled(Section)` +const ChatViewListCard = styled(Section) ` &::-webkit-scrollbar-thumb { background: ${(props) => props.theme.scrollbarColor}; border-radius: 10px; @@ -425,4 +418,3 @@ const ChatViewListCard = styled(Section)` overscroll-behavior: contain; scroll-behavior: smooth; `; - diff --git a/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx b/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx index 45aa9c3ba..4710c941e 100644 --- a/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx +++ b/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx @@ -1,11 +1,13 @@ import { useContext, useEffect, useState } from 'react'; import styled from 'styled-components'; -import { ethers } from 'ethers'; +import { Signer, ethers } from 'ethers'; import { useAccount, useChatData } from '../../../hooks'; import { ThemeContext } from '../theme/ThemeProvider'; - +import useGetChatProfile from '../../../hooks/useGetChatProfile'; +import useCreateChatProfile from '../../../hooks/useCreateChatProfile'; +import useDecryptPGPKey from '../../../hooks/useDecryptPGPKey'; import { getAddressFromSigner } from '../../../helpers'; import { IChatTheme } from '../theme'; @@ -18,17 +20,27 @@ import { device } from '../../../config'; interface IThemeProps { theme?: IChatTheme; } - +interface IConnectButtonProps { + autoConnect?: boolean; +} export const ConnectButtonSub = ({autoConnect = false}) => { const {wallet, connecting , connect, disconnect} = useAccount(); const { signer, + pgpPrivateKey, + account, + env, + setPgpPrivateKey, setAccount, setSigner, + alias, + setAlias } = useChatData(); const theme = useContext(ThemeContext); + const {fetchChatProfile} = useGetChatProfile(); + const {decryptPGPKey} = useDecryptPGPKey(); const setUserData = () => { @@ -43,6 +55,7 @@ export const ConnectButtonSub = ({autoConnect = false}) => { } else if (!wallet) { setAccount('') setSigner(undefined) + setPgpPrivateKey(null) } } useEffect(() => { @@ -51,6 +64,18 @@ export const ConnectButtonSub = ({autoConnect = false}) => { setUserData() }, [wallet]) + useEffect(() => { + (async () => { + if (!alias && signer) { + const user = await fetchChatProfile({signer: signer, env}); + console.log("calllingggg in connect button") + if (user) { + setAlias(user); + } + } + })(); + }, [alias, signer]); + return !signer ? ( diff --git a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx index 7a38fed61..2766ce75e 100644 --- a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx +++ b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx @@ -119,6 +119,8 @@ export const MessageInput: React.FC = ({ setConnectedProfile, pgpPrivateKey, signer, + alias, + setAlias } = useChatData(); const { fetchChat } = useFetchChat(); const { fetchChatProfile } = useGetChatProfile(); @@ -145,12 +147,13 @@ export const MessageInput: React.FC = ({ //need to do something about fetching connectedUser in every component useEffect(() => { (async () => { - if (!connectedProfile && account) { - const user = await fetchChatProfile({ profileId: account!, env }); - if (user) setConnectedProfile(user); + if (!alias && signer) { + const user = await fetchChatProfile({ signer: signer, env }); + console.log("calllingggg in message input") + if (user) setAlias(user); } })(); - }, [account]); + }, [alias]); useEffect(() => { const storedTimestampJSON = localStorage.getItem(chatId); @@ -183,6 +186,7 @@ export const MessageInput: React.FC = ({ setChatFeed(updateChatFeed); } } + console.log(chatFeed) }, [groupInformationSinceLastConnection]); useEffect(() => { @@ -201,7 +205,7 @@ export const MessageInput: React.FC = ({ (async () => { if (!account && !env) return; if (account && env) { - const chat = await fetchChat({ chatId }); + const chat = await fetchChat(); if (Object.keys(chat || {}).length) setChatFeed(chat as IFeeds); else { let newChatFeed; @@ -225,17 +229,19 @@ export const MessageInput: React.FC = ({ } } })(); - }, [chatId, pgpPrivateKey, account, env]); + }, [chatId, pgpPrivateKey, account, env, alias]); useEffect(() => { console.log('in useEffect') + console.log(((isRules ? verified : true) && isMember) || + (chatFeed && !chatFeed?.groupInformation), "letsseee") console.log(chatFeed) if (!account && !env && !chatId) return; if (account && env && chatId && chatFeed && chatFeed?.groupInformation) { setIsMember(checkIfMember(chatFeed, account)); setIsRules(checkIfAccessVerifiedGroup(chatFeed)); } - }, [chatId, chatFeed, account, env]); + }, [chatId, chatFeed, account, env, alias]); console.log(isMember) console.log(checkIfMember(chatFeed, account!)) const addEmoji = (emojiData: EmojiClickData, event: MouseEvent): void => { @@ -255,9 +261,7 @@ console.log(checkIfMember(chatFeed, account!)) const handleJoinGroup = async () => { if (chatFeed && chatFeed?.groupInformation?.isPublic) { - const response = await approveChatRequest({ - chatId, - }); + const response = await alias.chat.accept(chatId); if (response) { await updateChatFeed(); } @@ -332,11 +336,11 @@ console.log(checkIfMember(chatFeed, account!)) }; const isJoinGroup = () => { - return !!pgpPrivateKey && !isMember; + return !isMember; }; const isNotVerified = () => { - return !!pgpPrivateKey && !verified && isMember && isRules; + return !verified && isMember && isRules; }; const sendPushMessage = async (content: string, type: string) => { @@ -374,7 +378,7 @@ console.log(checkIfMember(chatFeed, account!)) const updateChatFeed = async () => { - const chat = await fetchChat({ chatId }); + const chat = await fetchChat(); if (Object.keys(chat || {}).length) { @@ -382,7 +386,7 @@ console.log(checkIfMember(chatFeed, account!)) } }; - return !(pgpPrivateKey && account) && isConnected ? ( + return !(account) && isConnected ? ( - ) : !checkIfIntent({ chat: chatFeed, account: account! }) && + ) : + // !checkIfIntent({ chat: chatFeed, account: account! }) && Object.keys(chatFeed || {}).length ? (
)} - {!!pgpPrivateKey && !verificationSuccessfull && ( + {!verificationSuccessfull && (
) : null} - {!!pgpPrivateKey && + { (((isRules ? verified : true) && isMember) || (chatFeed && !chatFeed?.groupInformation)) && ( <> -
+
{emoji && (
>; connectedProfile: IUser | undefined; setConnectedProfile: (connectedProfile: IUser) => void; + alias: any; + setAlias: React.Dispatch>; } export const initialChatDataContextValues: IChatDataContextValues = { @@ -48,7 +50,11 @@ export const initialChatDataContextValues: IChatDataContextValues = { connectedProfile: undefined, setConnectedProfile: () => { /** */ - } + }, + alias: null, + setAlias: () => { + /** */ + }, } diff --git a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx index a6f969222..243815fcc 100644 --- a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx +++ b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx @@ -9,8 +9,6 @@ import useGetChatProfile from '../hooks/useGetChatProfile'; import { IUser, SignerType } from '@pushprotocol/restapi'; import { IChatTheme, lightChatTheme } from '../components/chat/theme'; import { getAddressFromSigner, pCAIP10ToWallet } from '../helpers'; -import useCreateChatProfile from '../hooks/useCreateChatProfile'; -import useDecryptPGPKey from '../hooks/useDecryptPGPKey'; export interface IChatUIProviderProps { @@ -33,6 +31,7 @@ export const ChatUIProvider = ({ const [accountVal, setAccountVal] = useState(pCAIP10ToWallet(account!)); const [pushChatSocket, setPushChatSocket] = useState(null); const [signerVal, setSignerVal] = useState(signer); + const [alias, setAlias] = useState(null); const [pgpPrivateKeyVal, setPgpPrivateKeyVal] = useState(pgpPrivateKey); @@ -42,8 +41,6 @@ export const ChatUIProvider = ({ const [isPushChatSocketConnected, setIsPushChatSocketConnected] = useState(false); - const {createChatProfile} = useCreateChatProfile(); - const {decryptPGPKey} = useDecryptPGPKey(); useEffect(() => { (async()=>{ @@ -63,40 +60,9 @@ export const ChatUIProvider = ({ setPgpPrivateKeyVal(pgpPrivateKey); })() - }, [env,account,signer,pgpPrivateKey]) + }, [env,account, alias,signer]) - useEffect(() => { - (async () => { - if (accountVal && signerVal) { - if (!pgpPrivateKeyVal) await handleUserCreation(); - } - })(); - }, [accountVal, signerVal]); - - - const handleUserCreation = async () => { - if (!accountVal && !envVal) return; - try { - let user = await fetchChatProfile({ profileId: accountVal! ,env:envVal}); - if (!user) { - if (!signerVal) return; - user = await createChatProfile({ signer: signerVal ,env:envVal}); - } - if (user?.encryptedPrivateKey && !pgpPrivateKey) { - const decryptedPgpKey = await decryptPGPKey({ - encryptedPrivateKey: user.encryptedPrivateKey, - account: accountVal!, - signer: signerVal, - env: envVal, - }); - if(decryptedPgpKey) - setPgpPrivateKeyVal(decryptedPgpKey); - } - } catch (e: any) { - console.log(e); - } - }; @@ -111,12 +77,14 @@ const resetStates = () => { useEffect(() => { (async () => { let user; - if (account) { - user = await fetchChatProfile({ profileId: account,env }); - if (user) setConnectedProfile(user); + if (!alias && signer) { + console.log("userrr",user); + if (user) { + setAlias(user); + } } })(); - }, [account,env,pgpPrivateKey]); + }, [env, signer, alias]); const value: IChatDataContextValues = { account: accountVal, @@ -132,7 +100,9 @@ useEffect(() => { isPushChatSocketConnected, setIsPushChatSocketConnected, connectedProfile, - setConnectedProfile + setConnectedProfile, + alias, + setAlias }; @@ -144,4 +114,4 @@ useEffect(() => { ); -}; +}; \ No newline at end of file diff --git a/packages/uiweb/src/lib/helpers/chat/chat.ts b/packages/uiweb/src/lib/helpers/chat/chat.ts index 81c4ade7d..a2237d374 100644 --- a/packages/uiweb/src/lib/helpers/chat/chat.ts +++ b/packages/uiweb/src/lib/helpers/chat/chat.ts @@ -1,7 +1,7 @@ import * as PushAPI from '@pushprotocol/restapi'; import type { ENV } from '../../config'; import { Constants } from '../../config'; -import type { +import type { AccountEnvOptionsType, IGroup, IMessageIPFS, @@ -179,6 +179,7 @@ export const checkIfIntent = ({ chat, account, }: CheckIfIntentType): boolean => { + console.log(chat, account, 'checkIfIntent'); if (account) { if ( Object.keys(chat || {}).length && @@ -253,19 +254,19 @@ export const checkIfSameChat = ( chatId = walletToPCAIP10(chatId); if ( Object.keys(msg || {}).length && - (((chatId.toLowerCase() === msg.fromCAIP10?.toLowerCase()) && + (((chatId.toLowerCase() === (msg.fromDID?.toLowerCase())) && ( walletToPCAIP10(account!).toLowerCase() === - msg.toCAIP10?.toLowerCase())) || - ((chatId.toLowerCase() === msg.toCAIP10?.toLowerCase()) && + msg.toDID?.toLowerCase())) || + ((chatId.toLowerCase() === (msg.toDID?.toLowerCase())) && (walletToPCAIP10(account!).toLowerCase() === - msg.fromCAIP10?.toLowerCase()))) + msg.fromDID?.toLowerCase()))) ) { return true; } } else { if ( Object.keys(msg || {}).length && - (chatId.toLowerCase() === msg.toCAIP10?.toLowerCase()) + (chatId.toLowerCase() === msg.toDID?.toLowerCase()) ) { return true; } diff --git a/packages/uiweb/src/lib/helpers/timestamp.ts b/packages/uiweb/src/lib/helpers/timestamp.ts new file mode 100644 index 000000000..79f45065f --- /dev/null +++ b/packages/uiweb/src/lib/helpers/timestamp.ts @@ -0,0 +1,15 @@ +export const formatTime = (timestamp : any) => { + let date; +let timestamp1; + if (typeof timestamp === "string") { + timestamp1 = parseInt(timestamp ); + }else{ + timestamp1 = timestamp + } + const time = new Date(timestamp1!); + if (!isNaN(time.getTime())){ + const time1 = time.toLocaleTimeString('en-US'); + date = time1.slice(0, -6) + time1.slice(-2); + } + return date; +} \ No newline at end of file diff --git a/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts b/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts index 676705a7f..67e360503 100644 --- a/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts +++ b/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts @@ -9,7 +9,7 @@ interface ApproveChatParams { const useApproveChatRequest = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey,signer } =useChatData(); + const { account, env,pgpPrivateKey,signer, alias } =useChatData(); const approveChatRequest = useCallback(async (options:ApproveChatParams) => { const { @@ -17,14 +17,7 @@ const useApproveChatRequest = () => { } = options || {}; setLoading(true); try { - const response = await PushAPI.chat.approve({ - status: 'Approved', - account: account, - senderAddress: chatId, - signer:signer, // receiver's address or chatId of a group - pgpPrivateKey:pgpPrivateKey, - env: env, - }); + const response = await alias.chat.accept(chatId); setLoading(false); return response; } catch (error: Error | any) { @@ -35,7 +28,7 @@ const useApproveChatRequest = () => { } }, - [account,env,signer,pgpPrivateKey] + [account,env,signer,alias] ); diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts index d1bbd06dc..718c2143a 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts @@ -5,26 +5,22 @@ import { useChatData } from './useChatData'; interface fetchChat { - chatId: string; + chatId?: string; } const useFetchChat = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey } = useChatData(); + const { account, env,pgpPrivateKey, alias } = useChatData(); const fetchChat = useCallback( - async ({ chatId}: fetchChat) => { + async () => { setLoading(true); try { - const chat = await PushAPI.chat.chat({ - account: account? account : '0xeeE5A266D7cD954bE3Eb99062172E7071E664023', - toDecrypt: pgpPrivateKey ? true : false, - pgpPrivateKey: String(pgpPrivateKey), - recipient: chatId, - env: env - }); + console.log("chatss calling in hook before", alias); + const chat = await alias.chat.list("CHATS") + console.log('chatss in hook', chat); return chat; } catch (error: Error | any) { setLoading(false); @@ -36,10 +32,10 @@ const useFetchChat = () => { setLoading(false); } }, - [pgpPrivateKey,env,account] + [pgpPrivateKey,env,account, alias] ); return { fetchChat, error, loading }; }; -export default useFetchChat; +export default useFetchChat; \ No newline at end of file diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts index 0082622f9..5a6d49ec3 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts @@ -9,7 +9,7 @@ import { useChatData } from './useChatData'; interface HistoryMessagesParams { - threadHash: string; + chatId?: string; limit?: number; } @@ -19,20 +19,23 @@ const useFetchHistoryMessages const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey } = useChatData(); + const { account, env,pgpPrivateKey, alias } = useChatData(); - const historyMessages = useCallback(async ({threadHash,limit = 10,}:HistoryMessagesParams) => { + const historyMessages = useCallback(async ({chatId}: HistoryMessagesParams) => { setLoading(true); try { - const chatHistory:IMessageIPFS[] = await PushAPI.chat.history({ - threadhash: threadHash, - account:account ? account : '0xeeE5A266D7cD954bE3Eb99062172E7071E664023', - toDecrypt: pgpPrivateKey ? true : false, - pgpPrivateKey: String(pgpPrivateKey), - limit: limit, - env: env - }); + // const chatHistory:IMessageIPFS[] = await PushAPI.chat.history({ + // threadhash: threadHash, + // account:account ? account : '0xeeE5A266D7cD954bE3Eb99062172E7071E664023', + // toDecrypt: pgpPrivateKey ? true : false, + // pgpPrivateKey: String(pgpPrivateKey), + // limit: limit, + // env: env + // }); + console.log(alias, "chatHistoryyy") + const chatHistory = await alias.chat.history(chatId) + console.log(chatHistory, "chatHistoryyy") chatHistory.reverse(); return chatHistory; } catch (error: Error | any) { @@ -43,9 +46,9 @@ const useFetchHistoryMessages } finally { setLoading(false); } - }, [pgpPrivateKey,account,env]); + }, [pgpPrivateKey,account,env, alias]); return { historyMessages, error, loading }; }; -export default useFetchHistoryMessages; +export default useFetchHistoryMessages; \ No newline at end of file diff --git a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts index 91d8a737c..0d8759eb2 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts @@ -1,11 +1,10 @@ import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; import { useCallback, useEffect, useState } from 'react'; import { ENV } from '../../config'; -import * as PushAPI from '@pushprotocol/restapi'; - import { useChatData } from './useChatData'; import { SOCKET_TYPE } from '../../types'; import useGetChatProfile from '../useGetChatProfile'; +import { CONSTANTS } from '@pushprotocol/restapi'; export type PushChatSocketHookOptions = { account?: string | null; @@ -23,95 +22,93 @@ export const usePushChatSocket = () => { connectedProfile, setConnectedProfile, env, + alias } = useChatData(); -const {fetchChatProfile} = useGetChatProfile(); const [messagesSinceLastConnection, setMessagesSinceLastConnection] = useState({}); - const [acceptedRequestMessage, setAcceptedRequestMessage] = + const [acceptedRequestMessage, setAcceptedRequestMessage] = useState({}); + const [stream, setStream] = useState(); const [ groupInformationSinceLastConnection, setGroupInformationSinceLastConnection, ] = useState({}); - // useEffect(() => { - // // console.log(pgpPrivateKey, "pgppppppppp") - // // console.log(connectedProfile, "connectedProfileeeeeeeee") - // }, [pgpPrivateKey, connectedProfile]) - - const addSocketEvents = useCallback(() => { + const addSocketEvents = useCallback(async () => { console.log('addSocketEvents'); - pushChatSocket?.on(EVENTS.CONNECT, () => { + // if (!stre/z + stream.on(CONSTANTS.STREAM.CONNECT, () => { + // console.log(err,"errr"); + // console.log(connected,"connected");÷ + console.log('connecteddddd'); setIsPushChatSocketConnected(true); - }); + }) - pushChatSocket?.on(EVENTS.DISCONNECT, (reason: string) => { + stream.on(CONSTANTS.STREAM.DISCONNECT, (reason: string) => { setIsPushChatSocketConnected(false); }); - pushChatSocket?.on(EVENTS.CHAT_RECEIVED_MESSAGE, async (chat: any) => { - - - if (!connectedProfile || !pgpPrivateKey) { - return; - } + stream.on(CONSTANTS.STREAM.CHAT, async (chat: any) => { + console.log('chat', chat); if ( - ( chat.messageCategory === 'Request') && + (chat.messageCategory === 'Request') && (chat.messageContent === null) && (chat.messageType === null) ) { setAcceptedRequestMessage(chat); - } - else - { - const response = await PushAPI.chat.decryptConversation({ - messages: [chat], - connectedUser: connectedProfile, - pgpPrivateKey: pgpPrivateKey, - env: env, + } else { + // Extract 'from' and 'to' from the 'message' property + const fromDID = chat.from; + const toDID = chat.to.join(', '); // Use the appropriate separator if needed + // Create a new object with modified properties + const messageContent = chat.message.content; + const modifiedChat = { + ...chat, + fromDID: fromDID, + toDID: toDID, + messageContent: messageContent, + }; + delete modifiedChat.from; + delete modifiedChat.to; + console.log('modifiedChat', modifiedChat); + + setMessagesSinceLastConnection((chats: any) => { + return modifiedChat; }); - - if (response && response.length) { - setMessagesSinceLastConnection(response[0]); - } } - - }); - pushChatSocket?.on(EVENTS.CHAT_GROUPS, (groupInfo: any) => { - /** - * We receive a group creation or updated event. - */ - setGroupInformationSinceLastConnection(groupInfo); }); + + // pushChatSocket?.on(EVENTS.CHAT_GROUPS, (groupInfo: any) => { + // /** + // * We receive a group creation or updated event. + // */ + // setGroupInformationSinceLastConnection(groupInfo); + // }); + // eslint-disable-next-line react-hooks/exhaustive-deps }, [ - pushChatSocket, - account, - pgpPrivateKey, messagesSinceLastConnection, env, - connectedProfile, + alias, + stream ]); const removeSocketEvents = useCallback(() => { - pushChatSocket?.off(EVENTS.CONNECT); - pushChatSocket?.off(EVENTS.DISCONNECT); - pushChatSocket?.off(EVENTS.CHAT_GROUPS); - pushChatSocket?.off(EVENTS.CHAT_RECEIVED_MESSAGE); - }, [pushChatSocket]); + stream?.disconnect(); + }, [stream]); useEffect(() => { - if (pushChatSocket) { + if (stream) { addSocketEvents(); } return () => { - if (pushChatSocket) { + if (stream) { removeSocketEvents(); } }; - }, [pushChatSocket, pgpPrivateKey, connectedProfile]); + }, [stream, alias]); /** * Whenever the required params to create a connection object change @@ -119,30 +116,27 @@ const {fetchChatProfile} = useGetChatProfile(); * - create a new connection object */ useEffect(() => { - if (account) { - if (pushChatSocket && pushChatSocket.connected) { - // pushChatSocket?.disconnect(); - } else { - const main = async () => { - const connectionObject = createSocketConnection({ - user: account, - env, - socketType: SOCKET_TYPE.CHAT, - socketOptions: { autoConnect: true, reconnectionAttempts: 3 }, - }); - console.warn('new connection object: ', connectionObject); - - setPushChatSocket(connectionObject); - }; - main().catch((err) => console.error(err)); - } + if (!stream) { + const main = async () => { + + const stream = await alias.initStream( + [ + CONSTANTS.STREAM.CHAT, + ], + {} + ); + setStream(stream); + await stream.connect(); + console.warn('new connection object: ', stream); + }; + main().catch((err) => console.error(err)); } + // } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [account, env, pgpPrivateKey]); + }, [alias, env, stream]); return { - pushChatSocket, isPushChatSocketConnected, messagesSinceLastConnection, acceptedRequestMessage, diff --git a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts index 4c4ff6173..099f3ee5d 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts @@ -11,42 +11,38 @@ interface SendMessageParams { messageType?: 'Text' | 'Image' | 'File' | 'GIF' | 'MediaEmbed'; } -const usePushSendMessage = () => { +const usePushSendMessage = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { pgpPrivateKey, env, account } = useChatData(); + const { pgpPrivateKey, env, account, alias } = useChatData(); const sendMessage = useCallback( async (options: SendMessageParams) => { const { chatId, message, messageType } = options || {}; setLoading(true); try { - const response = await PushAPI.chat.send({ - messageContent: message, - messageType: messageType, - receiverAddress: chatId, - account: account ? account : undefined, - pgpPrivateKey: pgpPrivateKey ? pgpPrivateKey : undefined, - env: env, - }); + const response = await alias.chat.send(chatId, { + type: messageType, + content: message, + }) setLoading(false); if (!response) { return false; } return response; } catch (error: Error | any) { - + setLoading(false); setError(error.message); console.log(error); return error.message; } }, - [pgpPrivateKey, account,env] + [pgpPrivateKey, account, env, alias] ); return { sendMessage, error, loading }; }; -export default usePushSendMessage; +export default usePushSendMessage; \ No newline at end of file diff --git a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts index 8937a7026..e7359a99f 100644 --- a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts +++ b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts @@ -1,26 +1,35 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import { useCallback, useContext } from 'react'; +import { PushAPI, Env } from '@pushprotocol/restapi'; +import { useCallback, useContext, useEffect } from 'react'; import { ChatAndNotificationPropsContext } from '../context'; +import { useChatData } from './chat'; +import { SignerType } from '../types'; export interface GetProfileParams { - profileId: string; - env:PushAPI.Env + profileId?: string; + env: Env, + signer: SignerType } const useGetChatProfile = () => { + const { signer, alias, setAlias, setConnectedProfile } = useChatData(); + const fetchChatProfile = useCallback( async ({ profileId, + signer, env - }: GetProfileParams): Promise => { + }: GetProfileParams): Promise => { try { - const profile = await PushAPI.user.get({ - env: env, - account: profileId, - }); - return profile; + console.log('signerrr', signer); + console.log("env", env) + const userAlice = await PushAPI.initialize( + signer!, + { + env: env + }); + return userAlice; } catch (error) { - console.log(error); + console.log("errr", error); return; } }, @@ -30,4 +39,4 @@ const useGetChatProfile = () => { return { fetchChatProfile }; }; -export default useGetChatProfile; +export default useGetChatProfile; \ No newline at end of file diff --git a/packages/uiweb/yarn.lock b/packages/uiweb/yarn.lock index d714d5fff..4d3ac82a3 100644 --- a/packages/uiweb/yarn.lock +++ b/packages/uiweb/yarn.lock @@ -3618,6 +3618,11 @@ node-gyp-build@^4.2.0, node-gyp-build@^4.3.0: resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.6.1.tgz#24b6d075e5e391b8d5539d98c7fc5c210cac8a3e" integrity sha512-24vnklJmyRS8ViBNI8KbtK/r/DmXQMRiOMXTNz2nrTnAYUwjmEEbnnpB/+kt+yWRv73bPsSPRFddrcIbAxSiMQ== +normalize-wheel@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/normalize-wheel/-/normalize-wheel-1.0.1.tgz#aec886affdb045070d856447df62ecf86146ec45" + integrity sha512-1OnlAPZ3zgrk8B91HyRj+eVv+kS5u+Z0SCsak6Xil/kmgEia50ga7zfkumayonZrImffAxPU/5WcyGhzetHNPA== + object-inspect@^1.9.0: version "1.12.3" resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9" @@ -3816,11 +3821,24 @@ randombytes@^2.1.0: dependencies: safe-buffer "^5.1.0" +react-easy-crop@^4.1.4: + version "4.7.5" + resolved "https://registry.yarnpkg.com/react-easy-crop/-/react-easy-crop-4.7.5.tgz#1526827fc83e38b079372310f983bc0517ba6442" + integrity sha512-qKfI4PuhaH1jOLC3DQfQB0cE0z+3N7bfyPkPejQmylXNb8nstfPMH+oHj3gKgpBHLFUiQp/C1rY7sVCVgtjn3Q== + dependencies: + normalize-wheel "^1.0.1" + tslib "2.0.1" + react-icons@^4.10.1: version "4.10.1" resolved "https://registry.yarnpkg.com/react-icons/-/react-icons-4.10.1.tgz#3f3b5eec1f63c1796f6a26174a1091ca6437a500" integrity sha512-/ngzDP/77tlCfqthiiGNZeYFACw85fUjZtLbedmJ5DTlNDIwETxhwBzdOJ21zj4iJdvc0J3y7yOsX3PpxAJzrw== +react-image-file-resizer@^0.4.7: + version "0.4.8" + resolved "https://registry.yarnpkg.com/react-image-file-resizer/-/react-image-file-resizer-0.4.8.tgz#85f4ae4469fd2867d961568af660ef403d7a79af" + integrity sha512-Ue7CfKnSlsfJ//SKzxNMz8avDgDSpWQDOnTKOp/GNRFJv4dO9L5YGHNEnj40peWkXXAK2OK0eRIoXhOYpUzUTQ== + react-property@2.0.0: version "2.0.0" resolved "https://registry.npmjs.org/react-property/-/react-property-2.0.0.tgz" @@ -4214,6 +4232,11 @@ tslib@1.14.1, tslib@^1.9.0: resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== +tslib@2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.0.1.tgz#410eb0d113e5b6356490eec749603725b021b43e" + integrity sha512-SgIkNheinmEBgx1IUNirK0TUD4X9yjjBRTqqjggWCU3pUEqIk3/Uwl3yRixYKT6WjQuGiwDv4NomL3wqRCj+CQ== + tslib@^2.0.0, tslib@^2.1.0, tslib@^2.3.0: version "2.5.0" resolved "https://registry.npmjs.org/tslib/-/tslib-2.5.0.tgz" From 5db0221ee9ba05c4c54ebf2d5d8838e70a701e3d Mon Sep 17 00:00:00 2001 From: KlausMikhaelson Date: Thu, 16 Nov 2023 06:06:04 -0600 Subject: [PATCH 2/6] fix: reverted type change --- packages/uiweb/src/lib/hooks/useGetChatProfile.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts index e7359a99f..269786eeb 100644 --- a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts +++ b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts @@ -18,7 +18,7 @@ const useGetChatProfile = () => { profileId, signer, env - }: GetProfileParams): Promise => { + }: GetProfileParams): Promise => { try { console.log('signerrr', signer); console.log("env", env) From 1d49e23482afa8235f5ecec54735513f9c39da91 Mon Sep 17 00:00:00 2001 From: KlausMikhaelson Date: Thu, 16 Nov 2023 07:03:51 -0600 Subject: [PATCH 3/6] fix: removed unnecessary code --- .../ChatViewList/ApproveRequestBubble.tsx | 2 +- .../chat/ChatViewList/ChatViewList.tsx | 12 ++++++------ .../chat/ConnectButton/ConnectButton.tsx | 3 --- .../chat/MessageInput/MessageInput.tsx | 19 +++++-------------- packages/uiweb/src/lib/context/chatContext.ts | 6 ------ .../lib/dataProviders/ChatDataProvider.tsx | 7 ------- packages/uiweb/src/lib/helpers/chat/chat.ts | 12 ++++++------ .../uiweb/src/lib/hooks/chat/useFetchChat.ts | 4 ++-- .../lib/hooks/chat/useFetchHistoryMessages.ts | 4 ++-- .../src/lib/hooks/chat/usePushChatSocket.ts | 1 - .../src/lib/hooks/chat/usePushSendMessage.ts | 4 ++-- 11 files changed, 24 insertions(+), 50 deletions(-) diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx index e7f488a0d..b8a8510e3 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ApproveRequestBubble.tsx @@ -26,7 +26,7 @@ export const ApproveRequestBubble = ({ chatId, setChatFeed, }: IApproveRequestBubbleProps) => { - const { pgpPrivateKey, alias } = useChatData(); + const { alias } = useChatData(); const ApproveRequestText = { GROUP: `You were invited to the group ${chatFeed?.groupInformation?.groupName}. Please accept to continue messaging in this group.`, diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx index a6662cfb9..3c398cf42 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx @@ -52,7 +52,7 @@ export const ChatViewList: React.FC = ( options: IChatViewListProps ) => { const { chatId, limit = chatLimit, chatFilterList = [] } = options || {}; - const { pgpPrivateKey, account, connectedProfile, setConnectedProfile, signer, alias, setAlias } = + const { account, connectedProfile, setConnectedProfile, signer, alias, setAlias } = useChatData(); const [chatFeed, setChatFeed] = useState({} as IFeeds); const [chatStatusText, setChatStatusText] = useState(''); @@ -80,7 +80,7 @@ export const ChatViewList: React.FC = ( useEffect(() => { setMessages(undefined); setConversationHash(undefined); - }, [chatId, account, pgpPrivateKey, env]); + }, [chatId, account, env]); //need to make a common method for fetching chatFeed to ruse in messageInput useEffect(() => { @@ -123,7 +123,7 @@ export const ChatViewList: React.FC = ( setLoading(false); } })(); - }, [chatId, pgpPrivateKey, account, env, alias]); + }, [chatId, account, env, alias]); //moniters socket changes useEffect(() => { @@ -171,7 +171,7 @@ export const ChatViewList: React.FC = ( await getMessagesCall(); })(); // } - }, [conversationHash, pgpPrivateKey, account, env, chatFeed, alias]); + }, [conversationHash, account, env, chatFeed, alias]); useEffect(() => { scrollToBottom(); @@ -277,7 +277,7 @@ export const ChatViewList: React.FC = ( chatFeed && chatFeed?.groupInformation && !chatFeed?.groupInformation?.isPublic && - ((!isMember && pgpPrivateKey) || (!pgpPrivateKey)) + (!isMember) ); } @@ -383,7 +383,7 @@ export const ChatViewList: React.FC = ( {chatFeed && account && checkIfIntent({ - chat: chatFeed as any, + chat: chatFeed, account: account!, }) && ( { const { signer, - pgpPrivateKey, account, env, - setPgpPrivateKey, setAccount, setSigner, alias, @@ -55,7 +53,6 @@ export const ConnectButtonSub = ({autoConnect = false}) => { } else if (!wallet) { setAccount('') setSigner(undefined) - setPgpPrivateKey(null) } } useEffect(() => { diff --git a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx index 2766ce75e..5b4a63bef 100644 --- a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx +++ b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx @@ -115,9 +115,6 @@ export const MessageInput: React.FC = ({ const { account, env, - connectedProfile, - setConnectedProfile, - pgpPrivateKey, signer, alias, setAlias @@ -229,21 +226,15 @@ export const MessageInput: React.FC = ({ } } })(); - }, [chatId, pgpPrivateKey, account, env, alias]); + }, [chatId, account, env, alias]); useEffect(() => { - console.log('in useEffect') - console.log(((isRules ? verified : true) && isMember) || - (chatFeed && !chatFeed?.groupInformation), "letsseee") - console.log(chatFeed) if (!account && !env && !chatId) return; if (account && env && chatId && chatFeed && chatFeed?.groupInformation) { setIsMember(checkIfMember(chatFeed, account)); setIsRules(checkIfAccessVerifiedGroup(chatFeed)); } }, [chatId, chatFeed, account, env, alias]); -console.log(isMember) -console.log(checkIfMember(chatFeed, account!)) const addEmoji = (emojiData: EmojiClickData, event: MouseEvent): void => { setTypedMessage(typedMessage + emojiData.emoji); setShowEmojis(false); @@ -392,7 +383,7 @@ console.log(checkIfMember(chatFeed, account!)) overflow="hidden" borderRadius="13px" position="static" - padding={` ${pgpPrivateKey ? '13px 16px' : ''}`} + padding={'13px 16px'} background={`${theme.backgroundColor?.messageInputBackground}`} alignItems="center" justifyContent="space-between" @@ -400,7 +391,7 @@ console.log(checkIfMember(chatFeed, account!)) ) : - // !checkIfIntent({ chat: chatFeed, account: account! }) && + !checkIfIntent({ chat: chatFeed, account: account! }) && Object.keys(chatFeed || {}).length ? ( -
+
{emoji && (
>; - pgpPrivateKey: string | null; - setPgpPrivateKey: React.Dispatch>; signer: SignerType | undefined; setSigner: React.Dispatch>; env: Env; @@ -31,10 +29,6 @@ export const initialChatDataContextValues: IChatDataContextValues = { setSigner: () => { /**/ }, - pgpPrivateKey: '', - setPgpPrivateKey: () => { - /**/ - }, env: Constants.ENV.PROD, setEnv: () => { /**/ diff --git a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx index 243815fcc..4088397a8 100644 --- a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx +++ b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx @@ -24,7 +24,6 @@ export const ChatUIProvider = ({ children, account = null, theme, - pgpPrivateKey = null, signer = undefined, env = Constants.ENV.PROD, }: IChatUIProviderProps) => { @@ -32,9 +31,6 @@ export const ChatUIProvider = ({ const [pushChatSocket, setPushChatSocket] = useState(null); const [signerVal, setSignerVal] = useState(signer); const [alias, setAlias] = useState(null); - - const [pgpPrivateKeyVal, setPgpPrivateKeyVal] = - useState(pgpPrivateKey); const [envVal, setEnvVal] = useState(env); const {fetchChatProfile} = useGetChatProfile(); const [connectedProfile,setConnectedProfile]=useState(undefined); @@ -57,7 +53,6 @@ export const ChatUIProvider = ({ } } setSignerVal(signer); - setPgpPrivateKeyVal(pgpPrivateKey); })() }, [env,account, alias,signer]) @@ -91,8 +86,6 @@ useEffect(() => { signer:signerVal, setSigner:setSignerVal, setAccount: setAccountVal, - pgpPrivateKey: pgpPrivateKeyVal, - setPgpPrivateKey: setPgpPrivateKeyVal, env: envVal, setEnv: setEnvVal, pushChatSocket, diff --git a/packages/uiweb/src/lib/helpers/chat/chat.ts b/packages/uiweb/src/lib/helpers/chat/chat.ts index a2237d374..94cb249ea 100644 --- a/packages/uiweb/src/lib/helpers/chat/chat.ts +++ b/packages/uiweb/src/lib/helpers/chat/chat.ts @@ -172,24 +172,24 @@ export const getDefaultFeedObject = ({ }; type CheckIfIntentType = { - chat: IFeeds; + chat: any; account: string; }; export const checkIfIntent = ({ chat, account, }: CheckIfIntentType): boolean => { - console.log(chat, account, 'checkIfIntent'); + const ChatObject = chat[0]; if (account) { if ( - Object.keys(chat || {}).length && - chat.combinedDID + Object.keys(ChatObject || {}).length && + ChatObject.combinedDID .toLowerCase() .includes(walletToPCAIP10(account).toLowerCase()) ) { if ( - chat.intent && - chat.intent + ChatObject.intent && + ChatObject.intent .toLowerCase() .includes(walletToPCAIP10(account).toLowerCase()) ) diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts index 718c2143a..b90424bf4 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts @@ -11,7 +11,7 @@ interface fetchChat { const useFetchChat = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey, alias } = useChatData(); + const { account, env, alias } = useChatData(); const fetchChat = useCallback( @@ -32,7 +32,7 @@ const useFetchChat = () => { setLoading(false); } }, - [pgpPrivateKey,env,account, alias] + [env,account, alias] ); return { fetchChat, error, loading }; diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts index 5a6d49ec3..9a7b049a7 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts @@ -19,7 +19,7 @@ const useFetchHistoryMessages const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey, alias } = useChatData(); + const { account, env, alias } = useChatData(); const historyMessages = useCallback(async ({chatId}: HistoryMessagesParams) => { @@ -46,7 +46,7 @@ const useFetchHistoryMessages } finally { setLoading(false); } - }, [pgpPrivateKey,account,env, alias]); + }, [account,env, alias]); return { historyMessages, error, loading }; }; diff --git a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts index 0d8759eb2..8d2a7a7f0 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts @@ -14,7 +14,6 @@ export type PushChatSocketHookOptions = { export const usePushChatSocket = () => { const { account, - pgpPrivateKey, pushChatSocket, setPushChatSocket, setIsPushChatSocketConnected, diff --git a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts index 099f3ee5d..617f18583 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts @@ -15,7 +15,7 @@ const usePushSendMessage = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { pgpPrivateKey, env, account, alias } = useChatData(); + const { env, account, alias } = useChatData(); const sendMessage = useCallback( async (options: SendMessageParams) => { @@ -39,7 +39,7 @@ const usePushSendMessage = () => { return error.message; } }, - [pgpPrivateKey, account, env, alias] + [ account, env, alias] ); return { sendMessage, error, loading }; From 153336a708d9efb80629b67ad544a466d828d2c6 Mon Sep 17 00:00:00 2001 From: KlausMikhaelson Date: Thu, 16 Nov 2023 08:20:18 -0600 Subject: [PATCH 4/6] fix: fixed type error in fetch chat --- .../components/chat/ChatViewList/ChatViewList.tsx | 2 +- packages/uiweb/src/lib/helpers/chat/chat.ts | 13 ++++++------- packages/uiweb/src/lib/hooks/chat/useFetchChat.ts | 2 +- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx index 3c398cf42..f3ba8c041 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx @@ -383,7 +383,7 @@ export const ChatViewList: React.FC = ( {chatFeed && account && checkIfIntent({ - chat: chatFeed, + chat: chatFeed as IFeeds, account: account!, }) && ( { - const ChatObject = chat[0]; if (account) { if ( - Object.keys(ChatObject || {}).length && - ChatObject.combinedDID + Object.keys(chat || {}).length && + chat.combinedDID .toLowerCase() .includes(walletToPCAIP10(account).toLowerCase()) ) { if ( - ChatObject.intent && - ChatObject.intent + chat.intent && + chat.intent .toLowerCase() .includes(walletToPCAIP10(account).toLowerCase()) ) @@ -274,4 +273,4 @@ export const checkIfSameChat = ( console.log(chatId); return false; -}; +}; \ No newline at end of file diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts index b90424bf4..602e6cc79 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts @@ -21,7 +21,7 @@ const useFetchChat = () => { console.log("chatss calling in hook before", alias); const chat = await alias.chat.list("CHATS") console.log('chatss in hook', chat); - return chat; + return chat[0]; } catch (error: Error | any) { setLoading(false); setError(error.message); From bff2e193bc20359d0b1f80828378cb06830f9d21 Mon Sep 17 00:00:00 2001 From: Monalisha Mishra Date: Thu, 16 Nov 2023 19:03:07 +0300 Subject: [PATCH 5/6] fix: fixed code --- .../src/app/ChatUITest/ChatViewComponent.tsx | 4 +- .../chat/ChatProfile/AddWalletContent.tsx | 5 +- .../chat/ChatProfile/ChatProfile.tsx | 2 +- .../chat/ChatViewBubble/ChatViewBubble.tsx | 18 ++--- .../chat/ChatViewList/ChatViewList.tsx | 10 +-- .../chat/ConnectButton/ConnectButton.tsx | 26 +++--- .../chat/MessageInput/MessageInput.tsx | 25 +++--- packages/uiweb/src/lib/context/chatContext.ts | 8 +- .../lib/dataProviders/ChatDataProvider.tsx | 80 ++++++++----------- packages/uiweb/src/lib/helpers/chat/chat.ts | 16 ++-- packages/uiweb/src/lib/helpers/chat/search.ts | 2 +- packages/uiweb/src/lib/helpers/timestamp.ts | 30 +++---- packages/uiweb/src/lib/hooks/chat/index.ts | 1 - .../lib/hooks/chat/useApproveChatRequest.ts | 7 +- .../src/lib/hooks/chat/useChatProfile.ts | 10 ++- .../uiweb/src/lib/hooks/chat/useFetchChat.ts | 12 +-- .../hooks/chat/useFetchConversationHash.ts | 38 --------- .../lib/hooks/chat/useFetchHistoryMessages.ts | 21 ++--- .../lib/hooks/chat/useInitializePushUser.ts | 32 ++++++++ .../src/lib/hooks/chat/usePushChatSocket.ts | 49 +++--------- .../src/lib/hooks/chat/usePushSendMessage.ts | 13 ++- .../hooks/chatAndNotification/chat/index.ts | 1 - .../uiweb/src/lib/hooks/useGetChatProfile.ts | 36 ++++----- 23 files changed, 192 insertions(+), 254 deletions(-) delete mode 100644 packages/uiweb/src/lib/hooks/chat/useFetchConversationHash.ts create mode 100644 packages/uiweb/src/lib/hooks/chat/useInitializePushUser.ts diff --git a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx index 82e854cce..30e0db5cc 100644 --- a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx +++ b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx @@ -9,11 +9,11 @@ const ChatViewComponentTest = () => { 'bafyreidesy6f4iu34eqccmqh55g35wu36lvlz42c63ivtmgjjhezlzdqta', 'bafyreig3gs4tpwxumiz5fxypyt4omlxhvrvuj66kfoyioeshawlau6lgem', ]; - +console.log('in chat view component') return (

Chat UI Test page

- {/* {console.log('in close')}} /> */} + {console.log('in close')}} /> {/* {console.log('in close')}} modalBackground={MODAL_BACKGROUND_TYPE.OVERLAY} modalPositionType={MODAL_POSITION_TYPE.RELATIVE}/> */} diff --git a/packages/uiweb/src/lib/components/chat/ChatProfile/AddWalletContent.tsx b/packages/uiweb/src/lib/components/chat/ChatProfile/AddWalletContent.tsx index e99062b39..9ccddc723 100644 --- a/packages/uiweb/src/lib/components/chat/ChatProfile/AddWalletContent.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatProfile/AddWalletContent.tsx @@ -24,6 +24,7 @@ import CloseIcon from '../../../icons/close.svg'; import { ChatSearchInput, CustomStyleParamsType, ModalHeader } from '../reusables'; import useGetChatProfile from '../../../hooks/useGetChatProfile'; import { BackIcon } from '../../../icons/Back'; +import useChatProfile from '../../../hooks/chat/useChatProfile'; type AddWalletContentProps = { @@ -50,7 +51,7 @@ export const AddWalletContent = ({ const [filteredUserData, setFilteredUserData] = useState(null); const { account, env } = useChatData(); const isMobile = useMediaQuery(device.mobileL); - const {fetchChatProfile} = useGetChatProfile(); + const {fetchUserChatProfile} = useChatProfile(); const groupInfoToast = useToast(); const customSearchStyle:CustomStyleParamsType = { background:theme.backgroundColor?.modalInputBackground, @@ -64,7 +65,7 @@ export const AddWalletContent = ({ //fix ens search const newChatUser = await getNewChatUser({ searchText: searchedText, - fetchChatProfile, + fetchChatProfile:fetchUserChatProfile, env, }); if(newChatUser){ diff --git a/packages/uiweb/src/lib/components/chat/ChatProfile/ChatProfile.tsx b/packages/uiweb/src/lib/components/chat/ChatProfile/ChatProfile.tsx index e47d24135..26b6643f9 100644 --- a/packages/uiweb/src/lib/components/chat/ChatProfile/ChatProfile.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatProfile/ChatProfile.tsx @@ -68,7 +68,7 @@ export const ChatProfile: React.FC = ({ const fetchProfileData = async () => { if (isValidETHAddress(chatId)) { - const ChatProfile = await fetchUserChatProfile({ profileId: chatId }); + const ChatProfile = await fetchUserChatProfile({ profileId: chatId,env }); const result = await resolveNewEns(chatId, provider); setEnsName(result); setChatInfo(ChatProfile); diff --git a/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx b/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx index 55973f0d7..99ab8e81d 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewBubble/ChatViewBubble.tsx @@ -32,7 +32,7 @@ const SenderMessageAddress = ({ chat }: { chat: IMessagePayload }) => { const theme = useContext(ThemeContext); return ( <> - {(chat.fromDID).split(':')[1] !== account && ( + {(chat.fromCAIP10).split(':')[1] !== account && ( { fontWeight={theme.fontWeight?.chatReceivedBubbleAddressText} color={theme.textColor?.chatReceivedBubbleAddressText} > - {chat.fromDID.split(':')[1].slice(0, 6)}... - {chat.fromDID.split(':')[1].slice(-6)} + {chat.fromCAIP10.split(':')[1].slice(0, 6)}... + {chat.fromCAIP10.split(':')[1].slice(-6)} )} @@ -54,7 +54,7 @@ const SenderMessageProfilePicture = ({ chat }: { chat: IMessagePayload }) => { const [pfp, setPfp] = useState(''); const getUserPfp = async () => { const pfp = await getPfp({ - account: chat.fromDID.split(':')[1], + account: chat.fromCAIP10.split(':')[1], env: env, }); if (pfp) { @@ -63,10 +63,10 @@ const SenderMessageProfilePicture = ({ chat }: { chat: IMessagePayload }) => { }; useEffect(() => { getUserPfp(); - }, [account, chat.fromDID]); + }, [account, chat.fromCAIP10]); return (
- {(chat.fromDID || chat.fromDID).split(':')[1] !== account && ( + {(chat.fromCAIP10).split(':')[1] !== account && (
{pfp && ( { const { account } = useChatData(); const position = - pCAIP10ToWallet(decryptedMessagePayload.fromDID).toLowerCase() !== account?.toLowerCase() + pCAIP10ToWallet(decryptedMessagePayload.fromCAIP10).toLowerCase() !== account?.toLowerCase() ? 0 : 1; const { tweetId, messageType }: TwitterFeedReturnType = checkTwitterUrl({ @@ -348,7 +348,7 @@ export const ChatViewBubble = ({ decryptedMessagePayload }: { decryptedMessagePa }); const [isGroup, setIsGroup] = useState(false); useEffect(() => { - if ((decryptedMessagePayload.toDID).split(':')[0] === 'eip155') { + if ((decryptedMessagePayload.toCAIP10).split(':')[0] === 'eip155') { if (isGroup) { setIsGroup(false); } @@ -357,7 +357,7 @@ export const ChatViewBubble = ({ decryptedMessagePayload }: { decryptedMessagePa setIsGroup(true); } } - }, [decryptedMessagePayload.toDID, isGroup]); + }, [decryptedMessagePayload.toCAIP10, isGroup]); if (messageType === 'TwitterFeedLink') { decryptedMessagePayload.messageType = 'TwitterFeedLink'; diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx index f3ba8c041..c6fae0e36 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx @@ -34,6 +34,7 @@ import useGetChatProfile from '../../../hooks/useGetChatProfile'; import useFetchChat from '../../../hooks/chat/useFetchChat'; import { ApproveRequestBubble } from './ApproveRequestBubble'; import { formatTime } from '../../../helpers/timestamp'; +import useChatProfile from '../../../hooks/chat/useChatProfile'; /** * @interface IThemeProps @@ -64,7 +65,7 @@ export const ChatViewList: React.FC = ( const listInnerRef = useRef(null); const [isMember, setIsMember] = useState(false); const { fetchChat } = useFetchChat(); - const { fetchChatProfile } = useGetChatProfile(); + const { fetchUserChatProfile } = useChatProfile(); const { getGroup } = useGetGroup(); const { messagesSinceLastConnection, groupInformationSinceLastConnection } = @@ -86,20 +87,17 @@ export const ChatViewList: React.FC = ( useEffect(() => { (async () => { if (alias) { - // console.log('chatss'); - // console.log(account, env, 'chatss') + const chat = await fetchChat(); - // console.log(chat, 'chatss calling main', alias) if (chat) { setConversationHash(chat?.threadhash as string); setChatFeed(chat as IFeeds); } else { - console.log('chatss calling elsez') let newChatFeed; let group; const result = await getNewChatUser({ searchText: chatId, - fetchChatProfile, + fetchChatProfile:fetchUserChatProfile, env, }); if (result) { diff --git a/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx b/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx index fc78f01cc..6a144303f 100644 --- a/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx +++ b/packages/uiweb/src/lib/components/chat/ConnectButton/ConnectButton.tsx @@ -12,6 +12,7 @@ import useDecryptPGPKey from '../../../hooks/useDecryptPGPKey'; import { getAddressFromSigner } from '../../../helpers'; import { IChatTheme } from '../theme'; import { device } from '../../../config'; +import useChatProfile from '../../../hooks/chat/useChatProfile'; /** * @interface IThemeProps @@ -37,7 +38,7 @@ export const ConnectButtonSub = ({autoConnect = false}) => { setAlias } = useChatData(); const theme = useContext(ThemeContext); - const {fetchChatProfile} = useGetChatProfile(); + const {fetchUserChatProfile} = useChatProfile(); const {decryptPGPKey} = useDecryptPGPKey(); @@ -61,17 +62,18 @@ export const ConnectButtonSub = ({autoConnect = false}) => { setUserData() }, [wallet]) - useEffect(() => { - (async () => { - if (!alias && signer) { - const user = await fetchChatProfile({signer: signer, env}); - console.log("calllingggg in connect button") - if (user) { - setAlias(user); - } - } - })(); - }, [alias, signer]); + //initialise user hook + + // useEffect(() => { + // (async () => { + // if (!alias && signer) { + // const user = await fetchChatProfile({signer: signer, env}); + // if (user) { + // setAlias(user); + // } + // } + // })(); + // }, [alias, signer]); return !signer ? ( diff --git a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx index 5b4a63bef..e648de412 100644 --- a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx +++ b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx @@ -28,7 +28,7 @@ import { setAccessControl, } from '../../../helpers'; import useFetchChat from '../../../hooks/chat/useFetchChat'; -import useGetChatProfile from '../../../hooks/useGetChatProfile'; +import useChatProfile from '../../../hooks/chat/useChatProfile'; import useGetGroup from '../../../hooks/chat/useGetGroup'; import useApproveChatRequest from '../../../hooks/chat/useApproveChatRequest'; import { @@ -120,7 +120,7 @@ export const MessageInput: React.FC = ({ setAlias } = useChatData(); const { fetchChat } = useFetchChat(); - const { fetchChatProfile } = useGetChatProfile(); + const { fetchUserChatProfile } = useChatProfile(); const { getGroup } = useGetGroup(); const statusToast = useToast(); const textAreaRef = useRef(null); @@ -142,15 +142,16 @@ export const MessageInput: React.FC = ({ }, [textAreaRef, typedMessage]); //need to do something about fetching connectedUser in every component - useEffect(() => { - (async () => { - if (!alias && signer) { - const user = await fetchChatProfile({ signer: signer, env }); - console.log("calllingggg in message input") - if (user) setAlias(user); - } - })(); - }, [alias]); + //initalization not needed here + + // useEffect(() => { + // (async () => { + // if (!alias && signer) { + // const user = await fetchUserChatProfile({ profileId: account!,env }); + // if (user) setAlias(user); + // } + // })(); + // }, [alias]); useEffect(() => { const storedTimestampJSON = localStorage.getItem(chatId); @@ -209,7 +210,7 @@ export const MessageInput: React.FC = ({ let group; const result = await getNewChatUser({ searchText: chatId, - fetchChatProfile, + fetchChatProfile:fetchUserChatProfile, env, }); if (result) { diff --git a/packages/uiweb/src/lib/context/chatContext.ts b/packages/uiweb/src/lib/context/chatContext.ts index a7ab83f83..ac635d7ab 100644 --- a/packages/uiweb/src/lib/context/chatContext.ts +++ b/packages/uiweb/src/lib/context/chatContext.ts @@ -16,8 +16,8 @@ export interface IChatDataContextValues { setIsPushChatSocketConnected: React.Dispatch>; connectedProfile: IUser | undefined; setConnectedProfile: (connectedProfile: IUser) => void; - alias: any; - setAlias: React.Dispatch>; + pushUser: any; + setPushUser: React.Dispatch>; } export const initialChatDataContextValues: IChatDataContextValues = { @@ -45,8 +45,8 @@ export const initialChatDataContextValues: IChatDataContextValues = { setConnectedProfile: () => { /** */ }, - alias: null, - setAlias: () => { + pushUser: null, + setPushUser: () => { /** */ }, diff --git a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx index 4088397a8..3563701d7 100644 --- a/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx +++ b/packages/uiweb/src/lib/dataProviders/ChatDataProvider.tsx @@ -5,18 +5,16 @@ import { IChatDataContextValues, } from '../context/chatContext'; import { ThemeContext } from '../components/chat/theme/ThemeProvider'; -import useGetChatProfile from '../hooks/useGetChatProfile'; import { IUser, SignerType } from '@pushprotocol/restapi'; import { IChatTheme, lightChatTheme } from '../components/chat/theme'; import { getAddressFromSigner, pCAIP10ToWallet } from '../helpers'; - +import useInitializePushUser from '../hooks/chat/useInitializePushUser'; export interface IChatUIProviderProps { children: ReactNode; theme?: IChatTheme; account?: string | null; signer?: SignerType | undefined; - pgpPrivateKey?: string | null; env?: ENV; } @@ -27,64 +25,57 @@ export const ChatUIProvider = ({ signer = undefined, env = Constants.ENV.PROD, }: IChatUIProviderProps) => { - const [accountVal, setAccountVal] = useState(pCAIP10ToWallet(account!)); - const [pushChatSocket, setPushChatSocket] = useState(null); - const [signerVal, setSignerVal] = useState(signer); - const [alias, setAlias] = useState(null); + const [accountVal, setAccountVal] = useState( + pCAIP10ToWallet(account!) + ); + const [pushChatSocket, setPushChatSocket] = useState(null); + const [signerVal, setSignerVal] = useState(signer); + const [pushUser, setPushUser] = useState(null); const [envVal, setEnvVal] = useState(env); - const {fetchChatProfile} = useGetChatProfile(); - const [connectedProfile,setConnectedProfile]=useState(undefined); - + const [connectedProfile, setConnectedProfile] = useState( + undefined + ); + const { initializePushUser } = useInitializePushUser(); const [isPushChatSocketConnected, setIsPushChatSocketConnected] = - useState(false); + useState(false); useEffect(() => { - (async()=>{ + (async () => { resetStates(); setEnvVal(env); - + if (signer) { if (!account) { const address = await getAddressFromSigner(signer); setAccountVal(address); - } - else{ + } else { setAccountVal(account); } - } + } setSignerVal(signer); - })() - - }, [env,account, alias,signer]) - - - - - -const resetStates = () => { - setPushChatSocket(null); - setIsPushChatSocketConnected(false); - -}; - - + })(); + }, [env, account, signer]); -useEffect(() => { + useEffect(() => { (async () => { - let user; - if (!alias && signer) { - console.log("userrr",user); - if (user) { - setAlias(user); - } + if (Object.keys(signer || {}).length && account) { + const pushUser = await initializePushUser({ signer: signer!, account }); + setPushUser(pushUser); } })(); - }, [env, signer, alias]); + }, [signer, account, env]); + + const resetStates = () => { + setPushChatSocket(null); + setIsPushChatSocketConnected(false); + }; + + const value: IChatDataContextValues = { account: accountVal, - signer:signerVal, - setSigner:setSignerVal, + signer: signerVal, + setSigner: setSignerVal, setAccount: setAccountVal, env: envVal, setEnv: setEnvVal, @@ -94,11 +85,10 @@ useEffect(() => { setIsPushChatSocketConnected, connectedProfile, setConnectedProfile, - alias, - setAlias + pushUser, + setPushUser, }; - const PROVIDER_THEME = Object.assign({}, lightChatTheme, theme); return ( @@ -107,4 +97,4 @@ useEffect(() => { ); -}; \ No newline at end of file +}; diff --git a/packages/uiweb/src/lib/helpers/chat/chat.ts b/packages/uiweb/src/lib/helpers/chat/chat.ts index 293292d34..41520228a 100644 --- a/packages/uiweb/src/lib/helpers/chat/chat.ts +++ b/packages/uiweb/src/lib/helpers/chat/chat.ts @@ -218,10 +218,10 @@ export const getChatId = ({ msg: IMessageIPFS; account: string; }) => { - if (pCAIP10ToWallet(msg.fromDID).toLowerCase() === account.toLowerCase()) { - return msg.toDID; + if (pCAIP10ToWallet(msg.fromCAIP10).toLowerCase() === account.toLowerCase()) { + return msg.toCAIP10; } - return !isPCAIP(msg.toDID) ? msg.toDID : msg.fromDID; + return !isPCAIP(msg.toCAIP10) ? msg.toCAIP10 : msg.fromCAIP10; }; export const appendUniqueMessages = ( @@ -253,19 +253,19 @@ export const checkIfSameChat = ( chatId = walletToPCAIP10(chatId); if ( Object.keys(msg || {}).length && - (((chatId.toLowerCase() === (msg.fromDID?.toLowerCase())) && + (((chatId.toLowerCase() === (msg.fromCAIP10?.toLowerCase())) && ( walletToPCAIP10(account!).toLowerCase() === - msg.toDID?.toLowerCase())) || - ((chatId.toLowerCase() === (msg.toDID?.toLowerCase())) && + msg.toCAIP10?.toLowerCase())) || + ((chatId.toLowerCase() === (msg.toCAIP10?.toLowerCase())) && (walletToPCAIP10(account!).toLowerCase() === - msg.fromDID?.toLowerCase()))) + msg.fromCAIP10?.toLowerCase()))) ) { return true; } } else { if ( Object.keys(msg || {}).length && - (chatId.toLowerCase() === msg.toDID?.toLowerCase()) + (chatId.toLowerCase() === msg.toCAIP10?.toLowerCase()) ) { return true; } diff --git a/packages/uiweb/src/lib/helpers/chat/search.ts b/packages/uiweb/src/lib/helpers/chat/search.ts index ce5448dba..7a4b3aa06 100644 --- a/packages/uiweb/src/lib/helpers/chat/search.ts +++ b/packages/uiweb/src/lib/helpers/chat/search.ts @@ -74,7 +74,7 @@ export const getNewChatUser = async ({ // address = await getAddress(searchText, env); // } if (address) { - chatProfile = await fetchChatProfile({ profileId: address, env }); + chatProfile = await fetchChatProfile({ profileId: address,env }); if (!chatProfile) chatProfile = displayDefaultUser({ caip10: walletToPCAIP10(address) }); return chatProfile; diff --git a/packages/uiweb/src/lib/helpers/timestamp.ts b/packages/uiweb/src/lib/helpers/timestamp.ts index 79f45065f..a83c81a13 100644 --- a/packages/uiweb/src/lib/helpers/timestamp.ts +++ b/packages/uiweb/src/lib/helpers/timestamp.ts @@ -1,15 +1,15 @@ -export const formatTime = (timestamp : any) => { - let date; -let timestamp1; - if (typeof timestamp === "string") { - timestamp1 = parseInt(timestamp ); - }else{ - timestamp1 = timestamp - } - const time = new Date(timestamp1!); - if (!isNaN(time.getTime())){ - const time1 = time.toLocaleTimeString('en-US'); - date = time1.slice(0, -6) + time1.slice(-2); - } - return date; -} \ No newline at end of file +export const formatTime = (timestamp: any) => { + let date; + let timestamp1; + if (typeof timestamp === 'string') { + timestamp1 = parseInt(timestamp); + } else { + timestamp1 = timestamp; + } + const time = new Date(timestamp1!); + if (!isNaN(time.getTime())) { + const time1 = time.toLocaleTimeString('en-US'); + date = time1.slice(0, -6) + time1.slice(-2); + } + return date; +}; diff --git a/packages/uiweb/src/lib/hooks/chat/index.ts b/packages/uiweb/src/lib/hooks/chat/index.ts index d497e66d6..16e3f5f39 100644 --- a/packages/uiweb/src/lib/hooks/chat/index.ts +++ b/packages/uiweb/src/lib/hooks/chat/index.ts @@ -4,7 +4,6 @@ export * from './useChatData'; export * from './useChatProfile'; export * from './usePushChatSocket'; export * from './useFetchChat'; -export * from './useFetchConversationHash'; export * from './usePushSendMessage'; export * from './useGetGroupByID'; export * from './useAccount'; diff --git a/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts b/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts index 67e360503..644d39693 100644 --- a/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts +++ b/packages/uiweb/src/lib/hooks/chat/useApproveChatRequest.ts @@ -9,15 +9,14 @@ interface ApproveChatParams { const useApproveChatRequest = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env,pgpPrivateKey,signer, alias } =useChatData(); + const { account, env,signer, pushUser } =useChatData(); const approveChatRequest = useCallback(async (options:ApproveChatParams) => { const { - chatId, } = options || {}; setLoading(true); try { - const response = await alias.chat.accept(chatId); + const response = await pushUser.chat.accept(chatId); setLoading(false); return response; } catch (error: Error | any) { @@ -28,7 +27,7 @@ const useApproveChatRequest = () => { } }, - [account,env,signer,alias] + [account,env,signer,pushUser] ); diff --git a/packages/uiweb/src/lib/hooks/chat/useChatProfile.ts b/packages/uiweb/src/lib/hooks/chat/useChatProfile.ts index 8a6d71411..4d384ae31 100644 --- a/packages/uiweb/src/lib/hooks/chat/useChatProfile.ts +++ b/packages/uiweb/src/lib/hooks/chat/useChatProfile.ts @@ -4,13 +4,17 @@ import { useChatData } from './useChatData'; export interface ProfileParams { profileId: string; + env:PushAPI.Env } +//need to change it to new sdk method const useChatProfile = () => { - const { env } = useChatData(); + // const { env } = useChatData(); + const fetchUserChatProfile = useCallback( async ({ - profileId + profileId, + env }: ProfileParams): Promise => { try { const profile = await PushAPI.user.get({ @@ -23,7 +27,7 @@ const useChatProfile = () => { return; } }, - [env] + [] ); return { fetchUserChatProfile }; diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts index 602e6cc79..6ad60e341 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts @@ -4,23 +4,19 @@ import { useCallback, useContext, useState } from 'react'; import { useChatData } from './useChatData'; -interface fetchChat { - chatId?: string; -} + const useFetchChat = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env, alias } = useChatData(); + const { account, env, pushUser } = useChatData(); const fetchChat = useCallback( async () => { setLoading(true); try { - console.log("chatss calling in hook before", alias); - const chat = await alias.chat.list("CHATS") - console.log('chatss in hook', chat); + const chat = await pushUser.chat.list("CHATS") return chat[0]; } catch (error: Error | any) { setLoading(false); @@ -32,7 +28,7 @@ const useFetchChat = () => { setLoading(false); } }, - [env,account, alias] + [env,account, pushUser] ); return { fetchChat, error, loading }; diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchConversationHash.ts b/packages/uiweb/src/lib/hooks/chat/useFetchConversationHash.ts deleted file mode 100644 index 5b65d4c61..000000000 --- a/packages/uiweb/src/lib/hooks/chat/useFetchConversationHash.ts +++ /dev/null @@ -1,38 +0,0 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import { Env } from '@pushprotocol/restapi'; -import { useCallback, useContext, useState } from 'react'; -import { useChatData } from './useChatData'; - -interface conversationHashParams { - conversationId: string; -} - -const useFetchConversationHash = () => { - const [error, setError] = useState(); - const [loading, setLoading] = useState(false); - const { account, env } = useChatData(); - - const fetchConversationHash = useCallback( - async ({ conversationId }: conversationHashParams) => { - setLoading(true); - try { - const response = await PushAPI.chat.conversationHash({ - conversationId, - account: account ? account : '0xeeE5A266D7cD954bE3Eb99062172E7071E664023', - env: env, - }); - setLoading(false); - return response; - } catch (error: Error | any) { - setLoading(false); - setError(error.message); - console.log(error); - return; - } - }, - [env, account] - ); - return { fetchConversationHash, error, loading }; -}; - -export default useFetchConversationHash; diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts index 9a7b049a7..dde4850fc 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchHistoryMessages.ts @@ -1,8 +1,7 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import type { IMessageIPFS } from '@pushprotocol/restapi'; + import { useCallback, useContext, useState } from 'react'; -import { ChatDataContext } from '../../context'; + import { useChatData } from './useChatData'; @@ -19,23 +18,13 @@ const useFetchHistoryMessages const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { account, env, alias } = useChatData(); + const { account, env, pushUser } = useChatData(); const historyMessages = useCallback(async ({chatId}: HistoryMessagesParams) => { setLoading(true); try { - // const chatHistory:IMessageIPFS[] = await PushAPI.chat.history({ - // threadhash: threadHash, - // account:account ? account : '0xeeE5A266D7cD954bE3Eb99062172E7071E664023', - // toDecrypt: pgpPrivateKey ? true : false, - // pgpPrivateKey: String(pgpPrivateKey), - // limit: limit, - // env: env - // }); - console.log(alias, "chatHistoryyy") - const chatHistory = await alias.chat.history(chatId) - console.log(chatHistory, "chatHistoryyy") + const chatHistory = await pushUser.chat.history(chatId) chatHistory.reverse(); return chatHistory; } catch (error: Error | any) { @@ -46,7 +35,7 @@ const useFetchHistoryMessages } finally { setLoading(false); } - }, [account,env, alias]); + }, [account,env, pushUser]); return { historyMessages, error, loading }; }; diff --git a/packages/uiweb/src/lib/hooks/chat/useInitializePushUser.ts b/packages/uiweb/src/lib/hooks/chat/useInitializePushUser.ts new file mode 100644 index 000000000..b445c062d --- /dev/null +++ b/packages/uiweb/src/lib/hooks/chat/useInitializePushUser.ts @@ -0,0 +1,32 @@ +import {PushAPI, SignerType} from '@pushprotocol/restapi'; +import { useCallback, useContext } from 'react'; +import { useChatData } from './useChatData'; + +export interface ProfileParams { + signer: SignerType; + account:string; +} + +const useInitializePushUser = () => { + const { env } = useChatData(); + + const initializePushUser = useCallback( + async ({ + signer, + account + }: ProfileParams): Promise => { + try { + const pushUser = await PushAPI.initialize(signer, {env: env,account:account}) + return pushUser; + } catch (error) { + console.log(error); + return; + } + }, + [] + ); + + return { initializePushUser }; +}; + +export default useInitializePushUser; diff --git a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts index 8d2a7a7f0..23377f8f8 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts @@ -1,27 +1,16 @@ -import { createSocketConnection, EVENTS } from '@pushprotocol/socket'; import { useCallback, useEffect, useState } from 'react'; -import { ENV } from '../../config'; import { useChatData } from './useChatData'; -import { SOCKET_TYPE } from '../../types'; -import useGetChatProfile from '../useGetChatProfile'; + import { CONSTANTS } from '@pushprotocol/restapi'; -export type PushChatSocketHookOptions = { - account?: string | null; - env?: ENV; -}; + export const usePushChatSocket = () => { const { - account, - pushChatSocket, - setPushChatSocket, setIsPushChatSocketConnected, isPushChatSocketConnected, - connectedProfile, - setConnectedProfile, env, - alias + pushUser } = useChatData(); const [messagesSinceLastConnection, setMessagesSinceLastConnection] = useState({}); @@ -35,11 +24,8 @@ export const usePushChatSocket = () => { const addSocketEvents = useCallback(async () => { console.log('addSocketEvents'); - // if (!stre/z stream.on(CONSTANTS.STREAM.CONNECT, () => { - // console.log(err,"errr"); - // console.log(connected,"connected");÷ - console.log('connecteddddd'); + setIsPushChatSocketConnected(true); }) @@ -57,19 +43,19 @@ export const usePushChatSocket = () => { setAcceptedRequestMessage(chat); } else { // Extract 'from' and 'to' from the 'message' property - const fromDID = chat.from; - const toDID = chat.to.join(', '); // Use the appropriate separator if needed + //shfit to a new func + const fromCAIP10 = chat.from; + const toCAIP10 = chat.to.join(', '); // Use the appropriate separator if needed // Create a new object with modified properties const messageContent = chat.message.content; const modifiedChat = { ...chat, - fromDID: fromDID, - toDID: toDID, + fromCAIP10: fromCAIP10, + toCAIP10: toCAIP10, messageContent: messageContent, }; delete modifiedChat.from; delete modifiedChat.to; - console.log('modifiedChat', modifiedChat); setMessagesSinceLastConnection((chats: any) => { return modifiedChat; @@ -77,19 +63,11 @@ export const usePushChatSocket = () => { } }); - - // pushChatSocket?.on(EVENTS.CHAT_GROUPS, (groupInfo: any) => { - // /** - // * We receive a group creation or updated event. - // */ - // setGroupInformationSinceLastConnection(groupInfo); - // }); - // eslint-disable-next-line react-hooks/exhaustive-deps }, [ messagesSinceLastConnection, env, - alias, + pushUser, stream ]); @@ -107,7 +85,7 @@ export const usePushChatSocket = () => { removeSocketEvents(); } }; - }, [stream, alias]); + }, [stream, pushUser]); /** * Whenever the required params to create a connection object change @@ -118,7 +96,7 @@ export const usePushChatSocket = () => { if (!stream) { const main = async () => { - const stream = await alias.initStream( + const stream = await pushUser.initStream( [ CONSTANTS.STREAM.CHAT, ], @@ -130,10 +108,9 @@ export const usePushChatSocket = () => { }; main().catch((err) => console.error(err)); } - // } // eslint-disable-next-line react-hooks/exhaustive-deps - }, [alias, env, stream]); + }, [pushUser, env, stream]); return { isPushChatSocketConnected, diff --git a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts index 617f18583..a51a9f947 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushSendMessage.ts @@ -1,9 +1,6 @@ -import * as PushAPI from '@pushprotocol/restapi'; -import { useCallback, useContext, useState } from 'react'; -import useVerifyAccessControl from './useVerifyAccessControl'; +import { useCallback, useState } from 'react'; import { useChatData } from '..'; -import { ENV } from '../../config'; -import { setAccessControl } from '../../helpers'; + interface SendMessageParams { message: string; @@ -15,14 +12,14 @@ const usePushSendMessage = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { env, account, alias } = useChatData(); + const { env, account, pushUser } = useChatData(); const sendMessage = useCallback( async (options: SendMessageParams) => { const { chatId, message, messageType } = options || {}; setLoading(true); try { - const response = await alias.chat.send(chatId, { + const response = await pushUser.chat.send(chatId, { type: messageType, content: message, }) @@ -39,7 +36,7 @@ const usePushSendMessage = () => { return error.message; } }, - [ account, env, alias] + [ account, env, pushUser] ); return { sendMessage, error, loading }; diff --git a/packages/uiweb/src/lib/hooks/chatAndNotification/chat/index.ts b/packages/uiweb/src/lib/hooks/chatAndNotification/chat/index.ts index 49cf9937a..1304a70ad 100644 --- a/packages/uiweb/src/lib/hooks/chatAndNotification/chat/index.ts +++ b/packages/uiweb/src/lib/hooks/chatAndNotification/chat/index.ts @@ -1,7 +1,6 @@ export * from './useFetchChats'; export * from './useFetchRequests'; export * from './useFetchHistoryMessages'; -export * from './useFetchConversationHash'; export * from './useApproveChatRequest'; export * from './useFetchChat'; export * from './usePushSendMessage'; diff --git a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts index 269786eeb..c49f29848 100644 --- a/packages/uiweb/src/lib/hooks/useGetChatProfile.ts +++ b/packages/uiweb/src/lib/hooks/useGetChatProfile.ts @@ -1,35 +1,27 @@ -import { PushAPI, Env } from '@pushprotocol/restapi'; -import { useCallback, useContext, useEffect } from 'react'; -import { ChatAndNotificationPropsContext } from '../context'; -import { useChatData } from './chat'; -import { SignerType } from '../types'; +import * as PushAPI from '@pushprotocol/restapi'; +import { useCallback, useContext } from 'react'; +import { Constants } from '../config'; + export interface GetProfileParams { - profileId?: string; - env: Env, - signer: SignerType + profileId: string; + env:PushAPI.Env } const useGetChatProfile = () => { - const { signer, alias, setAlias, setConnectedProfile } = useChatData(); - const fetchChatProfile = useCallback( async ({ profileId, - signer, - env - }: GetProfileParams): Promise => { + env + }: GetProfileParams): Promise => { try { - console.log('signerrr', signer); - console.log("env", env) - const userAlice = await PushAPI.initialize( - signer!, - { - env: env - }); - return userAlice; + const profile = await PushAPI.user.get({ + env: env, + account: profileId, + }); + return profile; } catch (error) { - console.log("errr", error); + console.log(error); return; } }, From 4eb30e91989af8d435e1314fb7b0854f65d52d10 Mon Sep 17 00:00:00 2001 From: Monalisha Mishra Date: Thu, 16 Nov 2023 20:03:36 +0300 Subject: [PATCH 6/6] fix: added minor changes --- .../src/app/ChatUITest/ChatViewComponent.tsx | 2 +- .../chat/ChatViewList/ChatViewList.tsx | 22 ++++++++----------- .../chat/MessageInput/MessageInput.tsx | 18 +++++++-------- .../uiweb/src/lib/hooks/chat/useFetchChat.ts | 1 + .../src/lib/hooks/chat/usePushChatSocket.ts | 2 +- .../chat/usePushSendMessage.ts | 4 +--- 6 files changed, 22 insertions(+), 27 deletions(-) diff --git a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx index 30e0db5cc..3bdb3a6e5 100644 --- a/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx +++ b/packages/examples/sdk-frontend-react/src/app/ChatUITest/ChatViewComponent.tsx @@ -13,7 +13,7 @@ console.log('in chat view component') return (

Chat UI Test page

- {console.log('in close')}} /> + {/* {console.log('in close')}} /> */} {/* {console.log('in close')}} modalBackground={MODAL_BACKGROUND_TYPE.OVERLAY} modalPositionType={MODAL_POSITION_TYPE.RELATIVE}/> */} diff --git a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx index c6fae0e36..8232cb137 100644 --- a/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx +++ b/packages/uiweb/src/lib/components/chat/ChatViewList/ChatViewList.tsx @@ -53,7 +53,7 @@ export const ChatViewList: React.FC = ( options: IChatViewListProps ) => { const { chatId, limit = chatLimit, chatFilterList = [] } = options || {}; - const { account, connectedProfile, setConnectedProfile, signer, alias, setAlias } = + const { account, pushUser, } = useChatData(); const [chatFeed, setChatFeed] = useState({} as IFeeds); const [chatStatusText, setChatStatusText] = useState(''); @@ -86,8 +86,7 @@ export const ChatViewList: React.FC = ( //need to make a common method for fetching chatFeed to ruse in messageInput useEffect(() => { (async () => { - if (alias) { - + if (pushUser) { const chat = await fetchChat(); if (chat) { setConversationHash(chat?.threadhash as string); @@ -121,11 +120,10 @@ export const ChatViewList: React.FC = ( setLoading(false); } })(); - }, [chatId, account, env, alias]); + }, [chatId, account, env, pushUser]); //moniters socket changes useEffect(() => { - console.log('messagesSinceLastConnection', account, messagesSinceLastConnection, checkIfSameChat(messagesSinceLastConnection, account!, chatId)) if (checkIfSameChat(messagesSinceLastConnection, account!, chatId)) { const updatedChatFeed = chatFeed; updatedChatFeed.msg = messagesSinceLastConnection; @@ -136,7 +134,6 @@ export const ChatViewList: React.FC = ( setConversationHash(messagesSinceLastConnection.cid); } else { - console.log('messagesSinceLastConnection in group') const newChatViewList = appendUniqueMessages( messages as Messagetype, [messagesSinceLastConnection], @@ -169,7 +166,7 @@ export const ChatViewList: React.FC = ( await getMessagesCall(); })(); // } - }, [conversationHash, account, env, chatFeed, alias]); + }, [conversationHash, account, env, chatFeed, pushUser]); useEffect(() => { scrollToBottom(); @@ -187,7 +184,6 @@ export const ChatViewList: React.FC = ( } }, [messages]); - console.log('chatHistory') useEffect(() => { @@ -235,12 +231,12 @@ export const ChatViewList: React.FC = ( // } else { // threadHash = messages?.lastThreadHash; // } - - if (alias && chatId) { - console.log('chatHistory') - +console.log('in get message call') +console.log(pushUser) + if (pushUser && chatId) { + console.log('push user there') + const chatHistory = await historyMessages({chatId}); - console.log(chatHistory, 'chatHistory') if (chatHistory?.length) { if (Object.keys(messages || {}) && messages?.messages.length) { const newChatViewList = appendUniqueMessages( diff --git a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx index e648de412..4d634e08d 100644 --- a/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx +++ b/packages/uiweb/src/lib/components/chat/MessageInput/MessageInput.tsx @@ -116,8 +116,7 @@ export const MessageInput: React.FC = ({ account, env, signer, - alias, - setAlias + pushUser, } = useChatData(); const { fetchChat } = useFetchChat(); const { fetchUserChatProfile } = useChatProfile(); @@ -146,12 +145,12 @@ export const MessageInput: React.FC = ({ // useEffect(() => { // (async () => { - // if (!alias && signer) { + // if (!pushUser && signer) { // const user = await fetchUserChatProfile({ profileId: account!,env }); - // if (user) setAlias(user); + // if (user) setpushUser(user); // } // })(); - // }, [alias]); + // }, [pushUser]); useEffect(() => { const storedTimestampJSON = localStorage.getItem(chatId); @@ -202,7 +201,8 @@ export const MessageInput: React.FC = ({ useEffect(() => { (async () => { if (!account && !env) return; - if (account && env) { + if (pushUser) { + console.log('in fetch message input') const chat = await fetchChat(); if (Object.keys(chat || {}).length) setChatFeed(chat as IFeeds); else { @@ -227,7 +227,7 @@ export const MessageInput: React.FC = ({ } } })(); - }, [chatId, account, env, alias]); + }, [chatId, account, env, pushUser]); useEffect(() => { if (!account && !env && !chatId) return; @@ -235,7 +235,7 @@ export const MessageInput: React.FC = ({ setIsMember(checkIfMember(chatFeed, account)); setIsRules(checkIfAccessVerifiedGroup(chatFeed)); } - }, [chatId, chatFeed, account, env, alias]); + }, [chatId, chatFeed, account, env, pushUser]); const addEmoji = (emojiData: EmojiClickData, event: MouseEvent): void => { setTypedMessage(typedMessage + emojiData.emoji); setShowEmojis(false); @@ -253,7 +253,7 @@ export const MessageInput: React.FC = ({ const handleJoinGroup = async () => { if (chatFeed && chatFeed?.groupInformation?.isPublic) { - const response = await alias.chat.accept(chatId); + const response = await pushUser.chat.accept(chatId); if (response) { await updateChatFeed(); } diff --git a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts index 6ad60e341..f2b041283 100644 --- a/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts +++ b/packages/uiweb/src/lib/hooks/chat/useFetchChat.ts @@ -17,6 +17,7 @@ const useFetchChat = () => { setLoading(true); try { const chat = await pushUser.chat.list("CHATS") + console.log(chat) return chat[0]; } catch (error: Error | any) { setLoading(false); diff --git a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts index 23377f8f8..ee01e7e51 100644 --- a/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts +++ b/packages/uiweb/src/lib/hooks/chat/usePushChatSocket.ts @@ -93,7 +93,7 @@ export const usePushChatSocket = () => { * - create a new connection object */ useEffect(() => { - if (!stream) { + if (!stream && pushUser) { const main = async () => { const stream = await pushUser.initStream( diff --git a/packages/uiweb/src/lib/hooks/chatAndNotification/chat/usePushSendMessage.ts b/packages/uiweb/src/lib/hooks/chatAndNotification/chat/usePushSendMessage.ts index 646601d41..d59407c95 100644 --- a/packages/uiweb/src/lib/hooks/chatAndNotification/chat/usePushSendMessage.ts +++ b/packages/uiweb/src/lib/hooks/chatAndNotification/chat/usePushSendMessage.ts @@ -4,7 +4,6 @@ import { useCallback, useContext, useState } from 'react'; import { Constants } from '../../../config'; import { ChatMainStateContext, ChatAndNotificationPropsContext } from '../../../context'; import type { ChatMainStateContextType } from '../../../context/chatAndNotification/chat/chatMainStateContext'; -import useFetchChat from './useFetchChat'; interface SendMessageParams { message: string; @@ -16,12 +15,11 @@ interface SendMessageParams { const usePushSendMessage = () => { const [error, setError] = useState(); const [loading, setLoading] = useState(false); - const { setChatFeed, setChat, chatsFeed, chats, selectedChatId } = + const { setChat,chats, selectedChatId } = useContext(ChatMainStateContext); const { account, env, decryptedPgpPvtKey } = useContext(ChatAndNotificationPropsContext); - const { fetchChat } = useFetchChat(); const sendMessage = useCallback( async (options: SendMessageParams) => { const { receiver, message, messageType } = options || {};