Selaa lähdekoodia

group chat create fixes

Viktoriia 4 kuukautta sitten
vanhempi
commit
f3f8f1a5c8

+ 30 - 1
src/modules/api/chat/chat-api.ts

@@ -62,12 +62,41 @@ interface Message {
   encrypted: 0 | 1;
 }
 
+interface GroupMessage {
+  id: number;
+  sender: number;
+  recipient: number;
+  text: string;
+  status: 1 | 2 | 3 | 4;
+  sent_datetime: Date;
+  received_datetime: Date | null;
+  read_datetime: Date | null;
+  reply_to_id: number;
+  reactions: string;
+  edits: string;
+  attachement: -1 | Attachement;
+  encrypted: 0 | 1;
+  sender_avatar: string | null;
+  sender_name: string;
+}
+
 export interface PostGetChatWithReturn extends ResponseType {
   messages: (Message & {
     reply_to: Message;
   })[];
 }
 
+export interface PostGetGroupChatWithReturn extends ResponseType {
+  groupToken: string;
+  groupAvatar: string | null;
+  can_send_messages: boolean;
+  messages: (GroupMessage & {
+    reply_to: GroupMessage;
+    sender_avatar: string | null;
+    sender_name: string;
+  })[];
+}
+
 export interface PostSendMessage {
   token: string;
   to_uid: number;
@@ -268,7 +297,7 @@ export const chatApi = {
     no_of_messages: number,
     previous_than_message_id: number
   ) =>
-    request.postForm<PostGetChatWithReturn>(API.GET_GROUP_CHAT, {
+    request.postForm<PostGetGroupChatWithReturn>(API.GET_GROUP_CHAT, {
       token,
       group_token,
       no_of_messages,

+ 2 - 2
src/modules/api/chat/queries/use-post-get-group-conversation.tsx

@@ -1,7 +1,7 @@
 import { useQuery } from '@tanstack/react-query';
 
 import { chatQueryKeys } from '../chat-query-keys';
-import { chatApi, type PostGetChatWithReturn } from '../chat-api';
+import { chatApi, type PostGetGroupChatWithReturn } from '../chat-api';
 
 import type { BaseAxiosError } from '../../../../types';
 
@@ -12,7 +12,7 @@ export const usePostGetGroupChatQuery = (
   previous_than_message_id: number,
   enabled: boolean
 ) => {
-  return useQuery<PostGetChatWithReturn, BaseAxiosError>({
+  return useQuery<PostGetGroupChatWithReturn, BaseAxiosError>({
     queryKey: chatQueryKeys.getGroupChat(token, group_token, no_of_messages, previous_than_message_id),
     queryFn: async () => {
       const response = await chatApi.getGroupChat(

+ 33 - 27
src/screens/InAppScreens/MessagesScreen/Components/MoreModal.tsx

@@ -64,18 +64,19 @@ const MoreModal = () => {
   const handleMute = async () => {
     if (!chatData) return;
 
-    await muteUser(
-      {
-        token: chatData.token,
-        value: chatData.muted === 1 ? 0 : 1,
-        conversation_with_user: chatData.uid
-      },
-      {
-        onSuccess: () => {
-          setChatData({ ...chatData, muted: chatData.muted === 1 ? 0 : 1 });
+    chatData.uid &&
+      (await muteUser(
+        {
+          token: chatData.token,
+          value: chatData.muted === 1 ? 0 : 1,
+          conversation_with_user: chatData.uid
+        },
+        {
+          onSuccess: () => {
+            setChatData({ ...chatData, muted: chatData.muted === 1 ? 0 : 1 });
+          }
         }
-      }
-    );
+      ));
     chatData.refetch();
   };
 
@@ -87,11 +88,12 @@ const MoreModal = () => {
       buttonTitle: 'Block',
       message: `Are you sure you want to block ${name}?\nThis user will be blocked and you will not be able to send or receive messages from him/her.`,
       action: async () => {
-        await blockUser({
-          token: chatData.token,
-          value: 1,
-          conversation_with_user: chatData.uid
-        });
+        chatData.uid &&
+          (await blockUser({
+            token: chatData.token,
+            value: 1,
+            conversation_with_user: chatData.uid
+          }));
 
         chatData.refetch();
         chatData.refetchBlocked();
@@ -112,10 +114,11 @@ const MoreModal = () => {
       buttonTitle: 'Report',
       message: `Are you sure you want to report ${name}?\nIf you proceed, the chat history with ${name} will become visible to NomadMania admins for investigation.`,
       action: async () => {
-        await reportUser({
-          token: chatData.token,
-          reported_user_id: chatData.uid
-        });
+        chatData.uid &&
+          (await reportUser({
+            token: chatData.token,
+            reported_user_id: chatData.uid
+          }));
       }
     });
 
@@ -132,10 +135,11 @@ const MoreModal = () => {
       title: 'Delete conversation',
       message: `Are you sure you want to delete conversation with ${name}?\nThis conversation will be deleted for both sides.`,
       action: async () => {
-        await deleteChat({
-          token: chatData.token,
-          conversation_with_user: chatData.uid
-        });
+        chatData.uid &&
+          (await deleteChat({
+            token: chatData.token,
+            conversation_with_user: chatData.uid
+          }));
 
         chatData.refetch();
       }
@@ -170,9 +174,11 @@ const MoreModal = () => {
             style={styles.header}
             onPress={() => {
               SheetManager.hide('more-modal');
-              navigation.navigate(
-                ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: chatData.uid }] as never)
-              );
+              if (chatData?.uid) {
+                navigation.navigate(
+                  ...([NAVIGATION_PAGES.PUBLIC_PROFILE_VIEW, { userId: chatData.uid }] as never)
+                );
+              }
             }}
             disabled={chatData?.userType !== 'normal'}
           >

+ 3 - 2
src/screens/InAppScreens/MessagesScreen/Components/SwipeableRow.tsx

@@ -57,6 +57,7 @@ const SwipeableRow: React.FC<AppleStyleSwipeableRowProps> = ({
         SheetManager.show('more-modal', {
           payload: {
             uid: chat.uid,
+            groupToken: chat.groupToken,
             name: chat.name,
             avatar: chat.avatar,
             muted: chat.muted,
@@ -67,7 +68,7 @@ const SwipeableRow: React.FC<AppleStyleSwipeableRowProps> = ({
           } as any
         });
       } else {
-        await archiveChat({
+        chat.uid && await archiveChat({
           token,
           value: chat.archive === 1 ? 0 : 1,
           conversation_with_user: chat.uid
@@ -103,7 +104,7 @@ const SwipeableRow: React.FC<AppleStyleSwipeableRowProps> = ({
 
     const pressHandler = async () => {
       close();
-      await pinChat({
+      chat.uid && await pinChat({
         token,
         value: chat.pin === 1 ? 0 : 1,
         conversation_with_user: chat.uid

+ 12 - 13
src/screens/InAppScreens/MessagesScreen/GroupChatScreen/index.tsx

@@ -50,7 +50,7 @@ import {
   usePostReactToGroupMessageMutation,
   usePostGroupMessagesReadMutation
 } from '@api/chat';
-import { CustomMessage, Message, Reaction } from '../types';
+import { CustomMessage, GroupMessage, Reaction } from '../types';
 import { API_HOST, WEBSOCKET_URL } from 'src/constants';
 import ReactionBar from '../Components/ReactionBar';
 import OptionsMenu from '../Components/OptionsMenu';
@@ -183,7 +183,7 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           _id: Date.now() + Math.random(),
           text: '',
           createdAt: new Date(),
-          user: { _id: +currentUserId, name: 'Me' },
+          user: { _id: +currentUserId, name: 'Me', avatar: null as never },
           reactions: {},
           deleted: false,
           attachment: {
@@ -202,7 +202,8 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           tempMessage.replyMessage = {
             text: replyMessage.text,
             id: replyMessage._id,
-            name: replyMessage.user._id !== +currentUserId ? replyMessage.user.name : 'Me'
+            name:
+              replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
           };
         }
 
@@ -269,7 +270,7 @@ const GroupChatScreen = ({ route }: { route: any }) => {
         _id: Date.now() + Math.random(),
         text: '',
         createdAt: new Date(),
-        user: { _id: +currentUserId, name: 'Me' },
+        user: { _id: +currentUserId, name: 'Me', avatar: null as never },
         pending: true,
         deleted: false,
         reactions: {},
@@ -286,7 +287,7 @@ const GroupChatScreen = ({ route }: { route: any }) => {
         tempMessage.replyMessage = {
           text: replyMessage.text,
           id: replyMessage._id,
-          name: replyMessage.user._id !== +currentUserId ? replyMessage.user.name : 'Me'
+          name: replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
         };
       }
 
@@ -347,7 +348,7 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           _id: Date.now() + Math.random(),
           text: '',
           createdAt: new Date(),
-          user: { _id: +currentUserId, name: 'Me' },
+          user: { _id: +currentUserId, name: 'Me', avatar: null as never },
           deleted: false,
           reactions: {},
           isSending: true,
@@ -363,7 +364,8 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           msg.replyMessage = {
             text: replyMessage.text,
             id: replyMessage._id,
-            name: replyMessage.user._id !== +currentUserId ? replyMessage.user.name : 'Me'
+            name:
+              replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
           };
         }
 
@@ -573,7 +575,6 @@ const GroupChatScreen = ({ route }: { route: any }) => {
     let unsubscribe: any;
 
     const setupNotificationHandler = async () => {
-      // todo: implement dismissChatNotifications
       unsubscribe = await dismissChatNotifications(
         group_token,
         isSubscribed,
@@ -628,7 +629,6 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           };
         }
 
-        // todo: implement dismissChatNotifications
         await dismissChatNotifications(group_token, isSubscribed, setModalInfo, navigation);
       }
     };
@@ -846,14 +846,13 @@ const GroupChatScreen = ({ route }: { route: any }) => {
     }
   };
 
-  const mapApiMessageToGiftedMessage = (message: Message): CustomMessage => {
+  const mapApiMessageToGiftedMessage = (message: GroupMessage): CustomMessage => {
     return {
       _id: message.id,
       text: message.text,
       createdAt: new Date(message.sent_datetime + 'Z'),
       user: {
         _id: message.sender,
-        // todo: sender_name
         name: message.sender !== +currentUserId ? message.sender_name : 'Me',
         avatar:
           message.sender !== +currentUserId && message.sender_avatar
@@ -1302,13 +1301,13 @@ const GroupChatScreen = ({ route }: { route: any }) => {
         newMessages[0].replyMessage = {
           text: replyMessage.text,
           id: replyMessage._id,
-          name: replyMessage.user._id !== +currentUserId ? replyMessage.user.name : 'Me'
+          name: replyMessage.user._id !== +currentUserId ? (replyMessage.user.name as string) : 'Me'
         };
       }
       const user = {
         _id: +currentUserId,
         name: 'Me',
-        avatar: null
+        avatar: null as never
       };
       const message = { ...newMessages[0], pending: true, isSending: true, user };
 

+ 7 - 2
src/screens/InAppScreens/MessagesScreen/index.tsx

@@ -286,6 +286,7 @@ const MessagesScreen = () => {
       <SwipeableRow
         chat={{
           uid: item.uid,
+          groupToken: item.group_chat_token,
           name: item.name,
           avatar: item.avatar,
           pin: item.pin,
@@ -299,7 +300,11 @@ const MessagesScreen = () => {
         refetchBlocked={refetchBlocked}
       >
         <TouchableHighlight
-          key={`${item.uid}-${typingUsers[item.uid]}`}
+          key={
+            item.uid
+              ? `${item.uid}-${typingUsers[item.uid]}`
+              : `${item.group_chat_token}-${typingUsers[item.group_chat_token ?? '']}`
+          }
           activeOpacity={0.8}
           onPress={() => {
             if (!item.uid) {
@@ -377,7 +382,7 @@ const MessagesScreen = () => {
               </View>
 
               <View style={[styles.rowContainer, { flex: 1, gap: 6 }]}>
-                {typingUsers[item.uid] ? (
+                {typingUsers[item.uid ? item.uid : (item.group_chat_token ?? '')] ? (
                   <TypingIndicator />
                 ) : (
                   <Text numberOfLines={2} style={styles.chatMessage}>

+ 28 - 2
src/screens/InAppScreens/MessagesScreen/types.ts

@@ -1,7 +1,8 @@
 import { IMessage } from 'react-native-gifted-chat';
 
 export type Chat = {
-  uid: number;
+  uid: number | null;
+  group_chat_token: string | null;
   name: string;
   avatar: string | null;
   short: string;
@@ -28,7 +29,8 @@ export type Blocked = {
 };
 
 export type ChatProps = {
-  uid: number;
+  uid: number | null;
+  groupToken: string | null;
   name: string;
   avatar: string | null;
   pin: 0 | 1;
@@ -64,10 +66,34 @@ export type MessageSimple = {
   encrypted: 0 | 1;
 };
 
+export type MessageGroupSimple = {
+  id: number;
+  sender: number;
+  recipient: number;
+  text: string;
+  status: 1 | 2 | 3 | 4;
+  sent_datetime: Date;
+  received_datetime: Date | null;
+  read_datetime: Date | null;
+  reply_to_id: number;
+  reactions: string;
+  edits: string;
+  attachement: -1 | Attachement;
+  encrypted: 0 | 1;
+  sender_avatar: string | null;
+  sender_name: string;
+};
+
 export type Message = MessageSimple & {
   reply_to: MessageSimple;
 };
 
+export type GroupMessage = MessageGroupSimple & {
+  reply_to: MessageGroupSimple;
+  sender_avatar: string | null;
+  sender_name: string;
+};
+
 export interface CustomMessage extends IMessage {
   _id: number;
   replyMessage?: {

+ 4 - 4
src/screens/InAppScreens/MessagesScreen/utils.ts

@@ -24,7 +24,7 @@ export const formatDate = (dateString: Date): string => {
 };
 
 export const dismissChatNotifications = async (
-  chatWithUserId: number,
+  chatWithUserId: number | string,
   isSubscribed: boolean,
   setModalInfo: (data: any) => void,
   navigation: any
@@ -68,11 +68,11 @@ export const dismissChatNotifications = async (
     }
   };
 
-  const clearNotificationsFromUser = async (userId: number) => {
+  const clearNotificationsFromUser = async (userId: number | string) => {
     const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
     presentedNotifications.forEach((notification) => {
       const parsedParams = getNotificationData(notification);
-      const conversation_with_user = parsedParams?.id;
+      const conversation_with_user = parsedParams?.id ?? parsedParams?.group_token;
 
       if (conversation_with_user === userId) {
         Notifications.dismissNotificationAsync(notification.request.identifier);
@@ -86,7 +86,7 @@ export const dismissChatNotifications = async (
     handleNotification: async (notification) => {
       let conversation_with_user = 0;
       const parsedParams = getNotificationData(notification);
-      conversation_with_user = parsedParams?.id;
+      conversation_with_user = parsedParams?.id ?? parsedParams?.group_token;
 
       if (conversation_with_user === chatWithUserId) {
         return {