فهرست منبع

notifications

Viktoriia 8 ماه پیش
والد
کامیت
3f94b40997

+ 28 - 3
src/contexts/PushNotificationContext.tsx

@@ -1,7 +1,7 @@
 import React, { useEffect, useState, useContext, createContext } from 'react';
 import * as Notifications from 'expo-notifications';
 import { storage, StoreType } from 'src/storage';
-import { Linking, Platform } from 'react-native';
+import { AppState, AppStateStatus, Linking, Platform } from 'react-native';
 import { CommonActions, useNavigation } from '@react-navigation/native';
 import { NAVIGATION_PAGES } from 'src/types';
 import { usePostSetSettingsMutation } from '@api/notifications';
@@ -27,9 +27,30 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
   const { mutateAsync: setNotificationsSettings } = usePostSetSettingsMutation();
   const navigation = useNavigation();
   const updateUnreadMessagesCount = useMessagesStore((state) => state.updateUnreadMessagesCount);
+  const [appState, setAppState] = useState(AppState.currentState);
 
   const lastNotificationResponse = Notifications.useLastNotificationResponse();
 
+  useEffect(() => {
+    const handleAppStateChange = (nextAppState: AppStateStatus) => {
+      if (appState.match(/inactive|background/) && nextAppState === 'active' && isSubscribed) {
+        Notifications.getBadgeCountAsync().then((badgeCount) => {
+          if (badgeCount > 0) {
+            Notifications.setBadgeCountAsync(-1);
+          }
+        });
+        updateUnreadMessagesCount();
+      }
+      setAppState(nextAppState);
+    };
+
+    const subscription = AppState.addEventListener('change', handleAppStateChange);
+
+    return () => {
+      subscription.remove();
+    };
+  }, [appState]);
+
   useEffect(() => {
     if (lastNotificationResponse && Platform.OS === 'android') {
       const data = lastNotificationResponse.notification.request.content.data;
@@ -108,8 +129,6 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
         })
       });
 
-      Notifications.setBadgeCountAsync(0);
-
       const notificationListener = Notifications.addNotificationReceivedListener((notification) => {
         updateUnreadMessagesCount();
       });
@@ -197,6 +216,12 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
         }
       });
 
+      Notifications.getBadgeCountAsync().then((badgeCount) => {
+        if (badgeCount > 0) {
+          Notifications.setBadgeCountAsync(-1);
+        }
+      });
+
       return () => {
         notificationListener.remove();
         responseListener.remove();

+ 70 - 11
src/screens/InAppScreens/MessagesScreen/ChatScreen/index.tsx

@@ -145,35 +145,94 @@ const ChatScreen = ({ route }: { route: any }) => {
       });
       return;
     }
-    const subscription = Notifications.addNotificationReceivedListener((notification) => {
-      let conversation_with_user = 0;
+
+    const getNotificationData = (notification: Notifications.Notification) => {
       if (Platform.OS === 'android') {
         const data = notification.request.content.data;
         if (data?.params) {
-          const parsedParams = JSON.parse(data.params) ?? {};
-          conversation_with_user = parsedParams?.id;
+          try {
+            return JSON.parse(data.params) ?? {};
+          } catch (error) {
+            console.error('Error parsing params:', error);
+            return {};
+          }
+        } else {
+          Notifications.dismissNotificationAsync(notification.request.identifier);
+          return {};
         }
       } else {
         const data = (notification.request.trigger as Notifications.PushNotificationTrigger)
           ?.payload;
         if (data?.params) {
-          const parsedParams = JSON.parse(data.params as string) ?? {};
-          conversation_with_user = parsedParams?.id;
+          try {
+            return JSON.parse(data.params as string) ?? {};
+          } catch (error) {
+            console.error('Error parsing params:', error);
+            return {};
+          }
         }
       }
+    };
+
+    const clearNotificationsFromUser = async (userId: number) => {
+      const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
+      presentedNotifications.forEach((notification) => {
+        const parsedParams = getNotificationData(notification);
+        const conversation_with_user = parsedParams?.id;
+
+        if (conversation_with_user === userId) {
+          Notifications.dismissNotificationAsync(notification.request.identifier);
+        }
+      });
+    };
+
+    await clearNotificationsFromUser(chatWithUserId);
+
+    Notifications.setNotificationHandler({
+      handleNotification: async (notification) => {
+        let conversation_with_user = 0;
+        const parsedParams = getNotificationData(notification);
+        conversation_with_user = parsedParams?.id;
 
-      if (conversation_with_user === chatWithUserId) {
-        Notifications.dismissNotificationAsync(notification.request.identifier);
+        if (conversation_with_user === chatWithUserId) {
+          return {
+            shouldShowAlert: false,
+            shouldPlaySound: false,
+            shouldSetBadge: false
+          };
+        }
+
+        return {
+          shouldShowAlert: true,
+          shouldPlaySound: false,
+          shouldSetBadge: false
+        };
       }
     });
 
     return () => {
-      subscription.remove();
+      Notifications.setNotificationHandler({
+        handleNotification: async () => ({
+          shouldShowAlert: true,
+          shouldPlaySound: false,
+          shouldSetBadge: false
+        })
+      });
     };
   };
 
   useEffect(() => {
-    dismissChatNotifications(id);
+    let unsubscribe: any;
+
+    const setupNotificationHandler = async () => {
+      unsubscribe = await dismissChatNotifications(id);
+    };
+
+    setupNotificationHandler();
+
+    return () => {
+      if (unsubscribe) unsubscribe();
+    };
   }, [id]);
 
   useEffect(() => {
@@ -269,7 +328,7 @@ const ChatScreen = ({ route }: { route: any }) => {
       if (chatData?.messages) {
         const mappedMessages = chatData.messages.map(mapApiMessageToGiftedMessage);
 
-        if (unreadMessageIndex === null) {
+        if (unreadMessageIndex === null && Platform.OS === 'ios') {
           const firstUnreadIndex = mappedMessages.findLastIndex(
             (msg) => !msg.received && !msg?.deleted && msg.user._id === id
           );

+ 3 - 2
src/screens/InAppScreens/MessagesScreen/ChatScreen/styles.tsx

@@ -1,3 +1,4 @@
+import { Platform } from 'react-native';
 import { StyleSheet } from 'react-native';
 import { Colors } from 'src/theme';
 import { getFontSize } from 'src/utils';
@@ -97,12 +98,12 @@ export const styles = StyleSheet.create({
     flex: 1,
     alignItems: 'center',
     justifyContent: 'center',
-    transform: [{ scaleY: -1 }]
+    transform: Platform.OS === 'ios' ? [{ scaleY: -1 }] : [{ scaleY: -1 }, { scaleX: -1 }]
   },
   emptyChatText: {
     fontSize: getFontSize(14),
     fontWeight: '600',
     textAlign: 'center',
-    color: Colors.DARK_BLUE,
+    color: Colors.DARK_BLUE
   }
 });