aboutsummaryrefslogtreecommitdiff
path: root/extension/content_script.js
blob: 26da2b054ecec0fcff3513d267a6867b9e235d7d (plain)
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
import { io } from "socket.io-client";
import Peers from "./peers";
import Media from "./media";

const internals = {
  kSocketUrl: "https://junction.tranquil.services",
  kIceServers: [{ urls: "stun:stun.l.google.com:19302" }],

  port: null,
  socket: null,
  peers: {},

  onMessage(message) {
    internals[message.action](message.data);
  },

  async joinAudioCall({ currentUrl, tada }) {
    try {
      const mediaStream = await Media.start();

      internals.socket = io(internals.kSocketUrl, {
        transports: ["websocket"],
      });

      internals.socket.on("error", function (error) {
        console.error("GENERAL ERROR", error);
      });

      internals.socket.on("connect_error", function (error) {
        console.error("CONNNECT ERROR", error);
      });

      internals.socket.on("connect", function () {
        console.log("Connected to signaling server, group: ", currentUrl);
        internals.socket.emit("join", {
          room: currentUrl,
        });
      });

      internals.socket.on("disconnect", function () {
        console.log("disconnected from signaling server");
      });

      internals.socket.on("addPeer", function ({ peerId }) {
        /**
         * Eventually the whole rtc connection logic should be moved to Peers.
         * Now it only plays tadas.
         */
        Peers.add(peerId, tada);

        const peerConnection = new RTCPeerConnection(
          { iceServers: internals.kIceServers },
          { optional: [{ DtlsSrtpKeyAgreement: true }] },
        );

        internals.peers[peerId] = peerConnection;
        mediaStream.getTracks().forEach((track) => {
          peerConnection.addTrack(track, mediaStream);
        });

        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",
      });
      internals.port.disconnect();
    }
  },

  hangUp() {
    Peers.reset();
    Media.stop();
    internals.socket.close();
    internals.port.disconnect();
  },
};

internals.port = chrome.runtime.connect({ name: "content" });
internals.port.onMessage.addListener(internals.onMessage);

console.log("Content Script Loaded");

// Indicates to the background script that we executed correctly
true;