From 3af1ca5ff395ed1935fb0962927568ba6009acc9 Mon Sep 17 00:00:00 2001 From: KlausMikhaelson Date: Thu, 16 Nov 2023 05:54:51 -0600 Subject: [PATCH] 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"