Browse Source

status 2 ios

Viktoriia 4 months ago
parent
commit
d6a17a7468

+ 38 - 0
src/contexts/PushNotificationContext.tsx

@@ -8,6 +8,7 @@ import { usePostSetSettingsMutation } from '@api/notifications';
 import { useMessagesStore } from 'src/stores/unreadMessagesStore';
 import { useFriendsNotificationsStore } from 'src/stores/friendsNotificationsStore';
 import {
+  handleNotificationData,
   registerBackgroundNotificationTask,
   unregisterBackgroundNotificationTask
 } from 'src/utils/pushNotificationTask';
@@ -47,6 +48,26 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
             Notifications.setBadgeCountAsync(-1);
           }
         });
+        Notifications.getPresentedNotificationsAsync().then((notifications) => {
+          if (Platform.OS === 'ios' && notifications.length > 0) {
+            notifications.forEach((notification) => {
+              let groupToken;
+              let messageId;
+              let fromUser;
+              const parsedData =
+                JSON.parse(
+                  (notification.request.trigger as Notifications.PushNotificationTrigger)?.payload
+                    ?.params as string
+                ) ?? {};
+              groupToken = parsedData?.group_token;
+              messageId = (notification.request.trigger as Notifications.PushNotificationTrigger)
+                ?.payload?.message_id as number;
+              fromUser = parsedData?.id;
+
+              handleNotificationData(groupToken, messageId, fromUser);
+            });
+          }
+        });
         updateNotificationStatus();
         updateUnreadMessagesCount();
       }
@@ -159,6 +180,23 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
       const notificationListener = Notifications.addNotificationReceivedListener((notification) => {
         updateNotificationStatus();
         updateUnreadMessagesCount();
+
+        let groupToken;
+        let messageId;
+        let fromUser;
+        if (Platform.OS === 'ios') {
+          const parsedData =
+            JSON.parse(
+              (notification.request.trigger as Notifications.PushNotificationTrigger)?.payload
+                ?.params as string
+            ) ?? {};
+          groupToken = parsedData?.group_token;
+          messageId = (notification.request.trigger as Notifications.PushNotificationTrigger)
+            ?.payload?.message_id as number;
+          fromUser = parsedData?.id;
+
+          handleNotificationData(groupToken, messageId, fromUser);
+        }
       });
 
       const responseListener = Notifications.addNotificationResponseReceivedListener((response) => {

+ 14 - 0
src/screens/InAppScreens/MessagesScreen/ChatScreen/index.tsx

@@ -695,6 +695,20 @@ const ChatScreen = ({ route }: { route: any }) => {
         }
         break;
 
+      case 'messages_received':
+        if (data.conversation_with === id && data.received_messages_ids) {
+          setMessages(
+            (prevMessages) =>
+              prevMessages?.map((msg) => {
+                if (data.received_messages_ids.includes(msg._id)) {
+                  return { ...msg, sent: true };
+                }
+                return msg;
+              }) ?? []
+          );
+        }
+        break;
+
       default:
         break;
     }

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

@@ -709,6 +709,19 @@ const GroupChatScreen = ({ route }: { route: any }) => {
           );
         }
         break;
+      case 'messages_received':
+        if (data.group_token === group_token && data.received_messages_ids) {
+          setMessages(
+            (prevMessages) =>
+              prevMessages?.map((msg) => {
+                if (data.received_messages_ids.includes(msg._id)) {
+                  return { ...msg, sent: true };
+                }
+                return msg;
+              }) ?? []
+          );
+        }
+        break;
 
       default:
         break;

+ 9 - 0
src/utils/backgroundLocation.ts

