From 176ada858d5279ed6b9bcef4203ef10970fa9f50 Mon Sep 17 00:00:00 2001
From: luckylooky2 <luckylooky2@naver.com>
Date: Sat, 14 Sep 2024 09:02:48 +0900
Subject: [PATCH] =?UTF-8?q?Fix:=20AudioContext=20=EC=A0=81=EC=9A=A9,=20?=
 =?UTF-8?q?=ED=86=B5=ED=99=94=20=EC=A2=85=EB=A3=8C=20=EB=A1=9C=EC=A7=81=20?=
 =?UTF-8?q?=EB=B3=80=EA=B2=BD=20#50?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 src/pages/Call.tsx | 70 +++++++++++++++++++++++++++-------------------
 1 file changed, 42 insertions(+), 28 deletions(-)

diff --git a/src/pages/Call.tsx b/src/pages/Call.tsx
index 93ae54f..b7633c1 100644
--- a/src/pages/Call.tsx
+++ b/src/pages/Call.tsx
@@ -4,8 +4,10 @@ import Timer from "@components/Call/Timer";
 import TopicModal from "@components/Call/TopicModal";
 import TopicSelect from "@components/Call/TopicSelect";
 import VoteToast from "@components/Call/VoteToast";
+import { AudioContext } from "@contexts/AudioProvider";
 import { CallActionType, CallContext } from "@contexts/CallProvider";
-import { SocketContext } from "@contexts/SocketProvider";
+import { useSocket } from "@hooks/useSocket";
+import { useStream } from "@hooks/useStream";
 import Loading from "@utils/Loading";
 import MicrophoneSoundChecker from "@utils/MicrophoneSoundChecker";
 import {
@@ -34,8 +36,10 @@ const Call = () => {
   const [screen, setScreen] = useState(SCREEN.INIT);
   const [voteId, setVoteId] = useState<Id>(0);
   const [contents, setContents] = useState<any>([]);
+  const { audio } = useContext(AudioContext);
   const { callInfo, dispatch } = useContext(CallContext);
-  const { socket, setSocket } = useContext(SocketContext);
+  const { disconnectStream } = useStream();
+  const { socket } = useSocket();
   const videos = [
     useRef<HTMLVideoElement>(null),
     useRef<HTMLVideoElement>(null),
@@ -53,12 +57,12 @@ const Call = () => {
   // /call로 접근하였을 때 잘 login 화면으로 가는지?
   useEffect(() => {
     const status = [];
-    if (callInfo.opponent && callInfo.stream)
+    if (callInfo.opponent && audio.stream)
       for (let i = 0; i < totalNum; i++) {
         peer[i] = new Peer({
           initiator: callInfo.opponent[i].initiator,
           trickle: true,
-          stream: callInfo.stream,
+          stream: audio.stream,
           config: { iceServers: ICE_SERVER },
         });
         status.push(true);
@@ -160,11 +164,7 @@ const Call = () => {
 
     return () => {
       window.removeEventListener("beforeunload", preventClose);
-      stopMicrophone();
-      // 뒤로가기, 새로고침, 정상 종료(종료 버튼 및 강제 종료)
-      socket?.disconnect();
-      setSocket(null);
-      dispatch({ type: CallActionType.DEL_ALL });
+      hangUp();
     };
   }, []);
 
@@ -205,27 +205,39 @@ const Call = () => {
   const preventClose = useCallback((e: BeforeUnloadEvent) => {
     e.preventDefault();
     e.returnValue = true;
+    // return "이 페이지를 벗어나면 데이터가 초기화 됩니다.";
   }, []);
 
   const muteToggle = useCallback(() => {
-    const tracks = callInfo.stream?.getAudioTracks();
+    const tracks = audio.stream?.getAudioTracks();
     if (tracks) tracks[0].enabled = !tracks[0].enabled;
     setIsMuted((prev) => !prev);
   }, [callInfo]);
 
   // 정상 종료(종료 버튼 및 강제 종료)
   const hangUp = useCallback(() => {
-    for (let i = 0; i < totalNum; i++) peer[i]?.destroy();
-    for (let i = 0; i < totalNum; i++) peer[i]?.removeAllListeners();
+    for (let i = 0; i < totalNum; i++) {
+      peer[i]?.destroy();
+    }
+    for (let i = 0; i < totalNum; i++) {
+      peer[i]?.removeAllListeners();
+    }
     console.log("hang up");
-    stopMicrophone();
-    setIsMuted(true);
-    navigate("/");
-  }, [callInfo]);
-
-  const stopMicrophone = useCallback(() => {
-    const tracks = callInfo.stream?.getAudioTracks();
-    if (tracks) tracks[0].stop();
+    // stopMicrophone();
+
+    // 뒤로가기, 새로고침, 정상 종료(종료 버튼 및 강제 종료)
+    socket?.emit("leaveRoom", { roomName: callInfo.roomName });
+    dispatch({ type: CallActionType.DEL_ALL });
+    toast.error("통화가 종료되었습니다.");
+    disconnectStream();
+    timeoutId.current = setTimeout(() => {
+      // dispatch({ type: CallActionType.DEL_ALL });
+      // socket을 끊지 않으면 백엔드에서 leaveRoom이 되지 않음
+      // - 소켓을 유지하는 방법은 없는가?
+      // - 소켓이 끊어질 때는 당연히 끊고, 방을 나갈 때도 소켓을 유지하면서 끊어보자
+      // disconnectSocket();
+      setIsMuted(true);
+    }, COUNT.HANG_UP * MILLISECOND);
   }, [callInfo]);
 
   const openTopicSelect = useCallback(() => {
@@ -310,14 +322,8 @@ const Call = () => {
         }
         if (closed) {
           // 혼자 남은 경우 종료
-          toast.error("통화가 종료되었습니다.");
           dispatch({ type: CallActionType.SET_CURRNUM, payload: 1 });
-          timeoutId.current = setTimeout(() => {
-            dispatch({ type: CallActionType.DEL_ALL });
-            socket?.disconnect();
-            setSocket(null);
-            hangUp();
-          }, COUNT.HANG_UP * MILLISECOND);
+          navigate("/main");
         }
         return copy;
       });
@@ -419,7 +425,15 @@ const Call = () => {
         </div>
       </div>
       <div className="flex justify-center h-[10%]">
-        <CallButton onClick={hangUp} type="hang-up" img="hang-up.svg" />
+        <CallButton
+          onClick={() => {
+            // 이렇게 하면 3초를 기다리지 못함
+            // 3초를 기다리고 main으로 가게 하고 싶음
+            navigate("/main");
+          }}
+          type="hang-up"
+          img="hang-up.svg"
+        />
       </div>
     </div>
   );