initialize contact again when added to group or left

This commit is contained in:
slawk0
2024-12-15 17:24:44 +01:00
parent 8cad73d01d
commit 6d15b9afb7
7 changed files with 123 additions and 59 deletions

View File

@@ -42,7 +42,7 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
setIsLoading(false);
setNotFound(false);
}
} catch (e) {
} catch (e: any) {
setIsLoading(false);
console.error('Error fetching suggestions:', e);
setErrorMessage(
@@ -85,7 +85,7 @@ function AddGroupMember({ contact }: AddGroupMemberProps) {
modalRef.current.close();
}
reset();
} catch (e) {
} catch (e: any) {
console.error('Failed to add group member: ', e);
setIsLoading(false);
setErrorMessage(e.response?.data?.message || 'Failed to add member');

View File

@@ -12,7 +12,9 @@ function ContactProfile({ contact }: ContactProfileProps) {
<div className="flex items-center">
<div className="flex items-center p-2">
<img className="w-4 mr-2 invert" src={profile} alt="profile img" />
<p>{contact ? contact.username : null}</p>
<p>
{contact?.user_id} {contact ? contact.username : null}
</p>
</div>
<div className="flex-grow"></div>

View File

@@ -16,7 +16,7 @@ import {
} from '@/components/ui/alert-dialog';
type ContactsListProps = {
InitializeContact: (contact: ContactsProps) => void;
initializeContact: (contact: ContactsProps) => void;
setContactsList: React.Dispatch<React.SetStateAction<ContactsProps[]>>;
contactsList: ContactsProps[];
setCurrentContact: React.Dispatch<React.SetStateAction<ContactsProps | null>>;
@@ -27,7 +27,7 @@ type ContactsListProps = {
};
function ContactsList({
InitializeContact,
initializeContact,
contactsList,
setContactsList,
setCurrentContact,
@@ -44,10 +44,19 @@ function ContactsList({
useEffect(() => {
if (!socket) return;
socket?.on('added to group', () => {
socket.on(
'added to group',
(msg: {
username: string;
user_id: number;
group_id: number;
isadmin: false;
}) => {
console.log('added to group, fetching contacts');
console.error(msg);
fetchContacts();
});
},
);
return () => {
socket?.off('added to group');
@@ -103,7 +112,7 @@ function ContactsList({
<li
className="flex hover:bg-green-700 p-2 rounded cursor-pointer justify-between items-center min-h-[40px]"
onClick={() => {
InitializeContact(contact);
initializeContact(contact);
updateContactStatus(contact, true);
}}
>

View File

@@ -21,14 +21,37 @@ type ParticipantsProps = {
type ParticipantsBarProps = {
contact: ContactsProps | null;
initializeContact: (contact: ContactsProps) => void;
currentContact: ContactsProps | null;
};
function ParticipantsBar({ contact }: ParticipantsBarProps) {
function ParticipantsBar({
contact,
initializeContact,
currentContact,
}: ParticipantsBarProps) {
const [participants, setParticipants] = useState<ParticipantsProps[]>([]);
const [isGroupAdmin, setIsGroupAdmin] = useState<boolean>(false);
const user: UsernameType = useOutletContext();
const [isLoading, setIsLoading] = useState<boolean>(false);
const getParticipants = async () => {
try {
const response = await axiosClient.get(
`/api/chat/groups/getMembers/${contact?.conversation_id}`,
);
console.log(
'getParticipants for: ',
contact?.conversation_id,
'response: ',
response.data,
);
setParticipants(response.data);
} catch (e) {
console.error('Failed to get chat participants: ', e);
}
};
useEffect(() => {
if (participants.length > 0 && user?.user_id) {
const userIsAdmin = participants.some(
@@ -41,22 +64,6 @@ function ParticipantsBar({ contact }: ParticipantsBarProps) {
useEffect(() => {
if (contact) {
const getParticipants = async () => {
try {
const response = await axiosClient.get(
`/api/chat/groups/getMembers/${contact.conversation_id}`,
);
console.log(
'getParticipants for: ',
contact.conversation_id,
'response: ',
response.data,
);
setParticipants(response.data);
} catch (e) {
console.error('Failed to get chat participants: ', e);
}
};
getParticipants();
}
}, [contact]);
@@ -75,6 +82,25 @@ function ParticipantsBar({ contact }: ParticipantsBarProps) {
const { group_id } = msg;
console.log('Added to group: ', msg);
console.log('Current participants: ', participants);
console.log(
'HDDSLKDFLDK: ',
currentContact?.conversation_id,
currentContact?.user_id,
);
if (
msg.group_id == currentContact?.conversation_id &&
msg.user_id == user?.user_id
) {
initializeContact({
read: true,
username: msg.username,
user_id: msg.user_id,
id: currentContact?.id,
type: 'group',
conversation_id: msg.group_id,
last_active: new Date().toString(),
});
}
if (group_id === contact.conversation_id) {
setParticipants((prevMembers) => {
@@ -90,16 +116,19 @@ function ParticipantsBar({ contact }: ParticipantsBarProps) {
},
);
socket.on(
'left group',
(msg: { user_id: number; conversation_id: number }) => {
const { user_id } = msg;
socket.on('left group', (msg: { user_id: number; group_id: number }) => {
console.log(`(socket on "left group")`, msg);
// Initialize contact again to clear messages and participants list
if (
msg.group_id == currentContact?.conversation_id &&
msg.user_id == user?.user_id
) {
initializeContact(currentContact);
}
setParticipants((prevMembers) =>
prevMembers.filter((member) => member.user_id !== user_id),
);
},
prevMembers.filter((member) => member.user_id !== msg.user_id),
);
});
return () => {
socket?.off('added to group');
@@ -113,7 +142,7 @@ function ParticipantsBar({ contact }: ParticipantsBarProps) {
socket?.emit(
'remove user from group',
{
conversation_id: contact?.conversation_id,
group_id: contact?.conversation_id,
user_id: userId,
},
(response: { status: 'ok' | 'error'; message: string }) => {

View File

@@ -24,7 +24,9 @@ function UserProfile() {
</div>
<div className="text-gray-200">
<p>{user.username}</p>
<p>
{user?.user_id} {user.username}
</p>
</div>
</div>

View File

@@ -198,7 +198,7 @@ function Chat() {
InitializeContact={initializeContact}
/>
<ContactsList
InitializeContact={initializeContact}
initializeContact={initializeContact}
contactsList={contactsList}
setContactsList={setContactsList}
setCurrentContact={setCurrentContact}
@@ -237,7 +237,11 @@ function Chat() {
{/* Participants Bar */}
{currentContact?.type == 'group' ? (
<div className="w-80 bg-[#1E1E1E] flex-shrink-0">
<ParticipantsBar contact={currentContact} />
<ParticipantsBar
contact={currentContact}
initializeContact={initializeContact}
currentContact={currentContact}
/>
</div>
) : null}
</div>

View File

@@ -221,29 +221,47 @@ function initializeSocket(io) {
});
socket.on("remove user from group", async (msg, callback) => {
const { conversation_id, user_id } = msg;
if (!conversation_id) {
const { group_id, user_id } = msg;
if (!group_id || !user_id) {
return callback({
status: "error",
message: "No conversation id provided",
message: "Missing required parameters",
});
}
if (!user_id) {
return callback({ status: "error", message: "No user id provided" });
}
const result = await removeUserFromGroupById(conversation_id, user_id);
try {
const result = await removeUserFromGroupById(group_id, user_id);
if (result?.message) {
return callback({ status: "error", messsage: result.message });
return callback({ status: "error", message: result.message });
}
io.to(conversation_id).emit("left group", { conversation_id, user_id });
// Get all sockets in the room
const socketsInRoom = await io.in(group_id).fetchSockets();
for (const socketInstance of socketsInRoom) {
if (socketInstance.user_id === user_id) {
socketInstance.leave(group_id);
}
}
io.to(group_id).to(user_id).emit("left group", {
group_id,
user_id,
});
return callback({
status: "ok",
message: "Successfully removed user from group",
});
} catch (error) {
console.error("Failed to remove user from group:", error);
return callback({
status: "error",
message: "Internal server error",
});
}
});
socket.on("disconnect", (reason) => {