]> git.r.bdr.sh - rbdr/junction/blob - extension/content_script.js
Add safari code
[rbdr/junction] / extension / content_script.js
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 }) => {
54 addPeer({
55 peerId,
56 mediaStream,
57 onOffer: (data) => socket.emit("relayOffer", data),
58 socket
59 });
60 playTada();
61 });
62
63 socket.on("offerReceived", async ({ peerId, offer }) => {
64 socket.emit("relayAnswer", await answerPeerOffer({ peerId, offer }));
65 });
66
67 socket.on("answerReceived", (data) => processPeerAnswer(data));
68 socket.on("ICECandidateReceived", (data) => addIceCandidate(data));
69 socket.on("removePeer", (data) => removePeer(data));
70 } catch (err) {
71 internals.port.postMessage({
72 action: "error",
73 });
74 internals.port.disconnect();
75 }
76 },
77
78 hangUp() {
79 resetPeers();
80 stopMedia();
81 internals.socket.close();
82 internals.port.disconnect();
83 },
84 };
85
86 internals.port = chrome.runtime.connect({ name: "content" });
87 internals.port.onMessage.addListener(internals.onMessage);
88
89 console.debug("Content Script Loaded");
90
91 // Indicates to the background script that we executed correctly
92 true;