-
Notifications
You must be signed in to change notification settings - Fork 450
/
Copy pathmessagesStore.js
1423 lines (1270 loc) · 46.3 KB
/
messagesStore.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 cloneDeep from 'lodash/cloneDeep.js'
import Vue from 'vue'
import { showError } from '@nextcloud/dialogs'
import { t } from '@nextcloud/l10n'
import {
ATTENDEE,
CHAT,
CONVERSATION,
MESSAGE,
} from '../constants.ts'
import { hasTalkFeature } from '../services/CapabilitiesManager.ts'
import { fetchNoteToSelfConversation } from '../services/conversationsService.js'
import { EventBus } from '../services/EventBus.ts'
import {
deleteMessage,
editMessage,
updateLastReadMessage,
fetchMessages,
pollNewMessages,
getMessageContext,
postNewMessage,
postRichObjectToConversation,
} from '../services/messagesService.ts'
import { useCallViewStore } from '../stores/callView.ts'
import { useGuestNameStore } from '../stores/guestName.js'
import { usePollsStore } from '../stores/polls.ts'
import { useReactionsStore } from '../stores/reactions.js'
import { useSharedItemsStore } from '../stores/sharedItems.js'
import CancelableRequest from '../utils/cancelableRequest.js'
import { debugTimer } from '../utils/debugTimer.ts'
import { convertToUnix } from '../utils/formattedTime.ts'
/**
* Returns whether the given message contains a mention to self, directly
* or indirectly through a global mention.
*
* @param {object} context store context
* @param {object} message message object
* @return {boolean} true if the message contains a mention to self or all,
* false otherwise
*/
function hasMentionToSelf(context, message) {
if (!message.messageParameters) {
return false
}
for (const key in message.messageParameters) {
const param = message.messageParameters[key]
if (param.type === 'call') {
return true
}
if (param.type === 'guest'
&& context.getters.isActorGuest()
&& param.id === ('guest/' + context.getters.getActorId())
) {
return true
}
if (param.type === 'user'
&& context.getters.isActorUser()
&& param.id === context.getters.getUserId()
) {
return true
}
}
return false
}
/**
* Returns whether the given message is presented in DOM and visible (none of the ancestors has `display: none`)
*
* @param {string} messageId store context
* @return {boolean} whether the message is visible in the UI
*/
function isMessageVisible(messageId) {
const element = document.getElementById(`message_${messageId}`)
return element !== null && element.offsetParent !== null
}
const state = {
/**
* Map of conversation token to message list
*/
messages: {},
/**
* Map of conversation token to first known message id
*/
firstKnown: {},
/**
* Map of conversation token to last known message id
*/
lastKnown: {},
/**
* Cached last read message id for display.
*/
visualLastReadMessageId: {},
/**
* Loaded messages history parts of a conversation
*
* The messages list can still be empty due to message expiration,
* but if we ever loaded the history, we need to show an empty content
* instead of the loading animation
*/
loadedMessages: {},
/**
* Stores the cancel function returned by `cancelableFetchMessages`,
* which allows to cancel the previous request for old messages
* when quickly switching to a new conversation.
*/
cancelFetchMessages: null,
/**
* Stores the cancel function returned by `cancelableGetMessageContext`,
* which allows to cancel the previous request for the context messages
* when quickly switching to another conversation.
*/
cancelGetMessageContext: null,
/**
* Stores the cancel function returned by `cancelablePollNewMessages`,
* which allows to cancel the previous long polling request for new
* messages before making another one.
*/
cancelPollNewMessages: {},
/**
* Array of temporary message id to cancel function for the "postNewMessage" action
*/
cancelPostNewMessage: {},
}
const getters = {
/**
* Returns whether more messages can be loaded, which means that the current
* message list doesn't yet contain all future messages.
* If false, the next call to "pollNewMessages" will be blocking/long-polling.
*
* @param {object} state the state object.
* @param {object} getters the getters object.
* @return {boolean} true if more messages exist that needs loading, false otherwise
*/
hasMoreMessagesToLoad: (state, getters) => (token) => {
const conversation = getters.conversation(token)
if (!conversation) {
return false
}
return getters.getLastKnownMessageId(token) < conversation.lastMessage?.id
},
isMessagesListPopulated: (state) => (token) => {
return !!state.loadedMessages[token]
},
/**
* Gets the messages array
*
* @param {object} state the state object.
* @return {Array} the messages array (if there are messages in the store)
*/
messagesList: (state) => (token) => {
if (state.messages[token]) {
return Object.values(state.messages[token])
}
return []
},
message: (state) => (token, id) => {
if (state.messages[token]?.[id]) {
return state.messages[token][id]
}
return {}
},
getTemporaryReferences: (state) => (token, referenceId) => {
if (!state.messages[token]) {
return []
}
return Object.values(state.messages[token]).filter(message => {
return message.referenceId === referenceId
&& ('' + message.id).startsWith('temp-')
})
},
getFirstKnownMessageId: (state) => (token) => {
if (state.firstKnown[token] !== undefined) {
return state.firstKnown[token]
}
return null
},
getLastKnownMessageId: (state) => (token) => {
if (state.lastKnown[token]) {
return state.lastKnown[token]
}
return null
},
getVisualLastReadMessageId: (state) => (token) => {
if (state.visualLastReadMessageId[token]) {
return state.visualLastReadMessageId[token]
}
return null
},
getLastCallStartedMessageId: (state, getters) => (token) => {
return getters.messagesList(token).findLast((message) => message.systemMessage === 'call_started')?.id
},
getFirstDisplayableMessageIdAfterReadMarker: (state, getters) => (token, readMessageId) => {
if (!state.messages[token]) {
return null
}
return getters.messagesList(token).find(message => {
return message.id >= readMessageId
&& !String(message.id).startsWith('temp-')
&& message.systemMessage !== 'reaction'
&& message.systemMessage !== 'reaction_deleted'
&& message.systemMessage !== 'reaction_revoked'
&& message.systemMessage !== 'poll_voted'
&& message.systemMessage !== 'message_deleted'
&& message.systemMessage !== 'message_edited'
})?.id
},
getFirstDisplayableMessageIdBeforeReadMarker: (state, getters) => (token, readMessageId) => {
if (!state.messages[token]) {
return null
}
return getters.messagesList(token).findLast(message => {
return message.id < readMessageId
&& isMessageVisible(message.id)
&& !String(message.id).startsWith('temp-')
&& message.systemMessage !== 'reaction'
&& message.systemMessage !== 'reaction_deleted'
&& message.systemMessage !== 'reaction_revoked'
&& message.systemMessage !== 'poll_voted'
&& message.systemMessage !== 'message_deleted'
&& message.systemMessage !== 'message_edited'
})?.id
},
isSendingMessages: (state) => {
// the cancel handler only exists when a message is being sent
return Object.keys(state.cancelPostNewMessage).length !== 0
},
}
const mutations = {
setCancelFetchMessages(state, cancelFunction) {
state.cancelFetchMessages = cancelFunction
},
setCancelGetMessageContext(state, cancelFunction) {
state.cancelGetMessageContext = cancelFunction
},
setCancelPollNewMessages(state, { requestId, cancelFunction }) {
if (cancelFunction) {
Vue.set(state.cancelPollNewMessages, requestId, cancelFunction)
} else {
Vue.delete(state.cancelPollNewMessages, requestId)
}
},
setCancelPostNewMessage(state, { messageId, cancelFunction }) {
if (cancelFunction) {
Vue.set(state.cancelPostNewMessage, messageId, cancelFunction)
} else {
Vue.delete(state.cancelPostNewMessage, messageId)
}
},
/**
* Adds a message to the store.
*
* @param {object} state current store state;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.message message object;
*/
addMessage(state, { token, message }) {
if (!state.messages[token]) {
Vue.set(state.messages, token, {})
}
// TODO split adding and updating message in the store to different actions
// message.parent doesn't contain grand-parent, so we should keep it
// when updating message in store from new message.parent object
const storedMessage = state.messages[token][message.id]
const preparedMessage = !message.parent && storedMessage?.parent
? { ...message, parent: storedMessage.parent }
: message
Vue.set(state.messages[token], message.id, preparedMessage)
},
/**
* Deletes a message from the store.
*
* @param {object} state current store state;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.id message id;
*/
deleteMessage(state, { token, id }) {
if (state.messages[token][id]) {
Vue.delete(state.messages[token], id)
}
},
/**
* Deletes a message from the store.
*
* @param {object} state current store state;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {number} payload.id conversation token;
* @param {string} payload.placeholder Placeholder message until deleting finished
*/
markMessageAsDeleting(state, { token, id, placeholder }) {
if (!state.messages[token][id]) {
return
}
Vue.set(state.messages[token][id], 'messageType', 'comment_deleted')
Vue.set(state.messages[token][id], 'message', placeholder)
},
/**
* Adds a temporary message to the store.
*
* @param {object} state current store state;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.message message object;
*/
addTemporaryMessage(state, { token, message }) {
if (!state.messages[token]) {
Vue.set(state.messages, token, {})
}
Vue.set(state.messages[token], message.id, message)
},
/**
* Adds a temporary message to the store.
*
* @param {object} state current store state;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.id message id;
* @param {string|undefined} payload.uploadId the internal id of the upload;
* @param {string} payload.reason the reason the temporary message failed;
*/
markTemporaryMessageAsFailed(state, { token, id, uploadId = undefined, reason }) {
if (state.messages[token][id]) {
Vue.set(state.messages[token][id], 'sendingFailure', reason)
if (uploadId) {
Vue.set(state.messages[token][id], 'uploadId', uploadId)
}
}
},
/**
* @param {object} state current store state;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the first known chat message
*/
setFirstKnownMessageId(state, { token, id }) {
Vue.set(state.firstKnown, token, id)
},
/**
* @param {object} state current store state;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the last known chat message
*/
setLastKnownMessageId(state, { token, id }) {
Vue.set(state.lastKnown, token, id)
},
/**
* @param {object} state current store state;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the last read chat message
*/
setVisualLastReadMessageId(state, { token, id }) {
Vue.set(state.visualLastReadMessageId, token, id)
},
/**
* Deletes the messages entry from the store for the given conversation token.
*
* @param {object} state current store state
* @param {string} token Token of the conversation
*/
purgeMessagesStore(state, token) {
if (state.firstKnown[token]) {
Vue.delete(state.firstKnown, token)
}
if (state.lastKnown[token]) {
Vue.delete(state.lastKnown, token)
}
if (state.visualLastReadMessageId[token]) {
Vue.delete(state.visualLastReadMessageId, token)
}
if (state.messages[token]) {
Vue.delete(state.messages, token)
}
},
/**
* Clears the messages entry from the store for the given conversation token
* starting from defined id.
*
* @param {object} state current store state
* @param {object} payload payload;
* @param {string} payload.token the token of the conversation to be cleared;
* @param {number} payload.id the id of the message to be the first one after clear;
*/
clearMessagesHistory(state, { token, id }) {
Vue.set(state.firstKnown, token, id)
if (state.visualLastReadMessageId[token] && state.visualLastReadMessageId[token] < id) {
Vue.set(state.visualLastReadMessageId, token, id)
}
if (state.messages[token]) {
for (const messageId of Object.keys(state.messages[token])) {
if (+messageId < id) {
Vue.delete(state.messages[token], messageId)
}
}
}
},
// Increases reaction count for a particular reaction on a message
addReactionToMessage(state, { token, messageId, reaction }) {
const message = state.messages[token][messageId]
if (!message.reactions[reaction]) {
Vue.set(message.reactions, reaction, 0)
}
const reactionCount = message.reactions[reaction] + 1
Vue.set(message.reactions, reaction, reactionCount)
if (!message.reactionsSelf) {
Vue.set(message, 'reactionsSelf', [reaction])
} else {
Vue.set(message, 'reactionsSelf', message.reactionsSelf.concat(reaction))
}
},
loadedMessagesOfConversation(state, { token }) {
Vue.set(state.loadedMessages, token, true)
},
// Decreases reaction count for a particular reaction on a message
removeReactionFromMessage(state, { token, messageId, reaction }) {
const message = state.messages[token][messageId]
const reactionCount = message.reactions[reaction] - 1
if (reactionCount <= 0) {
Vue.delete(message.reactions, reaction)
} else {
Vue.set(message.reactions, reaction, reactionCount)
}
if (message.reactionsSelf?.includes(reaction)) {
Vue.set(message, 'reactionsSelf', message.reactionsSelf.filter(item => item !== reaction))
}
},
removeExpiredMessages(state, { token }) {
if (!state.messages[token]) {
return
}
const timestamp = convertToUnix(Date.now())
const messageIds = Object.keys(state.messages[token])
messageIds.forEach((messageId) => {
if (state.messages[token][messageId].expirationTimestamp
&& timestamp > state.messages[token][messageId].expirationTimestamp) {
Vue.delete(state.messages[token], messageId)
}
})
},
easeMessageList(state, { token, lastReadMessage }) {
if (!state.messages[token]) {
return
}
const messageIds = Object.keys(state.messages[token]).sort((a, b) => b - a)
if (messageIds.length < 300) {
return
}
// If lastReadMessage is rendered, keep it and +- 100 messages, otherwise only newest 200 messages
const lastReadMessageIndex = messageIds.findIndex(id => +id === lastReadMessage)
const messagesToRemove = lastReadMessageIndex !== -1
? messageIds.slice(lastReadMessageIndex + 99)
: messageIds.slice(199)
const newFirstKnown = messagesToRemove.shift()
const newMessagesToRemove = (lastReadMessageIndex !== -1 && lastReadMessageIndex > 100)
? messageIds.slice(0, lastReadMessageIndex - 99)
: []
const newLastKnown = newMessagesToRemove.pop()
messagesToRemove.forEach((messageId) => {
Vue.delete(state.messages[token], messageId)
})
newMessagesToRemove.forEach((messageId) => {
Vue.delete(state.messages[token], messageId)
})
if (state.firstKnown[token] && messagesToRemove.includes(state.firstKnown[token].toString())) {
Vue.set(state.firstKnown, token, +newFirstKnown)
}
if (state.lastKnown[token] && newMessagesToRemove.includes(state.lastKnown[token].toString())) {
Vue.set(state.lastKnown, token, +newLastKnown)
}
},
}
const actions = {
/**
* Adds message to the store.
*
* If the message has a parent message presented in the store, updates it as well.
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.message message object;
*/
processMessage(context, { token, message }) {
const sharedItemsStore = useSharedItemsStore()
if (message.systemMessage === 'message_deleted'
|| message.systemMessage === 'reaction'
|| message.systemMessage === 'reaction_deleted'
|| message.systemMessage === 'reaction_revoked'
|| message.systemMessage === 'message_edited') {
if (!message.parent) {
return
}
// If parent message is presented in store and is different, we update it
const parentInStore = context.getters.message(token, message.parent.id)
if (Object.keys(parentInStore).length !== 0 && JSON.stringify(parentInStore) !== JSON.stringify(message.parent)) {
context.commit('addMessage', { token, message: message.parent })
}
const reactionsStore = useReactionsStore()
if (message.systemMessage === 'message_deleted') {
reactionsStore.resetReactions(token, message.parent.id)
} else {
reactionsStore.processReaction(token, message)
}
if (message.systemMessage === 'message_edited' || message.systemMessage === 'message_deleted') {
// update conversation lastMessage, if it was edited or deleted
if (message.parent.id === context.getters.conversation(token).lastMessage?.id) {
context.dispatch('updateConversationLastMessage', { token, lastMessage: message.parent })
}
// Check existing messages for having a deleted / edited message as parent, and update them
context.getters.messagesList(token)
.filter(storedMessage => storedMessage.parent?.id === message.parent.id && JSON.stringify(storedMessage.parent) !== JSON.stringify(message.parent))
.forEach(storedMessage => {
context.commit('addMessage', { token, message: Object.assign({}, storedMessage, { parent: message.parent }) })
})
}
// Quit processing
return
}
if (message.referenceId) {
const tempMessages = context.getters.getTemporaryReferences(token, message.referenceId)
tempMessages.forEach(tempMessage => {
context.commit('deleteMessage', { token, id: tempMessage.id })
})
}
if (message.systemMessage === 'poll_voted') {
const pollsStore = usePollsStore()
pollsStore.debounceGetPollData({
token,
pollId: message.messageParameters.poll.id,
})
// Quit processing
return
}
if (message.systemMessage === 'poll_closed') {
const pollsStore = usePollsStore()
pollsStore.getPollData({
token,
pollId: message.messageParameters.poll.id,
})
}
if (message.systemMessage === 'history_cleared') {
context.commit('clearMessagesHistory', {
token,
id: message.id,
})
}
context.commit('addMessage', { token, message })
if (message.messageParameters && (message.messageType === 'comment' || message.messageType === 'voice-message')) {
if (message.messageParameters?.object || message.messageParameters?.file) {
// Handle voice messages, shares with single file, polls, deck cards, e.t.c
sharedItemsStore.addSharedItemFromMessage(token, message)
if (message.messageParameters?.object?.type === 'talk-poll') {
EventBus.emit('talk:poll-added', { token, message })
}
} else if (Object.keys(message.messageParameters).some(key => key.startsWith('file'))) {
// Handle shares with multiple files
}
}
},
/**
* Delete a message
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.id message id;
* @param {string} payload.placeholder Placeholder message until deleting finished
*/
async deleteMessage(context, { token, id, placeholder }) {
const message = Object.assign({}, context.getters.message(token, id))
context.commit('markMessageAsDeleting', { token, id, placeholder })
try {
const response = await deleteMessage({ token, id })
context.dispatch('processMessage', { token, message: response.data.ocs.data })
return response.status
} catch (error) {
// Restore the previous message state
context.commit('addMessage', { token, message })
throw error
}
},
/**
* Edit a message text
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token The conversation token
* @param {string} payload.messageId The message id
* @param {string} payload.updatedMessage The modified text of the message / file share caption
*/
async editMessage(context, { token, messageId, updatedMessage }) {
EventBus.emit('editing-message-processing', { messageId, value: true })
const message = Object.assign({}, context.getters.message(token, messageId))
context.commit('addMessage', {
token,
message: { ...message, message: updatedMessage },
})
try {
const response = await editMessage({
token,
messageId,
updatedMessage,
})
context.dispatch('processMessage', { token, message: response.data.ocs.data })
EventBus.emit('editing-message-processing', { messageId, value: false })
} catch (error) {
console.error(error)
// Restore the previous message state
context.commit('addMessage', { token, message })
EventBus.emit('editing-message-processing', { messageId, value: false })
throw error
}
},
/**
* Add a temporary message generated in the client to
* the store, these messages are deleted once the full
* message object is received from the server.
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.message message object;
*/
addTemporaryMessage(context, { token, message }) {
context.commit('addTemporaryMessage', { token, message })
// Update conversations list order
context.dispatch('updateConversationLastActive', token)
},
/**
* Mark a temporary message as failed to allow retrying it again
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.id message id;
* @param {string} payload.uploadId the internal id of the upload;
* @param {string} payload.reason the reason the temporary message failed;
*/
markTemporaryMessageAsFailed(context, { token, id, uploadId, reason }) {
context.commit('markTemporaryMessageAsFailed', { token, id, uploadId, reason })
},
/**
* Remove temporary message from store after receiving the parsed one from server
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token conversation token;
* @param {object} payload.id message id;
*/
removeTemporaryMessageFromStore(context, { token, id }) {
context.commit('deleteMessage', { token, id })
},
/**
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the first known chat message
*/
setFirstKnownMessageId(context, { token, id }) {
context.commit('setFirstKnownMessageId', { token, id })
},
/**
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the last known chat message
*/
setLastKnownMessageId(context, { token, id }) {
context.commit('setLastKnownMessageId', { token, id })
},
/**
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token Token of the conversation
* @param {string} data.id Id of the last read chat message
*/
setVisualLastReadMessageId(context, { token, id }) {
context.commit('setVisualLastReadMessageId', { token, id })
},
/**
* Deletes all messages of a conversation from the store only.
*
* @param {object} context default store context;
* @param {string} token the token of the conversation to be deleted;
*/
purgeMessagesStore(context, token) {
context.commit('purgeMessagesStore', token)
},
/**
* Clear all messages before defined id from the store only.
*
* @param {object} context default store context;
* @param {object} payload payload;
* @param {string} payload.token the token of the conversation to be cleared;
* @param {number} payload.id the id of the message to be the first one after clear;
*/
clearMessagesHistory(context, { token, id }) {
context.commit('clearMessagesHistory', { token, id })
},
/**
* Clears the last read message marker by moving it to the last message
* in the conversation.
*
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token the token of the conversation to be updated;
* @param {boolean} data.updateVisually whether to also clear the marker visually in the UI;
*/
async clearLastReadMessage(context, { token, updateVisually = false }) {
const conversation = context.getters.conversation(token)
if (hasTalkFeature(token, 'chat-read-last')) {
context.dispatch('updateLastReadMessage', { token, id: null, updateVisually })
return
}
// federated conversations don't proxy lastMessage id
if (!conversation?.lastMessage?.id) {
return
}
// set the id to the last message
context.dispatch('updateLastReadMessage', { token, id: conversation.lastMessage.id, updateVisually })
},
/**
* Updates the last read message in the store and also in the backend.
* Optionally also updated the marker visually in the UI if specified.
*
* @param {object} context default store context;
* @param {object} data the wrapping object;
* @param {string} data.token the token of the conversation to be updated;
* @param {number|null} data.id the id of the message on which to set the read marker;
* @param {boolean} data.updateVisually whether to also update the marker visually in the UI;
*/
async updateLastReadMessage(context, { token, id = 0, updateVisually = false }) {
const conversation = context.getters.conversation(token)
if (!conversation || conversation.lastReadMessage === id) {
return
}
if (id === 0) {
console.warn('updateLastReadMessage: should not set read marker with id=0')
return
}
// optimistic early commit to avoid indicator flickering
// skip for federated conversations
const idToUpdate = (id === null) ? conversation.lastMessage?.id : id
if (idToUpdate) {
context.dispatch('updateConversationLastReadMessage', { token, lastReadMessage: idToUpdate })
}
const visualIdToUpdate = idToUpdate ?? context.getters.messagesList(token).at(-1)?.id
if (updateVisually && visualIdToUpdate) {
context.commit('setVisualLastReadMessageId', { token, id: visualIdToUpdate })
}
if (context.getters.getUserId()) {
// only update on server side if there's an actual user, not guest
const response = await updateLastReadMessage(token, id)
context.dispatch('addConversation', response.data.ocs.data)
}
},
/**
* Fetches messages 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;
* @param {object} data.requestOptions request options;
* @param {string} data.lastKnownMessageId last known message id;
* @param {number} data.minimumVisible Minimum number of chat messages we want to load
* @param {boolean} data.includeLastKnown whether to include the last known message in the response;
* @param {number} [data.lookIntoFuture=0] direction of message fetch
*/
async fetchMessages(context, {
token,
lastKnownMessageId,
includeLastKnown,
requestOptions,
minimumVisible,
lookIntoFuture = CHAT.FETCH_OLD,
}) {
minimumVisible = (typeof minimumVisible === 'undefined') ? CHAT.MINIMUM_VISIBLE : minimumVisible
context.dispatch('cancelFetchMessages')
// Get a new cancelable request function and cancel function pair
const { request, cancel } = CancelableRequest(fetchMessages)
// Assign the new cancel function to our data value
context.commit('setCancelFetchMessages', cancel)
const response = await request({
token,
lastKnownMessageId,
includeLastKnown,
lookIntoFuture,
limit: CHAT.FETCH_LIMIT,
}, requestOptions)
let newestKnownMessageId = 0
if ('x-chat-last-common-read' in response.headers) {
const lastCommonReadMessage = parseInt(response.headers['x-chat-last-common-read'], 10)
context.dispatch('updateLastCommonReadMessage', {
token,
lastCommonReadMessage,
})
}
// Process each messages and adds it to the store
response.data.ocs.data.forEach(message => {
if (message.actorType === ATTENDEE.ACTOR_TYPE.GUESTS) {
// update guest display names cache
const guestNameStore = useGuestNameStore()
guestNameStore.addGuestName(message, { noUpdate: true })
}
context.dispatch('processMessage', { token, message })
newestKnownMessageId = Math.max(newestKnownMessageId, message.id)
if (message.systemMessage !== 'reaction'
&& message.systemMessage !== 'reaction_deleted'
&& message.systemMessage !== 'reaction_revoked'
&& message.systemMessage !== 'poll_voted'
) {
minimumVisible--
}
})
if (response.headers['x-chat-last-given']) {
const id = parseInt(response.headers['x-chat-last-given'], 10)
if (lookIntoFuture === CHAT.FETCH_NEW) {
context.dispatch('setLastKnownMessageId', { token, id })
} else {
context.dispatch('setFirstKnownMessageId', { token, id })
}
}
// For guests we also need to set the last known message id
// after the first grab of the history, otherwise they start loading
// the full history with fetchMessages().
if (includeLastKnown && newestKnownMessageId
&& !context.getters.getLastKnownMessageId(token)) {
context.dispatch('setLastKnownMessageId', {
token,
id: newestKnownMessageId,
})
}
context.commit('loadedMessagesOfConversation', { token })
if (minimumVisible > 0) {
debugTimer.tick(`${token} | fetch history`, 'first chunk')
const lastKnownMessageId = lookIntoFuture === CHAT.FETCH_NEW
? context.getters.getLastKnownMessageId(token)
: context.getters.getFirstKnownMessageId(token)
// There are not yet enough visible messages loaded, so fetch another chunk.
// This can happen when a lot of reactions or poll votings happen
return await context.dispatch('fetchMessages', {
token,
lastKnownMessageId,
includeLastKnown,
lookIntoFuture,
minimumVisible,
})
}
return response
},
/**
* Fetches messages 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;
* @param {number} data.messageId Message id to get the context for;
* @param {object} data.requestOptions request options;
* @param {number} data.minimumVisible Minimum number of chat messages we want to load
*/
async getMessageContext(context, { token, messageId, requestOptions, minimumVisible }) {
minimumVisible = (typeof minimumVisible === 'undefined') ? Math.floor(CHAT.MINIMUM_VISIBLE / 2) : minimumVisible
context.dispatch('cancelGetMessageContext')
// Get a new cancelable request function and cancel function pair
const { request, cancel } = CancelableRequest(getMessageContext)
// Assign the new cancel function to our data value
context.commit('setCancelGetMessageContext', cancel)
const response = await request({
token,
messageId,
limit: CHAT.FETCH_LIMIT / 2,
}, requestOptions)
let oldestKnownMessageId = messageId
let newestKnownMessageId = messageId
if ('x-chat-last-common-read' in response.headers) {
const lastCommonReadMessage = parseInt(response.headers['x-chat-last-common-read'], 10)
context.dispatch('updateLastCommonReadMessage', {
token,
lastCommonReadMessage,
})
}
// Process each messages and adds it to the store
response.data.ocs.data.forEach(message => {
if (message.actorType === ATTENDEE.ACTOR_TYPE.GUESTS) {
// update guest display names cache
const guestNameStore = useGuestNameStore()
guestNameStore.addGuestName(message, { noUpdate: true })
}