Welcome to mirror list, hosted at ThFree Co, Russian Federation.

messagesStore.js « store « src - github.com/nextcloud/spreed.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 49e5c3b06801da1fd99073c1ca60983bf676a882 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
/**
 * @copyright Copyright (c) 2019 Marco Ambrosini <marcoambrosini@icloud.com>
 *
 * @author Marco Ambrosini <marcoambrosini@icloud.com>
 *
 * @license AGPL-3.0-or-later
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */
import Vue from 'vue'
import {
	deleteMessage,
	updateLastReadMessage,
	fetchMessages,
	lookForNewMessages,
	postNewMessage,
	postRichObjectToConversation,
	addReactionToMessage,
	removeReactionFromMessage,
} from '../services/messagesService.js'

import SHA256 from 'crypto-js/sha256.js'
import Hex from 'crypto-js/enc-hex.js'
import CancelableRequest from '../utils/cancelableRequest.js'
import { showError } from '@nextcloud/dialogs'
import {
	ATTENDEE,
	CHAT,
} from '../constants.js'

/**
 * 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.getActorType() === ATTENDEE.ACTOR_TYPE.GUESTS
			&& param.id === ('guest/' + context.getters.getActorId())
		) {
			return true
		}
		if (param.type === 'user'
			&& context.getters.getActorType() === ATTENDEE.ACTOR_TYPE.USERS
			&& param.id === context.getters.getUserId()
		) {
			return true
		}
	}

	return false
}

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 `cancelableLookForNewMessages`,
	 * which allows to cancel the previous long polling request for new
	 * messages before making another one.
	 */
	cancelLookForNewMessages: {},
	/**
	 * 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 "lookForNewMessages" 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
	},

	isMessageListPopulated: (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]) {
			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
	},

	getFirstDisplayableMessageIdAfterReadMarker: (state, getters) => (token, readMessageId) => {
		if (!state.messages[token]) {
			return null
		}

		const displayableMessages = getters.messagesList(token).filter(message => {
			return message.id >= readMessageId
				&& !('' + message.id).startsWith('temp-')
		})

		if (displayableMessages.length) {
			return displayableMessages.shift().id
		}

		return null
	},

	isSendingMessages: (state) => {
		// the cancel handler only exists when a message is being sent
		return Object.keys(state.cancelPostNewMessage).length !== 0
	},

	// Returns true if the message has reactions
	hasReactions: (state) => (token, messageId) => {
		return Object.keys(state.messages[token][messageId].reactions).length !== 0
	},
}

const mutations = {
	setCancelFetchMessages(state, cancelFunction) {
		state.cancelFetchMessages = cancelFunction
	},

	setCancelLookForNewMessages(state, { requestId, cancelFunction }) {
		if (cancelFunction) {
			Vue.set(state.cancelLookForNewMessages, requestId, cancelFunction)
		} else {
			Vue.delete(state.cancelLookForNewMessages, 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} message the message;
	 */
	addMessage(state, message) {
		if (!state.messages[message.token]) {
			Vue.set(state.messages, message.token, {})
		}
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token], message.id,
				Object.assign(state.messages[message.token][message.id], message)
			)
		} else {
			Vue.set(state.messages[message.token], message.id, message)
		}
	},
	/**
	 * Deletes a message from the store.
	 *
	 * @param {object} state current store state;
	 * @param {object} message the message;
	 */
	deleteMessage(state, message) {
		if (state.messages[message.token][message.id]) {
			Vue.delete(state.messages[message.token], message.id)
		}
	},

	/**
	 * Deletes a message from the store.
	 *
	 * @param {object} state current store state;
	 * @param {object} data the wrapping object;
	 * @param {object} data.message the message;
	 * @param {string} data.placeholder Placeholder message until deleting finished
	 */
	markMessageAsDeleting(state, { message, placeholder }) {
		Vue.set(state.messages[message.token][message.id], 'messageType', 'comment_deleted')
		Vue.set(state.messages[message.token][message.id], 'message', placeholder)
	},
	/**
	 * Adds a temporary message to the store.
	 *
	 * @param {object} state current store state;
	 * @param {object} message the temporary message;
	 */
	addTemporaryMessage(state, message) {
		if (!state.messages[message.token]) {
			Vue.set(state.messages, message.token, {})
		}
		Vue.set(state.messages[message.token], message.id, message)
	},

	/**
	 * Adds a temporary message to the store.
	 *
	 * @param {object} state current store state;
	 * @param {object} data the wrapping object;
	 * @param {object} data.message the temporary message;
	 * @param {string} data.reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(state, { message, reason }) {
		if (state.messages[message.token][message.id]) {
			Vue.set(state.messages[message.token][message.id], 'sendingFailure', reason)
		}
	},

	/**
	 * @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
	 */
	deleteMessages(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)
		}
	},

	// Increases reaction count for a particular reaction on a message
	addReactionToMessage(state, { token, messageId, reaction }) {
		if (!state.messages[token][messageId].reactions[reaction]) {
			Vue.set(state.messages[token][messageId].reactions, reaction, 0)
		}
		const reactionCount = state.messages[token][messageId].reactions[reaction] + 1
		Vue.set(state.messages[token][messageId].reactions, reaction, reactionCount)

		if (!state.messages[token][messageId].reactionsSelf) {
			Vue.set(state.messages[token][messageId], 'reactionsSelf', [reaction])
		} else {
			state.messages[token][messageId].reactionsSelf.push(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 reactionCount = state.messages[token][messageId].reactions[reaction] - 1
		Vue.set(state.messages[token][messageId].reactions, reaction, reactionCount)
		if (state.messages[token][messageId].reactions[reaction] <= 0) {
			Vue.delete(state.messages[token][messageId].reactions, reaction)
		}

		if (state.messages[token][messageId].reactionsSelf) {
			const i = state.messages[token][messageId].reactionsSelf.indexOf(reaction)
			if (i !== -1) {
				Vue.delete(state.messages[token][messageId], 'reactionsSelf', i)
			}
		}
	},

	removeExpiredMessages(state, { token }) {
		if (!state.messages[token]) {
			return
		}

		const timestamp = (new Date()) / 1000
		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 }) {
		if (!state.messages[token]) {
			return
		}

		const messageIds = Object.keys(state.messages[token])
		if (messageIds.length < 300) {
			return
		}

		const messagesToRemove = messageIds.sort().reverse().slice(199)
		const newFirstKnown = messagesToRemove.shift()

		messagesToRemove.forEach((messageId) => {
			Vue.delete(state.messages[token], messageId)
		})

		if (state.firstKnown[token] && messagesToRemove.includes(state.firstKnown[token])) {
			Vue.set(state.firstKnown, token, newFirstKnown)
		}
	},
}

