-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
253 lines (231 loc) · 8.63 KB
/
index.js
File metadata and controls
253 lines (231 loc) · 8.63 KB
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
const channelIds = new Set()
const channelConnections = {}
let channelCounter = 0
const connectionStatusTypes = {
0: "INITIALIZING",
1: "SDP_CREATED"
}
const mediaSettings = {
video: true,
audio: true
}
const localMedia = new CustomMediaStream(mediaSettings)
const addUserButton = document.getElementById("add-user")
const addUserBtnSpinnerElement = document.getElementById("add-user-spinner");
const connectButtonElement = document.getElementById("connect")
const connectBtnSpinnerElement = document.getElementById("connect-spinner");
const remoteSDPElement = document.getElementById("remote-sdp")
const cancelAddUserElement = document.getElementById("cancel-add-user")
const videoBlockListElement = document.getElementById("video-block-list")
const usernameElement = document.getElementById("username")
let currentChannelId;
function logError(message) {
console.error(message)
}
// Video Block Control In UI
function getVideoBlockElement({ channelId, username }) {
const videoBlockTemplate = document.createElement("template")
videoBlockTemplate.innerHTML = `<div class="video-block" id="video-block-${channelId}">
<p>${username}</p>
<video autoplay></video>
</div>
`
return videoBlockTemplate.content.firstChild
}
function addVideoBlock({ channelId, username }) {
const videoBlockElement = getVideoBlockElement({ channelId, username })
videoBlockListElement.appendChild(videoBlockElement)
}
function removeVideoBlock({ channelId }) {
const videoBlockElement = document.getElementById(`${channelId}-video-block`)
videoBlockElement.remove()
}
// End
async function createOffer({ username } = {}) {
const channelId = channelCounter++;
if (channelIds.has(channelId)) {
logError(`ChannelId ${channelId} already exists, skipping connection`)
return
}
const lc = new RTCPeerConnection()
const iceCandidates = []
const connectionObject = { status: 0, connection: lc }
lc.onicecandidate = (e) => {
iceCandidates.push(e.candidate)
// console.log(`[Channel Id: ${channelId}] New ICE Candidate Added, Candidate: ${JSON.stringify({ candidate: e.candidate })}`)
}
lc.addTrack(localMedia.tracks.audioTrack)
lc.addTrack(localMedia.tracks.videoTrack)
lc.ontrack = ({ track, type }) => {
console.log(`Got ${type} Track!!`)
let videoElement = document.querySelector(`#video-block-${channelId} video`)
if (!videoElement) {
addVideoBlock({ channelId, username })
}
videoElement = document.querySelector(`#video-block-${channelId} video`)
if (videoElement.srcObject) {
videoElement.srcObject.addTrack(track)
} else {
videoElement.srcObject = new MediaStream([track])
}
}
const offer = await lc.createOffer()
await lc.setLocalDescription(offer)
await wait(5)
connectionObject.sdp = offer.sdp
connectionObject.status = 1
channelConnections[channelId] = connectionObject
return { channelId, sdp: offer.sdp, iceCandidates }
}
async function createAnswer({ remoteSDP, username } = {}) {
const channelId = channelCounter++;
if (channelIds.has(channelId)) {
logError(`ChannelId ${channelId} already exists, skipping connection`)
return
}
const rc = new RTCPeerConnection()
const iceCandidates = []
const connectionObject = { status: 0, connection: rc }
rc.onicecandidate = (e) => {
iceCandidates.push(e.candidate)
// console.log(`[Channel Id: ${channelId}] New ICE Candidate Added, Candidate: ${JSON.stringify({ candidate: e.candidate })}`)
}
rc.addTrack(localMedia.tracks.audioTrack)
rc.addTrack(localMedia.tracks.videoTrack)
rc.ontrack = ({ track, type }) => {
console.log(`Got ${type} Track!!`)
let videoElement = document.querySelector(`#video-block-${channelId} video`)
if (!videoElement) {
addVideoBlock({ channelId, username })
}
videoElement = document.querySelector(`#video-block-${channelId} video`)
if (videoElement.srcObject) {
videoElement.srcObject.addTrack(track)
} else {
videoElement.srcObject = new MediaStream([track])
}
}
await rc.setRemoteDescription({ type: "offer", sdp: remoteSDP })
const answer = await rc.createAnswer()
await rc.setLocalDescription(answer)
await wait(5)
connectionObject.sdp = answer.sdp
connectionObject.status = 1
channelConnections[channelId] = connectionObject
return { channelId, sdp: answer.sdp, iceCandidates }
}
async function addUser() {
addUserButton.disabled = true;
cancelAddUserElement.disabled = false;
// Loading for add user
addUserBtnSpinnerElement.classList.add("spinner");
const username = usernameElement.value
if (!username) {
alert('Username is required!')
addUserButton.disabled = false;
cancelAddUserElement.disabled = true;
addUserBtnSpinnerElement.classList.remove("spinner");
return
}
const { channelId, sdp: localSDP, iceCandidates } = await createOffer({ username })
currentChannelId = channelId
const connectionString = JSON.stringify({
sdp: localSDP,
iceCandidates
}, null, 2)
setModalContext({
header: "Here's your Connection String, send it to person to whom you want to connect!!",
body: connectionString,
buttons: [{
name: "Copy",
onClick: () => {
navigator.clipboard.writeText(connectionString)
}
}]
})
openModal()
usernameElement.value = ""
addUserBtnSpinnerElement.classList.remove("spinner");
}
async function connect() {
const remoteConnectionString = remoteSDPElement.value
let channelId;
if (!remoteConnectionString) return
connectBtnSpinnerElement.classList.add("spinner");
const { sdp: remoteSDP, iceCandidates = [] } = JSON.parse(remoteConnectionString)
const username = usernameElement.value
if (currentChannelId !== undefined) {
await channelConnections[currentChannelId].connection.setRemoteDescription({ type: "answer", sdp: remoteSDP })
channelId = currentChannelId
addUserButton.disabled = false;
cancelAddUserElement.disabled = true
currentChannelId = undefined
} else {
if (!username) {
alert('Username is required!')
addUserButton.disabled = false;
cancelAddUserElement.disabled = true
connectBtnSpinnerElement.classList.remove("spinner");
return
}
const { channelId: _channelId, sdp: localSDP, iceCandidates = [] } = await createAnswer({ remoteSDP, username })
channelId = _channelId
const connectionString = JSON.stringify({ sdp: localSDP, iceCandidates }, null, 2)
setModalContext({
header: "Here's your Connection String, send it to person to whom you want to connect!!",
body: connectionString,
buttons: [{
name: "Copy",
onClick: () => {
navigator.clipboard.writeText(connectionString)
}
}]
})
openModal()
}
for (let candidate of iceCandidates) {
await channelConnections[channelId].connection.addIceCandidate(candidate)
}
addUserButton.disabled = false;
cancelAddUserElement.disabled = true
remoteSDPElement.value = ""
usernameElement.value = ""
connectBtnSpinnerElement.classList.remove("spinner");
}
async function cancelAddUser() {
if (!currentChannelId) return
currentChannelId = null
}
// Event Listeners
addUserButton.addEventListener("click", addUser)
connectButtonElement.addEventListener("click", connect)
cancelAddUserElement.addEventListener("click", cancelAddUser)
//End
async function checkMediaPermissions() {
try {
const tracks = await localMedia.startStream()
if (!tracks.audioTrack && !tracks.videoTrack) {
return false
}
return true
} catch (error) {
return false
}
}
async function main() {
// Check Media
const isMediaAllowed = await checkMediaPermissions()
if (!isMediaAllowed) {
alert("You have to allow atleast one media to run this program!!")
return main()
}
const controlPanel = document.getElementById("control-pannel")
controlPanel.style.display = "flex";
//End
addVideoBlock({ channelId: "local", username: "You" })
const localVideo = document.querySelector("#video-block-local video")
const localMediaStream = new MediaStream()
localMediaStream.addTrack(localMedia.tracks.videoTrack)
localVideo.srcObject = localMediaStream
}
main()