@@ -15,7 +15,16 @@ TaskManager.defineTask(LOCATION_TASK_NAME, async ({ data, error }) => {
   }
   if (data) {
     const { locations } = data as any;
+    let lastLocationSentTime =
+      (storage.get('last_location_sent_time', StoreType.NUMBER) as number) ?? 0;
+
     if (locations && locations.length > 0) {
+      const now = Date.now();
+      if (now - lastLocationSentTime < 60 * 1000) {
+        return;
+      }
+      storage.set('last_location_sent_time', now);
+
       const { coords } = locations[0];
       const token = storage.get('token', StoreType.STRING);
 

+ 89 - 12
src/utils/pushNotificationTask.ts

@@ -1,7 +1,7 @@
 import * as TaskManager from 'expo-task-manager';
 import * as Notifications from 'expo-notifications';
 import { Platform } from 'react-native';
-import { API_URL, APP_VERSION } from 'src/constants';
+import { API_URL, APP_VERSION, WEBSOCKET_URL } from 'src/constants';
 import axios from 'axios';
 import { API } from 'src/types';
 import { storage, StoreType } from 'src/storage';
@@ -11,7 +11,6 @@ const BACKGROUND_NOTIFICATION_TASK = 'BACKGROUND-NOTIFICATION-TASK';
 TaskManager.defineTask(
   BACKGROUND_NOTIFICATION_TASK,
   async ({ data, error }: { data?: any; error?: any }) => {
-    console.log('Background notification task started', data);
     if (error) {
       return;
     }
@@ -22,15 +21,9 @@ TaskManager.defineTask(
       let messageId;
       let fromUser;
 
-      if (Platform.OS === 'ios') {
-        groupToken = data?.UIApplicationLaunchOptionsRemoteNotificationKey?.data?.group_token;
-        messageId = data?.UIApplicationLaunchOptionsRemoteNotificationKey?.data?.message_id;
-        fromUser = data?.UIApplicationLaunchOptionsRemoteNotificationKey?.data?.from_user;
-      } else {
-        groupToken = data?.notification?.data?.group_token;
-        messageId = data?.notification?.data?.message_id;
-        fromUser = data?.notification?.data?.from_user;
-      }
+      groupToken = data?.data?.group_token;
+      messageId = data?.data?.message_id;
+      fromUser = data?.data?.from_user;
 
       if ((!groupToken && !fromUser) || !messageId) return;
 
@@ -66,6 +59,25 @@ TaskManager.defineTask(
             }
           );
         }
+
+        const socket = new WebSocket(WEBSOCKET_URL);
+
+        socket.onopen = () => {
+          socket.send(JSON.stringify({ token }));
+          let data: any = { action: 'messages_received', messages_ids: [messageId] };
+          if (fromUser) {
+            data.conversation_with = fromUser;
+          } else {
+            data.conversation_with_group = groupToken;
+          }
+
+          socket.send(JSON.stringify(data));
+          socket.close();
+        };
+
+        socket.onerror = (error) => {
+          console.error('WebSocket error:', error);
+        };
       } catch (err) {
         console.error('Error sending notification data:', err);
       }
@@ -76,7 +88,7 @@ TaskManager.defineTask(
 export const registerBackgroundNotificationTask = async () => {
   const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_NOTIFICATION_TASK);
 
-  if (!isRegistered) {
+  if (!isRegistered && Platform.OS === 'ios') {
     await Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
   }
 };
@@ -88,3 +100,68 @@ export const unregisterBackgroundNotificationTask = async () => {
     await TaskManager.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
   }
 };
+
+export const handleNotificationData = async (
+  groupToken: string | undefined,
+  messageId: number,
+  fromUser: number | undefined
+) => {
+  const token = storage.get('token', StoreType.STRING);
+
+  if ((!groupToken && !fromUser) || !messageId) return;
+
+  try {
+    if (fromUser) {
+      await axios.postForm(
+        API_URL + '/' + API.MESSAGES_RECEIVED,
+        {
+          token,
+          from_user: fromUser,
+          messages_id: [messageId]
+        },
+        {
+          headers: {
+            Platform: Platform.OS,
+            'App-Version': APP_VERSION
+          }
+        }
+      );
+    } else {
+      await axios.postForm(
+        API_URL + '/' + API.GROUP_MESSAGES_RECEIVED,
+        {
+          token,
+          group_token: groupToken,
+          messages_id: [messageId]
+        },
+        {
+          headers: {
+            Platform: Platform.OS,
+            'App-Version': APP_VERSION
+          }
+        }
+      );
+    }
+
+    const socket = new WebSocket(WEBSOCKET_URL);
+
+    socket.onopen = () => {
+      socket.send(JSON.stringify({ token }));
+      let data: any = { action: 'messages_received', messages_ids: [messageId] };
+      if (fromUser) {
+        data.conversation_with = fromUser;
+      } else {
+        data.conversation_with_group = groupToken;
+      }
+
+      socket.send(JSON.stringify(data));
+      socket.close();
+    };
+
+    socket.onerror = (error) => {
+      console.error('WebSocket error:', error);
+    };
+  } catch (err) {
+    console.error('Error sending notification data:', err);
+  }
+};