checking membership on insertingMessages, improved error messages for client
This commit is contained in:
@@ -23,6 +23,7 @@ type ContactsListProps = {
|
||||
updateContactStatus: (contactObj: ContactsProps, read: boolean) => void;
|
||||
setMessages: React.Dispatch<React.SetStateAction<ChatMessages[]>>;
|
||||
currentContact: ContactsProps | null;
|
||||
setErrorMessage: React.Dispatch<React.SetStateAction<string | null>>;
|
||||
};
|
||||
|
||||
function ContactsList({
|
||||
@@ -32,6 +33,7 @@ function ContactsList({
|
||||
setCurrentContact,
|
||||
updateContactStatus,
|
||||
setMessages,
|
||||
setErrorMessage,
|
||||
}: ContactsListProps) {
|
||||
useEffect(() => {
|
||||
fetchContacts().catch((e) =>
|
||||
@@ -76,6 +78,7 @@ function ContactsList({
|
||||
setCurrentContact(null);
|
||||
localStorage.removeItem('contact');
|
||||
setMessages([]);
|
||||
setErrorMessage(null);
|
||||
setContactsList((prevContacts) =>
|
||||
prevContacts.filter((contact) => contact.id !== contactId),
|
||||
);
|
||||
@@ -140,9 +143,10 @@ function ContactsList({
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() =>
|
||||
removeContact(contact.id, contact.conversation_id)
|
||||
}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
removeContact(contact.id, contact.conversation_id);
|
||||
}}
|
||||
className="bg-red-600 hover:bg-red-500"
|
||||
>
|
||||
Leave Group
|
||||
|
||||
@@ -118,6 +118,7 @@ const MessageForm = ({ contact }: MessageFormProps) => {
|
||||
|
||||
const submitMessage: SubmitHandler<Input> = async (data) => {
|
||||
if ((!data.message && files.length === 0) || isSending) return;
|
||||
setErrorMessage(null);
|
||||
setIsSending(true);
|
||||
if (!socket) {
|
||||
console.error('Socket not initialized');
|
||||
|
||||
@@ -36,8 +36,6 @@ function MessagesArea({
|
||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
||||
const [shouldScrollToBottom, setShouldScrollToBottom] = useState(true);
|
||||
const previousMessagesLength = useRef(messages.length);
|
||||
const [deleteMessageLoading, setDeleteMessageLoading] =
|
||||
useState<boolean>(false);
|
||||
|
||||
const scrollToBottom = () => {
|
||||
const container = containerRef.current;
|
||||
@@ -74,7 +72,6 @@ function MessagesArea({
|
||||
|
||||
const deleteMessage = async (message_id: number) => {
|
||||
try {
|
||||
setDeleteMessageLoading(true);
|
||||
console.log('delete message: ', message_id);
|
||||
socket?.emit(
|
||||
'delete message',
|
||||
@@ -84,9 +81,7 @@ function MessagesArea({
|
||||
},
|
||||
(response: { status: string; message: string }) => {
|
||||
if (response.status == 'ok') {
|
||||
setDeleteMessageLoading(false);
|
||||
} else {
|
||||
setDeleteMessageLoading(false);
|
||||
console.error('Failed to delete message: ', response.message);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -61,8 +61,8 @@ function ParticipantsBar({ contact }: { contact: ContactsProps | null }) {
|
||||
socket.on(
|
||||
'left group',
|
||||
(msg: { user_id: number; conversation_id: number }) => {
|
||||
const { user_id, conversation_id } = msg;
|
||||
console.log('user left group id: ', user_id, conversation_id);
|
||||
const { user_id } = msg;
|
||||
console.log(`(socket on "left group")`, msg);
|
||||
setParticipants((prevMembers) =>
|
||||
prevMembers.filter((member) => member.user_id !== user_id),
|
||||
);
|
||||
|
||||
@@ -193,6 +193,7 @@ function Chat() {
|
||||
updateContactStatus={updateContactStatus}
|
||||
setMessages={setMessages}
|
||||
currentContact={currentContact}
|
||||
setErrorMessage={setErrorMessage}
|
||||
/>
|
||||
<hr />
|
||||
<UserProfile />
|
||||
|
||||
@@ -162,21 +162,33 @@ async function insertMessage(
|
||||
`senderId: ${senderId}, conversation_id: ${conversation_id}, content: ${content}, attachmentUrl: ${attachmentUrls}`,
|
||||
);
|
||||
|
||||
const checkMembershipQuery = `
|
||||
SELECT 1 FROM Memberships
|
||||
WHERE conversation_id = $1 AND user_id = $2
|
||||
LIMIT 1;
|
||||
`;
|
||||
|
||||
const query = `
|
||||
INSERT INTO Messages (conversation_id, user_id, content, attachment_urls)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING message_id, content, sent_at, attachment_urls, user_id AS sender_id, conversation_id;
|
||||
`;
|
||||
|
||||
try {
|
||||
const checkResult = await client.query(checkMembershipQuery, [
|
||||
conversation_id,
|
||||
senderId,
|
||||
]);
|
||||
if (checkResult.rows.length === 0) {
|
||||
console.error("User is not a member of the conversation");
|
||||
return [];
|
||||
}
|
||||
const result = await client.query(query, [
|
||||
conversation_id,
|
||||
senderId,
|
||||
content,
|
||||
attachmentUrls,
|
||||
]);
|
||||
console.log("insertmessageresult: ", result.rows);
|
||||
updateConversationLastActive(conversation_id);
|
||||
updateConversationLastActive(conversation_id, senderId);
|
||||
return result.rows[0];
|
||||
} catch (e) {
|
||||
console.error("Failed to insert message ", e);
|
||||
@@ -419,7 +431,8 @@ async function insertContact(userUsername, receiverUsername, read) {
|
||||
receiverUsername,
|
||||
]);
|
||||
if (!usersResult.rows[0]) {
|
||||
throw new Error("Users not found");
|
||||
console.error("Users not found");
|
||||
return null;
|
||||
}
|
||||
const { initiator_id, contact_id, contact_username } = usersResult.rows[0];
|
||||
|
||||
@@ -659,8 +672,21 @@ async function updateContactLastActive(user_id, contact_id) {
|
||||
}
|
||||
}
|
||||
|
||||
async function updateConversationLastActive(conversation_id) {
|
||||
//TODO CHECK IF USER IS MEMBER OF THAT CONVERSATION
|
||||
async function updateConversationLastActive(conversation_id, userId) {
|
||||
const checkMembershipQuery = `
|
||||
SELECT 1 FROM Memberships
|
||||
WHERE conversation_id = $1 AND user_id = $2
|
||||
LIMIT 1;
|
||||
`;
|
||||
|
||||
const checkResult = await client.query(checkMembershipQuery, [
|
||||
conversation_id,
|
||||
userId,
|
||||
]);
|
||||
if (checkResult.rows.length === 0) {
|
||||
console.error("User is not a member of the conversation");
|
||||
}
|
||||
|
||||
const query = `
|
||||
UPDATE Conversations
|
||||
SET last_active = NOW()
|
||||
@@ -683,9 +709,7 @@ async function getConversationsForUser(user_id) {
|
||||
|
||||
try {
|
||||
const result = await client.query(query, [user_id]);
|
||||
const conversationIds = result.rows.map((row) => row.conversation_id);
|
||||
console.log("getconversationsforuser: ", conversationIds);
|
||||
return conversationIds;
|
||||
return result.rows.map((row) => row.conversation_id);
|
||||
} catch (e) {
|
||||
console.error("Failed to get conversations for user ", e);
|
||||
return [];
|
||||
@@ -768,10 +792,6 @@ async function getMembers(conversation_id) {
|
||||
}
|
||||
}
|
||||
|
||||
function getTime() {
|
||||
return new Date();
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
client,
|
||||
insertUser,
|
||||
|
||||
@@ -112,8 +112,12 @@ function initializeSocket(io) {
|
||||
message: "Failed to insert message",
|
||||
});
|
||||
return;
|
||||
} else if (insertedMessage.length === 0) {
|
||||
callback({
|
||||
status: "error",
|
||||
message: "You are not an member of this conversation",
|
||||
});
|
||||
}
|
||||
|
||||
const { message_id, content, sent_at, sender_id, conversation_id } =
|
||||
insertedMessage;
|
||||
console.log("(socket) received from chat message", msg);
|
||||
|
||||
Reference in New Issue
Block a user