-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathintercom.html
More file actions
1510 lines (1271 loc) · 52.5 KB
/
intercom.html
File metadata and controls
1510 lines (1271 loc) · 52.5 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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
Project: WebRTC Intercom
Created: 2020.05.31
Author: Michael Spencer <code.with.michael@gmail.com>
License: MIT
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Intercom</title>
<script>
"use strict";
const DEFAULT_USERNAME = ''
// Messaging server info
const PROTO = 'http'
const SERVER = 'localhost'
const PORT = 8080
const PATH = '/jsonLoader'
const MESSAGE_TIMEOUT = 3000
const LONG_POLL_TIMEOUT = 30000
const RECONNECT_TIMEOUT = 3000
const DEBUG_LOGGING = true
</script>
<style>
:root {
--wallpaper-dark: #dfa849;
--wallpaper-light: #e7bd74;
--faceplate-image: url('assets/metal.png');
--faceplate-holes-image: url('assets/holes.png');
--light-off-image: url('assets/light-off.png');
--light-on-image: url('assets/light-on.png');
--light-flash-image: url('assets/light-on.png');
--switch-on-image: url('assets/switch-on.png');
--switch-off-image: url('assets/switch-off.png');
--switch-center-on-image: url('assets/switch-center.png');
--switch-center-off-image: url('assets/switch-off.png');
--connected-light-off-image: url('assets/connected-light-off.png');
--connected-light-on-image: url('assets/connected-light-on.png');
--talk-light-off-image: url('assets/talk-light-off.png');
--talk-light-on-image: url('assets/talk-light-on.png');
}
#textures {
width: 0;
height: 0;
overflow: hidden;
background-image:
var(--faceplate-image),
var(--faceplate-holes-image),
var(--light-off-image),
var(--light-on-image),
var(--light-flash-image),
var(--switch-on-image),
var(--switch-off-image),
var(--switch-center-on-image),
var(--switch-center-off-image),
var(--connected-light-off-image),
var(--connected-light-on-image),
var(--talk-light-off-image),
var(--talk-light-on-image);
}
* {
font-family: Arial, Helvetica, sans-serif;
user-select: none;
}
html {
background: repeating-linear-gradient(
to right,
var(--wallpaper-light),
var(--wallpaper-dark) 2px,
var(--wallpaper-dark) 108px,
var(--wallpaper-light) 110px,
var(--wallpaper-light) 150px
);
}
[data-type="template"] {
display: none !important;
}
#faceplate {
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-image: var(--faceplate-image);
background-position: left top;
width: 650px;
height: 500px;
border-radius: 10px;
box-shadow: 2px 10px 15px -5px;
}
#faceplate::before {
content: '';
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
border: 10px solid #000;
border-top: 10px solid #f7f7ce;
border-left: 10px solid #f7f78c;
border-radius: 10px;
opacity: 0.1
}
#faceplate::after {
content: '';
display: block;
position: absolute;
background-image: var(--faceplate-holes-image);
width: 299px;
height: 292px;
top: 60px;
left: 50px
}
#name-input {
display: block;
position: absolute;
width: 300px;
top: 25px;
right: 65px;
outline: none;
border: 0;
border-bottom: 1px solid rgba(100, 100, 50, .2);
font-size: 26px;
user-select: text;
background-color: transparent;
text-align: right;
font-weight: bold;
color: #000c;
text-shadow:
-1px -1px 3px #fff3,
1px 2px 2px #0006,
1px 2px 10px #fff6;
}
#name-input::placeholder {
color: #000c;
opacity: 1;
}
#user-list {
display: block;
position: absolute;
right: 0px;
top: 60px;
list-style: none;
margin: 0;
padding: 20px 10px 10px 20px;
font-size: 16px;
margin: 10px 0;
min-width: 220px;
max-width: 270px;
height: 400px;
overflow: hidden auto;
z-index: 1;
border: 1px solid #0006;
border-right: 0;
border-bottom: 0;
border-radius: 10px 0 10px 0;
background-color: #0001;
box-shadow: inset 10px 20px 30px 0px #000;
}
#user-list li:not(:last-child) {
margin-bottom: 5px;
}
#user-list .not-connected,
#user-list .no-users {
text-align: center;
padding: 10px;
font-weight: bold;
color: #000c;
text-shadow:
-1px -1px 3px #fff3,
1px 2px 2px #0006,
1px 2px 10px #fff6;
}
#user-list .user-item {
display: block;
position: relative;
padding-right: 55px;
margin-top: 2px;
/* ! height: 45px; */
}
#user-list .user-item >* {
display: inline-block;
line-height: 20px;
vertical-align: middle;
}
#user-list audio {
display: none !important;
}
#user-list .light {
position: relative;
top: 2px;
width: 40px;
height: 40px;
background:
var(--light-off-image) center center / 40px 40px no-repeat;
opacity: 0.8;
}
#user-list .light.on {
background-image: var(--light-on-image);
}
@keyframes light-flashing{
0% { background-image: var(--light-flash-image); }
49% { background-image: var(--light-flash-image); }
50% { background-image: var(--light-off-image); }
100%{ background-image: var(--light-off-image); }
}
#user-list .light.flashing {
animation: light-flashing 1s infinite;
}
#user-list .light.flashing:hover::before {
display: block;
position: absolute;
white-space: nowrap;
content: "click to cancel";
color: #fff;
font-size: 10px;
line-height: 10px;
top: -12px;
left: 50%;
transform: translateX(-50%);
height: 10px;
border: 1px solid #fff;
background-color: #222;
padding: 2px;
}
#user-list .toggle {
display: inline-block;
position: relative;
content:'';
width: 28px;
height: 50px;
background: var(--switch-off-image) center center / 28px 50px no-repeat;
}
#user-list .toggle.on {
background-image: var(--switch-on-image);
}
@keyframes toggle-waiting {
0% { background-image: var(--switch-center-on-image); }
49% { background-image: var(--switch-center-on-image); }
50% { background-image: var(--switch-center-off-image); }
100%{ background-image: var(--switch-center-off-image); }
}
#user-list .toggle.waiting {
/* animation: toggle-waiting 1s infinite; */
background-image: var(--switch-center-on-image)
}
#user-list .name {
font-weight: bold;
color: #000c;
text-shadow:
-1px -1px 3px #fff3,
1px 2px 2px #0006,
1px 2px 10px #fff6;
}
#user-list .button {
position: absolute;
top: 15px;
right: 25px;
width: 20px;
height: 20px;
border-radius: 20px;
border: 1px solid #555;
background-color: #222;
box-shadow:
inset 2px 6px 3px -3px #fff,
inset -2px -2px 3px -3px #fff;
}
#user-list .button.highlight {
background-color: #0c6;
}
#user-list .button.pressed {
border: 1px solid #444;
box-shadow:
inset 1px 2px 2px 2px #000,
inset 1px 3px 3px 1px #fff;
}
#user-list .button::before {
display: inline-block;
position: relative;
content: "talk";
color: #222;
font-size: 10px;
line-height: 24px;
height: 24px;
top: -3px;
left: -3px;
border: 1px solid #ccc3;
border-right: 0px;
border-radius: 20px 0 0 20px;
background-color: #f7f7f730;
box-shadow: inset 18px 8px 10px -2px #000a;
padding: 0 5px 0 26px;
z-index: -1;
}
#connected-light {
display: block;
position: absolute;
top: 15px;
left: 8px;
width: 76px;
height: 72px;
background: var(--connected-light-off-image) top left / 76px 72px no-repeat;
}
#connected-light:hover::before {
display: block;
position: absolute;
white-space: nowrap;
content: "click to connect";
color: #fff;
font-size: 10px;
line-height: 10px;
top: -12px;
left: 50%;
transform: translateX(-50%);
height: 10px;
border: 1px solid #fff;
background-color: #222;
padding: 2px;
}
#connected-light.on {
background-image: var(--connected-light-on-image)
}
#connected-light.on:hover::before {
display: block;
position: absolute;
white-space: nowrap;
content: "click to disconnect";
color: #fff;
font-size: 10px;
line-height: 10px;
top: -12px;
left: 50%;
transform: translateX(-50%);
height: 10px;
border: 1px solid #fff;
background-color: #222;
padding: 2px;
}
@keyframes connected-light-flashing {
0% { background-image: var(--connected-light-on-image); }
24% { background-image: var(--connected-light-on-image); }
25% { background-image: var(--connected-light-off-image); }
100%{ background-image: var(--connected-light-off-image); }
}
#connected-light.flashing {
animation: connected-light-flashing 3s infinite;
}
#connected-light.flashing:hover::before {
display: block;
position: absolute;
white-space: nowrap;
content: "reconnecting...";
color: #fff;
font-size: 10px;
line-height: 10px;
top: -12px;
left: 50%;
transform: translateX(-50%);
height: 10px;
border: 1px solid #fff;
background-color: #222;
padding: 2px;
}
#talk-light {
display: block;
position: absolute;
bottom: 5px;
left: 7px;
width: 91px;
height: 91px;
background: var(--talk-light-off-image) top left / 91px 91px no-repeat;
}
#talk-light:hover::before {
display: block;
position: absolute;
white-space: nowrap;
content: "press and hold to broadcast";
color: #fff;
font-size: 10px;
line-height: 10px;
top: -2px;
left: 50%;
transform: translateX(-50%);
height: 10px;
border: 1px solid #fff;
background-color: #222;
padding: 2px;
}
#talk-light.on {
background-image: var(--talk-light-on-image)
}
#talk-light.on:hover::before {
display: none;
}
#copyright {
display: block;
position: absolute;
font-size: 12px;
font-weight: bold;
text-align: center;
white-space: nowrap;
color: #222;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
z-index: -1;
opacity: 0.5;
}
#copyright:hover{
opacity: 1;
}
a {
text-decoration: none;
color: #0064f0;
}
</style>
</head>
<body>
<div id="textures"></div>
<div id="faceplate">
<input id="name-input" type="text" placeholder="Enter User Name"/>
<ul id="user-list">
<li class="not-connected" data-type="template">Not connected</li>
<li class="no-users" data-type="template">No other users connected</li>
<li class="user-item" data-type="template">
<audio autoplay></audio>
<span class="toggle"></span>
<span class="light"></span>
<span class="name">UserName</span>
<span class="button"></span>
</li>
</ul>
<span id="connected-light"></span>
<span id="talk-light"></span>
</div>
<div id="copyright">
WebRTC Intercom / Fork on <a href="https://github.com/codewithmichael/webrtc-intercom">GitHub</a><br/>
MIT License - Copyright © 2020 Michael Spencer<br/>
</div>
<script>(async () => {
"use strict";
//-[ Setup ]----------------------------------------------------------
const {
inputAudioStream,
nameInput,
userList,
connectedLight,
talkLight,
updateUserItems,
sendMessage,
} = Object.assign(this,
await prepareInputAudioStream(),
await prepareUserInterface(),
await prepareMessaging(),
)
//-[ App ]------------------------------------------------------------
let state = this.state = {
user: { name: DEFAULT_USERNAME },
users: [],
connections: {} // { <key=user_name>: { connection, dataChannel, localStream, remoteStream, offer, answer, connected:boolean }}
}
// Mute microphone by default
disableAudioTracks(inputAudioStream)
// Initialize empty user list
updateUserItems()
// Handle name change
if (nameInput.value) {
nameInput.value = nameInput.value.trim()
if (nameInput.value) state.user.name = nameInput.value
}
nameInput.value = state.user.name
nameInput.onblur = () => {
const name = nameInput.value.trim()
nameInput.value = name
register(name)
.catch(error => {
console.error(error)
nameInput.value = state.user.name || ''
nameInput.focus()
})
}
// Autoconnect
const { name } = state.user
if (name) {
await register(name)
.catch(error => {
console.error(error)
nameInput.value = state.user.name = ''
})
} else {
nameInput.focus()
}
// Manual disconnect/reconnect
connectedLight.onclick = async function() {
if (state.user.id) {
sendMessage({ unregister: state.user.id })
cancelLoopWait()
Object.keys(state.connections).forEach(name => disconnect(name))
state.user.id = undefined
onReceiveUsers([])
connectedLight.disable()
} else {
// Trigger a name registration attempt
nameInput.onblur()
}
}
// Broadcast
talkLight.onpress = function() {
if (!state.user.id) return
let activeConnections = Object.keys(state.connections)
.map(name => state.connections[name])
.filter(info => !!info.connected)
if (!activeConnections.length) return
let isBroadcasting = false
for ( let info of activeConnections) {
let { localStream, dataChannel } = info
if (!localStream) continue
enableAudioTracks(localStream)
if (dataChannel) sendDataChannelMessage(dataChannel, "begin_talk")
isBroadcasting = true
}
if (isBroadcasting) talkLight.enable()
}
talkLight.onrelease = function() {
Object.keys(state.connections)
.map(name => state.connections[name])
.forEach(info => {
let { localStream, dataChannel } = info
if (!localStream) return
disableAudioTracks(localStream)
if (dataChannel) sendDataChannelMessage(dataChannel, "end_talk")
})
talkLight.disable()
}
//-[ Data ]-----------------------------------------------------------
function toUser(data) {
let { id, name } = data || {}
if (typeof(id) === 'undefined') id = null
name = (name || '').trim()
return { id, name }
}
//-[ Actions ]--------------------------------------------------------
async function register(name) {
let message = { register: name }
let { id } = state.user
if (typeof(id) !== 'undefined' && id != null) {
message.id = id
}
return sendMessage(message)
.then(({ register: user, users }) => {
onReceiveUser(user)
onReceiveUsers(users)
})
.then(() => {
connectedLight.enable()
loopWait() // not returned!
})
}
async function performOffer(name) {
const targetUser = state.users.find(user => user.name === name)
if (!targetUser) throw new Error('User not found')
const { userItem } = targetUser
if (!userItem) throw new Error(`Display element not found for user: ${targetUser.name}`)
await disconnect(name)
const localStream = inputAudioStream ? inputAudioStream.clone() : undefined
disableAudioTracks(localStream)
userItem.toggle.wait()
userItem.light.flash()
const info = { name }
Object.assign(info, await createOfferConnection(localStream, onTrack))
state.connections[name] = info
const { connection, dataChannel, offer } = info
dataChannel.onopen = onOpen
dataChannel.onclose = onClose
dataChannel.onmessage = onMessage
const message = {
id: state.user.id,
offer: JSON.stringify(offer),
name
}
const response = sendMessage(message)
.catch(error => {
disconnect(name)
throw error
})
return { connection, offer, response }
function onTrack(event) {
const stream = event.streams[0]
if (stream) {
info.remoteStream = stream
if (userItem) userItem.audio.srcObject = stream
}
debugLog('Added remote WebRTC audio stream')
}
function onOpen(event) {
info.connected = true
userItem.toggle.enable()
userItem.light.enable()
userItem.button.onpress = onPress
userItem.button.onrelease = onRelease
debugLog(`Connection established with user: ${name}`)
}
function onClose(event) {
debugLog(`Data connection closed for user: ${name}`)
disconnect(name)
}
function onMessage(event) {
let { data } = event
if (!data) return
let { name } = info
let { userItem } = state.users.filter(u => u.name === name)[0] || {}
switch (data) {
case "begin_talk":
info.isTalking = true
if (userItem) userItem.button.highlight()
break
case "end_talk":
info.isTalking = false
if (userItem) userItem.button.unhighlight()
break
case "disconnect":
disconnect(name)
break
default:
console.error(`Unknown data channel message received: "${data}"`)
}
}
function onPress(event) {
if (!info.connected) return
enableAudioTracks(localStream)
talkLight.enable()
if (dataChannel) sendDataChannelMessage(dataChannel, "begin_talk")
}
function onRelease(event) {
disableAudioTracks(localStream)
talkLight.disable()
if (dataChannel) sendDataChannelMessage(dataChannel, "end_talk")
}
}
async function performAnswer(offer, name) {
const targetUser = state.users.find(user => user.name === name)
if (!targetUser) throw new Error('User not found')
const { userItem } = targetUser
if (!userItem) throw new Error(`Display element not found for user: ${targetUser.name}`)
await disconnect(name)
const localStream = inputAudioStream ? inputAudioStream.clone() : undefined
disableAudioTracks(localStream)
const info = { name } // must exist before calling createAnswerConneciton (for onTrack)
Object.assign(info, await createAnswerConnection(offer, localStream, onTrack, onDataChannel))
state.connections[name] = info
let { answer } = info
answer = JSON.stringify(answer)
const response = sendMessage({ id: state.user.id, answer, name })
.catch(error => {
disconnect(name)
throw error
})
const { connection } = info
return { connection, offer, answer, response }
function onDataChannel(event) {
info.dataChannel = event.channel
info.dataChannel.onclose = onClose
info.dataChannel.onmessage = onMessage
info.connected = true
userItem.toggle.enable()
userItem.light.enable()
userItem.button.onpress = onPress
userItem.button.onrelease = onRelease
debugLog('Added remote WebRTC data channel')
debugLog(`Connection established with user: ${name}`)
}
function onTrack(event) {
const stream = event.streams[0]
if (stream) {
info.remoteStream = stream
if (userItem) userItem.audio.srcObject = stream
}
debugLog('Added remote WebRTC audio stream')
}
function onClose(event) {
debugLog(`Data connection closed for user: ${name}`)
disconnect(name)
}
function onMessage(event) {
let { data } = event
if (!data) return
let { name } = info
let { userItem } = state.users.filter(u => u.name === name)[0] || {}
switch (data) {
case "begin_talk":
info.isTalking = true
if (userItem) userItem.button.highlight()
break
case "end_talk":
info.isTalking = false
if (userItem) userItem.button.unhighlight()
break
case "disconnect":
disconnect(name)
break
default:
console.error(`Unknown data channel message received: "${data}"`)
}
}
function onPress(event) {
if (!info.connected) return
let { localStream, dataChannel } = info
if (localStream) {
enableAudioTracks(localStream)
talkLight.enable()
}
if (dataChannel) {
sendDataChannelMessage(dataChannel, "begin_talk")
}
}
function onRelease(event) {
let { localStream, dataChannel } = info
if (localStream) disableAudioTracks(localStream)
talkLight.disable()
if (dataChannel) sendDataChannelMessage(dataChannel, "end_talk")
}
}
async function disconnect(name) {
const info = state.connections[name]
if (info) {
delete state.connections[name]
const targetUser = state.users.find(user => user.name === name)
const userItem = (targetUser || {}).userItem
const {
connection,
dataChannel,
localStream,
remoteStream,
connected,
} = info
if (connected && dataChannel) sendDataChannelMessage(dataChannel, 'disconnect')
if (userItem) {
userItem.toggle.disable()
userItem.light.disable()
userItem.audio.srcObject = undefined
userItem.button.onpress = undefined
userItem.button.onrelease = undefined
}
if (localStream) disableAudioTracks(localStream)
if (remoteStream) disableAudioTracks(remoteStream)
if (dataChannel) await closeDataChannel(dataChannel)
if (connection) await closeConnection(connection)
debugLog('Disconnected from user: ' + targetUser.name)
return true
}
return false
}
var _cancelLoopWait
function cancelLoopWait() {
if (!_cancelLoopWait) _cancelLoopWait = []
_cancelLoopWait.forEach(cancel => cancel())
_cancelLoopWait.length = 0
}
async function loopWait() {
let cancelled = false
cancelLoopWait()
_cancelLoopWait.push(cancel)
return startLoop()
function cancel() {
cancelled = true
}
async function startLoop() {
while (!cancelled && state.user && state.user.id) {
await sendMessage({ wait: state.user.id }, LONG_POLL_TIMEOUT)
.then(response => {
if (cancelled) return
let { messages } = response
if (messages) for (let message of messages) {
onReceiveMessage(message)
}
})
.catch(error => {
if (error.name === 'AbortError') return
console.error(error)
connectedLight.disable()
cancel()
attempReconnect()
})
}
async function attempReconnect() {
let cancelledReconnect = false
cancelLoopWait()
_cancelLoopWait.push(cancelReconnect)
connectedLight.flash()
const users = Object.keys(state.connections)
.map(k => state.connections[k])
.filter(({ offer, answer }) => offer && answer)
.map(({ name }) => ({ name }))
onReceiveUsers(users)
debugLog('Server connection lost')
let timer = setInterval(() => {
if (cancelledReconnect) {
clearInterval(timer)
return
}
register(nameInput.value)
.then(() => {
clearInterval(timer)
connectedLight.enable()
debugLog('Server connection reestablished')
})
.catch(error => debugLog('Reconnect attempt failed'))
}, RECONNECT_TIMEOUT)
function cancelReconnect() {
cancelledReconnect = true
}
}
}
}
//-[ Events ]--------------------------------------------------------
function onReceiveMessage(message)
{
if (!message || !state.user || !state.user.id) return
let { register, unregister, offer, answer, reject } = message
if (register) {
let { register: user, users } = message
onReceiveUser(user)
onReceiveUsers(users)
} else if (unregister) {
let { unregister: user, users } = message
disconnect(user.name)
onReceiveUsers(users)
} else if (offer) {
let { name } = message
onReceiveOffer(offer, name)
.catch(error => {
disconnect(name)
return error
})
} else if (answer) {
let { name } = message
onReceiveAnswer(answer, name)
.catch(error => {
disconnect(name)
return error
})
} else if (reject) {
let { reject: user } = message
let { name } = user
onReceiveReject(name)
.catch(error => {
disconnect(name)
return error
})
}
}
function onReceiveUser(user) {
let { id, name, old_name } = user
if (id) {
user = toUser(user)
state.user = user
nameInput.value = name
} else if (old_name) {
if (state.connections[old_name]) {
state.connections[name] = state.connections[old_name]
state.connections[name].name = name
delete state.connections[old_name]
}
}
}