-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcircuit-call-button.js
More file actions
408 lines (357 loc) · 11.4 KB
/
circuit-call-button.js
File metadata and controls
408 lines (357 loc) · 11.4 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
const template = document.createElement('template');
template.innerHTML = `
<style>
* {
box-sizing: border-box
}
:host {
display: inline-block;
cursor: pointer;
border-radius: 5px;
background:#88c541;
color: white;
padding: 2px 6px;
}
:host([inprogress]) {
background:#c22026;
}
:host([disabled]) button {
cursor: not-allowed;
}
button {
cursor: pointer;
outline: none;
background: inherit;
color: inherit;
font-size: inherit;
font-weight: inherit;
font-family: inherit;
border: inherit;
border-radius: inherit;
padding: inherit;
margin: inherit;
}
</style>
<button></button>
<audio id="ringback" autoplay></audio>
<audio id="audio" autoplay></audio>
`;
export class CircuitCallButton extends HTMLElement {
// Attributes we care about getting change notifications for
static get observedAttributes() {
return ['video', 'target', 'guestToken'];
}
get connected() {
return this.hasAttribute('connected');
}
set _connected(isConnected) {
if (isConnected) {
this.setAttribute('connected', '');
} else {
this.removeAttribute('connected');
}
}
set target(value) {
this._direct = this._validateEmail(value);
this._target = value;
// Reflect to attribute
this.setAttribute('target', value);
}
get target() {
return this._target;
}
set guestToken(value) {
this._guestToken = value;
// Reflect to attribute
this.setAttribute('guestToken', value);
}
get guestToken() {
return this._guestToken;
}
set firstName(value) {
this._firstName = value;
// Reflect to attribute
this.setAttribute('firstName', value);
}
get firstName() {
return this._firstName;
}
set lastName(value) {
this._lastName = value;
// Reflect to attribute
this.setAttribute('lastName', value);
}
get lastName() {
return this._lastName;
}
get client() {
return this._client;
}
constructor() {
super();
this.EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
this._client = null;
this.attachShadow({ mode: 'open' });
this.shadowRoot.appendChild(template.content.cloneNode(true));
this._click = this._click.bind(this);
}
_validateTarget() {
this._direct = this.EMAIL_REGEX.test(String(this._target).toLowerCase());
}
// Delay Circuit initialization to speed up page load. This way the SDK
// can be loaded with 'async'
async _init() {
Circuit.logger.setLevel(1);
if (this._guestToken) {
// Use the guest SDK instead
this._client = Circuit.GuestClient({
domain: this._domain,
client_id: this._clientId
});
} else {
this._client = Circuit.Client({
domain: this._domain,
client_id: this._clientId
});
}
this._client.addEventListener('connectionStateChanged', e => {
this._connected = e.state === 'Connected';
});
this._client.addEventListener('callStatus', e => {
this.call = e.call;
// Update 'inprogress' attribute and button text
if (e.call.state === 'Initiated') {
this.removeAttribute('inprogress');
this._btn.textContent = this._callingText;
} else if (e.call.state === 'Started') {
// Another user has started the conference
this._btn.textContent = this._joinText;
this.removeAttribute('inprogress'); // remote call is in progress, but not the local call
} else if (e.call.state === 'ActiveRemote') {
// User has joined the conference on another device
// TODO: Offer pulling the call
this.removeAttribute('inprogress');
this._btn.textContent = this._callingText;
} else {
this.setAttribute('inprogress', '');
this._btn.textContent = this._hangupText;
this.removeAttribute('disabled', '');
}
// Set/clear ringback tone
const ringbackEl = this.shadowRoot.querySelector('#ringback');
if (e.call.state === 'Delivered') {
ringbackEl.src = this._ringbackTone;
} else {
ringbackEl.removeAttribute('src');
ringbackEl.load();
}
// Set remote audio stream
this.shadowRoot.querySelector('#audio').srcObject = e.call.remoteAudioStream;
this.dispatchEvent(new CustomEvent('callchange', { detail: e.call }));
});
this._client.addEventListener('callEnded', e => {
this.call = null;
this.removeAttribute('inprogress');
this._btn.textContent = this._defaultText;
const ringbackEl = this.shadowRoot.querySelector('#ringback');
ringbackEl.removeAttribute('src');
ringbackEl.load();
// Raise without a call object as parameter
this.dispatchEvent(new CustomEvent('callchange'));
// Wait a bit to ensure call is successfully terminated, then logout
// Comment out for now due to a presence bug.
//setTimeout(this._client.logout, 200);
});
this.dispatchEvent(new CustomEvent('initialized', { detail: this.client }));
}
async _getCredentials() {
let res = await fetch(`${this._poolUrl}?clientId=${this._clientId}&domain=${this._domain}`);
res = await res.json();
if (!res || !res.token) {
throw Error('No pool users found');
}
const cred = atob(res.token).split(':');
this._client.setOauthConfig({client_id: cred[2]});
return {
username: cred[0],
password: cred[1]
};
}
async _connect() {
if (!Circuit) {
throw Error('circuit-sdk is not loaded');
}
!this._client && this._init();
try {
if (this._client.connectionState === 'Connected') {
return;
} else if (this._client.connectionState === 'Disconnected') {
if (this._poolUrl) {
const cred = await this._getCredentials();
await this._client.logon(cred);
} else if (!this._guestToken) {
await this._client.logon();
}
} else {
await this._waitForConnected(5000);
}
} catch (err) {
console.error('Error connecting to Circuit', err);
throw new Error('Error connecting to Circuit');
}
}
async _waitForConnected(timeoutms) {
return new Promise((resolve, reject) => {
const check = () => {
if (this._client.connectionState === 'Connected') {
resolve();
} else if ((timeoutms -= 100) < 0) {
reject('timed out');
} else {
setTimeout(check, 100);
}
}
setTimeout(check, 100);
});
}
async _click() {
if (this.getAttribute('disabled') !== null) {
return;
}
if (this.call) {
if (this._direct) {
await this._hangup();
} else {
await this._client.leaveConference(this.call.callId);
}
} else {
if (this._direct) {
await this._makeCall();
} else if (this._guestToken) {
await this._joinConference();
} else {
await this._startConference();
}
}
}
async _waitingRoom(token) {
try {
this._waiting = true;
this.setAttribute('waiting', this._waiting);
this.dispatchEvent(new CustomEvent('waitingchange', { detail: this._waiting }));
await this._client.monitorSession(token);
} finally {
this._waiting = false;
this.setAttribute('waiting', this._waiting);
this.dispatchEvent(new CustomEvent('waitingchange', { detail: this._waiting }));
}
}
async _joinConference() {
if (this._waiting) {
this._client.cancelMonitor();
return;
}
// For better user feedback change call to inprogress before call
// state is 'Initiated'
const origText = this._btn.textContent;
this._btn.textContent = this._callingText;
this.setAttribute('disabled', '');
try {
await this._connect();
await this._waitingRoom(this._guestToken);
this.call = await this._client.joinConference({
token: this._guestToken,
firstName: this._firstName || 'unknown',
lastName: this._lastName || 'unknown'
}, { audio: true, video: this._sendVideo });
} catch (err) {
this.removeAttribute('disabled');
this._btn.textContent = origText;
}
}
async _startConference() {
// For better user feedback change call to inprogress before call
// state is 'Initiated'
const origText = this._btn.textContent;
this._btn.textContent = this._callingText;
this.setAttribute('disabled', '');
try {
await this._connect();
const startedCalls = await this._client.getStartedCalls();
const remoteCall = startedCalls && startedCalls.find(c => c.convId === this._target);
if (remoteCall) {
await this._client.joinConference(remoteCall.callId, { audio: true, video: this._sendVideo });
} else {
this.call = await this._client.startConference(this._target, { audio: true, video: this._sendVideo });
}
} catch (err) {
this.removeAttribute('disabled');
this._btn.textContent = origText;
}
}
async _makeCall() {
// For better user feedback change call to inprogress before call
// state is 'Initiated'
const origText = this._btn.textContent;
this._btn.textContent = this._callingText;
this.setAttribute('disabled', '');
try {
await this._connect();
this.call = await this._client.makeCall(this._target, {audio: true, video: this._sendVideo}, true);
} catch (err) {
this.removeAttribute('disabled');
this._btn.textContent = origText;
}
}
async _hangup() {
await this._client.endCall(this.call.callId);
}
// Lifecycle hooks
connectedCallback() {
this._btn = this.shadowRoot.querySelector('button');
this._defaultText = this.textContent && this.textContent.replace(/^\s+|\s+$/g, '') || 'Call';
this._btn.textContent = this._defaultText;
this._btn.addEventListener('click', this._click);
this._clientId = this.getAttribute('clientId');
this._domain = this.getAttribute('domain') || 'circuitsandbox.net';
this._poolUrl = this.getAttribute('poolUrl');
this._target = this.getAttribute('target');
this._validateTarget();
this._guestToken = this.getAttribute('guestToken');
this._waiting = false;
this._firstName = this.getAttribute('firstName');
this._lastName = this.getAttribute('lastName');
this._sendVideo = this.getAttribute('video') !== null;
this._callingText = this.getAttribute('callingText') || 'Calling...';
this._joinText = this.getAttribute('joinText') || 'Join';
this._hangupText = this.getAttribute('hangupText') || 'Hangup';
this._ringbackTone = this.getAttribute('ringbackTone') || 'https://upload.wikimedia.org/wikipedia/commons/c/cd/US_ringback_tone.ogg';
}
disconnectedCallback() {
if (!this._btn) {
return;
}
this._btn.removeEventListener('click', this._click);
}
attributeChangedCallback(attrName, oldValue, newValue) {
switch (attrName) {
case 'video':
// Send video if attribute is present
newValue = newValue !== null;
if (this._sendVideo !== !!newValue) {
this._sendVideo = !!newValue;
this._client && this.call && this._client.toggleVideo(this.call.callId)
.catch(console.error);
}
break;
case 'target':
this._target = newValue;
this._validateTarget();
break;
case 'guestToken':
this._guestToken = newValue;
break;
}
}
}
customElements.define('circuit-call-button', CircuitCallButton);