const actions = {

	/**
	 * Adds message to the store.
	 *
	 * If the message has a parent message object,
	 * first it adds the parent to the store.
	 *
	 * @param {object} context default store context;
	 * @param {object} message the message;
	 */
	processMessage(context, message) {
		if (message.parent) {
			context.commit('addMessage', message.parent)
			message.parent = message.parent.id
		}

		if (message.referenceId) {
			const tempMessages = context.getters.getTemporaryReferences(message.token, message.referenceId)
			tempMessages.forEach(tempMessage => {
				context.commit('deleteMessage', tempMessage)
			})
		}

		if (message.systemMessage === 'reaction'
			|| message.systemMessage === 'reaction_deleted'
			|| message.systemMessage === 'reaction_revoked') {
			context.commit('resetReactions', {
				token: message.token,
				messageId: message.parent,
			})
		}

		if (message.systemMessage === 'poll_voted') {
			context.dispatch('debounceGetPollData', {
				token: message.token,
				pollId: message.messageParameters.poll.id,
			})
		}

		if (message.systemMessage === 'poll_closed') {
			context.dispatch('getPollData', {
				token: message.token,
				pollId: message.messageParameters.poll.id,
			})
		}

		// Filter out some system messages
		if (message.systemMessage !== 'reaction'
			&& message.systemMessage !== 'reaction_deleted'
			&& message.systemMessage !== 'reaction_revoked'
			&& message.systemMessage !== 'poll_voted'
		) {
			context.commit('addMessage', message)
		}

		 if ((message.messageType === 'comment' && message.message === '{file}' && message.messageParameters?.file)
			|| (message.messageType === 'comment' && message.message === '{object}' && message.messageParameters?.object)) {
			context.dispatch('addSharedItemMessage', {
				message,
			})
		 }
	},

	/**
	 * Delete a message
	 *
	 * @param {object} context default store context;
	 * @param {object} data the wrapping object;
	 * @param {object} data.message the message to be deleted;
	 * @param {string} data.placeholder Placeholder message until deleting finished
	 */
	async deleteMessage(context, { message, placeholder }) {
		const messageObject = Object.assign({}, context.getters.message(message.token, message.id))
		context.commit('markMessageAsDeleting', { message, placeholder })

		let response
		try {
			response = await deleteMessage(message)
		} catch (e) {
			// Restore the previous message state
			context.commit('addMessage', messageObject)
			throw e
		}

		const systemMessage = response.data.ocs.data
		if (systemMessage.parent) {
			context.commit('addMessage', systemMessage.parent)
			systemMessage.parent = systemMessage.parent.id
		}

		context.commit('addMessage', systemMessage)

		return response.status
	},

	/**
	 * Creates a temporary message ready to be posted, based
	 * on the message to be replied and the current actor
	 *
	 * @param {object} context default store context;
	 * @param {object} data the wrapping object;
	 * @param {string} data.text message string;
	 * @param {string} data.token conversation token;
	 * @param {string} data.uploadId upload id;
	 * @param {number} data.index index;
	 * @param {object} data.file file to upload;
	 * @param {string} data.localUrl local URL of file to upload;
	 * @param {boolean} data.isVoiceMessage whether the temporary file is a voice message
	 * @return {object} temporary message
	 */
	createTemporaryMessage(context, { text, token, uploadId, index, file, localUrl, isVoiceMessage }) {
		const messageToBeReplied = context.getters.getMessageToBeReplied(token)
		const date = new Date()
		let tempId = 'temp-' + date.getTime()
		const messageParameters = {}
		if (file) {
			tempId += '-' + uploadId + '-' + Math.random()
			messageParameters.file = {
				type: 'file',
				file,
				mimetype: file.type,
				id: tempId,
				name: file.newName || file.name,
				// index, will be the id from now on
				uploadId,
				localUrl,
				index,
			}
		}

		const message = Object.assign({}, {
			id: tempId,
			actorId: context.getters.getActorId(),
			actorType: context.getters.getActorType(),
			actorDisplayName: context.getters.getDisplayName(),
			timestamp: 0,
			systemMessage: '',
			messageType: isVoiceMessage ? 'voice-message' : '',
			message: text,
			messageParameters,
			token,
			isReplyable: false,
			sendingFailure: '',
			reactions: {},
			referenceId: Hex.stringify(SHA256(tempId)),
		})

		/**
		 * If the current message is a quote-reply message, add the parent key to the
		 * temporary message object.
		 */
		if (messageToBeReplied) {
			message.parent = messageToBeReplied.id
		}
		return message
	},

	/**
	 * 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} message the temporary message;
	 */
	addTemporaryMessage(context, message) {
		context.commit('addTemporaryMessage', message)
		// Update conversations list order
		context.dispatch('updateConversationLastActive', message.token)
	},

	/**
	 * Mark a temporary message as failed to allow retrying it again
	 *
	 * @param {object} context default store context;
	 * @param {object} data the wrapping object;
	 * @param {object} data.message the temporary message;
	 * @param {string} data.reason the reason the temporary message failed;
	 */
	markTemporaryMessageAsFailed(context, { message, reason }) {
		context.commit('markTemporaryMessageAsFailed', { message, reason })
	},

	/**
	 * Remove temporary message from store after receiving the parsed one from server
	 *
	 * @param {object} context default store context;
	 * @param {object} message the temporary message;
	 */
	removeTemporaryMessageFromStore(context, message) {
		context.commit('deleteMessage', message)
	},

	/**
	 * @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;
	 */
	deleteMessages(context, token) {
		context.commit('deleteMessages', token)
	},

	/**
	 * 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 {object} 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.conversations[token]
		if (!conversation || !conversation.lastMessage) {
			return
		}
		// set the id to the last message
		context.dispatch('updateLastReadMessage', { token, id: conversation.lastMessage.id, updateVisually })
		context.dispatch('markConversationRead', token)
	},

	/**
	 * 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 {object} data.token the token of the conversation to be updated;
	 * @param {number} 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.conversations[token]
		if (!conversation || conversation.lastReadMessage === id) {
			return
		}

		if (id === 0) {
			console.warn('updateLastReadMessage: should not set read marker with id=0')
		}

		// optimistic early commit to avoid indicator flickering
		context.dispatch('updateConversationLastReadMessage', { token, lastReadMessage: id })
		if (updateVisually) {
			context.commit('setVisualLastReadMessageId', { token, id })
		}

		if (context.getters.getUserId()) {
			// only update on server side if there's an actual user, not guest
			await updateLastReadMessage(token, id)
		}
	},

	/**
	 * 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;
	 */
	async fetchMessages(context, { token, lastKnownMessageId, includeLastKnown, requestOptions, minimumVisible }) {
		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,
			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
				context.dispatch('setGuestNameIfEmpty', message)
			}
			context.dispatch('processMessage', 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']) {
			context.dispatch('setFirstKnownMessageId', {
				token,
				id: parseInt(response.headers['x-chat-last-given'], 10),
			})
		}

		// 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) {
			// 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: context.getters.getFirstKnownMessageId(token),
				includeLastKnown,
				minimumVisible,
			})
		}

		return response
	},

	/**
	 * Cancels a previously running "fetchMessages" action if applicable.
	 *
	 * @param {object} context default store context;
	 * @return {boolean} true if a request got cancelled, false otherwise
	 */
	cancelFetchMessages(context) {
		if (context.state.cancelFetchMessages) {
			context.state.cancelFetchMessages('canceled')
			context.commit('setCancelFetchMessages', null)
			return true
		}
		return false
	},

	/**
	 * Fetches newly created messages that belong to a particular conversation
	 * specified with its token.
	 *
	 * This call will long-poll when hasMoreMessagesToLoad() returns false.
	 *
	 * @param {object} context default store context;
	 * @param {object} data the wrapping object;
	 * @param {string} data.token The conversation token;
	 * @param {string} data.requestId id to identify request uniquely
	 * @param {object} data.requestOptions request options;
	 * @param {number} data.lastKnownMessageId The id of the last message in the store.
	 */
	async lookForNewMessages(context, { token, lastKnownMessageId, requestId, requestOptions }) {
		context.dispatch('cancelLookForNewMessages', { requestId })

		// Get a new cancelable request function and cancel function pair
		const { request, cancel } = CancelableRequest(lookForNewMessages)

		// Assign the new cancel function to our data value
		context.commit('setCancelLookForNewMessages', { cancelFunction: cancel, requestId })

		const response = await request({ token, lastKnownMessageId }, requestOptions)
		context.commit('setCancelLookForNewMessages', { requestId })

		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,
			})
		}

		const conversation = context.getters.conversation(token)
		let countNewMessages = 0
		let hasNewMention = conversation.unreadMention
		let lastMessage = null
		// 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,
				// force in case the display name has changed since
				// the last fetch
				context.dispatch('forceGuestName', message)
			}
			context.dispatch('processMessage', message)
			if (!lastMessage || message.id > lastMessage.id) {
				if (!message.systemMessage) {
					countNewMessages++

					// parse mentions data to update "conversation.unreadMention",
					// if needed
					if (!hasNewMention && hasMentionToSelf(context, message)) {
						hasNewMention = true
					}
				}
				lastMessage = message
			}

			// Overwrite the conversation.hasCall property so people can join
			// after seeing the message in the chat.
			if (conversation && conversation.lastMessage && message.id > conversation.lastMessage.id) {
				if (message.systemMessage === 'call_started') {
					context.dispatch('overwriteHasCallByChat', {
						token,
						hasCall: true,
					})
				} else if (message.systemMessage === 'call_ended'
					|| message.systemMessage === 'call_ended_everyone'
					|| message.systemMessage === 'call_missed') {
					context.dispatch('overwriteHasCallByChat', {
						token,
						hasCall: false,
					})
				}
			}

			// in case we encounter an already read message, reset the counter
			// this is probably unlikely to happen unless one starts browsing from
			// an earlier page and scrolls down
			if (conversation.lastReadMessage === message.id) {
				// discard counters
				countNewMessages = 0
				hasNewMention = conversation.unreadMention
			}
		})

		context.dispatch('setLastKnownMessageId', {
			token,
			id: parseInt(response.headers['x-chat-last-given'], 10),
		})

		if (conversation && conversation.lastMessage && lastMessage.id > conversation.lastMessage.id) {
			context.dispatch('updateConversationLastMessage', {
				token,
				lastMessage,
			})

			// only increase the counter if the conversation store was out of sync with the message list
			if (countNewMessages > 0) {
				context.commit('updateUnreadMessages', {
					token,
					unreadMessages: conversation.unreadMessages + countNewMessages,
					// only update the value if it's been changed to true
					unreadMention: conversation.unreadMention !== hasNewMention ? hasNewMention : undefined,
				})
			}
		}

		context.commit('loadedMessagesOfConversation', { token })

		return response
	},

	/**
	 * Cancels a previously running "lookForNewMessages" action if applicable.
	 *
	 * @param {object} context default store context;
	 * @param {string} requestId request id
	 * @return {boolean} true if a request got cancelled, false otherwise
	 */
	cancelLookForNewMessages(context, { requestId }) {
		if (context.state.cancelLookForNewMessages[requestId]) {
			context.state.cancelLookForNewMessages[requestId]('canceled')
			context.commit('setCancelLookForNewMessages', { requestId })
			return true
		}
		return false
	},

	/**
	 * Sends the given temporary message to the server.
	 *
	 * @param {object} context default store context;
	 * @param {object} data Passed in parameters
	 * @param {object} data.temporaryMessage temporary message, must already have been added to messages list.
	 * @param {object} data.options post request options.
	 */
	async postNewMessage(context, { temporaryMessage, options }) {
		const { request, cancel } = CancelableRequest(postNewMessage)
		context.commit('setCancelPostNewMessage', { messageId: temporaryMessage.id, cancelFunction: cancel })

		const timeout = setTimeout(() => {
			context.dispatch('cancelPostNewMessage', { messageId: temporaryMessage.id })
			context.dispatch('markTemporaryMessageAsFailed', {
				message: temporaryMessage,
				reason: 'timeout',
			})
		}, 30000)

		try {
			const response = await request(temporaryMessage, options)
			clearTimeout(timeout)
			context.commit('setCancelPostNewMessage', { messageId: temporaryMessage.id, cancelFunction: null })

			if ('x-chat-last-common-read' in response.headers) {
				const lastCommonReadMessage = parseInt(response.headers['x-chat-last-common-read'], 10)
				context.dispatch('updateLastCommonReadMessage', {
					token: temporaryMessage.token,
					lastCommonReadMessage,
				})
			}

			// If successful, deletes the temporary message from the store
			context.dispatch('removeTemporaryMessageFromStore', temporaryMessage)

			const message = response.data.ocs.data
			// And adds the complete version of the message received
			// by the server
			context.dispatch('processMessage', message)

			const conversation = context.getters.conversation(temporaryMessage.token)

			// update lastMessage and lastReadMessage
			// do it conditionally because there could have been more messages appearing concurrently
			if (conversation && conversation.lastMessage && message.id > conversation.lastMessage.id) {
				context.dispatch('updateConversationLastMessage', {
					token: conversation.token,
					lastMessage: message,
				})
			}
			if (conversation && message.id > conversation.lastReadMessage) {
				// no await to make it async
				context.dispatch('updateLastReadMessage', {
					token: conversation.token,
					id: message.id,
					updateVisually: true,
				})
			}

			return response
		} catch (error) {
			if (timeout) {
				clearTimeout(timeout)
			}
			context.commit('setCancelPostNewMessage', { messageId: temporaryMessage.id, cancelFunction: null })

			let statusCode = null
			console.error(`error while submitting message ${error}`, error)
			if (error.isAxiosError) {
				statusCode = error?.response?.status
			}

			// FIXME: don't use showError here but set a flag
			// somewhere that makes Vue trigger the error message

			// 403 when room is read-only, 412 when switched to lobby mode
			if (statusCode === 403) {
				showError(t('spreed', 'No permission to post messages in this conversation'))
				context.dispatch('markTemporaryMessageAsFailed', {
					message: temporaryMessage,
					reason: 'read-only',
				})
			} else if (statusCode === 412) {
				showError(t('spreed', 'No permission to post messages in this conversation'))
				context.dispatch('markTemporaryMessageAsFailed', {
					message: temporaryMessage,
					reason: 'lobby',
				})
			} else {
				showError(t('spreed', 'Could not post message: {errorMessage}', { errorMessage: error.message || error }))
				context.dispatch('markTemporaryMessageAsFailed', {
					message: temporaryMessage,
					reason: 'other',
				})
			}
			throw error
		}
	},

	/**
	 * Cancels a previously running "postNewMessage" action if applicable.
	 *
	 * @param {object} context default store context;
	 * @param {string} messageId the message id for which to cancel;
	 * @return {boolean} true if a request got cancelled, false otherwise
	 */
	cancelPostNewMessage(context, { messageId }) {
		if (context.state.cancelPostNewMessage[messageId]) {
			context.state.cancelPostNewMessage[messageId]('canceled')
			context.commit('setCancelPostNewMessage', { messageId, cancelFunction: null })
			return true
		}
		return false
	},

	/**
	 * Posts a simple text message to a room
	 *
	 * @param {object} context default store context;
	 * will be forwarded;
	 * @param {object} data the wrapping object;
	 * @param {object} data.messageToBeForwarded the message object;
	 */
	async forwardMessage(context, { messageToBeForwarded }) {
		const response = await postNewMessage(messageToBeForwarded, { silent: false })
		return response
	},

	/**
	 * Posts a simple text message to a room
	 *
	 * @param {object} context default store context;
	 * will be forwarded;
	 * @param {object} data the wrapping object;
	 * @param {string} data.token token of the target conversation
	 * @param {object} data.richObject the rich object;
	 */
	async forwardRichObject(context, { token, richObject }) {
		const response = await postRichObjectToConversation(token, richObject)
		return response
	},

	/**
	 * Adds a single reaction to a message for the current user.
	 *
	 * @param {*} context the context object
	 * @param {*} param1 conversation token, message id and selected emoji (string)
	 */
	async addReactionToMessage(context, { token, messageId, selectedEmoji }) {
		try {
			context.commit('addReactionToMessage', {
				token,
				messageId,
				reaction: selectedEmoji,
			})
			// The response return an array with the reaction details for this message
			const response = await addReactionToMessage(token, messageId, selectedEmoji)
			// We replace the reaction details in the reactions store and wipe the old
			// values
			context.dispatch('updateReactions', {
				token,
				messageId,
				reactionsDetails: response.data.ocs.data,
			})
		} catch (error) {
			// Restore the previous state if the request fails
			context.commit('removeReactionFromMessage', {
				token,
				messageId,
				reaction: selectedEmoji,
			})
			console.error(error)
			showError(t('spreed', 'Failed to add reaction'))
		}
	},

	/**
	 * Removes a single reaction from a message for the current user.
	 *
	 * @param {*} context the context object
	 * @param {*} param1 conversation token, message id and selected emoji (string)
	 */
	async removeReactionFromMessage(context, { token, messageId, selectedEmoji }) {
		try {
			context.commit('removeReactionFromMessage', {
				token,
				messageId,
				reaction: selectedEmoji,
			})
			// The response return an array with the reaction details for this message
			const response = await removeReactionFromMessage(token, messageId, selectedEmoji)
			// We replace the reaction details in the reactions store and wipe the old
			// values
			context.dispatch('updateReactions', {
				token,
				messageId,
				reactionsDetails: response.data.ocs.data,
			})
		} catch (error) {
			// Restore the previous state if the request fails
			context.commit('addReactionToMessage', {
				token,
				messageId,
				reaction: selectedEmoji,
			})
			console.error(error)
			showError(t('spreed', 'Failed to remove reaction'))
		}
	},

	async removeExpiredMessages(context, { token }) {
		context.commit('removeExpiredMessages', { token })
	},

	async easeMessageList(context, { token }) {
		context.commit('easeMessageList', { token })
	},
}

export default { state, mutations, getters, actions }