diff --git a/package.json b/package.json index 2cef235029..f9d2e95c80 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "@pushprotocol/ledgerlive": "latest", "@pushprotocol/restapi": "1.4.38", "@pushprotocol/socket": "0.5.3", - "@pushprotocol/uiweb": "1.1.19", + "@pushprotocol/uiweb": "1.1.20", "@reduxjs/toolkit": "^1.7.1", "@testing-library/dom": "^9.0.1", "@testing-library/jest-dom": "^4.2.4", diff --git a/src/components/chat/w2wChat/chatBox/ChatBox.tsx b/src/components/chat/w2wChat/chatBox/ChatBox.tsx index 88c1fe4594..864652e062 100644 --- a/src/components/chat/w2wChat/chatBox/ChatBox.tsx +++ b/src/components/chat/w2wChat/chatBox/ChatBox.tsx @@ -2,11 +2,11 @@ import { ethers } from 'ethers'; import React, { useContext, useEffect, useRef, useState } from 'react'; import { useLocation, useNavigate } from 'react-router-dom'; - +import { ChatViewList, MessageInput } from '@pushprotocol/uiweb'; // External Packages import MuiAlert, { AlertProps } from '@mui/material/Alert'; import Snackbar from '@mui/material/Snackbar'; -import * as PushAPI from '@pushprotocol/restapi'; +import { VideoCallStatus } from '@pushprotocol/restapi'; import 'font-awesome/css/font-awesome.min.css'; import { CID } from 'ipfs-http-client'; import { BsDashLg } from 'react-icons/bs'; @@ -97,9 +97,9 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { const [isGroup, setIsGroup] = useState(false); const [showGroupInfo, setShowGroupInfo] = useState(false); const groupInfoRef = useRef(null); - const { connectedUser, setConnectedUser, createUserIfNecessary } = useContext(ChatUserContext); + const { connectedUser, setConnectedUser, createUserIfNecessary, pushUser } = useContext(ChatUserContext); const { videoObject } = useContext(VideoCallContext); - + const [chatId, setChatId] = useState(""); const listInnerRef = useRef(null); const topRef = useRef(null); const bottomRef = useRef(null); @@ -114,6 +114,17 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { useClickAway(groupInfoRef, () => setShowGroupInfo(false)); + + useEffect(() => { + if(currentChat?.groupInformation){ + setChatId(currentChat?.groupInformation?.chatId) + }else{ + setChatId(currentChat?.did); + } + + + + },[currentChat]) //resolve web3 names useResolveWeb3Name(!isGroup ? currentChat?.wallets?.split(',')[0].toString() : null); @@ -174,38 +185,26 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { if (wasLastListPresentProp && !lastThreadHashFetchedProp) return; setChatsLoading(true); // scrollToNext(); - const { chatsResponse, lastThreadHash, lastListPresent } = await getChats({ + const { chatsResponse, lastListPresent } = await getChats({ account, - pgpPrivateKey: connectedUser.privateKey, + pushUser, chatId: currentChat?.did || currentChat?.groupInformation?.chatId, - threadHash: lastThreadHashFetchedProp!, limit: chatsFetchedLimit, }); + console.log("my chat" ,chatsResponse); // remove this custom decryption after SDK issue is resolved in future - const promiseArrToDecryptMsg = []; - chatsResponse.forEach((chat) => - promiseArrToDecryptMsg.push( - w2wHelper.decryptMessages({ - savedMsg: chat, - connectedUser, - account, - currentChat, - inbox, - }) - ) - ); - const decryptedMsgArr = await Promise.all(promiseArrToDecryptMsg); - decryptedMsgArr.sort((a, b) => { - return a.timestamp! > b.timestamp! ? 1 : -1; - }); + + - setMessages([...decryptedMsgArr, ...messagesProp]); - setLastThreadHashFetched(lastThreadHash); + setMessages([...chatsResponse]); + // setLastThreadHashFetched(lastThreadHash); setWasLastListPresent(lastListPresent); setChatsLoading(false); }; + + useEffect(() => { setWasLastListPresent(false); setLastThreadHashFetched(null); @@ -240,8 +239,14 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { if (currentChat?.wallets) return caip10ToWallet(currentChat?.wallets?.split(',')[0].toString()); }; + useEffect(() => { + const test = async () => { + console.log("my userr", await pushUser.chat.list("CHATS")) + } + test(); + },[pushUser]) const fetchInboxApi = async (): Promise => { - const inboxes: Feeds[] = await fetchInbox({connectedUser}); + const inboxes: Feeds[] = await fetchInbox({connectedUser, pushUser}); setInbox(inboxes); return inboxes?.find((x) => x.wallets.split(':')[1]?.toLowerCase() === currentChat.wallets.split(':')[1]?.toLowerCase()); }; @@ -261,14 +266,11 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { createdUser = await createUserIfNecessary(); } const signer = await provider.getSigner(); + let receiverAddress= isGroup ? currentChat.groupInformation?.chatId : currentChat?.wallets - const sendResponse = await PushAPI.chat.send({ - messageContent: message, - messageType: messageType, - receiverAddress: isGroup ? currentChat.groupInformation?.chatId : currentChat?.wallets, - signer: signer!, - pgpPrivateKey: connectedUser?.privateKey || createdUser?.privateKey, - env: appConfig.appEnv, + const sendResponse = await pushUser.chat.send(receiverAddress,{ + content:message, + type: messageType, }); if (typeof sendResponse !== 'string') { @@ -313,11 +315,12 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { setLoading(true); // If the user is not registered in the protocol yet, his did will be his wallet address const didOrWallet: string = connectedUser.wallets.split(':')[1]; - let intents = await PushAPI.chat.requests({ account: didOrWallet!, env: appConfig.appEnv, toDecrypt: true, pgpPrivateKey:connectedUser.privateKey }); + let intents = await pushUser.chat.list('REQUESTS') setReceivedIntents(intents); setLoading(false); } + console.log("requestsss" , receivedIntents); async function ApproveIntent(status: string): Promise { setMessageBeingSent(true); let updatedIntent: any; @@ -326,14 +329,9 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { if (!connectedUser.publicKey) { createdUser = await createUserIfNecessary(); } - const signer = await provider.getSigner(); - updatedIntent = await PushAPI.chat.approve({ - status: 'Approved', - signer: signer!, - senderAddress: isGroup ? currentChat.groupInformation?.chatId : currentChat.intentSentBy, - pgpPrivateKey: connectedUser?.privateKey || createdUser?.privateKey, - env: appConfig.appEnv, - }); + let senderAddress= isGroup ? currentChat.groupInformation?.chatId : currentChat.intentSentBy, + + updatedIntent = await pushUser.chat.accept(senderAddress); let activeChat = currentChat; activeChat.intent = updatedIntent.data; @@ -388,17 +386,14 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { !currentChat.intent?.toLowerCase().includes(currentChat.wallets.split(':')[1]?.toLowerCase()) ) { let createdUser; - if (!connectedUser.publicKey) { + if (!connectedUser.privateKey) { createdUser = await createUserIfNecessary(); } - const signer = await provider.getSigner(); - const sendResponse = await PushAPI.chat.send({ - messageContent: message, - messageType: messageType, - receiverAddress: currentChat?.wallets.split(':')[1], - signer: signer!, - pgpPrivateKey: connectedUser.privateKey || createdUser?.privateKey, - env: appConfig.appEnv, + let receiverAddress= currentChat?.wallets.split(':')[1] + + const sendResponse = await pushUser.chat.send(receiverAddress,{ + content: message, + type: messageType, }); if (typeof sendResponse !== 'string') { @@ -406,6 +401,7 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { sendResponse.messageContent = message; setNewMessage(''); let result = await fetchInboxApi(); + console.log("newww", result) result.msg.messageContent = message; setChat(result); chatBoxToast.showMessageToast({ @@ -457,7 +453,7 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { return produce(oldData, (draft) => { draft.local.address = account; draft.incoming[0].address = caip10ToWallet(currentChat.wallets.toString()); - draft.incoming[0].status = PushAPI.VideoCallStatus.INITIALIZED; + draft.incoming[0].status = VideoCallStatus.INITIALIZED; draft.meta.chatId = currentChat.chatId; }); }); @@ -645,87 +641,33 @@ const ChatBox = ({ showGroupInfoModal }): JSX.Element => { > {/* style={{overflow: "scroll",backgroundColor:'red'}} */} {/* */} - {Loading ? ( - - - - ) : ( - <> - {chatsLoading && ( - - - - )} + <>
- {messages?.map((msg, i) => { - //const isLast = i === messages.length - 1 - //const noTail = !isLast && messages[i + 1]?.fromDID === msg.fromDID - - showTime = false; - if (i >= 0) { - const duration = new Date(messages[i]?.timestamp); - const dateString = duration.toDateString(); - if (dateString !== time || i === 0) { - showTime = true; - time = dateString; - } - } - return ( -
- {!showTime ? null : ( - - )} - - -
- ); - })} + +
- + {checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser, isGroup }) && ( - ApproveIntent('Approved')} - isGroup={isGroup} - /> + )} - )} + {/*
*/}
- {checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser,isGroup }) ? null : ( + {checkIfChatExist({ chats:receivedIntents, currentChat, connectedUser,isGroup }) ? + + + + : ( <> - + + + + {/* { setSnackbarText={setSnackbarText} isJoinGroup = {(!checkIfChatExist({ chats:inbox, currentChat, connectedUser,isGroup }) && isGroup)} approveIntent= {ApproveIntent} - /> + /> */} )} @@ -751,6 +693,13 @@ const SpinnerWrapper = styled.div` height: ${(props) => props.height || '90px'}; `; +const MessageInputWrapper = styled.div` + margin-top: auto; + margin-botton: 0; + width: 100%; + z-index: 99; +` + const MessageContainer = styled(ItemVV2)` align-items: unset; display: block; diff --git a/src/components/chat/w2wChat/chats/Chats.tsx b/src/components/chat/w2wChat/chats/Chats.tsx index fc0ed9ddb1..0597a66fd4 100644 --- a/src/components/chat/w2wChat/chats/Chats.tsx +++ b/src/components/chat/w2wChat/chats/Chats.tsx @@ -7,7 +7,7 @@ import { TwitterTweetEmbed } from 'react-twitter-embed'; import styled from 'styled-components'; // Internal Components -import * as PushAPI from '@pushprotocol/restapi'; +import {PushAPI} from '@pushprotocol/restapi'; import LoaderSpinner, { LOADER_TYPE } from 'components/reusables/loaders/LoaderSpinner'; import { ImageV2, ItemHV2, ItemVV2, SpanV2 } from 'components/reusables/SharedStylingV2'; import { shortenText } from 'helpers/UtilityHelper'; @@ -35,9 +35,10 @@ interface ChatProps { messageBeingSent: boolean; ApproveIntent?: Function; isGroup?: boolean; + pushUser: PushAPI; } -export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, isGroup }: ChatProps) { +export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, isGroup, pushUser }: ChatProps) { const { currentChat }: ContextType = useContext(Context); const { web3NameList }: AppContextType = useContext(AppContext); const [showImageModal, setShowImageModal] = useState(false); @@ -63,8 +64,8 @@ export default function Chats({ msg, caip10, messageBeingSent, ApproveIntent, is setProfilePicture(member.image); } else { // console.log(msg) - let user = await PushAPI.user.get({ account: msg.fromCAIP10, env: appConfig.appEnv }); - setProfilePicture(user.profilePicture); + let user = await pushUser.info(); + setProfilePicture(user.profile.picture); } }; diff --git a/src/components/chat/w2wChat/groupChat/createGroup/CreateGroupModalContent.tsx b/src/components/chat/w2wChat/groupChat/createGroup/CreateGroupModalContent.tsx index 275f61b838..e509f6e030 100644 --- a/src/components/chat/w2wChat/groupChat/createGroup/CreateGroupModalContent.tsx +++ b/src/components/chat/w2wChat/groupChat/createGroup/CreateGroupModalContent.tsx @@ -5,7 +5,7 @@ import React, { useContext } from 'react'; import styled, { ThemeProvider, useTheme } from 'styled-components'; import { useClickAway } from 'react-use'; import { ethers } from 'ethers'; -import * as PushAPI from '@pushprotocol/restapi'; +import { PushAPI} from '@pushprotocol/restapi'; // Internal Components import { ModalInnerComponentType } from 'hooks/useModalBlur'; @@ -37,7 +37,7 @@ export const CreateGroupModalContent = ({ onClose, onConfirm: createGroup, toast const [groupTypeObject, setGroupTypeObject] = React.useState(); const [isLoading, setIsLoading] = React.useState(false); const [memberList, setMemberList] = React.useState([]); - const { connectedUser, setConnectedUser , createUserIfNecessary} = useContext(ChatUserContext); + const { connectedUser, setConnectedUser , pushUser, createUserIfNecessary} = useContext(ChatUserContext); const {provider } = useAccount(); const themes = useTheme(); const createGroupToast = useToast(); @@ -65,19 +65,17 @@ export const CreateGroupModalContent = ({ onClose, onConfirm: createGroup, toast createdUser = await createUserIfNecessary(); } const signer = await provider.getSigner(); - const createGroupRes = await PushAPI.chat.createGroup({ - groupName: groupNameData, - groupDescription: groupDescriptionData, + const createGroupRes = await pushUser.chat.group.create(groupNameData,{ + + description: groupDescriptionData, members: memberWalletList, - groupImage: groupImageData ?? profilePicture, + image: groupImageData ?? profilePicture, admins: adminWalletList, - isPublic: groupTypeObject.groupTypeData == 'public' ? true : false, + private: groupTypeObject.groupTypeData == 'public' ? false : true, signer: signer!, - pgpPrivateKey: connectedUser?.privateKey || createdUser?.privateKey, - env: appConfig.appEnv, }); if (typeof createGroupRes !== 'string') { - const inboxes: Feeds[] = await fetchInbox({connectedUser}); + const inboxes: Feeds[] = await fetchInbox({connectedUser, pushUser}); setInbox(inboxes); createGroupToast.showMessageToast({ toastTitle: 'Success', diff --git a/src/components/chat/w2wChat/groupChat/createGroup/GroupDetailsContent.tsx b/src/components/chat/w2wChat/groupChat/createGroup/GroupDetailsContent.tsx index fda7e4ae1b..f4e0d00089 100644 --- a/src/components/chat/w2wChat/groupChat/createGroup/GroupDetailsContent.tsx +++ b/src/components/chat/w2wChat/groupChat/createGroup/GroupDetailsContent.tsx @@ -5,7 +5,7 @@ import React from 'react'; import styled, { ThemeProvider, useTheme } from 'styled-components'; import * as PushAPI from '@pushprotocol/restapi'; import { MdError } from 'react-icons/md'; - +import {Moda} // Internal Components import ModalConfirmButton from 'primaries/SharedModalComponents/ModalConfirmButton'; import { ImageV2, ItemHV2, ItemVV2, SpanV2 } from 'components/reusables/SharedStylingV2'; @@ -19,7 +19,7 @@ import { device } from 'config/Globals'; import GroupModalHeader from './GroupModalHeader'; import AutoImageClipper from 'primaries/AutoImageClipper'; import useToast from 'hooks/useToast'; - +import { CreateGroupModal } from '@pushprotocol/uiweb'; export const GroupDetailsContent = ({ groupNameData, groupDescriptionData, @@ -78,31 +78,7 @@ export const GroupDetailsContent = ({ }; const handleValidation = async () => { - try { - const getGroupResponse = await PushAPI.chat.getGroupByName({ groupName: groupNameData, env: appConfig.appEnv }); - if (typeof getGroupResponse !== 'string') { - setErrorInfo((x) => ({ - ...x, - name: 'Group Name should be unique! Please retry!', - })); - - return false; - } - } catch (e) { - groupDetailToast.showMessageToast({ - toastTitle: 'Error', - toastMessage: 'Error in finding group name', - toastType: 'ERROR', - getToastIcon: (size) => ( - - ), - }); - - } - + if (!isLengthValid(groupNameData, 50)) { setErrorInfo((x) => ({ ...x, diff --git a/src/components/chat/w2wChat/groupChat/groupInfo/groupInfoModalContent.tsx b/src/components/chat/w2wChat/groupChat/groupInfo/groupInfoModalContent.tsx index a024152689..cec4f5c413 100644 --- a/src/components/chat/w2wChat/groupChat/groupInfo/groupInfoModalContent.tsx +++ b/src/components/chat/w2wChat/groupChat/groupInfo/groupInfoModalContent.tsx @@ -25,6 +25,7 @@ import { getUpdatedAdminList, getUpdatedMemberList, updateGroup, + updateGroupMembers } from '../../../../../helpers/w2w/groupChat'; import { getDefaultFeed } from '../../../../../helpers/w2w/user'; import { Feeds } from '../../../../../types/chat'; @@ -41,7 +42,7 @@ import { copyToClipboard, shortenText } from 'helpers/UtilityHelper'; export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { const { currentChat, setChat, inbox, receivedIntents }: AppContext = useContext(Context); - const { connectedUser } = useContext(ChatUserContext); + const { connectedUser, pushUser } = useContext(ChatUserContext); const [copyText, setCopyText] = useState(''); const { account } = useAccount(); const groupInfoToast = useToast(); @@ -73,6 +74,8 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { handleClose(); }; + console.log("valueee", memberList) + const makeGroupAdmin = async () => { const groupMemberList = convertToWalletAddressList([ ...currentChat?.groupInformation?.members, @@ -81,6 +84,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { const newAdminList = getUpdatedAdminList(currentChat?.groupInformation, selectedMemeberAddress, false); try { const { updateResponse, updatedCurrentChat } = await updateGroup({ + pushUser, currentChat, connectedUser, adminList: newAdminList, @@ -120,6 +124,8 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { setSelectedMemeberAddress(null); }; + + const dismissGroupAdmin = async () => { const groupMemberList = convertToWalletAddressList([ ...currentChat?.groupInformation?.members, @@ -129,6 +135,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { try { const { updateResponse, updatedCurrentChat } = await updateGroup({ currentChat, + pushUser, connectedUser, adminList: newAdminList, memeberList: groupMemberList, @@ -173,6 +180,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { try { const { updateResponse, updatedCurrentChat } = await updateGroup({ currentChat, + pushUser, connectedUser, adminList, memeberList: updatedMemberList, @@ -212,6 +220,69 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { setSelectedMemeberAddress(null); }; + const updateMembers = async () => { + const newMembersToAdd = memberList.map((member) => member.wallets); + console.log(newMembersToAdd); + try { + setIsLoading(true); + const { updateResponse, updatedCurrentChat } = await updateGroupMembers({ + role: "MEMBER", + currentChat, + pushUser, + memeberList: newMembersToAdd + + }) + + console.log("checking the responseee",updateResponse); + + if (typeof updateResponse !== 'string') { + setSelectedMemeberAddress(null); + if (updatedCurrentChat) setChat(updatedCurrentChat); + } else { + groupInfoToast.showMessageToast({ + toastTitle: 'Error', + toastMessage: updateResponse, + toastType: 'ERROR', + getToastIcon: (size) => ( + + ), + }); + setSelectedMemeberAddress(null); + } + setIsLoading(false); + groupInfoToast.showMessageToast({ + toastTitle: 'Success', + toastMessage: 'Group Invitation sent', + toastType: 'SUCCESS', + getToastIcon: (size) => ( + + ), + }); + handleClose(); + } catch (error) { + setIsLoading(false); + console.log('Error', error); + groupInfoToast.showMessageToast({ + toastTitle: 'Error', + toastMessage: error.message, + toastType: 'ERROR', + getToastIcon: (size) => ( + + ), + }); + } + setIsLoading(false); + } + const addMembers = async () => { //Already Present Members and PendingMembers const groupMemberList = convertToWalletAddressList([ @@ -229,8 +300,10 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { try { setIsLoading(true); const { updateResponse, updatedCurrentChat } = await updateGroup({ + currentChat, connectedUser, + pushUser, adminList, memeberList: members, }); @@ -547,7 +620,7 @@ export const GroupInfoModalContent = ({ onClose }: ModalInnerComponentType) => { {showAddMoreWalletModal && ( { receivedIntents, setReceivedIntents }: AppContext = useContext(Context); - const { connectedUser} = useContext(ChatUserContext); + const { connectedUser, pushUser} = useContext(ChatUserContext); const [selectedIntentSnap, setSelectedIntentSnap] = useState(); const { chainId, account } = useAccount(); const [limit, setLimit] = useState(10); @@ -38,7 +38,7 @@ const IntentFeed = ({isLoading}): JSX.Element => { const updateIntents=async({chatLimit}:{chatLimit?:number})=>{ try{ setIntentLoading(true) - const intents=await fetchIntent({connectedUser, limit}) + const intents=await fetchIntent({connectedUser,pushUser, limit:chatLimit, page:1}) if(intents?.length>10 && receivedIntents?.length === intents?.length){ setIsFetchingDone(true); } @@ -64,7 +64,8 @@ const IntentFeed = ({isLoading}): JSX.Element => { const showWayPoint = (index: any) => { return Number(index) === receivedIntents?.length - 1 && !intentLoading && !bgUpdateLoading; }; - +// console.log("in", receivedIntents); + // console return ( <> { const { setChat, setInbox, currentChat, receivedIntents, setActiveTab, activeTab, inbox, setHasUserBeenSearched, filteredUserData, setFilteredUserData }: AppContext = useContext(Context); - const { connectedUser } = useContext(ChatUserContext); + const { connectedUser, pushUser } = useContext(ChatUserContext); const [feeds, setFeeds] = useState([]); const [messagesLoading, setMessagesLoading] = useState(true); @@ -48,24 +48,23 @@ const MessageFeed = (props: MessageFeedPropsI): JSX.Element => { const messageFeedToast = useToast(); const onFeedClick = (feed:Feeds,i:number):void => { - if((receivedIntents?.filter((userExist) => userExist.did && props?.filteredUserData[0]?.did && userExist.did?.toLowerCase() === props?.filteredUserData[0]?.did?.toLowerCase())) -.length) + if((receivedIntents?.filter((userExist) => userExist.did && props?.filteredUserData[0]?.did && userExist.did?.toLowerCase() === props?.filteredUserData[0]?.did?.toLowerCase()))?.length) { setActiveTab(1); } setChat(feed); setSelectedChatSnap(i); setHasUserBeenSearched(false); - filteredUserData.length>0 ? setFilteredUserData([]):null; + filteredUserData?.length>0 ? setFilteredUserData([]):null; } const fetchInboxApi = async ({limit}): Promise => { try { - const inboxes:Feeds[] = await fetchInbox({connectedUser, limit}); + const inboxes:Feeds[] = await fetchInbox({connectedUser, pushUser, limit}); if(inboxes?.length>10 && inboxes?.length===feeds?.length){ setIsFetchingDone(true); } - else if(inboxes.length<10){ + else if(inboxes?.length<10){ setIsFetchingDone(true); } if (JSON.stringify(inbox) !== JSON.stringify(inboxes)){ @@ -83,6 +82,7 @@ const MessageFeed = (props: MessageFeedPropsI): JSX.Element => { setShowError(false); return inboxes; } catch (e) { + console.log("checkkk" ,e) if (!showError) { messageFeedToast.showMessageToast({ toastTitle: 'Error', @@ -128,8 +128,8 @@ const MessageFeed = (props: MessageFeedPropsI): JSX.Element => { updateInbox({chatLimit:limit}); } else { const searchFn = async (): Promise => { - if (props.filteredUserData.length) { - if (Object(props.filteredUserData[0]).wallets?.toLowerCase() === walletToCAIP10({ account })?.toLowerCase()) { + if (props.filteredUserData?.length) { + if (Object(props.filteredUserData[0])?.wallets?.toLowerCase() === walletToCAIP10({ account })?.toLowerCase()) { messageFeedToast.showMessageToast({ toastTitle: 'Error', toastMessage: "You can't send intent to yourself", @@ -151,7 +151,7 @@ const MessageFeed = (props: MessageFeedPropsI): JSX.Element => { ({feed,isNew} = await getDefaultGroupFeed({groupData:searchedData as IGroup,inbox,intents:receivedIntents})); } else { - feed = await getDefaultFeed({userData:searchedData as User,inbox,intents:receivedIntents}); + feed = await getDefaultFeed({userData:searchedData as User, pushUser, inbox,intents:receivedIntents}); } if(isNew && !feed?.groupInformation?.isPublic) { diff --git a/src/contexts/ChatUserContext.tsx b/src/contexts/ChatUserContext.tsx index 39b688bdfc..0cd2d4b72a 100644 --- a/src/contexts/ChatUserContext.tsx +++ b/src/contexts/ChatUserContext.tsx @@ -1,5 +1,6 @@ -import * as PushAPI from "@pushprotocol/restapi"; +// import * as PushAPI from "@pushprotocol/restapi"; import { ProgressHookType } from "@pushprotocol/restapi"; +import { useEffect } from "react"; import { LOADER_SPINNER_TYPE } from 'components/reusables/loaders/LoaderSpinner'; import { appConfig } from 'config'; import { ethers } from 'ethers'; @@ -7,13 +8,42 @@ import * as w2wHelper from 'helpers/w2w'; import { useAccount } from "hooks"; import React, { createContext, useState } from 'react'; import { BlockedLoadingI, ConnectedUser, User } from 'types/chat'; - +import { PushAPI } from "@pushprotocol/restapi"; +import { ENV } from "@pushprotocol/restapi/src/lib/constants"; export const ChatUserContext = createContext({}) //this context is global and it is called in APP.tsx const ChatUserContextProvider = (props) => { const [connectedUser, setConnectedUser] = useState(); const { account, provider } = useAccount(); + const [pushUser, setPushUser] = useState(null); + const [signerValue, setSignerValue] = useState() + + + + useEffect(() => { + (async () => { + if(account) { + + const signer = await provider.getSigner(); + setSignerValue(signer); + } + })(); + },[account]) + + useEffect(() => { + ( + async() =>{ + if(Object.keys(signerValue || {}).length && account){ + const pushUser = await PushAPI.initialize(signerValue!, {env: ENV.PROD , account}); + setPushUser(pushUser) + } + } + )() + + },[signerValue, account]) + +console.log("the user" ,pushUser); //this blocked loading is a modal which shows during the PGP keys generation time const [blockedLoading, setBlockedLoading] = useState({ @@ -46,6 +76,9 @@ const ChatUserContextProvider = (props) => { progress: 0 }; + console.log(onboardingProgress) + + console.log("decrypting..." ,progressHook); if (progressHook) { switch (progressHook.progressId) { case "PUSH-CREATE-01": @@ -127,10 +160,9 @@ const ChatUserContextProvider = (props) => { const getUser = async () => { console.log("getUser"); const caip10: string = w2wHelper.walletToCAIP10({ account }); - const user: User = await PushAPI.user.get({ - account: caip10, - env: appConfig.appEnv - }); + + const user: User = await pushUser?.info() + console.log(user); let connectedUser: ConnectedUser; // TODO: Change this to do verification on ceramic to validate if did is valid @@ -144,16 +176,16 @@ const ChatUserContextProvider = (props) => { throw Error('Invalid user'); } const _signer = await provider.getSigner(); - const privateKeyArmored = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: user.encryptedPrivateKey, - signer: _signer, - env: appConfig.appEnv, - toUpgrade: true, - progressHook: onboardingProgressReformatter - }); + // const privateKeyArmored = await pushUser.chat.decryptPGPKey({ + // encryptedPGPPrivateKey: user.encryptedPrivateKey, + // signer: _signer, + // env: appConfig.appEnv, + // toUpgrade: true, + // progressHook: onboardingProgressReformatter + // }); - setPgpPvtKey(privateKeyArmored); - connectedUser = { ...user, privateKey: privateKeyArmored }; + // setPgpPvtKey(privateKeyArmored); + connectedUser = { ...user }; } else { connectedUser = { // We only need to provide this information when it's a new user @@ -171,37 +203,40 @@ const ChatUserContextProvider = (props) => { sigType: '', signature: '', linkedListHash: '', - privateKey: '', + // privateKey: '', }; } setConnectedUser(connectedUser); }; + (async() => { + console.log("inffffooo" , await pushUser?.info()) + })() + + const createUserIfNecessary = async (): Promise => { try { const signer = await provider.getSigner(); - await PushAPI.user.create({ - account: account, - env: appConfig.appEnv, - signer: signer, + const user = await PushAPI.initialize(signer, { + env: ENV.PROD, + account:account, + autoUpgrade: true, progressHook: onboardingProgressReformatter - }); - const createdUser = await PushAPI.user.get({ - account: account, - env: appConfig.appEnv - }); - const pvtkey = await PushAPI.chat.decryptPGPKey({ - encryptedPGPPrivateKey: createdUser.encryptedPrivateKey, - signer: signer, - env: appConfig.appEnv, - toUpgrade: true, - progressHook: onboardingProgressReformatter - }); + }) + const createdUser = await user.info(); + + // const pvtkey = await PushAPI.chat.decryptPGPKey({ + // encryptedPGPPrivateKey: createdUser.encryptedPrivateKey, + // signer: signer, + // env: appConfig.appEnv, + // autoUpgrade: true, + // progressHook: onboardingProgressReformatter + // }); - const createdConnectedUser = { ...createdUser, privateKey: pvtkey }; + const createdConnectedUser = { ...createdUser }; setConnectedUser(createdConnectedUser); - setPgpPvtKey(pvtkey); + // setPgpPvtKey(pvtkey); return createdConnectedUser ; } catch (e) { @@ -212,6 +247,7 @@ const ChatUserContextProvider = (props) => { return ( , memeberList:Array, } +type updateGroupMembers = { + pushUser:PushAPI, + currentChat:Feeds, + role:"ADMIN" | "MEMBER", + adminList?:Array, + memeberList?:Array, +} + + export const checkIfGroup = (feed: Feeds): boolean => { if (feed?.hasOwnProperty('groupInformation') && feed?.groupInformation ) return true; return false; @@ -72,7 +83,7 @@ export const getChatsnapMessage = (feed: Feeds, account: string, isIntent?: bool } return { - type: feed.msg.messageType, + type: feed.msg?.messageType, message: feed.msg.messageContent, }; }; @@ -109,22 +120,50 @@ export const getUpdatedMemberList = (feed:Feeds,walletAddress:string): Array { + const { memeberList, role, pushUser, currentChat, adminList} =options; + let chatId= currentChat?.groupInformation?.chatId + // userAlice.chat.group.update(chatid, {options?}) +try { + console.log("startingggggg") +const updateResponse = await pushUser.chat.group.add(chatId, { + role: role, + accounts: memeberList +}); + +console.log("i is updated", updateResponse); + +let updatedCurrentChat = null; + console.log(currentChat); + if(typeof updateResponse !== 'string') + { + updatedCurrentChat = currentChat; + updatedCurrentChat.groupInformation = updateResponse; + } + return {updateResponse,updatedCurrentChat}; +} catch (error) { + console.log("err", error.message); + return; +} + +} export const updateGroup = async(options:UpdateGroupType) => { - const { currentChat, connectedUser,adminList,memeberList } = options; - const updateResponse = await PushAPI.chat.updateGroup({ - chatId: currentChat?.groupInformation?.chatId, - groupName: currentChat?.groupInformation?.groupName, - groupDescription: currentChat?.groupInformation?.groupDescription, - groupImage: currentChat?.groupInformation?.groupImage, + const { currentChat, connectedUser,adminList,memeberList, pushUser } = options; + let chatId= currentChat?.groupInformation?.chatId + const updateResponse = await pushUser.chat.group.update(chatId,{ + + name: currentChat?.groupInformation?.groupName, + description: currentChat?.groupInformation?.groupDescription, + image: currentChat?.groupInformation?.groupImage, members: memeberList, admins: adminList, account: connectedUser?.wallets, - pgpPrivateKey: connectedUser?.privateKey, - env: appConfig.appEnv, + }); let updatedCurrentChat = null; + console.log(currentChat); if(typeof updateResponse !== 'string') { updatedCurrentChat = currentChat; diff --git a/src/helpers/w2w/user.ts b/src/helpers/w2w/user.ts index 1eeedcac8a..10249b582a 100644 --- a/src/helpers/w2w/user.ts +++ b/src/helpers/w2w/user.ts @@ -1,10 +1,10 @@ -import * as PushAPI from '@pushprotocol/restapi'; +import {PushAPI} from '@pushprotocol/restapi'; import { profilePicture } from 'config/W2WConfig'; import * as w2wHelper from 'helpers/w2w/'; + import { ConnectedUser, Feeds, IGroup, MessageIPFS, User } from 'types/chat'; import { walletToCAIP10 } from '.'; import { appConfig } from '../../config'; -import { decrypt, message } from 'openpgp'; export function checkConnectedUser(connectedUser: ConnectedUser): boolean { if ( @@ -100,26 +100,25 @@ export const getDefaultFeed = async ({ userData, inbox, intents, + pushUser }: { walletAddress?: string; userData?: User; inbox: Feeds[]; intents: Feeds[]; + pushUser?: any }): Promise => { const user = userData ?? - (await PushAPI.user.get({ - account: walletAddress!, - env: appConfig.appEnv, - })); + (await pushUser.chat.list("CHATS")) let feed:Feeds; - const inboxUser = inbox.filter((inb) => inb.did?.toLowerCase() === user.did?.toLowerCase()); + const inboxUser = inbox?.filter((inb) => inb.did?.toLowerCase() === user.did?.toLowerCase()); - const intentUser = intents.filter((userExist) => userExist.did?.toLowerCase() === user.did?.toLowerCase()); - if (inboxUser.length) { + const intentUser = intents?.filter((userExist) => userExist.did?.toLowerCase() === user.did?.toLowerCase()); + if (inboxUser?.length) { feed = inboxUser[0]; - } else if(intentUser.length){ + } else if(intentUser?.length){ feed = intentUser[0]; } else { @@ -139,12 +138,12 @@ export const getDefaultGroupFeed = async ({ }): Promise<{feed:Feeds,isNew:boolean}> => { let isNew:boolean = false; let feed:Feeds; - const inboxGroup = inbox.filter((inb) => inb?.groupInformation?.chatId === groupData.chatId); + const inboxGroup = inbox?.filter((inb) => inb?.groupInformation?.chatId === groupData.chatId); - const intentGroup = intents.filter((int) =>int?.groupInformation?.chatId === groupData.chatId); - if (inboxGroup.length) { + const intentGroup = intents?.filter((int) =>int?.groupInformation?.chatId === groupData.chatId); + if (inboxGroup?.length) { feed = inboxGroup[0]; - } else if(intentGroup.length){ + } else if(intentGroup?.length){ feed = intentGroup[0]; } else { @@ -188,13 +187,15 @@ export const getDefaultFeedObject = ({user,groupInformation}:{user?:User,groupIn -export const fetchInbox = async ({connectedUser, page, limit}:{connectedUser:any, page?:number, limit?:number}):Promise=> { - let inboxes:Feeds[] = await PushAPI.chat.chats({ account: connectedUser.wallets!, env: appConfig.appEnv, toDecrypt: true, pgpPrivateKey: connectedUser.privateKey, page, limit}); +export const fetchInbox = async ({connectedUser, pushUser, page, limit}:{connectedUser?:any, pushUser: PushAPI, page?:number, limit?:number}):Promise=> { + let inboxes:Feeds[] = await pushUser?.chat?.list("CHATS", {page, limit}); + console.log("my inboaxes", inboxes) return inboxes }; -export const fetchIntent = async ({connectedUser, page, limit}:{connectedUser:any, page?:number, limit?:number}): Promise => { - let intents = await PushAPI.chat.requests({account:connectedUser.wallets.split(':')[1], env:appConfig.appEnv, toDecrypt: true, pgpPrivateKey: connectedUser.privateKey, page, limit}); +export const fetchIntent = async ({connectedUser, pushUser, page, limit}:{connectedUser:any, pushUser: PushAPI , page?:number, limit?:number}): Promise => { + let intents = await pushUser?.chat?.list("REQUESTS", {page, limit}); + console.log("my intens", intents) return intents; }; @@ -203,8 +204,9 @@ export const getUpdatedChatAndIntent= async ({chatList,message,connectedUser,acc let decryptedChat:MessageIPFS; //change to common decryption for getUpdatedInbox and getUpdatedChats using filter - const updatedFeed = chatList.filter(feed=>(feed.did?.toLowerCase() === message.fromCAIP10?.toLowerCase()) || (feed?.groupInformation?.chatId === message.toCAIP10)); - if(updatedFeed.length && checkInbox){ + const updatedFeed = chatList?.filter(feed=>(feed.did?.toLowerCase() === message.fromCAIP10?.toLowerCase()) || (feed?.groupInformation?.chatId === message.toCAIP10)); + console.log("seeee",updatedFeed) + if(updatedFeed?.length && checkInbox){ decryptedChat = await w2wHelper.decryptMessages({ savedMsg: message, connectedUser, diff --git a/src/modules/chat/ChatModule.tsx b/src/modules/chat/ChatModule.tsx index 2900ed2cad..77cfe589eb 100644 --- a/src/modules/chat/ChatModule.tsx +++ b/src/modules/chat/ChatModule.tsx @@ -2,7 +2,7 @@ import { ethers } from 'ethers'; import React, { useContext, useEffect, useState } from 'react'; import { useNavigate } from "react-router-dom"; - +import { ChatViewList } from '@pushprotocol/uiweb'; // External Packages import * as PushAPI from "@pushprotocol/restapi"; import ReactGA from 'react-ga'; @@ -100,8 +100,11 @@ function Chat({ chatid }) { getUpdatedGroup(socketData.groupInformationSinceLastConnection); } },[socketData.groupInformationSinceLastConnection]) + console.log("current chat", currentChat); + const getUpdatedChats = async(chat) => { + console.log("somechat", chat); if((currentChat.did?.toLowerCase() === chat.fromCAIP10?.toLowerCase()) || currentChat?.groupInformation?.chatId === chat.toCAIP10){ const decryptedChat:MessageIPFS = await w2wHelper.decryptMessages({ savedMsg: chat, @@ -138,6 +141,7 @@ function Chat({ chatid }) { recipient: caip10ToWallet(message?.fromCAIP10), env: appConfig.appEnv }); + console.log("",fetchedChat); if(checkIfIntent({chat:fetchedChat, account})){ setReceivedIntents(prev=> [fetchedChat, ...prev]); @@ -208,6 +212,8 @@ const getUpdatedGroup = async(groupInfo) => { setInbox(prev=>[fetchedChat,...prev]) } } + + console.log("fettt", receivedIntents); // let isInInbox = false; // const updatedInbox = inbox.map(feed => { // if(feed?.groupInformation?.chatId === groupInfo.chatId){ diff --git a/src/sections/chat/ChatSidebarSection.tsx b/src/sections/chat/ChatSidebarSection.tsx index ab05028826..60ff29bf75 100644 --- a/src/sections/chat/ChatSidebarSection.tsx +++ b/src/sections/chat/ChatSidebarSection.tsx @@ -6,9 +6,8 @@ import React, { useContext, useEffect, useState } from 'react'; import { AiOutlineQrcode } from 'react-icons/ai'; import { useClickAway } from 'react-use'; import styled, { useTheme } from 'styled-components'; - +import { CreateGroupModal } from '@pushprotocol/uiweb'; // Internal Compoonents -import * as PushAPI from "@pushprotocol/restapi"; import { ReactComponent as CreateGroupIcon } from 'assets/chat/group-chat/creategroup.svg'; import { ReactComponent as CreateGroupFillIcon } from 'assets/chat/group-chat/creategroupfill.svg'; import IntentFeed from 'components/chat/w2wChat/intentFeed/IntentFeed'; @@ -69,13 +68,14 @@ const ChatSidebarSection = ({ showCreateGroupModal, autofilledSearch }) => { const isNewTagVisible = getIsNewTagVisible(new Date("2023-02-22T00:00:00.000"), 90); - const { connectedUser, displayQR, setDisplayQR } = useContext(ChatUserContext); + const { connectedUser, displayQR, setDisplayQR, pushUser } = useContext(ChatUserContext); const { activeTab, setActiveTab } = useContext(Context); const [updateProfileImage, setUserProfileImage] = useState(connectedUser?.profilePicture); const [loadingRequests, setLoadingRequests] = useState(true); const [showQR, setShowQR] = useState(false); + const [showGroupModal, setShowGroupModal] = useState(false); const containerRef = React.useRef(null); const updateProfile = (image: string) => { @@ -97,7 +97,7 @@ const ChatSidebarSection = ({ showCreateGroupModal, autofilledSearch }) => { useClickAway(containerRef, () => closeQRDropdown()) const fetchIntentApi = async (): Promise => { - const intents = await fetchIntent({connectedUser}); + const intents = await fetchIntent({connectedUser, pushUser}); if (JSON.stringify(intents) != JSON.stringify(receivedIntents)) { setReceivedIntents(intents); setLoadingRequests(false); @@ -162,7 +162,7 @@ const ChatSidebarSection = ({ showCreateGroupModal, autofilledSearch }) => { > Requests - {!loadingRequests && receivedIntents.length > 0 && ( + {!loadingRequests && receivedIntents?.length > 0 && ( { fontSize="12px" borderRadius={GLOBALS.ADJUSTMENTS.RADIUS.SMALL} > - {receivedIntents.length} + {receivedIntents?.length} )} @@ -188,13 +188,13 @@ const ChatSidebarSection = ({ showCreateGroupModal, autofilledSearch }) => { onClick={closeQRDropdown} > {activeTab == 0 && } - {activeTab == 0 && filteredUserData.length == 0 && ( + {activeTab == 0 && filteredUserData?.length == 0 && ( showCreateGroupModal()} + onClick={()=>setShowGroupModal(true)} background="transparent" hover={theme.chat.snapFocusBg} hoverBackground="transparent" @@ -219,8 +219,11 @@ const ChatSidebarSection = ({ showCreateGroupModal, autofilledSearch }) => { {isNewTagVisible && } )} + { + showGroupModal && setShowGroupModal(false)}/> + } - {activeTab == 0 && filteredUserData.length == 0 && ( + {activeTab == 0 && filteredUserData?.length == 0 && ( 0 ? true : false; return { chatsResponse: chats, lastThreadHash, lastListPresent }; - } - return { chatsResponse: [], lastThreadHash: null, lastListPresent: false }; + }; \ No newline at end of file diff --git a/src/services/chats/getGroup.ts b/src/services/chats/getGroup.ts index 1f827d6ee4..ff3dba288c 100644 --- a/src/services/chats/getGroup.ts +++ b/src/services/chats/getGroup.ts @@ -1,12 +1,13 @@ - +import { useContext } from "react"; import { IGroup } from "types/chat"; import { getGroupbyChatId } from "./getGroupByChatId"; import { getGroupByName } from "./getGroupByName"; - +import { ChatUserContext } from 'contexts/ChatUserContext'; export const getGroup = async (searchedGroup:string,setInvalidSearch:()=>void): Promise => { + const { pushUser } = useContext(ChatUserContext); let group: IGroup; try{ - group = await getGroupbyChatId(searchedGroup); + group = await getGroupbyChatId(searchedGroup, pushUser); } catch (err) { if((err.message as string).includes('No group with chatId')){ try{ diff --git a/src/services/chats/getGroupByChatId.ts b/src/services/chats/getGroupByChatId.ts index f89b92d81b..0d3dc75b13 100644 --- a/src/services/chats/getGroupByChatId.ts +++ b/src/services/chats/getGroupByChatId.ts @@ -1,10 +1,11 @@ -import * as PushAPI from "@pushprotocol/restapi"; +import {PushAPI} from "@pushprotocol/restapi"; import { appConfig } from "config"; import { IGroup } from "types/chat"; -export const getGroupbyChatId = async (chatId:string): Promise => { +export const getGroupbyChatId = async (chatId:string , pushUser:PushAPI): Promise => { try{ - const getGroupResponse = await PushAPI.chat.getGroup({ chatId: chatId, env: appConfig.appEnv }); + const getGroupResponse = await pushUser.chat.group.info(chatId); + console.log("myyy chattt", getGroupResponse) return getGroupResponse; } catch(e){ diff --git a/src/services/chats/getGroupByName.ts b/src/services/chats/getGroupByName.ts index 39c2218f60..f5a91f489d 100644 --- a/src/services/chats/getGroupByName.ts +++ b/src/services/chats/getGroupByName.ts @@ -2,6 +2,7 @@ import * as PushAPI from "@pushprotocol/restapi"; import { appConfig } from "config"; import { IGroup } from "types/chat"; +//not being used anymore as unique names are not required export const getGroupByName = async (groupName:string): Promise => { try{ const getGroupResponse = await PushAPI.chat.getGroupByName({ groupName: groupName, env: appConfig.appEnv }); diff --git a/src/types/chat.ts b/src/types/chat.ts index 201074f3a9..6e624bd201 100644 --- a/src/types/chat.ts +++ b/src/types/chat.ts @@ -1,3 +1,4 @@ +import { IMessageIPFS } from "@pushprotocol/restapi" export interface MessageIPFS { fromCAIP10: string toCAIP10: string @@ -35,7 +36,7 @@ export interface User { } export interface ConnectedUser extends User { - privateKey: string | null; + privateKey?: string | null; } export interface Member { wallet: string; @@ -77,7 +78,7 @@ export interface ChatMetaI { export interface Feeds { chatId?: string; - msg: MessageIPFS; + msg: IMessageIPFS; did: string; wallets: string; profilePicture: string | null; diff --git a/yarn.lock b/yarn.lock index 93bcf61d73..1e30005254 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5444,7 +5444,7 @@ __metadata: "@pushprotocol/ledgerlive": latest "@pushprotocol/restapi": 1.4.38 "@pushprotocol/socket": 0.5.3 - "@pushprotocol/uiweb": 1.1.19 + "@pushprotocol/uiweb": 1.1.20 "@reduxjs/toolkit": ^1.7.1 "@testing-library/dom": ^6.12.2 "@testing-library/jest-dom": ^4.2.4 @@ -5706,9 +5706,9 @@ __metadata: languageName: node linkType: hard -"@pushprotocol/uiweb@npm:1.1.19": - version: 1.1.19 - resolution: "@pushprotocol/uiweb@npm:1.1.19" +"@pushprotocol/uiweb@npm:1.1.20": + version: 1.1.20 + resolution: "@pushprotocol/uiweb@npm:1.1.20" dependencies: "@livekit/components-react": ^1.2.2 "@livekit/components-styles": ^1.0.6 @@ -5740,7 +5740,7 @@ __metadata: axios: ^0.27.2 react: ">=16.8.0" styled-components: ^6.0.8 - checksum: 1180e8a37039825f5bfd518b1e7675b3bc2a95b7a511cddb22d0390cf742cfb7589dc28b59fc82bfc8f43ed1da9324374653275d0a5f88452b8b2fa83dd607df + checksum: 4df4b3661b5ec5ef92e319dbd9620c47793d729ee2161e4afbebc704d68f45b07bdf0a6fbc8e935e3def0e009a297168e79fc9bf2073284289f8cd7c9362f70c languageName: node linkType: hard