]>
Commit | Line | Data |
---|---|---|
1 | import { io } from "socket.io-client"; | |
2 | import { initializeTada } from "./tada"; | |
3 | import { | |
4 | addPeer, | |
5 | addIceCandidate, | |
6 | answerPeerOffer, | |
7 | processPeerAnswer, | |
8 | removePeer, | |
9 | resetPeers, | |
10 | } from "./peers"; | |
11 | import { startMedia, stopMedia } from "./media"; | |
12 | ||
13 | const internals = { | |
14 | kSocketUrl: "https://junction.tranquil.services", | |
15 | kIceServers: [{ urls: "stun:stun.l.google.com:19302" }], | |
16 | ||
17 | port: null, | |
18 | socket: null, | |
19 | ||
20 | onMessage(message) { | |
21 | internals[message.action](message.data); | |
22 | }, | |
23 | ||
24 | onError(error) { | |
25 | // TODO: How do we want to handle errors? | |
26 | console.error(error.stack || error); | |
27 | }, | |
28 | ||
29 | async joinAudioCall({ currentUrl, tada }) { | |
30 | try { | |
31 | const mediaStream = await startMedia(); | |
32 | const playTada = initializeTada(tada); | |
33 | ||
34 | const socket = (internals.socket = io(internals.kSocketUrl, { | |
35 | transports: ["websocket"], | |
36 | })); | |
37 | ||
38 | socket.on("error", internals.handleError); | |
39 | socket.on("connect_error", internals.handleError); | |
40 | ||
41 | socket.on("connect", () => { | |
42 | console.debug("Connected to signaling server, group: ", currentUrl); | |
43 | playTada(); | |
44 | socket.emit("join", { | |
45 | room: currentUrl, | |
46 | }); | |
47 | }); | |
48 | ||
49 | socket.on("disconnect", () => { | |
50 | console.debug("disconnected from signaling server"); | |
51 | }); | |
52 | ||
53 | socket.on("addPeer", ({ peerId, shouldCreateOffer }) => { | |
54 | addPeer({ | |
55 | peerId, | |
56 | shouldCreateOffer, | |
57 | mediaStream, | |
58 | onOffer: (data) => socket.emit("relayOffer", data), | |
59 | socket | |
60 | }); | |
61 | playTada(); | |
62 | }); | |
63 | ||
64 | socket.on("offerReceived", async ({ peerId, offer }) => { | |
65 | socket.emit("relayAnswer", await answerPeerOffer({ peerId, offer })); | |
66 | }); | |
67 | ||
68 | socket.on("answerReceived", (data) => processPeerAnswer(data)); | |
69 | socket.on("ICECandidateReceived", (data) => addIceCandidate(data)); | |
70 | socket.on("removePeer", (data) => removePeer(data)); | |
71 | } catch (err) { | |
72 | internals.port.postMessage({ | |
73 | action: "error", | |
74 | }); | |
75 | internals.port.disconnect(); | |
76 | } | |
77 | }, | |
78 | ||
79 | hangUp() { | |
80 | resetPeers(); | |
81 | stopMedia(); | |
82 | internals.socket.close(); | |
83 | internals.port.disconnect(); | |
84 | }, | |
85 | }; | |
86 | ||
87 | internals.port = chrome.runtime.connect({ name: "content" }); | |
88 | internals.port.onMessage.addListener(internals.onMessage); | |
89 | ||
90 | console.debug("Content Script Loaded"); | |
91 | ||
92 | // Indicates to the background script that we executed correctly | |
93 | true; |