-
Notifications
You must be signed in to change notification settings - Fork 453
/
Copy pathsignaling.js
1606 lines (1437 loc) · 44.1 KB
/
signaling.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
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
/**
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
import axios from '@nextcloud/axios'
import {
showError,
showWarning,
TOAST_PERMANENT_TIMEOUT,
} from '@nextcloud/dialogs'
import { t } from '@nextcloud/l10n'
import {
generateOcsUrl,
} from '@nextcloud/router'
import CancelableRequest from './cancelableRequest.js'
import Encryption from './e2ee/encryption.js'
import { messagePleaseTryToReload } from './talkDesktopUtils.ts'
import { PARTICIPANT } from '../constants.js'
import { hasTalkFeature } from '../services/CapabilitiesManager.ts'
import { EventBus } from '../services/EventBus.ts'
import { rejoinConversation } from '../services/participantsService.js'
import { pullSignalingMessages } from '../services/signalingService.js'
import store from '../store/index.js'
const Signaling = {
Base: {},
Internal: {},
Standalone: {},
/**
* Creates a connection to the signaling server
*
* @param {object} settings The signaling settings
* @return {Standalone|Internal}
*/
createConnection(settings) {
if (!settings) {
console.error('Signaling settings are not given')
}
if (settings.signalingMode !== 'internal') {
return new Signaling.Standalone(settings, settings.server)
} else {
return new Signaling.Internal(settings)
}
},
}
/**
* @param {object} settings The signaling settings
*/
function Base(settings) {
this.settings = settings
this.sessionId = ''
this.currentRoomToken = null
this.currentCallToken = null
this.currentCallFlags = null
this.currentCallSilent = null
this.currentCallRecordingConsent = null
this.nextcloudSessionId = null
this.handlers = {}
this.features = {}
this._sendVideoIfAvailable = true
this.signalingConnectionTimeout = null
this.signalingConnectionWarning = null
this.signalingConnectionError = null
}
Signaling.Base = Base
Signaling.Base.prototype.on = function(ev, handler) {
if (!Object.prototype.hasOwnProperty.call(this.handlers, ev)) {
this.handlers[ev] = [handler]
} else {
this.handlers[ev].push(handler)
}
let servers = []
switch (ev) {
case 'stunservers':
case 'turnservers':
servers = this.settings[ev] || []
if (servers.length) {
handler(servers)
}
break
}
}
Signaling.Base.prototype.off = function(ev, handler) {
if (!Object.prototype.hasOwnProperty.call(this.handlers, ev)) {
return
}
let pos = this.handlers[ev].indexOf(handler)
while (pos !== -1) {
this.handlers[ev].splice(pos, 1)
pos = this.handlers[ev].indexOf(handler)
}
}
Signaling.Base.prototype._trigger = function(ev, args) {
let handlers = this.handlers[ev]
if (handlers) {
handlers = handlers.slice(0)
for (let i = 0, len = handlers.length; i < len; i++) {
const handler = handlers[i]
handler.apply(handler, args)
}
}
// Convert webrtc event names to kebab-case for "vue/custom-event-name-casing"
const kebabCase = string => string
.replace(/([a-z])([A-Z])/g, '$1-$2')
.replace(/[\s_]+/g, '-')
.toLowerCase()
EventBus.emit('signaling-' + kebabCase(ev), args)
}
Signaling.Base.prototype.setSettings = function(settings) {
if (!settings) {
// Signaling object is expected to always have a settings object
return
}
this.settings = settings
this._trigger('settingsUpdated', [settings])
if (this._pendingUpdateSettingsPromise) {
this._pendingUpdateSettingsPromise.resolve()
delete this._pendingUpdateSettingsPromise
}
}
Signaling.Base.prototype.getSessionId = function() {
return this.sessionId
}
Signaling.Base.prototype.getCurrentCallFlags = function() {
return this.currentCallFlags
}
Signaling.Base.prototype._resetCurrentCallParameters = function() {
this.currentCallToken = null
this.currentCallFlags = null
this.currentCallSilent = null
this.currentCallRecordingConsent = null
}
Signaling.Base.prototype.disconnect = function() {
this.sessionId = ''
this._trigger('sessionId', [this.sessionId])
this._resetCurrentCallParameters()
}
Signaling.Base.prototype.hasFeature = function(feature) {
return this.features && this.features[feature]
}
Signaling.Base.prototype.emit = function(ev, data) {
switch (ev) {
case 'joinRoom':
this.joinRoom(data)
break
case 'joinCall':
this.joinCall(data, arguments[2])
break
case 'leaveRoom':
this.leaveCurrentRoom()
break
case 'leaveCall':
this.leaveCurrentCall()
break
case 'message':
this.sendCallMessage(data)
break
}
}
Signaling.Base.prototype.leaveCurrentRoom = function() {
if (this.currentRoomToken) {
this.leaveRoom(this.currentRoomToken)
this.currentRoomToken = null
this.nextcloudSessionId = null
}
}
Signaling.Base.prototype.updateCurrentCallFlags = function(flags) {
return new Promise((resolve, reject) => {
if (this.currentCallToken) {
this.updateCallFlags(this.currentCallToken, flags).then(() => { resolve() }).catch(reason => { reject(reason) })
} else {
resolve()
}
})
}
Signaling.Base.prototype.leaveCurrentCall = function() {
return new Promise((resolve, reject) => {
if (this.currentCallToken) {
this.leaveCall(this.currentCallToken).then(() => { resolve() }).catch(reason => { reject(reason) })
this._resetCurrentCallParameters()
} else {
resolve()
}
})
}
Signaling.Base.prototype.joinRoom = function(token, sessionId) {
return new Promise((resolve, reject) => {
console.debug('Joined')
this.currentRoomToken = token
this.nextcloudSessionId = sessionId
this._trigger('joinRoom', [token])
resolve()
if (this.currentCallToken === token) {
// We were in this call before, join again.
this.joinCall(token, this.currentCallFlags, this.currentCallSilent, this.currentCallRecordingConsent)
} else {
this._resetCurrentCallParameters()
}
this._joinRoomSuccess(token, sessionId)
})
}
Signaling.Base.prototype._leaveRoomSuccess = function(/* token */) {
// Override in subclasses if necessary.
}
Signaling.Base.prototype.leaveRoom = function(token) {
this.leaveCurrentCall()
.then(() => {
this._trigger('leaveRoom', [token])
this._doLeaveRoom(token)
return new Promise((resolve, reject) => {
this._leaveRoomSuccess(token)
resolve()
// We left the current room.
if (token === this.currentRoomToken) {
this.currentRoomToken = null
this.nextcloudSessionId = null
}
})
})
}
Signaling.Base.prototype.getSendVideoIfAvailable = function() {
return this._sendVideoIfAvailable
}
Signaling.Base.prototype.setSendVideoIfAvailable = function(sendVideoIfAvailable) {
this._sendVideoIfAvailable = sendVideoIfAvailable
}
Signaling.Base.prototype._joinCallSuccess = function(/* token */) {
// Override in subclasses if necessary.
}
Signaling.Base.prototype.joinCall = function(token, flags, silent, recordingConsent) {
return new Promise((resolve, reject) => {
this._trigger('beforeJoinCall', [token])
axios.post(generateOcsUrl('apps/spreed/api/v4/call/{token}', { token }), {
flags,
silent,
recordingConsent,
})
.then(function() {
this.currentCallToken = token
this.currentCallFlags = flags
this.currentCallSilent = silent
this.currentCallRecordingConsent = recordingConsent
this._trigger('joinCall', [token, flags])
resolve()
this._joinCallSuccess(token)
}.bind(this))
.catch(function(e) {
reject(new Error())
console.error('Connection failed, reason: ', e)
this._trigger('joinCallFailed', [token, e.response?.data?.ocs])
}.bind(this))
})
}
Signaling.Base.prototype._leaveCallSuccess = function(/* token */) {
// Override in subclasses if necessary.
}
Signaling.Base.prototype.updateCallFlags = function(token, flags) {
return new Promise((resolve, reject) => {
if (!token) {
reject(new Error())
return
}
axios.put(generateOcsUrl('apps/spreed/api/v4/call/{token}', { token }), {
flags,
})
.then(function() {
this.currentCallFlags = flags
this._trigger('updateCallFlags', [token, flags])
resolve()
}.bind(this))
.catch(function() {
reject(new Error())
})
})
}
Signaling.Base.prototype.leaveCall = function(token, keepToken, all = false) {
return new Promise((resolve, reject) => {
if (!token) {
reject(new Error())
return
}
this._trigger('beforeLeaveCall', [token, keepToken])
axios.delete(generateOcsUrl('apps/spreed/api/v4/call/{token}', { token }), {
data: {
all,
},
})
.then(function() {
this._trigger('leaveCall', [token, keepToken])
this._leaveCallSuccess(token)
resolve()
// We left the current call.
if (!keepToken && token === this.currentCallToken) {
this._resetCurrentCallParameters()
}
}.bind(this))
.catch(function() {
this._trigger('leaveCall', [token, keepToken])
reject(new Error())
// We left the current call.
if (!keepToken && token === this.currentCallToken) {
this._resetCurrentCallParameters()
}
}.bind(this))
})
}
// Connection to the internal signaling server provided by the app.
/**
* @param {object} settings The signaling settings
*/
function Internal(settings) {
Signaling.Base.prototype.constructor.apply(this, arguments)
this.hideWarning = settings.hideWarning
this.spreedArrayConnection = []
this.pullMessageErrorToast = null
this.pullMessagesFails = 0
this.pullMessagesRequest = null
this.isSendingMessages = false
this.sendInterval = window.setInterval(function() {
this.sendPendingMessages()
}.bind(this), 500)
this._joinCallAgainOnceDisconnected = false
Signaling.Base.prototype._trigger.call(this, 'settingsUpdated', [settings])
}
Internal.prototype = new Signaling.Base()
Internal.prototype.constructor = Internal
Signaling.Internal = Internal
Signaling.Internal.prototype.disconnect = function() {
this.spreedArrayConnection = []
if (this.sendInterval) {
window.clearInterval(this.sendInterval)
this.sendInterval = null
}
Signaling.Base.prototype.disconnect.apply(this, arguments)
}
Signaling.Internal.prototype.on = function(ev/*, handler */) {
Signaling.Base.prototype.on.apply(this, arguments)
switch (ev) {
case 'connect':
// A connection is established if we can perform a request
// through it.
this._sendMessageWithCallback(ev)
break
}
}
Signaling.Internal.prototype.forceReconnect = function(newSession, flags) {
if (newSession) {
console.warn('Forced reconnects with a new session are not supported in the internal signaling; same session as before will be used')
}
if (flags !== undefined) {
this.currentCallFlags = flags
}
// FIXME Naive reconnection routine; as the same session is kept peers
// must be explicitly ended before the reconnection is forced.
this.leaveCall(this.currentCallToken, true).then(() => {
this._joinCallAgainOnceDisconnected = true
})
}
Signaling.Internal.prototype._sendMessageWithCallback = function(ev) {
const message = [{
ev,
}]
this._sendMessages(message)
.then(function(result) {
this._trigger(ev, [result.data.ocs.data])
}.bind(this))
.catch(function(err) {
console.error(err)
showError(t('spreed', 'Sending signaling message has failed'))
})
}
Signaling.Internal.prototype._sendMessages = function(messages) {
return axios.post(generateOcsUrl('apps/spreed/api/v3/signaling/{token}', { token: this.currentRoomToken }), {
messages: JSON.stringify(messages),
})
}
Signaling.Internal.prototype._joinRoomSuccess = function(token, sessionId) {
this._joinCallAgainOnceDisconnected = false
this.sessionId = sessionId
this._trigger('sessionId', [this.sessionId])
this._startPullingMessages()
}
Signaling.Internal.prototype._doLeaveRoom = function(token) {
this._joinCallAgainOnceDisconnected = false
this.pullMessagesRequest?.('canceled')
}
Signaling.Internal.prototype.sendCallMessage = function(data) {
if (OC.debug) {
console.debug('Sending', data)
}
if (data.type === 'answer') {
console.debug('ANSWER', data)
} else if (data.type === 'offer') {
console.debug('OFFER', data)
}
this.spreedArrayConnection.push({
ev: 'message',
fn: JSON.stringify(data),
sessionId: this.sessionId,
})
}
/**
* @private
*/
Signaling.Internal.prototype._startPullingMessages = function() {
const token = this.currentRoomToken
if (!token) {
return
}
// Abort ongoing request
if (this.pullMessagesRequest !== null) {
this.pullMessagesRequest('canceled')
}
// Connect to the messages endpoint and pull for new messages
const { request, cancel } = CancelableRequest(pullSignalingMessages)
this.pullMessagesRequest = cancel
request(token)
.then(function(result) {
this.pullMessagesFails = 0
if (this.pullMessageErrorToast) {
this.pullMessageErrorToast.hideToast()
this.pullMessageErrorToast = null
}
result.data.ocs.data.forEach(message => {
let localParticipant
if (OC.debug) {
console.debug('Received', message)
}
this._trigger('onBeforeReceiveMessage', [message])
switch (message.type) {
case 'usersInRoom':
this._trigger('usersInRoom', [message.data])
this._trigger('participantListChanged')
localParticipant = message.data.find(participant => participant.sessionId === this.sessionId)
if (this._joinCallAgainOnceDisconnected && !localParticipant.inCall) {
this._joinCallAgainOnceDisconnected = false
this.joinCall(this.currentCallToken, this.currentCallFlags, this.currentCallSilent, this.currentCallRecordingConsent)
}
break
case 'message':
if (typeof (message.data) === 'string') {
message.data = JSON.parse(message.data)
}
this._trigger('message', [message.data])
break
default:
console.error('Unknown Signaling Message', message)
break
}
this._trigger('onAfterReceiveMessage', [message])
})
this._startPullingMessages()
}.bind(this))
.catch(function(error) {
if (token !== this.currentRoomToken) {
// User navigated away in the meantime. Ignore
} else if (axios.isCancel(error)) {
console.debug('Pulling messages request was cancelled')
} else if (error?.response?.status === 409) {
// Participant joined a second time and this session was killed
console.error('Session was killed but the conversation still exists')
this._trigger('pullMessagesStoppedOnFail')
EventBus.emit('duplicate-session-detected')
} else if (error?.response?.status === 404 || error?.response?.status === 403) {
// Conversation was deleted or the user was removed
console.error('Conversation was not found anymore')
EventBus.emit('deleted-session-detected')
} else if (token) {
if (this.pullMessagesFails === 1) {
this.pullMessageErrorToast = showError(t('spreed', 'Lost connection to signaling server. Trying to reconnect.'), {
timeout: TOAST_PERMANENT_TIMEOUT,
})
}
if (this.pullMessagesFails === 30) {
if (this.pullMessageErrorToast) {
this.pullMessageErrorToast.hideToast()
}
// Giving up after 5 minutes
this.pullMessageErrorToast = showError(t('spreed', 'Lost connection to signaling server.') + '\n' + messagePleaseTryToReload, {
timeout: TOAST_PERMANENT_TIMEOUT,
})
return
}
this.pullMessagesFails++
// Retry to pull messages after 10 seconds
window.setTimeout(function() {
this._startPullingMessages()
}.bind(this), 10000)
}
}.bind(this))
}
/**
* @private
*/
Signaling.Internal.prototype.sendPendingMessages = function() {
if (!this.spreedArrayConnection.length || this.isSendingMessages) {
return
}
const pendingMessagesLength = this.spreedArrayConnection.length
this.isSendingMessages = true
this._sendMessages(this.spreedArrayConnection).then(function(/* result */) {
this.spreedArrayConnection.splice(0, pendingMessagesLength)
this.isSendingMessages = false
}.bind(this)).catch(function(/* xhr, textStatus, errorThrown */) {
console.error('Sending pending signaling messages has failed.')
this.isSendingMessages = false
}.bind(this))
}
Signaling.Internal.prototype._joinCallSuccess = function(token) {
if (this.hideWarning) {
return
}
EventBus.emit('signaling-internal-show-warning', token)
}
/**
* @param {object} settings The signaling settings
* @param {string|string[]} urls The url of the signaling server
*/
function Standalone(settings, urls) {
Signaling.Base.prototype.constructor.apply(this, arguments)
if (typeof (urls) === 'string') {
urls = [urls]
}
// We can connect to any of the servers.
const idx = Math.floor(Math.random() * urls.length)
// TODO(jojo): Try other server if connection fails.
let url = urls[idx]
// Make sure we are using websocket urls.
if (url.startsWith('https://')) {
url = 'wss://' + url.slice(8)
} else if (url.startsWith('http://')) {
url = 'ws://' + url.slice(7)
}
if (url.endsWith('/')) {
url = url.slice(0, -1)
}
this.url = url + '/spreed'
this.welcomeTimeoutMs = 3000
this.initialReconnectIntervalMs = 1000
this.maxReconnectIntervalMs = 16000
this.reconnectIntervalMs = this.initialReconnectIntervalMs
this.helloResponseErrorCount = 0
this.ownSessionJoined = false
this.joinedUsers = {}
this.rooms = []
this.connect()
Signaling.Base.prototype._trigger.call(this, 'settingsUpdated', [settings])
}
Standalone.prototype = new Signaling.Base()
Standalone.prototype.constructor = Standalone
Signaling.Standalone = Standalone
Signaling.Standalone.prototype.reconnect = function() {
if (this.reconnectTimer) {
return
}
// Wiggle interval a little bit to prevent all clients from connecting
// simultaneously in case the server connection is interrupted.
const interval = this.reconnectIntervalMs - (this.reconnectIntervalMs / 2) + (this.reconnectIntervalMs * Math.random())
console.info('Reconnect in', interval)
this.reconnected = true
this.reconnectTimer = window.setTimeout(function() {
this.reconnectTimer = null
this.connect()
}.bind(this), interval)
this.reconnectIntervalMs = this.reconnectIntervalMs * 2
if (this.reconnectIntervalMs > this.maxReconnectIntervalMs) {
this.reconnectIntervalMs = this.maxReconnectIntervalMs
}
if (this.socket) {
this.socket.close()
this.socket = null
}
}
Signaling.Standalone.prototype.connect = function() {
if (this.signalingConnectionError === null
&& this.signalingConnectionWarning === null) {
this.signalingConnectionTimeout = setTimeout(() => {
this.signalingConnectionWarning = showWarning(t('spreed', 'Establishing signaling connection is taking longer than expected …'), {
timeout: TOAST_PERMANENT_TIMEOUT,
})
}, 2000)
}
if (this._pendingUpdateSettingsPromise) {
console.info('Deferring establishing signaling connection until signaling settings are updated')
this._pendingUpdateSettingsPromise.then(() => {
// "reconnect()" is called instead of "connect()", even if that
// slightly delays the connection, as "reconnect()" prevents
// duplicated connection requests.
this.reconnect()
})
return
}
console.debug('Connecting to ' + this.url + ' for ' + this.settings.token)
this.callbacks = {}
this.id = 1
this.pendingMessages = []
this.connected = false
this._forceReconnect = false
this._isRejoiningConversationWithNewSession = false
this.socket = new WebSocket(this.url)
window.signalingSocket = this.socket
this.socket.onopen = function(event) {
console.debug('Connected', event)
if (this.signalingConnectionTimeout !== null) {
clearTimeout(this.signalingConnectionTimeout)
this.signalingConnectionTimeout = null
}
if (this.signalingConnectionWarning !== null) {
this.signalingConnectionWarning.hideToast()
this.signalingConnectionWarning = null
}
this.reconnectIntervalMs = this.initialReconnectIntervalMs
if (this.settings.helloAuthParams['2.0']) {
this.waitForWelcomeTimeout = setTimeout(this.welcomeTimeout.bind(this), this.welcomeTimeoutMs)
} else {
this.sendHello()
}
}.bind(this)
this.socket.onerror = function(event) {
console.error('Error', event)
if (this.signalingConnectionTimeout !== null) {
clearTimeout(this.signalingConnectionTimeout)
this.signalingConnectionTimeout = null
}
if (this.signalingConnectionWarning !== null) {
this.signalingConnectionWarning.hideToast()
this.signalingConnectionWarning = null
}
if (this.signalingConnectionError === null) {
this.signalingConnectionError = showError(t('spreed', 'Failed to establish signaling connection. Retrying …'), {
timeout: TOAST_PERMANENT_TIMEOUT,
})
}
this.reconnect()
}.bind(this)
this.socket.onclose = function(event) {
console.debug('Close', event)
if (this.signalingConnectionTimeout !== null) {
clearTimeout(this.signalingConnectionTimeout)
this.signalingConnectionTimeout = null
}
if (this.signalingConnectionWarning !== null) {
this.signalingConnectionWarning.hideToast()
this.signalingConnectionWarning = null
}
if (event.code === 1001 && this.signalingConnectionError !== null) {
this.signalingConnectionError.hideToast()
this.signalingConnectionError = null
}
if (this.socket && event.code !== 1001) {
console.debug('Reconnecting socket as the connection was closed unexpected')
this.reconnect()
}
}.bind(this)
this.socket.onmessage = function(event) {
let data = event.data
if (typeof (data) === 'string') {
data = JSON.parse(data)
}
if (OC.debug) {
console.debug('Received', data)
}
const id = data.id
if (id && Object.prototype.hasOwnProperty.call(this.callbacks, id)) {
const cb = this.callbacks[id]
delete this.callbacks[id]
cb(data)
}
this._trigger('onBeforeReceiveMessage', [data])
const message = {}
switch (data.type) {
case 'welcome':
this.welcomeReceived(data)
break
case 'hello':
if (!id) {
// Only process if not received as result of our "hello".
this.helloResponseReceived(data)
}
break
case 'room':
if (this.currentRoomToken && data.room.roomid !== this.currentRoomToken) {
this._trigger('roomChanged', [this.currentRoomToken, data.room.roomid])
this.joinedUsers = {}
this.currentRoomToken = null
this.nextcloudSessionId = null
} else {
// TODO(fancycode): Only fetch properties of room that was modified.
EventBus.emit('should-refresh-conversations')
}
break
case 'event':
this.processEvent(data)
break
case 'message':
data.message.data.from = data.message.sender.sessionid
this._trigger('message', [data.message.data])
break
case 'control':
message.type = 'control'
message.payload = data.control.data
message.from = data.control.sender.sessionid
this._trigger('message', [message])
break
case 'dialout':
this.processDialOutEvent(data)
break
case 'transient':
this.processTransientEvent(data)
break
case 'error':
switch (data.error.code) {
case 'processing_failed':
console.error('An error occurred processing the signaling message, please ask your server administrator to check the log file')
break
case 'token_expired':
this.processErrorTokenExpired()
break
default:
console.error('Ignore unknown error', data)
this._trigger('error', [data.error])
break
}
break
default:
if (!id) {
console.error('Ignore unknown event', data)
}
break
}
this._trigger('onAfterReceiveMessage', [data])
}.bind(this)
}
Signaling.Standalone.prototype.welcomeReceived = function(data) {
console.debug('Welcome received', data)
if (this.waitForWelcomeTimeout !== null) {
clearTimeout(this.waitForWelcomeTimeout)
this.waitForWelcomeTimeout = null
}
this.features = {}
let i
if (data.welcome && data.welcome.features) {
const features = data.welcome.features
for (i = 0; i < features.length; i++) {
this.features[features[i]] = true
}
}
this.sendHello()
}
Signaling.Standalone.prototype.welcomeTimeout = function() {
console.warn('No welcome received, assuming old-style signaling server')
this.sendHello()
}
Signaling.Standalone.prototype.sendBye = function() {
if (this.connected) {
this.doSend({
type: 'bye',
bye: {},
})
}
this.resumeId = null
this.signalingRoomJoined = null
}
Signaling.Standalone.prototype.disconnect = function() {
this.sendBye()
if (this.socket) {
this.socket.close()
this.socket = null
}
Signaling.Base.prototype.disconnect.apply(this, arguments)
}
Signaling.Standalone.prototype.forceReconnect = function(newSession, flags) {
if (flags !== undefined) {
this.currentCallFlags = flags
}
if (!this.connected) {
if (!newSession) {
// Not connected, will do reconnect anyway.
return
}
this._forceReconnect = true
this.resumeId = null
this.signalingRoomJoined = null
return
}
this._forceReconnect = false
if (newSession) {
if (this.currentCallToken) {
// Mark this session as "no longer in the call".
this.leaveCall(this.currentCallToken, true)
}
this._isRejoiningConversationWithNewSession = true
rejoinConversation(this.currentRoomToken)
.then(response => {
store.commit('setInCall', {
token: this.currentRoomToken,
sessionId: this.nextcloudSessionId,
flags: PARTICIPANT.CALL_FLAG.DISCONNECTED,
})
this.nextcloudSessionId = response.data.ocs.data.sessionId
store.dispatch('setCurrentParticipant', response.data.ocs.data)
store.commit('setInCall', {
token: this.currentRoomToken,
sessionId: this.nextcloudSessionId,
flags: this.currentCallFlags || PARTICIPANT.CALL_FLAG.DISCONNECTED,
})
this.sendBye()
if (this.socket) {
// Trigger reconnect.
this.socket.close()
}
})
} else if (this.socket) {
// Trigger reconnect.
this.socket.close()
}
}
Signaling.Standalone.prototype.sendCallMessage = function(data) {
if (data.type === 'control') {
this.doSend({
type: 'control',
control: {
recipient: {
type: 'session',
sessionid: data.to,
},
data: data.payload,
},
})
return
}
this.doSend({
type: 'message',
message: {
recipient: {
type: 'session',
sessionid: data.to,
},
data,
},
})
}
Signaling.Standalone.prototype.sendRoomMessage = function(data) {
if (!this.currentCallToken) {
console.warn('Not in a room, not sending room message', data)
return
}
this.doSend({
type: 'message',
message: {
recipient: {
type: 'room',
},
data,
},
})
}
Signaling.Standalone.prototype.doSend = function(msg, callback) {
if ((!this.connected && msg.type !== 'hello') || this.socket === null) {
// Defer sending any messages until the hello response has been
// received and when the socket is open
this.pendingMessages.push([msg, callback])
return
}
if (callback) {
const id = this.id++
this.callbacks[id] = callback
msg.id = '' + id
}
if (OC.debug) {
console.debug('Sending', msg)
}
this.socket.send(JSON.stringify(msg))
}
Signaling.Standalone.prototype._getBackendUrl = function(baseURL = undefined) {
return generateOcsUrl('apps/spreed/api/v3/signaling/backend', {}, { baseURL })
}
Signaling.Standalone.prototype.sendHello = function() {
if (this.resumeId) {
console.debug('Trying to resume session', this.sessionId)
const msg = {
type: 'hello',
hello: {
version: '1.0',
resumeid: this.resumeId,
},
}
this.doSend(msg, this.helloResponseReceived.bind(this))
return
}
// Already reconnected with a new session.
this._forceReconnect = false