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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
|
// TODO(fancycode): Should load through AMD if possible.
/* global SimpleWebRTC, OC, OCA: false */
var webrtc;
var guestNamesTable = {};
var spreedMappingTable = {};
var spreedPeerConnectionTable = [];
(function(OCA, OC) {
'use strict';
OCA.SpreedMe = OCA.SpreedMe || {};
var previousUsersInRoom = [];
var usersInCallMapping = {};
var ownPeer = null;
var ownScreenPeer = null;
var hasLocalMedia = false;
var selfInCall = 0; // OCA.SpreedMe.app.FLAG_DISCONNECTED, not available yet.
var delayedCreatePeer = [];
function updateParticipantsUI(currentUsersNo) {
'use strict';
if (!currentUsersNo) {
currentUsersNo = 1;
}
var $appContentElement = $(OCA.SpreedMe.app.mainCallElementSelector),
participantsClass = 'participants-' + currentUsersNo,
hadScreensharing = $appContentElement.hasClass('screensharing'),
hadSidebar = $appContentElement.hasClass('with-app-sidebar');
if (!$appContentElement.hasClass(participantsClass)) {
$appContentElement.attr('class', '').addClass(participantsClass);
if (currentUsersNo > 1) {
$appContentElement.addClass('incall');
} else {
$appContentElement.removeClass('incall');
}
if (hadScreensharing) {
$appContentElement.addClass('screensharing');
}
if (hadSidebar) {
$appContentElement.addClass('with-app-sidebar');
}
}
}
function createScreensharingPeer(signaling, sessionId) {
var currentSessionId = signaling.getSessionid();
var useMcu = signaling.hasFeature("mcu");
if (useMcu && !webrtc.webrtc.getPeers(currentSessionId, 'screen').length) {
if (ownScreenPeer) {
ownScreenPeer.end();
}
// Create own publishing stream.
ownScreenPeer = webrtc.webrtc.createPeer({
id: currentSessionId,
type: 'screen',
sharemyscreen: true,
enableDataChannels: false,
receiveMedia: {
offerToReceiveAudio: 0,
offerToReceiveVideo: 0
},
broadcaster: currentSessionId,
});
webrtc.emit('createdPeer', ownScreenPeer);
ownScreenPeer.start();
}
if (sessionId === currentSessionId) {
return;
}
if (useMcu) {
// TODO(jojo): Already create peer object to avoid duplicate offers.
// TODO(jojo): We should use "requestOffer" as with regular
// audio/video peers. Not possible right now as there is no way
// for clients to know that screensharing is active and an offer
// from the MCU should be requested.
webrtc.connection.sendOffer(sessionId, "screen");
} else if (!useMcu) {
var screenPeers = webrtc.webrtc.getPeers(sessionId, 'screen');
var screenPeerSharedTo = screenPeers.find(function(screenPeer) {
return screenPeer.sharemyscreen === true;
});
if (!screenPeerSharedTo) {
var peer = webrtc.webrtc.createPeer({
id: sessionId,
type: 'screen',
sharemyscreen: true,
enableDataChannels: false,
receiveMedia: {
offerToReceiveAudio: 0,
offerToReceiveVideo: 0
},
broadcaster: currentSessionId,
});
webrtc.emit('createdPeer', peer);
peer.start();
}
}
}
function checkStartPublishOwnPeer(signaling) {
'use strict';
var currentSessionId = signaling.getSessionid();
if (!hasLocalMedia || webrtc.webrtc.getPeers(currentSessionId, 'video').length) {
// No media yet or already publishing.
return;
}
if (ownPeer) {
OCA.SpreedMe.webrtc.removePeers(ownPeer.id);
OCA.SpreedMe.speakers.remove(ownPeer.id, true);
OCA.SpreedMe.videos.remove(ownPeer.id);
delete spreedMappingTable[ownPeer.id];
ownPeer.end();
}
// Create own publishing stream.
ownPeer = webrtc.webrtc.createPeer({
id: currentSessionId,
type: "video",
enableDataChannels: true,
receiveMedia: {
offerToReceiveAudio: 0,
offerToReceiveVideo: 0
}
});
webrtc.emit('createdPeer', ownPeer);
ownPeer.start();
}
function userHasStreams(user) {
var flags = user;
if (flags.hasOwnProperty('inCall')) {
flags = flags.inCall;
}
flags = flags || OCA.SpreedMe.app.FLAG_DISCONNECTED;
var REQUIRED_FLAGS = OCA.SpreedMe.app.FLAG_WITH_AUDIO | OCA.SpreedMe.app.FLAG_WITH_VIDEO;
return (flags & REQUIRED_FLAGS) !== 0;
}
function usersChanged(signaling, newUsers, disconnectedSessionIds) {
'use strict';
var currentSessionId = signaling.getSessionid();
var useMcu = signaling.hasFeature("mcu");
if (useMcu && newUsers.length) {
checkStartPublishOwnPeer(signaling);
}
newUsers.forEach(function(user) {
if (!user.inCall) {
return;
}
// TODO(fancycode): Adjust property name of internal PHP backend to be all lowercase.
var sessionId = user.sessionId || user.sessionid;
if (!sessionId || sessionId === currentSessionId || previousUsersInRoom.indexOf(sessionId) !== -1) {
return;
}
previousUsersInRoom.push(sessionId);
// TODO(fancycode): Adjust property name of internal PHP backend to be all lowercase.
spreedMappingTable[sessionId] = user.userId || user.userid;
var videoView = OCA.SpreedMe.videos.videoViews[sessionId];
if (!videoView) {
OCA.SpreedMe.videos.add(sessionId);
}
var createPeer = function() {
var peer = webrtc.webrtc.createPeer({
id: sessionId,
type: "video",
enableDataChannels: true,
receiveMedia: {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
}
});
webrtc.emit('createdPeer', peer);
peer.start();
};
if (!webrtc.webrtc.getPeers(sessionId, 'video').length) {
if (useMcu) {
// TODO(jojo): Already create peer object to avoid duplicate offers.
webrtc.connection.requestOffer(user, "video");
} else if (userHasStreams(selfInCall) && (!userHasStreams(user) || sessionId < currentSessionId)) {
// To avoid overloading the user joining a room (who previously called
// all the other participants), we decide who calls who by comparing
// the session ids of the users: "larger" ids call "smaller" ones.
console.log("Starting call with", user);
createPeer();
} else if (userHasStreams(selfInCall) && userHasStreams(user) && sessionId > currentSessionId) {
// If the remote peer is not aware that it was disconnected
// from the current peer the remote peer will not send a new
// offer; thus, if the current peer does not receive a new
// offer in a reasonable time, the current peer calls the
// remote peer instead of waiting to be called to
// reestablish the connection.
delayedCreatePeer[sessionId] = setTimeout(function() {
createPeer();
}, 10000);
}
}
//Send shared screen to new participants
if (webrtc.getLocalScreen()) {
createScreensharingPeer(signaling, sessionId);
}
});
disconnectedSessionIds.forEach(function(sessionId) {
console.log('XXX Remove peer', sessionId);
OCA.SpreedMe.webrtc.removePeers(sessionId);
OCA.SpreedMe.speakers.remove(sessionId, true);
OCA.SpreedMe.videos.remove(sessionId);
delete spreedMappingTable[sessionId];
delete guestNamesTable[sessionId];
});
previousUsersInRoom = previousUsersInRoom.diff(disconnectedSessionIds);
updateParticipantsUI(previousUsersInRoom.length + 1);
}
function usersInCallChanged(signaling, users) {
// The passed list are the users that are currently in the room,
// i.e. that are in the call and should call each other.
var currentSessionId = signaling.getSessionid();
var currentUsersInRoom = [];
var userMapping = {};
selfInCall = OCA.SpreedMe.app.FLAG_DISCONNECTED;
var sessionId;
for (sessionId in users) {
if (!users.hasOwnProperty(sessionId)) {
continue;
}
var user = users[sessionId];
if (!user.inCall) {
continue;
}
if (sessionId === currentSessionId) {
selfInCall = user.inCall;
continue;
}
currentUsersInRoom.push(sessionId);
userMapping[sessionId] = user;
}
if (!selfInCall) {
// Own session is no longer in the call, disconnect from all others.
usersChanged(signaling, [], previousUsersInRoom);
return;
}
var newSessionIds = currentUsersInRoom.diff(previousUsersInRoom);
var disconnectedSessionIds = previousUsersInRoom.diff(currentUsersInRoom);
var newUsers = [];
newSessionIds.forEach(function(sessionId) {
newUsers.push(userMapping[sessionId]);
});
if (newUsers.length || disconnectedSessionIds.length) {
usersChanged(signaling, newUsers, disconnectedSessionIds);
}
}
/**
* @param {OCA.Talk.Application} app
*/
function initWebRTC(app) {
Array.prototype.diff = function(a) {
return this.filter(function(i) {
return a.indexOf(i) < 0;
});
};
var signaling = app.signaling;
signaling.on('usersLeft', function(users) {
users.forEach(function(user) {
delete usersInCallMapping[user];
});
usersChanged(signaling, [], users);
});
signaling.on('usersChanged', function(users) {
users.forEach(function(user) {
var sessionId = user.sessionId || user.sessionid;
usersInCallMapping[sessionId] = user;
});
usersInCallChanged(signaling, usersInCallMapping);
});
signaling.on('usersInRoom', function(users) {
usersInCallMapping = {};
users.forEach(function(user) {
var sessionId = user.sessionId || user.sessionid;
usersInCallMapping[sessionId] = user;
});
usersInCallChanged(signaling, usersInCallMapping);
});
signaling.on('leaveCall', function (token, reconnect) {
// When the MCU is used and there is a connection error the call is
// left and then joined again to perform the reconnection. In those
// cases the call should be kept active from the point of view of
// WebRTC.
if (reconnect) {
return;
}
webrtc.leaveCall();
});
signaling.on('message', function (message) {
if (message.type !== 'offer') {
return;
}
var peers = OCA.SpreedMe.webrtc.webrtc.peers;
var stalePeer = peers.find(function(peer) {
if (peer.sharemyscreen) {
return false;
}
return peer.id === message.from && peer.type === message.roomType && peer.sid !== message.sid;
});
if (stalePeer) {
stalePeer.end();
if (message.roomType === 'video') {
OCA.SpreedMe.speakers.remove(stalePeer.id, true);
OCA.SpreedMe.videos.remove(stalePeer.id);
}
}
if (message.roomType === 'video' && delayedCreatePeer[message.from]) {
clearTimeout(delayedCreatePeer[message.from]);
delete delayedCreatePeer[message.from];
}
// MCU screen offers do not include the "broadcaster" property,
// which is expected by SimpleWebRTC in screen offers from a remote
// peer, so it needs to be explicitly added.
if (signaling.hasFeature("mcu") && message.roomType === 'screen') {
message.broadcaster = message.from;
}
});
webrtc = new SimpleWebRTC({
localVideoEl: 'localVideo',
remoteVideosEl: '',
autoRequestMedia: true,
debug: false,
media: {
audio: true,
video: true
},
autoAdjustMic: false,
audioFallback: true,
detectSpeakingEvents: true,
connection: signaling,
enableDataChannels: true,
nick: OC.getCurrentUser().displayName
});
if (signaling.hasFeature('mcu')) {
// Force "Plan-B" semantics if the MCU is used, which doesn't support
// "Unified Plan" with SimpleWebRTC yet.
webrtc.webrtc.config.peerConnectionConfig.sdpSemantics = 'plan-b';
}
OCA.SpreedMe.webrtc = webrtc;
OCA.SpreedMe.webrtc.startMedia = function (token) {
webrtc.joinCall(token);
};
var spreedListofSpeakers = {};
var spreedListofSharedScreens = {};
var latestSpeakerId = null;
var unpromotedSpeakerId = null;
var latestScreenId = null;
var screenSharingActive = false;
window.addEventListener('resize', function() {
if (screenSharingActive) {
$('#screens').children('video').each(function() {
$(this).width('100%');
$(this).height($('#screens').height());
});
}
});
var sendDataChannelToAll = function(channel, message, payload) {
// If running with MCU, the message must be sent through the
// publishing peer and will be distributed by the MCU to subscribers.
var conn = OCA.SpreedMe.webrtc.connection;
if (ownPeer && conn.hasFeature && conn.hasFeature('mcu')) {
ownPeer.sendDirectly(channel, message, payload);
return;
}
OCA.SpreedMe.webrtc.sendDirectlyToAll(channel, message, payload);
};
OCA.SpreedMe.videos = {
videoViews: [],
add: function(id) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
var user = usersInCallMapping[id];
if (user && !userHasStreams(user)) {
console.log("User has no stream", id);
}
var userId = spreedMappingTable[id];
var videoView = new OCA.Talk.Views.VideoView({
peerId: id
});
videoView.setParticipant(userId);
videoView.setScreenAvailable(!!spreedListofSharedScreens[id]);
OCA.SpreedMe.videos.videoViews[id] = videoView;
videoView.$el.prependTo($('#videos'));
return videoView;
},
remove: function(id) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
if (!OCA.SpreedMe.videos.videoViews[id]) {
return;
}
OCA.SpreedMe.videos.videoViews[id].$el.remove();
delete OCA.SpreedMe.videos.videoViews[id];
},
addPeer: function(peer) {
var signaling = OCA.SpreedMe.app.signaling;
if (peer.id === webrtc.connection.getSessionid()) {
console.log("Not adding video for own peer", peer);
OCA.SpreedMe.videos.startSendingNick(peer);
return;
}
var videoView = OCA.SpreedMe.videos.videoViews[peer.id];
if (!videoView) {
videoView = OCA.SpreedMe.videos.add(peer.id);
}
// Initialize ice restart counter for peer
spreedPeerConnectionTable[peer.id] = 0;
peer.pc.addEventListener('iceconnectionstatechange', function () {
var userId = spreedMappingTable[peer.id];
switch (peer.pc.iceConnectionState) {
case 'checking':
console.log('Connecting to peer...');
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.CHECKING);
break;
case 'connected':
case 'completed': // on caller side
console.log('Connection established.');
if (peer.pc.iceConnectionState === 'connected') {
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.CONNECTED);
} else {
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.COMPLETED);
}
// Ensure that the peer name is shown, as the name
// indicator for registered users without microphone
// nor camera will not be updated later.
if (userId && userId.length) {
videoView.setParticipant(userId, peer.nick);
}
// Send the current information about the video and microphone state
if (!OCA.SpreedMe.webrtc.webrtc.isVideoEnabled()) {
OCA.SpreedMe.webrtc.emit('videoOff');
} else {
OCA.SpreedMe.webrtc.emit('videoOn');
}
if (!OCA.SpreedMe.webrtc.webrtc.isAudioEnabled()) {
OCA.SpreedMe.webrtc.emit('audioOff');
} else {
OCA.SpreedMe.webrtc.emit('audioOn');
}
if (!OC.getCurrentUser()['uid']) {
var currentGuestNick = localStorage.getItem("nick");
sendDataChannelToAll('status', 'nickChanged', currentGuestNick);
}
// Reset ice restart counter for peer
if (spreedPeerConnectionTable[peer.id] > 0) {
spreedPeerConnectionTable[peer.id] = 0;
}
break;
case 'disconnected':
console.log('Disconnected.');
if (!signaling.hasFeature("mcu")) {
// ICE failures will be handled in "iceFailed"
// below for MCU installations.
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.DISCONNECTED);
setTimeout(function() {
// If the peer is still disconnected after 5 seconds we try ICE restart.
if(peer.pc.iceConnectionState === 'disconnected') {
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.DISCONNECTED_LONG);
if (spreedPeerConnectionTable[peer.id] < 5) {
if (peer.pc.localDescription.type === 'offer' &&
peer.pc.signalingState === 'stable') {
spreedPeerConnectionTable[peer.id] ++;
console.log('ICE restart.');
peer.icerestart();
}
}
}
}, 5000);
}
break;
case 'failed':
console.log('Connection failed.');
if (!signaling.hasFeature("mcu")) {
// ICE failures will be handled in "iceFailed"
// below for MCU installations.
if (spreedPeerConnectionTable[peer.id] < 5) {
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.FAILED);
if (peer.pc.localDescription.type === 'offer' &&
peer.pc.signalingState === 'stable') {
spreedPeerConnectionTable[peer.id] ++;
console.log('ICE restart.');
peer.icerestart();
}
} else {
console.log('ICE failed after 5 tries.');
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.FAILED_NO_RESTART);
}
}
break;
case 'closed':
console.log('Connection closed.');
videoView.setConnectionStatus(OCA.Talk.Views.VideoView.ConnectionStatus.CLOSED);
break;
}
OCA.SpreedMe.speakers.updateVideoContainerDummyIfLatestSpeaker(peer.id);
});
},
// The nick name below the avatar is distributed through the
// DataChannel of the PeerConnection and only sent once during
// establishment. For the MCU case, the sending PeerConnection
// is created once and then never changed when more participants
// join. For this, we periodically send the nick to all other
// participants through the sending PeerConnection.
//
// TODO: The name for the avatar should come from the participant
// list which already has all information and get rid of using the
// DataChannel for this.
startSendingNick: function(peer) {
if (!signaling.hasFeature("mcu")) {
return;
}
OCA.SpreedMe.videos.stopSendingNick(peer);
peer.nickInterval = setInterval(function() {
var payload;
var user = OC.getCurrentUser();
if (!user.uid) {
payload = localStorage.getItem("nick");
} else {
payload = {
"name": user.displayName,
"userid": user.uid
};
}
peer.sendDirectly('status', "nickChanged", payload);
}, 1000);
},
stopSendingNick: function(peer) {
if (!peer.nickInterval) {
return;
}
clearInterval(peer.nickInterval);
peer.nickInterval = null;
}
};
OCA.SpreedMe.speakers = {
switchVideoToId: function(id) {
if (screenSharingActive || latestSpeakerId === id) {
return;
}
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (!videoView) {
console.warn('promote: no video found for ID', id);
return;
}
var oldVideoView = OCA.SpreedMe.videos.videoViews[latestSpeakerId];
if (oldVideoView) {
oldVideoView.setPromoted(false);
}
videoView.setPromoted(true);
OCA.SpreedMe.speakers.updateVideoContainerDummy(id);
latestSpeakerId = id;
},
unpromoteLatestSpeaker: function() {
if (latestSpeakerId) {
var oldVideoView = OCA.SpreedMe.videos.videoViews[latestSpeakerId];
if (oldVideoView) {
oldVideoView.setPromoted(false);
}
unpromotedSpeakerId = latestSpeakerId;
latestSpeakerId = null;
$('.videoContainer-dummy').remove();
}
},
updateVideoContainerDummyIfLatestSpeaker: function(id) {
if (latestSpeakerId !== id) {
return;
}
OCA.SpreedMe.speakers.updateVideoContainerDummy(id);
},
updateVideoContainerDummy: function(id) {
$('.videoContainer-dummy').remove();
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.$el.after(videoView.newDummyVideoContainer());
}
},
add: function(id, notPromote) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
if (notPromote) {
spreedListofSpeakers[id] = 1;
return;
}
spreedListofSpeakers[id] = (new Date()).getTime();
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.setSpeaking(true);
}
if (latestSpeakerId === id) {
return;
}
OCA.SpreedMe.speakers.switchVideoToId(id);
},
remove: function(id, enforce) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
if (enforce) {
delete spreedListofSpeakers[id];
}
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.setSpeaking(false);
}
if (latestSpeakerId !== id) {
return;
}
var mostRecentTime = 0,
mostRecentId = null;
for (var currentId in spreedListofSpeakers) {
// skip loop if the property is from prototype
if (!spreedListofSpeakers.hasOwnProperty(currentId)) {
continue;
}
// skip non-string ids
if (!(typeof currentId === 'string' || currentId instanceof String)) {
continue;
}
var currentTime = spreedListofSpeakers[currentId];
if (currentTime > mostRecentTime && OCA.SpreedMe.videos.videoViews[currentId]) {
mostRecentTime = currentTime;
mostRecentId = currentId;
}
}
if (mostRecentId !== null) {
OCA.SpreedMe.speakers.switchVideoToId(mostRecentId);
} else if (enforce === true) {
// if there is no mostRecentId available, there is no user left in call
// remove the remaining dummy container then too
OCA.SpreedMe.speakers.unpromoteLatestSpeaker();
$('.videoContainer-dummy').remove();
}
}
};
OCA.SpreedMe.sharedScreens = {
screenViews: [],
switchScreenToId: function(id) {
var screenView = OCA.SpreedMe.sharedScreens.screenViews[id];
if (!screenView) {
console.warn('promote: no screen video found for ID', id);
return;
}
if(latestScreenId === id) {
return;
}
for (var currentId in spreedListofSharedScreens) {
// skip loop if the property is from prototype
if (!spreedListofSharedScreens.hasOwnProperty(currentId)) {
continue;
}
// skip non-string ids
if (!(typeof currentId === 'string' || currentId instanceof String)) {
continue;
}
screenView = OCA.SpreedMe.sharedScreens.screenViews[currentId];
if (currentId === id) {
screenView.$el.removeClass('hidden');
} else {
screenView.$el.addClass('hidden');
}
}
var oldVideoView = OCA.SpreedMe.videos.videoViews[latestScreenId];
if (oldVideoView) {
oldVideoView.setScreenVisible(false);
}
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.setScreenVisible(true);
}
latestScreenId = id;
},
add: function(id) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
spreedListofSharedScreens[id] = (new Date()).getTime();
var currentUser = OCA.SpreedMe.webrtc.connection.getSessionid();
if (currentUser !== id) {
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.setScreenAvailable(true);
}
}
OCA.SpreedMe.sharedScreens.switchScreenToId(id);
},
remove: function(id) {
if (!(typeof id === 'string' || id instanceof String)) {
return;
}
var screenView = OCA.SpreedMe.sharedScreens.screenViews[id];
if (screenView) {
screenView.$el.remove();
delete OCA.SpreedMe.sharedScreens.screenViews[id];
}
delete spreedListofSharedScreens[id];
var videoView = OCA.SpreedMe.videos.videoViews[id];
if (videoView) {
videoView.setScreenAvailable(false);
}
var mostRecentTime = 0,
mostRecentId = null;
for (var currentId in spreedListofSharedScreens) {
// skip loop if the property is from prototype
if (!spreedListofSharedScreens.hasOwnProperty(currentId)) {
continue;
}
// skip non-string ids
if (!(typeof currentId === 'string' || currentId instanceof String)) {
continue;
}
var currentTime = spreedListofSharedScreens[currentId];
if (currentTime > mostRecentTime) {
mostRecentTime = currentTime;
mostRecentId = currentId;
}
}
if (mostRecentId !== null) {
OCA.SpreedMe.sharedScreens.switchScreenToId(mostRecentId);
}
}
};
OCA.SpreedMe.webrtc.on('createdPeer', function (peer) {
console.log('PEER CREATED', peer);
if (peer.type === 'video') {
OCA.SpreedMe.videos.addPeer(peer);
// Make sure required data channels exist for all peers. This
// is required for peers that get created by SimpleWebRTC from
// received "Offer" messages. Otherwise the "channelMessage"
// will not be called.
peer.getDataChannel('status');
}
});
function checkPeerMedia(peer, track, mediaType) {
var defer = $.Deferred();
peer.pc.getStats(track).then(function(stats) {
var result = false;
stats.forEach(function(statsReport) {
if (!result && statsReport.mediaType !== mediaType || !statsReport.hasOwnProperty('bytesReceived')) {
return;
}
if (statsReport.bytesReceived > 0) {
OCA.SpreedMe.webrtc.emit('unmute', {
id: peer.id,
name: mediaType
});
result = true;
}
});
if (result) {
defer.resolve();
} else {
defer.reject();
}
});
return defer;
}
function stopPeerCheckMedia(peer) {
if (peer.check_audio_interval) {
clearInterval(peer.check_audio_interval);
peer.check_audio_interval = null;
}
if (peer.check_video_interval) {
clearInterval(peer.check_video_interval);
peer.check_video_interval = null;
}
OCA.SpreedMe.videos.stopSendingNick(peer);
}
function startPeerCheckMedia(peer, stream) {
stopPeerCheckMedia(peer);
peer.check_video_interval = setInterval(function() {
stream.getVideoTracks().forEach(function(video) {
checkPeerMedia(peer, video, 'video').then(function() {
clearInterval(peer.check_video_interval);
peer.check_video_interval = null;
});
});
}, 1000);
peer.check_audio_interval = setInterval(function() {
stream.getAudioTracks().forEach(function(audio) {
checkPeerMedia(peer, audio, 'audio').then(function() {
clearInterval(peer.check_audio_interval);
peer.check_audio_interval = null;
});
});
}, 1000);
}
OCA.SpreedMe.webrtc.on('peerStreamAdded', function (peer) {
// With the MCU, a newly subscribed stream might not get the
// "audioOn"/"videoOn" messages as they are only sent when
// a user starts publishing. Instead wait for initial data
// and trigger events locally.
if (!OCA.SpreedMe.app.signaling.hasFeature("mcu")) {
return;
}
startPeerCheckMedia(peer, peer.stream);
});
OCA.SpreedMe.webrtc.on('peerStreamRemoved', function (peer) {
stopPeerCheckMedia(peer);
});
OCA.SpreedMe.webrtc.on('localScreenStopped', function() {
app.disableScreensharingButton();
});
OCA.SpreedMe.webrtc.webrtc.on('iceFailed', function (/* peer */) {
var signaling = OCA.SpreedMe.app.signaling;
if (!signaling.hasFeature("mcu")) {
// ICE restarts will be handled by "iceConnectionStateChange"
// above.
return;
}
// For now assume the connection to the MCU is interrupted on ICE
// failures and force a reconnection of all streams.
if (ownPeer) {
OCA.SpreedMe.webrtc.removePeers(ownPeer.id);
OCA.SpreedMe.speakers.remove(ownPeer.id, true);
OCA.SpreedMe.videos.remove(ownPeer.id);
delete spreedMappingTable[ownPeer.id];
ownPeer.end();
ownPeer = null;
}
usersChanged(signaling, [], previousUsersInRoom);
usersInCallMapping = {};
previousUsersInRoom = [];
// Reconnects with a new session id will trigger "usersChanged"
// with the users in the room and that will re-establish the
// peerconnection streams.
signaling.forceReconnect(true);
});
OCA.SpreedMe.webrtc.on('localMediaStarted', function (configuration) {
console.log('localMediaStarted');
app.startLocalMedia(configuration);
hasLocalMedia = true;
var signaling = OCA.SpreedMe.app.signaling;
if (signaling.hasFeature("mcu")) {
checkStartPublishOwnPeer(signaling);
}
});
OCA.SpreedMe.webrtc.on('localMediaError', function(error) {
console.log('Access to microphone & camera failed', error);
hasLocalMedia = false;
var message;
if ((error.name === "NotSupportedError" &&
OCA.SpreedMe.webrtc.capabilities.supportRTCPeerConnection) ||
(error.name === "NotAllowedError" &&
error.message && error.message.indexOf("Only secure origins") !== -1)) {
message = t('spreed', 'Access to microphone & camera is only possible with HTTPS');
message += ': ' + t('spreed', 'Please move your setup to HTTPS');
} else if (error.name === "NotAllowedError") {
message = t('spreed', 'Access to microphone & camera was denied');
} else if(!OCA.SpreedMe.webrtc.capabilities.support) {
console.log('WebRTC not supported');
message = t('spreed', 'WebRTC is not supported in your browser');
message += ': ' + t('spreed', 'Please use a different browser like Firefox or Chrome');
} else {
message = t('spreed', 'Error while accessing microphone & camera');
console.log('Error while accessing microphone & camera: ', error.message || error.name);
}
app.startWithoutLocalMedia({audio: false, video: false});
OC.Notification.show(message, {
type: 'error',
timeout: 15,
});
});
OCA.SpreedMe.webrtc.on('channelOpen', function(channel) {
console.log('%s datachannel is open', channel.label);
});
OCA.SpreedMe.webrtc.on('channelMessage', function (peer, label, data) {
if (label === 'status') {
if(data.type === 'speaking') {
OCA.SpreedMe.speakers.add(peer.id);
} else if(data.type === 'stoppedSpeaking') {
OCA.SpreedMe.speakers.remove(peer.id);
} else if(data.type === 'audioOn') {
OCA.SpreedMe.webrtc.emit('unmute', {id: peer.id, name:'audio'});
} else if(data.type === 'audioOff') {
OCA.SpreedMe.webrtc.emit('mute', {id: peer.id, name:'audio'});
} else if(data.type === 'videoOn') {
OCA.SpreedMe.webrtc.emit('unmute', {id: peer.id, name:'video'});
} else if(data.type === 'videoOff') {
OCA.SpreedMe.webrtc.emit('mute', {id: peer.id, name:'video'});
} else if (data.type === 'nickChanged') {
var payload = data.payload || '';
if (typeof(payload) === 'string') {
OCA.SpreedMe.webrtc.emit('nick', {id: peer.id, name:data.payload});
app._messageCollection.updateGuestName(new Hashes.SHA1().hex(peer.id), data.payload);
} else {
OCA.SpreedMe.webrtc.emit('nick', {id: peer.id, name: payload.name, userid: payload.userid});
}
}
} else if (label === 'hark') {
// Ignore messages from hark datachannel
} else {
console.log('Uknown message from %s datachannel', label, data);
}
});
OCA.SpreedMe.webrtc.on('videoAdded', function(video, peer) {
console.log('VIDEO ADDED', peer);
if (peer.type === 'screen') {
OCA.SpreedMe.webrtc.emit('screenAdded', video, peer);
return;
}
var videoView = OCA.SpreedMe.videos.videoViews[peer.id];
if (videoView) {
var userId = spreedMappingTable[peer.id];
var guestName = guestNamesTable[peer.id];
var participantName = peer.nick;
if (!userId || !userId.length) {
participantName = peer.nick || guestName;
}
videoView.setParticipant(userId, participantName);
videoView.setVideoElement(video);
}
var otherSpeakerPromoted = false;
for (var key in spreedListofSpeakers) {
if (spreedListofSpeakers.hasOwnProperty(key) && spreedListofSpeakers[key] > 1) {
otherSpeakerPromoted = true;
break;
}
}
if (!otherSpeakerPromoted) {
OCA.SpreedMe.speakers.add(peer.id);
} else {
OCA.SpreedMe.speakers.add(peer.id, true);
}
});
OCA.SpreedMe.webrtc.on('speaking', function(){
sendDataChannelToAll('status', 'speaking');
OCA.SpreedMe.app._localVideoView.setSpeaking(true);
});
OCA.SpreedMe.webrtc.on('stoppedSpeaking', function(){
sendDataChannelToAll('status', 'stoppedSpeaking');
OCA.SpreedMe.app._localVideoView.setSpeaking(false);
});
// a peer was removed
OCA.SpreedMe.webrtc.on('videoRemoved', function(video, peer) {
var screens;
if (peer) {
if (peer.type === 'video') {
// a removed peer can't speak anymore ;)
OCA.SpreedMe.speakers.remove(peer.id, true);
var videoView = OCA.SpreedMe.videos.videoViews[peer.id];
if (videoView) {
videoView.setVideoElement(null);
}
} else if (peer.type === 'screen') {
OCA.SpreedMe.sharedScreens.remove(peer.id);
}
} else if (video.id === 'localScreen') {
// SimpleWebRTC notifies about stopped screensharing through
// the generic "videoRemoved" API, but the stream must be
// handled differently.
OCA.SpreedMe.webrtc.emit('localScreenStopped');
OCA.SpreedMe.sharedScreens.remove(OCA.SpreedMe.webrtc.connection.getSessionid());
}
// Check if there are still some screens
screens = document.getElementById('screens');
if (!screens || !screens.hasChildNodes()) {
screenSharingActive = false;
$(OCA.SpreedMe.app.mainCallElementSelector).removeClass('screensharing');
if (unpromotedSpeakerId) {
OCA.SpreedMe.speakers.switchVideoToId(unpromotedSpeakerId);
unpromotedSpeakerId = null;
}
}
});
// Send the audio on and off events via data channel
OCA.SpreedMe.webrtc.on('audioOn', function() {
sendDataChannelToAll('status', 'audioOn');
});
OCA.SpreedMe.webrtc.on('audioOff', function() {
sendDataChannelToAll('status', 'audioOff');
});
OCA.SpreedMe.webrtc.on('videoOn', function() {
sendDataChannelToAll('status', 'videoOn');
});
OCA.SpreedMe.webrtc.on('videoOff', function() {
sendDataChannelToAll('status', 'videoOff');
});
OCA.SpreedMe.webrtc.on('screenAdded', function(video, peer) {
OCA.SpreedMe.speakers.unpromoteLatestSpeaker();
screenSharingActive = true;
$(OCA.SpreedMe.app.mainCallElementSelector).addClass('screensharing');
var screens = document.getElementById('screens');
if (screens) {
var screenView = new OCA.Talk.Views.ScreenView({
peerId: peer? peer.id: undefined
});
screenView.setVideoElement(video);
if (peer) {
var participantName = peer.nick || guestNamesTable[peer.id];
screenView.setParticipantName(participantName);
}
screenView.$el.prependTo($('#screens'));
if (peer) {
OCA.SpreedMe.sharedScreens.screenViews[peer.id] = screenView;
OCA.SpreedMe.sharedScreens.add(peer.id);
} else {
OCA.SpreedMe.sharedScreens.screenViews[OCA.SpreedMe.webrtc.connection.getSessionid()] = screenView;
OCA.SpreedMe.sharedScreens.add(OCA.SpreedMe.webrtc.connection.getSessionid());
}
}
});
// Local screen added.
OCA.SpreedMe.webrtc.on('localScreenAdded', function(video) {
OCA.SpreedMe.webrtc.emit('screenAdded', video, null);
var signaling = OCA.SpreedMe.app.signaling;
var currentSessionId = signaling.getSessionid();
for (var sessionId in usersInCallMapping) {
if (!usersInCallMapping.hasOwnProperty(sessionId)) {
continue;
} else if (!usersInCallMapping[sessionId].inCall) {
continue;
} else if (sessionId === currentSessionId) {
// Running with MCU, no need to create screensharing
// subscriber for client itself.
continue;
}
createScreensharingPeer(signaling, sessionId);
}
});
OCA.SpreedMe.webrtc.on('localScreenStopped', function() {
var signaling = OCA.SpreedMe.app.signaling;
if (!signaling.hasFeature('mcu')) {
// Only need to notify clients here if running with MCU.
// Otherwise SimpleWebRTC will notify each client on its own.
return;
}
var currentSessionId = signaling.getSessionid();
OCA.SpreedMe.webrtc.getPeers().forEach(function(existingPeer) {
if (ownScreenPeer && existingPeer.type === 'screen' && existingPeer.id === currentSessionId) {
ownScreenPeer = null;
existingPeer.end();
signaling.sendRoomMessage({
roomType: 'screen',
type: 'unshareScreen'
});
}
});
});
// Peer changed nick
OCA.SpreedMe.webrtc.on('nick', function(data) {
// Video
var videoView = OCA.SpreedMe.videos.videoViews[data.id];
if (videoView) {
videoView.setParticipant(data.userid, data.name);
}
//Screen
var screenView = OCA.SpreedMe.sharedScreens.screenViews[data.id];
if (screenView) {
screenView.setParticipantName(data.name);
}
if (!data.userid && data.name) {
guestNamesTable[data.id] = data.name;
}
OCA.SpreedMe.speakers.updateVideoContainerDummyIfLatestSpeaker(data.id);
});
// Peer is muted
OCA.SpreedMe.webrtc.on('mute', function(data) {
var videoView = OCA.SpreedMe.videos.videoViews[data.id];
if (!videoView) {
return;
}
if (data.name === 'video') {
videoView.setVideoAvailable(false);
} else {
videoView.setAudioAvailable(false);
}
OCA.SpreedMe.speakers.updateVideoContainerDummyIfLatestSpeaker(data.id);
});
// Peer is umuted
OCA.SpreedMe.webrtc.on('unmute', function(data) {
var videoView = OCA.SpreedMe.videos.videoViews[data.id];
if (!videoView) {
return;
}
if (data.name === 'video') {
videoView.setVideoAvailable(true);
} else {
videoView.setAudioAvailable(true);
}
OCA.SpreedMe.speakers.updateVideoContainerDummyIfLatestSpeaker(data.id);
});
}
OCA.SpreedMe.initWebRTC = initWebRTC;
})(OCA, OC);
|