-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
309 lines (218 loc) · 9.49 KB
/
script.js
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
let localStream;
const app_id = "438b0a9bb09b4df992cad2765963018d"
const token = null;
const uid = String(Math.floor(Math.random() * 10000 ))
let client
let channel;
let queryString = window.location.search
let urlParams = new URLSearchParams(queryString)
let roomId = urlParams.get('room')
// const io = require('socket.io-client');
let audioTrack
// const socket = io('https://api-video-call-by-gift.onrender.com');
if (!roomId){
window.location = 'lobby.html'
}
const servers = {
iceServers:[
{
urls:['stun:stun1.l.google.com:19302', 'stun:stun2.l.google.com:19302']
}
]
}
const init = async() => {
// socket.on('connect', () => {
// socket.emit('joinRoom', { room: roomId});
// console.log(`Connected as ${userId}`);
// });
// socket.on('disconnect', () => {
// console.log('Disconnected from the WebSocket server');
// });
// socket.on('error', (error) => {
// console.error('WebSocket error:', error);
// });
// // channel = client.createChannel(roomId)
// // channel = client.createChannel('main')
// // await channel.join()
// socket.on('MemberJoined', () => {
// })
// socket.on('MemberLeft', () => {
// })
// socket.on('MessageFromPeer', () => {
// })
client = await AgoraRTM.createInstance(app_id)
await client.login({uid, token})
channel = client.createChannel(roomId)
// channel = client.createChannel('main')
await channel.join()
channel.on('MemberJoined', handleUserJoined)
channel.on('MemberLeft', handleUserLeft)
client.on('MessageFromPeer', handleMessageFromPeer)
localStream = await navigator.mediaDevices.getUserMedia({video:true, audio:true})
document.getElementById('client-1').srcObject = localStream
// createOffer()
// console.log("called the function")
createPopUp();
console.log('pop up done')
}
const closePopUp = () => {
console.log("Closing pop-up");
const popUp = document.querySelector('.pop-up');
console.log("here in pop up also")
if (popUp) {
console.log("here in pop up")
popUp.remove();
}
};
const createPopUp = () => {
const popUp = document.createElement('div');
popUp.className = 'pop-up';
const popUpContent = document.createElement('div');
popUpContent.className = 'pop-up-content';
const closeBtnContainer = document.createElement('div');
closeBtnContainer.className = 'close-btn-container';
const closeBtn = document.createElement('button');
closeBtn.id = 'close-btn';
closeBtn.className = 'close-btn';
closeBtn.innerHTML = '×';
console.log("Close button: ", closeBtn);
closeBtn.addEventListener('click', () => {
console.log("Close button clicked");
closePopUp();
});
// Add closeBtn directly to popUpContent
popUpContent.appendChild(closeBtn);
popUp.appendChild(popUpContent);
closeBtnContainer.appendChild(closeBtn);
popUpContent.appendChild(closeBtnContainer);
popUpContent.innerHTML += `
<h4>This video call currently supports only 2 participants.</h4>
<p>Share the following link to invite others:</p>
<input type="text" id="meeting-link" value="${window.location.href}" readonly>
<button onclick="copyMeetingLink()">Copy Link</button>
`;
popUp.appendChild(popUpContent);
document.body.appendChild(popUp);
document.getElementById('close-btn').addEventListener('click', closePopUp);
};
// window.addEventListener('beforeunload', closePopUp);
window.copyMeetingLink = () => {
const meetingLinkInput = document.getElementById('meeting-link');
meetingLinkInput.select();
document.execCommand('copy');
alert('Meeting link copied to clipboard!');
};
const handleUserLeft = async (MemberId) => {
document.getElementById('client-2').style.display = 'none'
document.getElementById('client-1').classList.remove('small-frame')
}
const handleMessageFromPeer= async (message, MemberId) => {
message = JSON.parse(message.text)
if(message.type === 'offer') {
createAnswer(MemberId, message.offer)
}
if(message.type === 'answer') {
addAnswer(message.answer)
}
if(message.type === 'candidate') {
if(peerConnection) {
peerConnection.addIceCandidate(message.candidate)
}
}
console.log('Message: ', message)
}
const handleUserJoined = async(MemberId)=> {
console.log('A new user joined the rom', MemberId)
createOffer(MemberId)
console.log("called the function")
}
const createPeerConnection = async (MemberId) => {
peerConnection = new RTCPeerConnection(servers)
const remoteStream = new MediaStream()
document.getElementById('client-2').srcObject = remoteStream
document.getElementById('client-2').style.display = 'block'
document.getElementById('client-1').classList.add('small-frame')
if (!localStream) {
localStream = await navigator.mediaDevices.getUserMedia({video:true, audio:true})
console.log("checking localstream")
document.getElementById('client-1').srcObject = localStream
}
localStream.getTracks().forEach((track) => {
peerConnection.addTrack(track, localStream)
})
peerConnection.ontrack = (event) => {
event.streams[0].getTracks().forEach((track) => {
remoteStream.addTrack(track)
})
}
peerConnection.onicecandidate = async (event) => {
if(event.candidate) {
//websocket to send icecandidates
client.sendMessageToPeer({text: JSON.stringify({'type': 'candidate', 'candidate': event.candidate})}, MemberId)
}
}
}
//create sdp offer for peer connection
const createOffer = async (MemberId) => {
await createPeerConnection(MemberId)
const offer = await peerConnection.createOffer()
await peerConnection.setLocalDescription(offer)
//websocket to send message to peer
client.sendMessageToPeer({text: JSON.stringify({'type': 'offer', 'offer': offer})}, MemberId)
// console.log('Offer:', offer)
}
const createAnswer = async (MemberId, offer) => {
await createPeerConnection(MemberId)
await peerConnection.setRemoteDescription(offer)
const answer = await peerConnection.createAnswer()
await peerConnection.setLocalDescription(answer)
client.sendMessageToPeer({text: JSON.stringify({'type': 'answer', 'answer': answer})}, MemberId)
}
const addAnswer = async(answer) => {
if(!peerConnection.currentRemoteDescription) {
peerConnection.setRemoteDescription(answer)
}
}
const leaveChannel = async () => {
await channel.leave()
await client.logout()
}
const toggleCamera = async () => {
let videoTrack = localStream.getTracks().find(track => track.kind === 'video')
if(videoTrack.enabled){
videoTrack.enabled = false
document.getElementById('camera-btn').style.backgroundColor = 'rgb(255, 80, 80)'
} else {
videoTrack.enabled = true
document.getElementById('camera-btn').style.backgroundColor = 'rgb(179, 102, 249, .9)'
}
}
const toggleMic = async () => {
audioTrack = localStream.getTracks().find(track => track.kind === 'audio')
if(audioTrack.enabled){
audioTrack.enabled = false
document.getElementById('mic-btn').style.backgroundColor = 'rgb(255, 80, 80)'
} else {
audioTrack.enabled = true
document.getElementById('mic-btn').style.backgroundColor = 'rgb(179, 102, 249, .9)'
}
}
// const toggleMic = async () => {
// let audioTrack = localStream.getAudioTracks()[0];
// if (audioTrack) {
// // Mute/unmute the audio track
// audioTrack.enabled = !audioTrack.enabled;
// // Create a new stream with the updated audio track
// const newStream = new MediaStream();
// newStream.addTrack(audioTrack);
// // Replace the local stream with the new stream
// document.getElementById('client-1').srcObject = newStream;
// // Update the mic-btn background color
// const micBtnColor = audioTrack.enabled ? 'rgb(179, 102, 249, .9)' : 'rgb(255, 80, 80)';
// document.getElementById('mic-btn').style.backgroundColor = micBtnColor;
// }
// };
window.addEventListener('beforeunload', leaveChannel)
document.getElementById('camera-btn').addEventListener('click', toggleCamera)
document.getElementById('mic-btn').addEventListener('click', toggleMic)
init()