- internals.socket.on('removePeer', function() {
-
- internals.peers--;
- console.log(`There are now ${internals.peers} participants`);
- });
-
- internals.createAudioElement(data.tada);
- }
- catch (err) {
-
- internals.port.postMessage({
- action: 'error'
- });
- internals.port.disconnect();
- internals.createAudioElement(data.tada);
- }
- },
-
- hangUp() {
- document.querySelectorAll('.junction-call-audio').forEach((audioElement) => audioElement.remove());
- internals.socket.close();
+ peerConnection.onicecandidate = (event) => {
+ if (event.candidate) {
+ internals.socket.emit("relayICECandidate", {
+ peerId: peerId,
+ candidate: event.candidate,
+ });
+ }
+ };
+
+ const remoteStream = new MediaStream();
+ peerConnection.ontrack = (event) => {
+ remoteStream.addTrack(event.track);
+ const remoteAudioElement = new Audio();
+ remoteAudioElement.srcObject = remoteStream;
+ remoteAudioElement.play();
+ };
+
+ peerConnection.onnegotiationneeded = async () => {
+ console.log("Creating RTC offer to ", peerId);
+ const offer = await peerConnection.createOffer();
+ await peerConnection.setLocalDescription(offer);
+
+ // Emit the offer to the peer
+ internals.socket.emit("relayOffer", { offer, peerId });
+ };
+
+ console.log(`There are now ${Peers.count()} participants`);
+ });
+
+ internals.socket.on("offerReceived", async ({ offer, peerId }) => {
+ const peerConnection = internals.peers[peerId];
+
+ const remoteDescription = new RTCSessionDescription(offer);
+ await peerConnection.setRemoteDescription(remoteDescription);
+
+ const answer = await peerConnection.createAnswer();
+ await peerConnection.setLocalDescription(answer);
+
+ // Send the answer to the peer
+ internals.socket.emit("relayAnswer", { answer, peerId });
+ });
+
+ internals.socket.on("answerReceived", async ({ answer, peerId }) => {
+ const peerConnection = internals.peers[peerId];
+ const remoteDescription = new RTCSessionDescription(answer);
+ await peerConnection.setRemoteDescription(remoteDescription);
+ });
+
+ internals.socket.on(
+ "ICECandidateReceived",
+ async ({ candidate, peerId }) => {
+ const peerConnection = internals.peers[peerId];
+ const iceCandidate = new RTCIceCandidate(candidate);
+ await peerConnection.addIceCandidate(iceCandidate);
+ },
+ );
+
+ internals.socket.on("removePeer", function ({ peerId }) {
+ delete internals.peers[peerId];
+ Peers.remove(peerId);
+ console.log(`There are now ${Peers.count()} participants`);
+ });
+ } catch (err) {
+ internals.port.postMessage({
+ action: "error",
+ });