-
Notifications
You must be signed in to change notification settings - Fork 453
/
Copy pathparticipantsStore.js
1291 lines (1141 loc) · 41.7 KB
/
participantsStore.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 Hex from 'crypto-js/enc-hex.js'
import SHA1 from 'crypto-js/sha1.js'
import Vue from 'vue'
import { showError, showSuccess } from '@nextcloud/dialogs'
import { emit } from '@nextcloud/event-bus'
import { t } from '@nextcloud/l10n'
import { generateUrl } from '@nextcloud/router'
import { ATTENDEE, PARTICIPANT } from '../constants.js'
import { banActor } from '../services/banService.ts'
import {
joinCall,
leaveCall,
} from '../services/callsService.js'
import { hasTalkFeature, setRemoteCapabilities } from '../services/CapabilitiesManager.ts'
import { EventBus } from '../services/EventBus.ts'
import {
promoteToModerator,
demoteFromModerator,
removeAttendeeFromConversation,
resendInvitations,
sendCallNotification,
joinConversation,
leaveConversation,
removeCurrentUserFromConversation,
grantAllPermissionsToParticipant,
removeAllPermissionsFromParticipant,
setPermissions,
setTyping,
fetchParticipants,
} from '../services/participantsService.js'
import SessionStorage from '../services/SessionStorage.js'
import { talkBroadcastChannel } from '../services/talkBroadcastChannel.js'
import { useCallViewStore } from '../stores/callView.js'
import { useGuestNameStore } from '../stores/guestName.js'
import CancelableRequest from '../utils/cancelableRequest.js'
import { messagePleaseTryToReload } from '../utils/talkDesktopUtils.ts'
/**
* Emit global event for user status update with the status from a participant
*
* @param {object} participant - a participant object
*/
function emitUserStatusUpdated(participant) {
if (participant.actorType === ATTENDEE.ACTOR_TYPE.USERS) {
emit('user_status:status.updated', {
status: participant.status,
message: participant.statusMessage,
icon: participant.statusIcon,
clearAt: participant.statusClearAt,
userId: participant.actorId,
})
}
}
const state = {
attendees: {
},
peers: {
},
phones: {
},
inCall: {
},
joiningCall: {
},
connecting: {
},
connectionFailed: {
},
typing: {
},
speaking: {
},
// TODO: moved from callViewStore, separate to callExtras (with typing + speaking)
participantRaisedHands: {
},
initialised: {
},
/**
* Stores the cancel function returned by `cancelableFetchParticipants`,
* which allows to cancel the previous request for participants
* when quickly switching to a new conversation.
*/
cancelFetchParticipants: null,
speakingInterval: null,
}
const getters = {
isInCall: (state) => (token) => {
return !!(state.inCall[token] && Object.keys(state.inCall[token]).length > 0)
},
isJoiningCall: (state) => (token) => {
return !!(state.joiningCall[token] && Object.keys(state.joiningCall[token]).length > 0)
},
isConnecting: (state) => (token) => {
return !!(state.connecting[token] && Object.keys(state.connecting[token]).length > 0)
},
connectionFailed: (state) => (token) => {
return state.connectionFailed[token]
},
/**
* Gets the participants array.
*
* @param {object} state - the state object.
* @return {Array} the participants array (if there are participants in the
* store).
*/
participantsList: (state) => (token) => {
if (state.attendees[token]) {
return Object.values(state.attendees[token])
}
return []
},
/**
* Gets the array of external session ids.
*
* @param {object} state - the state object.
* @param {object} getters - the getters object.
* @param {object} rootState - the rootState object.
* @param {object} rootGetters - the rootGetters object.
* @return {Array} the typing session IDs array.
*/
externalTypingSignals: (state, getters, rootState, rootGetters) => (token) => {
if (!state.typing[token]) {
return []
}
return Object.keys(state.typing[token]).filter(sessionId => rootGetters.getSessionId() !== sessionId)
},
/**
* Gets the array of external session ids.
*
* @param {object} state - the state object.
* @param {object} getters - the getters object.
* @param {object} rootState - the rootState object.
* @param {object} rootGetters - the rootGetters object.
* @return {boolean} the typing status of actor.
*/
actorIsTyping: (state, getters, rootState, rootGetters) => {
if (!state.typing[rootGetters.getToken()]) {
return false
}
return Object.keys(state.typing[rootGetters.getToken()]).some(sessionId => rootGetters.getSessionId() === sessionId)
},
/**
* Gets the participants array filtered to include only those that are
* currently typing.
*
* @param {object} state - the state object.
* @param {object} getters - the getters object.
* @param {object} rootState - the rootState object.
* @param {object} rootGetters - the rootGetters object.
* @return {Array} the participants array (for registered users only).
*/
participantsListTyping: (state, getters, rootState, rootGetters) => (token) => {
if (!getters.externalTypingSignals(token).length) {
return []
}
return getters.participantsList(token).filter(attendee => {
// Check if participant's sessionId matches with any of sessionIds from signaling...
return getters.externalTypingSignals(token).some((sessionId) => attendee.sessionIds.includes(sessionId))
// ... and it's not the participant with same actorType and actorId as yourself
&& (attendee.actorType !== rootGetters.getActorType() || attendee.actorId !== rootGetters.getActorId())
})
},
/**
* Gets the speaking information for the participant.
*
* @param {object} state - the state object.
* param {number} attendeeId - attendee's ID for the participant in conversation.
* @return {object|undefined}
*/
getParticipantSpeakingInformation: (state) => (attendeeId) => {
return state.speaking[attendeeId]
},
participantRaisedHandList: (state) => {
return state.participantRaisedHands
},
getParticipantRaisedHand: (state) => (sessionIds) => {
for (let i = 0; i < sessionIds.length; i++) {
if (state.participantRaisedHands[sessionIds[i]]) {
// note: only the raised states are stored, so no need to confirm
return state.participantRaisedHands[sessionIds[i]]
}
}
return { state: false, timestamp: null }
},
/**
* Replaces the legacy getParticipant getter. Returns a callback function in which you can
* pass in the token and attendeeId as arguments to get the participant object.
*
* @param {*} state - the state object.
* param {string} token - the conversation token.
* param {number} attendeeId - Unique identifier for a participant in a conversation.
* @return {object} - The participant object.
*/
getParticipant: (state) => (token, attendeeId) => {
if (state.attendees[token] && state.attendees[token][attendeeId]) {
return state.attendees[token][attendeeId]
}
return null
},
/**
* Gets the initialisation status of the participants for a conversation.
* This is used to determine if the participants have been fetched for a
* conversation or not.
*
* @param {object} state - the state object.
* param {string} token - the conversation token.
* @return {boolean} - The initialisation status of the participants.
*/
participantsInitialised: (state) => (token) => {
return state.initialised[token]
},
/**
* Replaces the legacy getParticipant getter. Returns a callback function in which you can
* pass in the token and attendeeId as arguments to get the participant object.
*
* @param {*} state - the state object.
* param {string} token - the conversation token.
* param {number} attendeeId - Unique identifier for a participant in a conversation.
* @return {object|null} - The participant object.
*/
findParticipant: (state) => (token, participantIdentifier) => {
if (!state.attendees[token]) {
return null
}
if (participantIdentifier.attendeeId) {
return state.attendees[token][participantIdentifier.attendeeId] ?? null
}
// Fallback, sometimes actorId and actorType are set before the attendeeId
return Object.entries(state.attendees[token]).find(([attendeeId, attendee]) => {
return (participantIdentifier.actorType && participantIdentifier.actorId
&& attendee.actorType === participantIdentifier.actorType
&& attendee.actorId === participantIdentifier.actorId)
|| (participantIdentifier.sessionId && attendee.sessionIds.includes(participantIdentifier.sessionId))
})?.[1] ?? null
},
getPeer: (state) => (token, sessionId, userId) => {
if (state.peers[token]) {
if (Object.prototype.hasOwnProperty.call(state.peers[token], sessionId)) {
return state.peers[token][sessionId]
}
}
// Fallback to the participant list, if we have a user id that should be easy
if (state.attendees[token] && userId) {
let foundAttendee = null
Object.keys(state.attendees[token]).forEach((attendeeId) => {
if (state.attendees[token][attendeeId].actorType === ATTENDEE.ACTOR_TYPE.USERS
&& state.attendees[token][attendeeId].actorId === userId) {
foundAttendee = attendeeId
}
})
if (foundAttendee) {
return state.attendees[token][foundAttendee]
}
}
return {}
},
getPhoneStatus: (state) => (callId) => {
return state.phones[callId]?.state?.status
},
getPhoneMute: (state) => (callId) => {
return state.phones[callId]?.mute
},
participantsInCall: (state) => (token) => {
if (state.attendees[token]) {
return Object.values(state.attendees[token]).filter(attendee => attendee.inCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED).length
}
return 0
},
getParticipantBySessionId: (state) => (token, sessionId) => {
return Object.values(Object(state.attendees[token])).find(attendee => attendee.sessionIds.includes(sessionId))
},
}
const mutations = {
/**
* Add a message to the store.
*
* @param {object} state - current store state.
* @param {object} data - the wrapping object.
* @param {object} data.token - the token of the conversation.
* @param {object} data.participant - the participant.
*/
addParticipant(state, { token, participant }) {
if (!state.attendees[token]) {
Vue.set(state.attendees, token, {})
}
Vue.set(state.attendees[token], participant.attendeeId, participant)
},
updateParticipant(state, { token, attendeeId, updatedData }) {
if (state.attendees[token] && state.attendees[token][attendeeId]) {
state.attendees[token][attendeeId] = Object.assign({}, state.attendees[token][attendeeId], updatedData)
} else {
console.error('Error while updating the participant')
}
},
deleteParticipant(state, { token, attendeeId }) {
if (state.attendees[token] && state.attendees[token][attendeeId]) {
Vue.delete(state.attendees[token], attendeeId)
} else {
console.error('The conversation you are trying to purge doesn\'t exist')
}
},
setParticipantsInitialised(state, { token, initialised }) {
Vue.set(state.initialised, token, initialised)
},
setInCall(state, { token, sessionId, flags }) {
if (flags === PARTICIPANT.CALL_FLAG.DISCONNECTED) {
if (state.inCall[token] && state.inCall[token][sessionId]) {
Vue.delete(state.inCall[token], sessionId)
}
} else {
if (!state.inCall[token]) {
Vue.set(state.inCall, token, {})
}
Vue.set(state.inCall[token], sessionId, flags)
}
},
connectionFailed(state, { token, payload }) {
Vue.set(state.connectionFailed, token, payload)
},
clearConnectionFailed(state, token) {
Vue.delete(state.connectionFailed, token)
},
joiningCall(state, { token, sessionId, flags }) {
if (!state.joiningCall[token]) {
Vue.set(state.joiningCall, token, {})
}
Vue.set(state.joiningCall[token], sessionId, flags)
},
finishedJoiningCall(state, { token, sessionId }) {
if (state.joiningCall[token] && state.joiningCall[token][sessionId]) {
Vue.delete(state.joiningCall[token], sessionId)
if (!Object.keys(state.joiningCall[token]).length) {
Vue.delete(state.joiningCall, token)
}
}
},
connecting(state, { token, sessionId, flags }) {
if (!state.connecting[token]) {
Vue.set(state.connecting, token, {})
}
Vue.set(state.connecting[token], sessionId, flags)
},
finishedConnecting(state, { token, sessionId }) {
if (state.connecting[token] && state.connecting[token][sessionId]) {
Vue.delete(state.connecting[token], sessionId)
if (!Object.keys(state.connecting[token]).length) {
Vue.delete(state.connecting, token)
}
}
},
/**
* Sets the typing status of a participant in a conversation.
*
* Note that "updateParticipant" should not be called to add a "typing"
* property to an existing participant, as the participant would be reset
* when the participants are purged whenever they are fetched again.
* Similarly, "addParticipant" can not be called either to add a participant
* if it was not fetched yet but the signaling reported it as being typing,
* as the attendeeId would be unknown.
*
* @param {object} state - current store state.
* @param {object} data - the wrapping object.
* @param {string} data.token - the conversation that the participant is
* typing in.
* @param {string} data.sessionId - the Nextcloud session ID of the
* participant.
* @param {boolean} data.typing - whether the participant is typing or not.
* @param {number} data.expirationTimeout - id of timeout to watch for received signal expiration.
*/
setTyping(state, { token, sessionId, typing, expirationTimeout }) {
if (!state.typing[token]) {
Vue.set(state.typing, token, {})
}
if (state.typing[token][sessionId]) {
clearTimeout(state.typing[token][sessionId].expirationTimeout)
}
if (typing) {
Vue.set(state.typing[token], sessionId, { expirationTimeout })
} else {
Vue.delete(state.typing[token], sessionId)
}
},
/**
* Sets the speaking status of a participant in a conversation / call.
*
* Note that "updateParticipant" should not be called to add a "speaking"
* property to an existing participant, as the participant would be reset
* when the participants are purged whenever they are fetched again.
* Similarly, "addParticipant" can not be called either to add a participant
* if it was not fetched yet but the call model reported it as being
* speaking, as the attendeeId would be unknown.
*
* @param {object} state - current store state.
* @param {object} data - the wrapping object.
* @param {string} data.attendeeId - the attendee ID of the participant in conversation.
* @param {boolean} data.speaking - whether the participant is speaking or not
*/
setSpeaking(state, { attendeeId, speaking }) {
// create a dummy object for current call
if (!state.speaking[attendeeId]) {
Vue.set(state.speaking, attendeeId, { speaking, lastTimestamp: Date.now(), totalCountedTime: 0 })
}
state.speaking[attendeeId].speaking = speaking
},
/**
* Tracks the interval id to update speaking information for a current call.
*
* @param {object} state - current store state.
* @param {number} interval - interval id.
*/
setSpeakingInterval(state, interval) {
Vue.set(state, 'speakingInterval', interval)
},
/**
* Update speaking information for a participant.
*
* @param {object} state - current store state.
* @param {object} data - the wrapping object.
* @param {string} data.attendeeId - the attendee ID of the participant in conversation.
* @param {boolean} data.speaking - whether the participant is speaking or not
*/
updateTimeSpeaking(state, { attendeeId, speaking }) {
if (!state.speaking[attendeeId]) {
return
}
const currentTimestamp = Date.now()
const currentSpeakingState = state.speaking[attendeeId].speaking
if (!currentSpeakingState && !speaking) {
// false -> false, no updates
return
}
if (currentSpeakingState) {
// true -> false / true -> true, participant is still speaking or finished to speak, update total time
state.speaking[attendeeId].totalCountedTime += (currentTimestamp - state.speaking[attendeeId].lastTimestamp)
}
// false -> true / true -> false / true -> true, update timestamp of last check / signal
state.speaking[attendeeId].lastTimestamp = currentTimestamp
},
/**
* Purge the speaking information for recent call when local participant leaves call
* (including cases when the call ends for everyone).
*
* @param {object} state - current store state.
*/
purgeSpeakingStore(state) {
Vue.set(state, 'speaking', {})
if (state.speakingInterval) {
clearInterval(state.speakingInterval)
Vue.set(state, 'speakingInterval', null)
}
},
setParticipantHandRaised(state, { sessionId, raisedHand }) {
if (!sessionId) {
throw new Error('Missing or empty sessionId argument in call to setParticipantHandRaised')
}
if (raisedHand && raisedHand.state) {
Vue.set(state.participantRaisedHands, sessionId, raisedHand)
} else {
Vue.delete(state.participantRaisedHands, sessionId)
}
},
clearParticipantHandRaised(state) {
state.participantRaisedHands = {}
},
/**
* Purge a given conversation from the previously added participants.
*
* @param {object} state - current store state.
* @param {string} token - the conversation to purge.
*/
purgeParticipantsStore(state, token) {
if (state.attendees[token]) {
Vue.delete(state.attendees, token)
}
},
addPeer(state, { token, peer }) {
if (!state.peers[token]) {
Vue.set(state.peers, token, [])
}
Vue.set(state.peers[token], peer.sessionId, peer)
},
purgePeersStore(state, token) {
if (state.peers[token]) {
Vue.delete(state.peers, token)
}
},
setCancelFetchParticipants(state, cancelFunction) {
state.cancelFetchParticipants = cancelFunction
},
setPhoneState(state, { callid, value = {} }) {
if (!state.phones[callid]) {
Vue.set(state.phones, callid, { state: null, mute: 0 })
}
Vue.set(state.phones[callid], 'state', value)
},
setPhoneMute(state, { callid, value }) {
if (!state.phones[callid]) {
Vue.set(state.phones, callid, { state: null, mute: 0 })
}
Vue.set(state.phones[callid], 'mute', value)
},
deletePhoneState(state, callid) {
Vue.delete(state.phones, callid)
},
}
const actions = {
/**
* Add participant to the store.
*
* Only call this after purgeParticipantsStore, otherwise use addParticipantOnce.
*
* @param {object} context - default store context.
* @param {Function} context.commit - the contexts commit function.
* @param {object} data - the wrapping object.
* @param {string} data.token - the conversation to add the participant.
* @param {object} data.participant - the participant.
*/
addParticipant({ commit }, { token, participant }) {
commit('addParticipant', { token, participant })
},
/**
* Only add a participant when they are not there yet
*
* @param {object} context - default store context.
* @param {Function} context.commit - the contexts commit function.
* @param {object} context.getters - the contexts getters object.
* @param {object} data - the wrapping object.
* @param {string} data.token - the conversation to add the participant.
* @param {object} data.participant - the participant.
*/
addParticipantOnce({ commit, getters }, { token, participant }) {
const attendee = getters.findParticipant(token, participant)
if (!attendee) {
commit('addParticipant', { token, participant })
commit('setParticipantsInitialised', { token, initialised: false })
}
},
async promoteToModerator({ commit, getters }, { token, attendeeId }) {
const attendee = getters.getParticipant(token, attendeeId)
if (!attendee) {
return
}
await promoteToModerator(token, {
attendeeId,
})
// FIXME: don't promote already promoted or read resulting type from server response
const updatedData = {
participantType: attendee.participantType === PARTICIPANT.TYPE.GUEST ? PARTICIPANT.TYPE.GUEST_MODERATOR : PARTICIPANT.TYPE.MODERATOR,
}
commit('updateParticipant', { token, attendeeId, updatedData })
},
async demoteFromModerator({ commit, getters }, { token, attendeeId }) {
const attendee = getters.getParticipant(token, attendeeId)
if (!attendee) {
return
}
await demoteFromModerator(token, {
attendeeId,
})
// FIXME: don't demote already demoted, use server response instead
const updatedData = {
participantType: attendee.participantType === PARTICIPANT.TYPE.GUEST_MODERATOR ? PARTICIPANT.TYPE.GUEST : PARTICIPANT.TYPE.USER,
}
commit('updateParticipant', { token, attendeeId, updatedData })
},
async removeParticipant({ commit, getters }, { token, attendeeId, banParticipant, internalNote = '' }) {
const attendee = getters.getParticipant(token, attendeeId)
if (!attendee) {
return
}
if (hasTalkFeature(token, 'ban-v1') && banParticipant) {
try {
await banActor(token, {
actorId: attendee.actorId,
actorType: attendee.actorType,
internalNote,
})
showSuccess(t('spreed', 'Participant is banned successfully'))
} catch (error) {
showError(t('spreed', 'Error while banning the participant'))
throw error
}
} else {
await removeAttendeeFromConversation(token, attendeeId)
}
commit('deleteParticipant', { token, attendeeId })
},
/**
* Purges a given conversation from the previously added participants
*
* @param {object} context default store context;
* @param {Function} context.commit the contexts commit function.
* @param {string} token the conversation to purge;
*/
purgeParticipantsStore({ commit }, token) {
commit('purgeParticipantsStore', token)
},
addPeer({ commit }, { token, peer }) {
commit('addPeer', { token, peer })
},
purgePeersStore({ commit }, token) {
commit('purgePeersStore', token)
},
updateSessionId({ commit, getters }, { token, participantIdentifier, sessionId }) {
const attendee = getters.findParticipant(token, participantIdentifier)
if (!attendee) {
console.error('Participant not found for conversation', token, participantIdentifier)
return
}
const updatedData = {
sessionId,
inCall: PARTICIPANT.CALL_FLAG.DISCONNECTED,
}
commit('updateParticipant', { token, attendeeId: attendee.attendeeId, updatedData })
},
updateUser({ commit, getters }, { token, participantIdentifier, updatedData }) {
const attendee = getters.findParticipant(token, participantIdentifier)
if (!attendee) {
console.error('Participant not found for conversation', token, participantIdentifier)
return
}
commit('updateParticipant', { token, attendeeId: attendee.attendeeId, updatedData })
},
/**
* Fetches participants that belong to a particular conversation
* specified with its token.
*
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token the conversation token;
* @return {object|null}
*/
async fetchParticipants(context, { token }) {
// Cancel a previous request
context.dispatch('cancelFetchParticipants')
// Get a new cancelable request function and cancel function pair
const { request, cancel } = CancelableRequest(fetchParticipants)
// Assign the new cancel function to our data value
context.commit('setCancelFetchParticipants', cancel)
try {
const response = await request(token)
const hasUserStatuses = !!response.headers['x-nextcloud-has-user-statuses']
context.dispatch('patchParticipants', { token, newParticipants: response.data.ocs.data, hasUserStatuses })
if (context.state.initialised[token] === false) {
context.commit('setParticipantsInitialised', { token, initialised: true })
}
// Discard current cancel function
context.commit('setCancelFetchParticipants', null)
return response
} catch (exception) {
if (exception?.response?.status === 403) {
context.dispatch('fetchConversation', { token })
} else if (!CancelableRequest.isCancel(exception)) {
console.error(exception)
showError(t('spreed', 'An error occurred while fetching the participants'))
}
return null
}
},
/**
* Update participants in the store with specified token.
*
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token the conversation token;
* @param {object} data.newParticipants the participant array;
* @param {boolean} data.hasUserStatuses whether participants has user statuses or not;
*/
async patchParticipants(context, { token, newParticipants, hasUserStatuses }) {
const guestNameStore = useGuestNameStore()
const currentParticipants = context.state.attendees[token]
for (const attendeeId of Object.keys(Object(currentParticipants))) {
if (!newParticipants.some(participant => participant.attendeeId === +attendeeId)) {
context.commit('deleteParticipant', { token, attendeeId })
}
}
newParticipants.forEach(participant => {
if (context.state.attendees[token]?.[participant.attendeeId]) {
context.dispatch('updateParticipantIfHasChanged', { token, participant, hasUserStatuses })
} else {
context.dispatch('addParticipant', { token, participant })
if (hasUserStatuses) {
emitUserStatusUpdated(participant)
}
}
if (participant.participantType === PARTICIPANT.TYPE.GUEST
|| participant.participantType === PARTICIPANT.TYPE.GUEST_MODERATOR) {
guestNameStore.addGuestName({
token,
actorId: Hex.stringify(SHA1(participant.sessionIds[0])),
actorDisplayName: participant.displayName,
}, { noUpdate: false })
}
})
},
/**
* Update participant in store according to a new participant object
*
* @param {object} context store context
* @param {object} data the wrapping object;
* @param {string} data.token the conversation token;
* @param {object} data.participant the new participant object;
* @param {boolean} data.hasUserStatuses whether user status is enabled or not;
* @return {boolean} whether the participant was changed
*/
updateParticipantIfHasChanged(context, { token, participant, hasUserStatuses }) {
const { attendeeId } = participant
const oldParticipant = context.state.attendees[token][attendeeId]
// Check if any property has changed
const changedEntries = Object.entries(participant).filter(([key, value]) => {
// "sessionIds" is the only property with non-primitive (array) value and cannot be compared by ===
return key === 'sessionIds'
? JSON.stringify(oldParticipant[key]) !== JSON.stringify(value)
: oldParticipant[key] !== value
})
if (changedEntries.length === 0) {
return false
}
const updatedData = Object.fromEntries(changedEntries)
context.commit('updateParticipant', { token, attendeeId, updatedData })
// check if status-related properties have been changed
if (hasUserStatuses && changedEntries.some(([key]) => key.startsWith('status'))) {
emitUserStatusUpdated(participant)
}
return true
},
/**
* Cancels a previously running "fetchParticipants" action if applicable.
*
* @param {object} context default store context;
* @return {boolean} true if a request got cancelled, false otherwise
*/
cancelFetchParticipants(context) {
if (context.state.cancelFetchParticipants) {
context.state.cancelFetchParticipants('canceled')
context.commit('setCancelFetchParticipants', null)
return true
}
return false
},
async joinCall({ commit, getters, state }, { token, participantIdentifier, flags, silent, recordingConsent }) {
// SUMMARY: join call process
// There are 2 main steps to join a call:
// 1. Join the call (signaling-join-call)
// 2A. Wait for the users list (signaling-users-in-room) INTERNAL server event
// 2B. Wait for the users list (signaling-users-changed) EXTERNAL server event
// In case of failure, we receive a signaling-join-call-failed event
// Exception 1: We may receive the users list before the signaling-join-call event
// In this case, we use the isParticipantsListReceived flag to handle this case
// Exception 2: We may receive the users list in a second event of signaling-users-changed or signaling-users-in-room
// In this case, we always check if the list is the updated one (it has the current participant in the call)
const { sessionId } = participantIdentifier ?? {}
if (!sessionId) {
console.error('Trying to join call without sessionId')
return
}
const attendee = getters.findParticipant(token, participantIdentifier)
if (!attendee) {
console.error('Participant not found for conversation', token, participantIdentifier)
return
}
let isParticipantsListReceived = false
let connectingTimeout = null
commit('joiningCall', { token, sessionId, flags })
const handleJoinCall = ([token, flags]) => {
commit('setInCall', { token, sessionId, flags })
commit('finishedJoiningCall', { token, sessionId })
if (isParticipantsListReceived) {
finishConnecting()
} else {
commit('connecting', { token, sessionId, flags })
// Fallback in case we never receive the users list after joining the call
connectingTimeout = setTimeout(() => {
// If, by accident, we never receive a users list, just switch to
// "Waiting for others to join the call …" after some seconds.
finishConnecting()
}, 10000)
}
}
const handleJoinCallFailed = ([token, payload]) => {
finishConnecting()
commit('connectionFailed', {
token,
payload
})
commit('setInCall', {
token,
sessionId: participantIdentifier.sessionId,
flags: PARTICIPANT.CALL_FLAG.DISCONNECTED,
})
}
const handleParticipantsListReceived = (payload, key) => {
const participant = payload[0].find(p => p[key] === sessionId)
if (participant && participant.inCall !== PARTICIPANT.CALL_FLAG.DISCONNECTED) {
if (state.joiningCall[token]?.[sessionId]) {
isParticipantsListReceived = true
commit('connecting', { token, sessionId, flags })
return
}
finishConnecting()
}
}
const handleUsersInRoom = (payload) => {
handleParticipantsListReceived(payload, 'sessionId')
}
const handleUsersChanged = (payload) => {
handleParticipantsListReceived(payload, 'nextcloudSessionId')
}
const finishConnecting = () => {
commit('finishedConnecting', { token, sessionId })
commit('finishedJoiningCall', { token, sessionId })
EventBus.off('signaling-join-call', handleJoinCall)
EventBus.off('signaling-join-call-failed', handleJoinCallFailed)
EventBus.off('signaling-users-in-room', handleUsersInRoom)
EventBus.off('signaling-users-changed', handleUsersChanged)
clearTimeout(connectingTimeout)
}
EventBus.once('signaling-join-call', handleJoinCall)
EventBus.once('signaling-join-call-failed', handleJoinCallFailed)
EventBus.on('signaling-users-in-room', handleUsersInRoom)
EventBus.on('signaling-users-changed', handleUsersChanged)
try {
const actualFlags = await joinCall(token, flags, silent, recordingConsent)
const updatedData = {
inCall: actualFlags,
}
commit('updateParticipant', { token, attendeeId: attendee.attendeeId, updatedData })
const callViewStore = useCallViewStore()
callViewStore.handleJoinCall(getters.conversation(token))
} catch (e) {
console.error('Error while joining call: ', e)
}
},
async leaveCall({ commit, getters }, { token, participantIdentifier, all = false }) {
if (!participantIdentifier?.sessionId) {
console.error('Trying to leave call without sessionId')
}
const attendee = getters.findParticipant(token, participantIdentifier)
if (!attendee) {
console.error('Participant not found for conversation', token, participantIdentifier)
return
}
await leaveCall(token, all)
const updatedData = {
inCall: PARTICIPANT.CALL_FLAG.DISCONNECTED,
}
commit('updateParticipant', { token, attendeeId: attendee.attendeeId, updatedData })
// clear raised hands as they were specific to the call
commit('clearParticipantHandRaised')
commit('setInCall', {
token,
sessionId: participantIdentifier.sessionId,
flags: PARTICIPANT.CALL_FLAG.DISCONNECTED,
})
},
/**
* Resends email invitations for the given conversation.
* If no userId is set, send to all applicable participants.
*
* @param {object} _ - unused.
* @param {object} data - the wrapping object.
* @param {string} data.token - conversation token.
* @param {number} [data.attendeeId] - attendee id to target, or null for all.
* @param {string} [data.actorId] - if attendee is provided, the actorId (email) to show in the message.
*/
async resendInvitations(_, { token, attendeeId, actorId }) {
if (attendeeId) {
try {
await resendInvitations(token, attendeeId)
showSuccess(t('spreed', 'Invitation was sent to {actorId}', { actorId }))
} catch (error) {
showError(t('spreed', 'Could not send invitation to {actorId}', { actorId }))
}
} else {
try {
await resendInvitations(token)
showSuccess(t('spreed', 'Invitations sent'))
} catch (e) {
showError(t('spreed', 'Error occurred when sending invitations'))
}
}