-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathApp.js
321 lines (282 loc) · 8 KB
/
App.js
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { useEffect, useRef, useState } from "react";
import {
addDoc,
collection,
query,
onSnapshot,
setDoc,
getDoc,
getDocs,
updateDoc,
deleteDoc,
doc,
} from "firebase/firestore";
import {
Button,
SafeAreaView,
StatusBar,
StyleSheet,
View,
} from "react-native";
import {
ScreenCapturePickerView,
RTCPeerConnection,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStream,
MediaStreamTrack,
mediaDevices,
registerGlobals,
} from "react-native-webrtc";
import { db } from "./firebase";
import GettingCall from "./components/GettingCall";
import AppButton from "./components/AppButton";
import Video from "./components/Video";
const peerConstraints = {
iceServers: [
{
urls: "stun:stun.l.google.com:19302",
},
],
};
function App() {
const [localStream, setLocalStream] = useState(null);
const [remoteStream, setRemoteStream] = useState(null);
const [gettingCall, setGettingCall] = useState(false);
const connecting = useRef(false);
let pc = useRef(false);
// Global state
useEffect(() => {
const cRef = doc(db, "meet", "chatId");
const subscribe = onSnapshot(cRef, (snapshot) => {
const data = snapshot.data();
// On answer start the call
if (pc.current && !pc.current.remoteDescription && data && data.answer) {
pc.current.setRemoteDescription(new RTCSessionDescription(data.answer));
}
// if there is offer for chatId set the getting call flag
if (data && data.offer && !connecting.current) {
setGettingCall(true);
}
});
// On Delete of collection call hangup
// The other side has clicked on hangup
const qdelete = query(collection(cRef, "callee"));
const subscribeDelete = onSnapshot(qdelete, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type == "removed") {
hangup();
}
});
});
return () => {
subscribe();
subscribeDelete();
};
}, []);
async function setupWebrtc() {
pc.current = new RTCPeerConnection(peerConstraints);
// Get the audio and video stream for the call
const stream = await getStream();
if (stream) {
setLocalStream(stream);
pc.current.addStream(stream);
}
// Get the remote stream once it is available
pc.current.onaddstream = (event) => {
setRemoteStream(event.stream);
};
}
async function create() {
console.log("calling");
connecting.current = true;
// setUp webrtc
await setupWebrtc();
// Document for the call
const cRef = doc(db, "meet", "chatId");
// await setDoc(cRef, {});
// Exchange the ICE candidates between the caller and callee
collectIceCandidates(cRef, "caller", "callee");
if (pc.current) {
// Create the offer for the call
// Store the offer under the document
console.log("create");
try {
let sessionConstraints = {
mandatory: {
OfferToReceiveAudio: true,
OfferToReceiveVideo: true,
VoiceActivityDetection: true,
},
};
const offerDescription = await pc.current.createOffer(
sessionConstraints
);
await pc.current.setLocalDescription(offerDescription);
const cWithOffer = {
offer: {
type: offerDescription.type,
sdp: offerDescription.sdp,
},
};
// cRef.set(cWithOffer)
await setDoc(cRef, cWithOffer);
} catch (error) {
console.log("error", error);
}
}
}
const join = async () => {
console.log("Joining the call");
connecting.current = true;
setGettingCall(false);
//const cRef = firestore().collection("meet").doc("chatId")
const cRef = doc(db, "meet", "chatId");
// const offer = (await cRef.get()).data()?.offer
const offer = (await getDoc(cRef)).data()?.offer;
if (offer) {
// Setup Webrtc
await setupWebrtc();
// Exchange the ICE candidates
// Check the parameters, Its reversed. Since the joining part is callee
collectIceCandidates(cRef, "callee", "caller");
if (pc.current) {
pc.current.setRemoteDescription(new RTCSessionDescription(offer));
// Create the answer for the call
// Updates the document with answer
const answer = await pc.current.createAnswer();
pc.current.setLocalDescription(answer);
const cWithAnswer = {
answer: {
type: answer.type,
sdp: answer.sdp,
},
};
// cRef.update(cWithAnswer)
await updateDoc(cRef, cWithAnswer);
}
}
};
/**
* For disconnectign the call, close the connection, release the stream,
* and delete the document for the call
**/
async function hangup() {
console.log("hangup");
setGettingCall(false);
connecting.current = false;
streamCleanUp();
firebaseCleanUp();
if (pc.current) {
pc.current.close();
}
}
// Helper function
async function getStream() {
let isVoiceOnly = false;
let mediaConstraints = {
audio: true,
video: {
frameRate: 30,
facingMode: "user",
},
};
try {
const mediaStream = await mediaDevices.getUserMedia(mediaConstraints);
if (isVoiceOnly) {
let videoTrack = mediaStream.getVideoTracks()[0];
videoTrack.enabled = false;
}
return mediaStream;
} catch (err) {
console.log("err", err);
}
}
async function streamCleanUp() {
console.log("streamCleanUp");
if (localStream) {
localStream.getTracks().forEach((t) => t.stop());
localStream.release();
}
setLocalStream(null);
setRemoteStream(null);
}
async function firebaseCleanUp() {
console.log("firebaseCleanUp");
const cRef = doc(db, "meet", "chatId");
if (cRef) {
const qee = query(collection(cRef, "callee"));
const calleeCandidate = await getDocs(qee);
calleeCandidate.forEach(async (candidate) => {
await deleteDoc(candidate.ref);
});
const qer = query(collection(cRef, "caller"));
const callerCandidate = await getDocs(qer);
callerCandidate.forEach(async (candidate) => {
await deleteDoc(candidate.ref);
});
deleteDoc(cRef);
}
}
async function collectIceCandidates(cRef, localName, remoteName) {
console.log("localName", localName);
const candidateCollection = collection(db, "meet", "chatId", localName);
if (pc.current) {
// on new ICE candidate add it to firestore
console.log("test");
pc.current.onicecandidate = (event) => {
event.candidate &&
addDoc(candidateCollection, event.candidate.toJSON());
};
}
// Get the ICE candidate added to firestore and update the local PC
q = query(collection(cRef, remoteName));
const unsubscribe = onSnapshot(q, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type == "added") {
const candidate = new RTCIceCandidate(change.doc.data());
pc.current.addIceCandidate(candidate);
}
});
});
}
// Displays the gettingCall Component
if (gettingCall) {
console.log("gettingCall");
return <GettingCall hangup={hangup} join={join}></GettingCall>;
}
// Displays local stream on calling
// Displays both local and remote stream once call is connected
if (localStream) {
console.log("localStream");
return (
<Video
hangup={hangup}
localStream={localStream}
remoteStream={remoteStream}
></Video>
);
}
return (
<SafeAreaView style={{ flex: 1 }}>
<StatusBar barStyle="dark-content" />
<View style={styles.container}>
<AppButton
iconName="video"
backgroundColor="grey"
onPress={create}
></AppButton>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
export default App;