-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpeer.ts
177 lines (162 loc) · 5.1 KB
/
peer.ts
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
import { createPeer, type ISession, type Peer } from "@pulsebeam/peer";
import { create } from "zustand";
import { produce } from "immer";
const DEFAULT_GROUP = "default";
const DEFAULT_CONNECT_TIMEOUT_MS = 3_000;
interface SessionProps {
key: number;
sess: ISession;
remoteStream: MediaStream | null;
loading: boolean;
}
export interface PeerState {
ref: Peer | null;
loading: boolean;
sessions: Record<string, SessionProps>;
localStream: MediaStream | null;
setLocalStream: (_: MediaStream) => void;
start: (peerId: string) => Promise<void>;
stop: () => void;
connect: (otherPeerId: string) => void;
peerId: string;
isMuted: boolean;
toggleMute: () => void;
}
export const usePeerStore = create<PeerState>((set, get) => ({
ref: null,
sessions: {},
loading: false,
localStream: null,
peerId: "",
setLocalStream: (localStream: MediaStream) => {
set({ localStream });
},
start: async (peerId) => {
if (get().ref) return;
if (get().loading) return;
set({ loading: true });
try {
const urlParams = new URLSearchParams(window.location.search);
const forceRelay = urlParams.get("forceRelay");
const baseUrl = urlParams.get("baseUrl");
const isDevelopment = urlParams.get("development");
// See https://pulsebeam.dev/docs/ for learning about token management
let token;
if (isDevelopment !== null) {
// WARNING!
// PLEASE ONLY USE THIS FOR TESTING ONLY. FOR PRODUCTION,
// YOU MUST USE YOUR OWN AUTH SERVER TO GENERATE THE TOKEN.
const form = new URLSearchParams({
apiKey: "kid_<...>",
apiSecret: "sk_<...>",
groupId: DEFAULT_GROUP,
peerId: peerId,
});
if (
form.get("apiKey") === "kid_<...>" ||
form.get("appSecret") === "sk_<...>"
) {
console.error(
"ERROR: Keys not set see https://pulsebeam.dev/docs/getting-started/quick-start/",
);
}
// See https://pulsebeam.dev/docs/getting-started/what-happened/
// For explanation of this token-serving method
const resp = await fetch(
"https://cloud.pulsebeam.dev/sandbox/token",
{
body: form,
method: "POST",
},
);
token = await resp.text();
} else {
// See https://pulsebeam.dev/docs/guides/token/#example-nodejs-http-server
// For explanation of this token-serving method
const resp = await fetch(
`/auth?groupId=${DEFAULT_GROUP}&peerId=${peerId}`,
);
token = await resp.text();
}
const p = await createPeer({
baseUrl: baseUrl || undefined,
token,
forceRelay: forceRelay != null,
});
p.onsession = (s) => {
// For you app consider your UI/UX in what you want to support
// In this app, we support multiple sessions at a time.
const id = `${s.other.peerId}:${s.other.connId}`;
s.ontrack = ({ streams }) => {
console.log("ontrack", streams[0]);
set(produce((state: PeerState) => {
state.sessions[id].remoteStream = streams[0];
state.sessions[id].key = performance.now();
}));
};
s.onconnectionstatechange = () => {
console.log(s.connectionState);
if (s.connectionState === "closed") {
set((state) => {
const { [id]: _, ...rest } = state.sessions;
return { sessions: rest };
});
} else {
const loading = s.connectionState !== "connected";
set(produce((state: PeerState) => {
state.sessions[id].loading = loading;
state.sessions[id].key = performance.now();
}));
}
};
const localStream = get().localStream;
if (localStream) {
localStream.getTracks().forEach((track) =>
s.addTrack(track, localStream)
);
}
set(produce((state: PeerState) => {
state.sessions[id] = {
key: performance.now(),
sess: s,
loading: true,
remoteStream: null,
};
}));
};
p.onstatechange = () => {
if (p.state === "closed") get().stop();
};
set({ ref: p });
p.start();
} catch (error) {
console.error("Error starting peer:", error);
}
set({ loading: false, peerId });
},
stop: () => {
get().ref?.close();
set({ ref: null });
},
connect: async (otherPeerId) => {
set({ loading: true });
const abort = new AbortController();
const timeoutId = window.setTimeout(
() => abort.abort(),
DEFAULT_CONNECT_TIMEOUT_MS,
);
await get().ref?.connect(DEFAULT_GROUP, otherPeerId, abort.signal);
window.clearTimeout(timeoutId);
set({ loading: false });
},
isMuted: true,
toggleMute: () => {
set(produce((state: PeerState) => {
const isMuted = !state.isMuted;
state.localStream?.getAudioTracks().forEach((track) => {
track.enabled = !isMuted;
});
state.isMuted = isMuted;
}));
},
}));