Bläddra i källkod

status 2 test for group chat

Viktoriia 4 månader sedan
förälder
incheckning
48f527cd6b
3 ändrade filer med 90 tillägg och 4 borttagningar
  1. 3 2
      app.config.ts
  2. 25 2
      src/contexts/PushNotificationContext.tsx
  3. 62 0
      src/utils/pushNotificationTask.ts

+ 3 - 2
app.config.ts

@@ -71,7 +71,7 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
     },
     associatedDomains: ['applinks:nomadmania.com'],
     infoPlist: {
-      UIBackgroundModes: ['location', 'fetch'],
+      UIBackgroundModes: ['location', 'fetch', 'remote-notification'],
       NSLocationAlwaysUsageDescription:
         'Turn on location service to allow NomadMania.com find friends nearby.',
       NSPhotoLibraryUsageDescription:
@@ -128,7 +128,8 @@ export default ({ config }: ConfigContext): ExpoConfig => ({
       'USER_FACING_NOTIFICATIONS',
       'INTERNET',
       'CAMERA',
-      'MODIFY_AUDIO_SETTINGS'
+      'MODIFY_AUDIO_SETTINGS',
+      'FOREGROUND_SERVICE'
     ],
     versionCode: 85 // 2.0.31, last version sent to Google is 84 (2.0.30)
   },

+ 25 - 2
src/contexts/PushNotificationContext.tsx

@@ -7,6 +7,10 @@ import { NAVIGATION_PAGES } from 'src/types';
 import { usePostSetSettingsMutation } from '@api/notifications';
 import { useMessagesStore } from 'src/stores/unreadMessagesStore';
 import { useFriendsNotificationsStore } from 'src/stores/friendsNotificationsStore';
+import {
+  registerBackgroundNotificationTask,
+  unregisterBackgroundNotificationTask
+} from 'src/utils/pushNotificationTask';
 
 const PushNotificationContext = createContext<{
   isSubscribed: boolean;
@@ -124,8 +128,24 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
     }
   }, [lastNotificationResponse]);
 
+  const checkNotificationPermissions = async () => {
+    const { status } = await Notifications.getPermissionsAsync();
+    return status;
+  };
+
   useEffect(() => {
+    const getPermissionsStatus = async () => {
+      const status = await checkNotificationPermissions();
+      if (status !== 'granted' && isSubscribed) {
+        await unsubscribeFromNotifications();
+
+        return;
+      }
+    };
+
     if (isSubscribed) {
+      getPermissionsStatus();
+
       Notifications.setNotificationHandler({
         handleNotification: async () => ({
           shouldShowAlert: true,
@@ -134,14 +154,14 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
         })
       });
 
+      registerBackgroundNotificationTask();
+
       const notificationListener = Notifications.addNotificationReceivedListener((notification) => {
         updateNotificationStatus();
         updateUnreadMessagesCount();
       });
 
       const responseListener = Notifications.addNotificationResponseReceivedListener((response) => {
-        console.log('Notification response received');
-
         let screenName;
         let url;
         let parentScreen;
@@ -232,6 +252,8 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
         notificationListener.remove();
         responseListener.remove();
       };
+    } else {
+      unregisterBackgroundNotificationTask();
     }
   }, [isSubscribed]);
 
@@ -253,6 +275,7 @@ export const PushNotificationProvider = ({ children }: { children: React.ReactNo
     storage.remove('deviceToken');
     storage.set('subscribed', false);
     setIsSubscribed(false);
+    unregisterBackgroundNotificationTask();
   };
 
   const toggleSubscription = async () => {

+ 62 - 0
src/utils/pushNotificationTask.ts

@@ -0,0 +1,62 @@
+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 axios from 'axios';
+import { API } from 'src/types';
+import { storage, StoreType } from 'src/storage';
+
+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');
+    if (error) {
+      return;
+    }
+
+    if (data) {
+      const token = storage.get('token', StoreType.STRING);
+
+      const { notification } = data;
+
+      if (!notification.data?.group_token || !notification.data?.message_id) return;
+
+      try {
+        const response = await axios.postForm(
+          API_URL + '/' + API.GROUP_MESSAGES_RECEIVED,
+          {
+            token,
+            group_token: notification.data.group_token,
+            messages_id: [notification.data.message_id]
+          },
+          {
+            headers: {
+              Platform: Platform.OS,
+              'App-Version': APP_VERSION
+            }
+          }
+        );
+      } catch (err) {
+        console.error('Error sending notification data:', err);
+      }
+    }
+  }
+);
+
+export const registerBackgroundNotificationTask = async () => {
+  const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_NOTIFICATION_TASK);
+
+  if (!isRegistered) {
+    await Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
+  }
+};
+
+export const unregisterBackgroundNotificationTask = async () => {
+  const isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_NOTIFICATION_TASK);
+
+  if (isRegistered) {
+    await TaskManager.unregisterTaskAsync(BACKGROUND_NOTIFICATION_TASK);
+  }
+};