최정우 최정우 2023-05-08
230508 최정우 푸시 알림 관련 기능 추가
@1f69c05d37131066e9f06b97b7d45a656778c3e6
client/views/pages/App.jsx
--- client/views/pages/App.jsx
+++ client/views/pages/App.jsx
@@ -47,34 +47,8 @@
 function App() {
 
   /**************** Firebase 푸시 설정 (시작) ****************/
-  const [token, setToken] = React.useState('');
-
   const messaging = getMessaging();
-  getToken(messaging, {
-    vapidKey: 'BCVKYse4XZVC_IZHOBdq99RtUVHDtOwaPSv2tK3NNaJve2f-UTqmqOfQuJ-eZZbHDuPPeJyeStJtFjlACqtwz8s'
-  }).then((currentToken) => {
-    console.log('currentToken : ', currentToken);
-    if (currentToken) {
-      setToken(currentToken);
-
-      /* navigator.clipboard.writeText(currentToken).then(() => {
-          console.log("Text copied to clipboard... : ", currentToken);
-      }).catch(err => {
-          console.log('Something went wrong', err);
-      }); */
-
-      // Send the token to your server and update the UI if necessary
-      // ...
-    } else {
-      // Show permission request UI
-      console.log('No registration token available. Request permission to generate one.');
-      // ...
-    }
-  }).catch((err) => {
-    console.log('An error occurred while retrieving token. ', err);
-    // ...
-  });
-
+  
   onMessage(messaging, (payload) => {
     console.log('Message received. ', payload);
   });
@@ -83,23 +57,77 @@
     console.log('Message received. ', payload);
   }); */
 
-  function requestPermission() {
-    console.log("권한 요청 중...");
+  const [token, setToken] = React.useState(null);
+  const requestToken = (loginUser) => {
+    if (!window.Notification) {
+      console.log('[requestToken()] 푸쉬 알람을 지원하지 않는 브라우저라, 푸쉬 토큰을 가지고오지 않습니다.');
+    } else {
+      if (Notification.permission == "granted") {
+        getToken(messaging, {
+          vapidKey: 'BCVKYse4XZVC_IZHOBdq99RtUVHDtOwaPSv2tK3NNaJve2f-UTqmqOfQuJ-eZZbHDuPPeJyeStJtFjlACqtwz8s'
+        }).then((currentToken) => {
+          console.log('currentToken : ', currentToken);
+          if (currentToken) {
+            setToken(currentToken);
+
+            if (CommonUtil.isEmpty(loginUser) == false
+                && (CommonUtil.isEmpty(loginUser['push_token']) || loginUser['push_token'] != currentToken)) {  
+              loginUser['push_token'] = currentToken
+              userUpdateForPushToken(loginUser);
+            }
+      
+            /* navigator.clipboard.writeText(currentToken).then(() => {
+                console.log("Text copied to clipboard... : ", currentToken);
+            }).catch(err => {
+                console.log('Something went wrong', err);
+            }); */
+      
+          } else {
+            // Show permission request UI
+            console.log('No registration token available. Request permission to generate one.');
+            // ...
+          }
+        }).catch((err) => {
+          console.log('Firebase getToken Error ', err);
+        });
+      } else {
+        console.log('[requestToken()] 푸쉬 알람을 권한 : ', Notification.permission);
+      }
+    }
+  }
+
+  const [isPush, setIsPush] = React.useState(null);
+  const requestPermission = (loginUser) => {
     try {
-      Notification.requestPermission().then((permission) => {
-        if (permission === "granted") {
-          console.log("알림 권한이 허용됨");
-          // FCM 메세지 처리
-        } else {
-          console.log("알림 권한 허용 안됨");
-        }
-      });
+      if (!window.Notification) {
+        alert('푸쉬 알람을 지원하지 않는 브라우저입니다.');
+      } else {
+        Notification.requestPermission().then((permission) => {
+          console.log('permission : ', permission);
+          if (permission == "granted") {
+            setIsPush(true);
+
+            // FCM 메세지 처리
+            if (CommonUtil.isEmpty(loginUser) == false
+                && (CommonUtil.isEmpty(loginUser['is_push']) || loginUser['is_push'] == false)) {
+              loginUser['is_push'] = true;
+              userUpdateForIsPush(loginUser);
+            }
+          } else {
+            setIsPush(false);
+
+            if (CommonUtil.isEmpty(loginUser) == false
+                && (CommonUtil.isEmpty(loginUser['is_push']) || loginUser['is_push'] == true)) {
+              loginUser['is_push'] = false;
+              userUpdateForIsPush(loginUser);
+            }
+          }
+        });
+      }
     } catch (e) {
       console.error(e);
     }
   }
-
-  requestPermission();
   /**************** Firebase 푸시 설정 (종료) ****************/
 
 
@@ -130,9 +158,43 @@
       //로그인 사용자 정보 전역 변수에 저장
       dispatch(setLoginUser(data));
       //클라이언트 로그인 체크 (콜백)
-      clientLoginCheck(data);
+      if (CommonUtil.isEmpty(clientLoginCheck) == false) {
+        clientLoginCheck(data);
+      }
     }).catch((error) => {
       console.log('login() /user/loginUserSelectOne.json error : ', error);
+    });
+  };
+
+  //사용자 수정 (푸시 알림 여부)
+  const userUpdateForIsPush = (loginUser) => {
+    fetch("/user/userUpdateForIsPush.json", {
+      method: "POST",
+      headers: {
+        'Content-Type': 'application/json; charset=UTF-8'
+      },
+      body: JSON.stringify(loginUser),
+    }).then((response) => response.json()).then((data) => {
+      console.log("사용자 수정 (푸시 알림 여부) : ", data);
+      loginUserSelectOne();
+    }).catch((error) => {
+      console.log('login() /user/userUpdateForIsPush.json error : ', error);
+    });
+  };
+
+  //사용자 수정 (푸시 알림 토큰)
+  const userUpdateForPushToken = (loginUser) => {
+    fetch("/user/userUpdateForPushToken.json", {
+      method: "POST",
+      headers: {
+        'Content-Type': 'application/json; charset=UTF-8'
+      },
+      body: JSON.stringify(loginUser),
+    }).then((response) => response.json()).then((data) => {
+      console.log("사용자 수정 (푸시 알림 토큰) : ", data);
+      loginUserSelectOne();
+    }).catch((error) => {
+      console.log('login() /user/userUpdateForPushToken.json error : ', error);
     });
   };
 
@@ -186,6 +248,16 @@
           alert('권한 관련 에러 - 관리자에게 문의바랍니다.');
           console.log('권한 관련 에러 - 관리자에게 문의바랍니다 : ', loginResultData);
         }
+
+        if (CommonUtil.isEmpty(isPush)) {
+          requestPermission(loginResultData);
+        }
+        if (CommonUtil.isEmpty(token)) {
+          requestToken(loginResultData);
+        }
+      } else {
+        setIsPush(null);
+        setToken(null);
       }
     });
   }, [location]);
Add a comment
List