File size: 5,723 Bytes
a0fda44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { useState } from "react";
import { useRef } from "react";
import { useEffect } from "react";
import useSocket from "./useSocket";
import Peer from "simple-peer";
import useSendMessage from "./useSendMessage";
import { useDispatch, useSelector } from "react-redux";
import { modalActions } from "../store/modalSlice";
import useCounter from "./useCounter";

const usePeer = ({ mediaOptions, callDetail }) => {
  const userMediaRef = useRef();
  const partnerMediaRef = useRef();

  //   Get id of chat room both user belongs to
  const currentChatRoomId = useSelector(
    (state) => state.chatReducer.currentChatRoom._id
  );
  const [userStream, setUserStream] = useState();
  //   Call status to show calling, ringing, ongoing
  const [callStatus, setCallStatus] = useState("calling");
  //   Call acceptance state
  const [callAccepted, setCallAccepted] = useState();
  //   Duration counter for call
  const {
    formattedTime: duration,
    startCounter,
    stopCounter,
  } = useCounter({ showCentiseconds: false });
  //   Get socket instances
  const { socketEmit, socketListen, socket, userId } = useSocket();
  //   Send call details to database
  const { sendMessage } = useSendMessage();

  const dispatch = useDispatch();

  // Get user media and attach to ref
  useEffect(() => {
    if (userMediaRef.current) {
      navigator.mediaDevices.getUserMedia(mediaOptions).then((stream) => {
        setUserStream(stream);
        userMediaRef.current.srcObject = stream;
      });
    }
  }, []);

  // If user is the one initiating call
  useEffect(() => {
    if (callDetail.caller && userStream) {
      const peer = new Peer({
        initiator: true,
        trickle: false,
        stream: userStream,
      });
      peer.on("signal", (signalData) => {
        socketEmit(
          "user:callRequest",
          {
            signalData,
            callType: mediaOptions.video ? "video" : "voice",
            chatRoomId: currentChatRoomId,
            userId,
          },
          (callAcknowledged) => {
            // Caller acknowledges call request
            setCallStatus(callAcknowledged ? "ringing" : "calling");
            // While call receiver hasn't picked call
            setTimeout(() => {
              if (!callAccepted) {
                dispatch(modalActions.closeModal());
                denyCall("Missed");
              }
            }, 60000);
          }
        );
      });
      socketListen("user:callAccepted", ({ signalData }) => {
        peer.signal(signalData);
        setCallAccepted(true);
        // Start duration
        startCounter();
      });
      peer.on("stream", (stream) => {
        partnerMediaRef.current.srcObject = stream;
      });
      peer.on("close", () => {
        socket.off("user:callAccepted");
        dispatch(modalActions.closeModal());
        userStream.getTracks().forEach(function (track) {
          track.stop();
        });
      });
      socketListen("user:endCall", () => {
        peer.destroy();
      });
    }
  }, [userStream]);

  //   If user is the one receiving call
  useEffect(() => {
    if (callAccepted && userStream && !callDetail.caller) {
      const peer = new Peer({
        initiator: false,
        trickle: false,
        stream: userStream,
      });

      peer.on("signal", (signalData) => {
        socketEmit("user:callAccepted", {
          signalData,
          chatRoomId: callDetail.chatRoomId,
        });

        // Start duration
        startCounter();
      });

      peer.signal(callDetail.callerSignal);

      peer.on("stream", (stream) => {
        partnerMediaRef.current.srcObject = stream;
      });

      peer.on("close", () => {
        dispatch(modalActions.closeModal());
        userStream.getTracks().forEach(function (track) {
          track.stop();
        });
      });
    }
  }, [callAccepted, userStream]);

  //   If call is denied by any user
  useEffect(() => {
    socketListen("user:callDenied", () => {
      // If user is the caller, show reason for disconnection
      if (callDetail.caller) {
        setCallStatus("Call denied");
        setTimeout(() => {
          dispatch(modalActions.closeModal());
        }, 1000);
      } else {
        dispatch(modalActions.closeModal());
      }

      userStream.getTracks().forEach(function (track) {
        track.stop();
      });
    });

    return () => {
      socket.off("user:callDenied");
    };
  }, [userStream]);

  //   Accept call
  const acceptCall = () => {
    setCallAccepted(true);
  };

  //   Deny call
  const denyCall = (reason) => {
    // Emit call denied to caller
    socketEmit("user:callDenied", {
      chatRoomId: callDetail.caller ? currentChatRoomId : callDetail.chatRoomId,
    });

    sendMessage({
      callType: mediaOptions.video ? "video" : "voice",
      callRejectReason: reason,
      sender: callDetail.caller ? userId : callDetail.callerId,
      chatRoomId: callDetail.caller ? currentChatRoomId : callDetail.chatRoomId,
    });

    // End duration
    stopCounter();
  };

  //   End call
  const endCall = () => {
    socketEmit("user:endCall", {
      duration,
      chatRoomId: callDetail.caller ? currentChatRoomId : callDetail.chatRoomId,
    });

    sendMessage({
      callType: mediaOptions.video ? "video" : "voice",
      callDuration: duration,
      sender: callDetail.caller ? userId : callDetail.callerId,
      chatRoomId: callDetail.caller ? currentChatRoomId : callDetail.chatRoomId,
    });

    // End duration
    stopCounter();
  };

  return {
    userStream,
    userMediaRef,
    partnerMediaRef,
    callStatus,
    acceptCall,
    callAccepted,
    endCall,
    denyCall,
    duration,
  };
};

export default usePeer;