const createRoom = async () => {
const callDoc = doc(collection(db, "calls"));
const offerCandidates = collection(callDoc, "offerCandidates");
const answerCandidates = collection(callDoc, "answerCandidates");
setCallId(callDoc.id);
pc.current.onicecandidate = (event) => {
if (event.candidate) {
addDoc(offerCandidates, event.candidate.toJSON());
}
};
const offerDescription = await pc.current.createOffer();
await pc.current.setLocalDescription(offerDescription);
const offer = {
sdp: offerDescription.sdp,
type: offerDescription.type,
};
await setDoc(callDoc, { offer });
onSnapshot(callDoc, (snapshot) => {
const data = snapshot.data();
if (!pc.current.currentRemoteDescription && data?.answer) {
const answerDescription = new RTCSessionDescription(data.answer);
pc.current.setRemoteDescription(answerDescription);
}
});
onSnapshot(answerCandidates, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === 'added') {
const candidate = new RTCIceCandidate(change.doc.data());
pc.current.addIceCandidate(candidate);
}
});
});
};