-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathSBUGroupChannelViewModel.swift
831 lines (703 loc) · 32.8 KB
/
SBUGroupChannelViewModel.swift
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
//
// SBUGroupChannelViewModel.swift
// SendbirdUIKit
//
// Created by Hoon Sung on 2021/02/15.
// Copyright © 2021 Sendbird, Inc. All rights reserved.
//
import Foundation
import SendbirdChatSDK
import simd
public protocol SBUGroupChannelViewModelDataSource: SBUBaseChannelViewModelDataSource {
/// Asks to data source to return the array of index path that represents starting point of channel.
/// - Parameters:
/// - viewModel: `SBUGroupChannelViewModel` object.
/// - channel: `GroupChannel` object from `viewModel`
/// - Returns: The array of `IndexPath` object representing starting point.
func groupChannelViewModel(
_ viewModel: SBUGroupChannelViewModel,
startingPointIndexPathsForChannel channel: GroupChannel?
) -> [IndexPath]?
}
public protocol SBUGroupChannelViewModelDelegate: SBUBaseChannelViewModelDelegate {
/// Called when the channel has received mentional member list. Please refer to `loadSuggestedMentions(with:)` in `SBUGroupChannelViewModel`.
/// - Parameters:
/// - viewModel: `SBUGroupChannelViewModel` object.
/// - members: Mentional members
func groupChannelViewModel(
_ viewModel: SBUGroupChannelViewModel,
didReceiveSuggestedMentions members: [SBUUser]?
)
func groupChannelViewModel(
_ viewModel: SBUGroupChannelViewModel,
didFinishUploadingFileAt index: Int,
multipleFilesMessageRequestId requestId: String
)
}
open class SBUGroupChannelViewModel: SBUBaseChannelViewModel {
// MARK: - Logic properties (Public)
public weak var delegate: SBUGroupChannelViewModelDelegate? {
get { self.baseDelegate as? SBUGroupChannelViewModelDelegate }
set { self.baseDelegate = newValue }
}
public weak var dataSource: SBUGroupChannelViewModelDataSource? {
get { self.baseDataSource as? SBUGroupChannelViewModelDataSource }
set { self.baseDataSource = newValue }
}
/// A completion handler that is called after sending a multiple files message is completed.
/// - Since: 3.10.0
public var sendMultipleFilesMessageCompletionHandler: SendbirdChatSDK.MultipleFilesMessageHandler?
// MARK: - Logic properties (private)
var messageCollection: MessageCollection?
var debouncer: SBUDebouncer?
var suggestedMemberList: [SBUUser]?
var query: MemberListQuery?
/// (GroupChannel only) If this option is `true`, when a list is received through the local cache during initialization, it is displayed first.
/// - Since: 3.3.5
var displaysLocalCachedListFirst: Bool = false
var formCaches = [Int64: SBUForm.Cache]()
// MARK: - LifeCycle
public init(channel: BaseChannel? = nil,
channelURL: String? = nil,
messageListParams: MessageListParams? = nil,
startingPoint: Int64? = .max,
delegate: SBUGroupChannelViewModelDelegate? = nil,
dataSource: SBUGroupChannelViewModelDataSource? = nil,
displaysLocalCachedListFirst: Bool = false) {
super.init()
self.delegate = delegate
self.dataSource = dataSource
self.displaysLocalCachedListFirst = displaysLocalCachedListFirst
SendbirdChat.addChannelDelegate(
self,
identifier: "\(SBUConstant.groupChannelDelegateIdentifier).\(self.description)"
)
if let channel = channel {
self.channel = channel
self.channelURL = channel.channelURL
} else if let channelURL = channelURL {
self.channelURL = channelURL
}
self.customizedMessageListParams = messageListParams
self.startingPoint = startingPoint
self.debouncer = SBUDebouncer(
debounceTime: SBUGlobals.userMentionConfig?.debounceTime ?? SBUDebouncer.defaultTime
)
guard let channelURL = self.channelURL else { return }
self.loadChannel(
channelURL: channelURL,
messageListParams: self.customizedMessageListParams
)
}
deinit {
self.messageCollection?.dispose()
SendbirdChat.removeChannelDelegate(
forIdentifier: "\(SBUConstant.groupChannelDelegateIdentifier).\(self.description)"
)
}
// MARK: - Channel related
public override func loadChannel(channelURL: String,
messageListParams: MessageListParams? = nil,
completionHandler: ((BaseChannel?, SBError?) -> Void)? = nil) {
if let messageListParams = messageListParams {
self.customizedMessageListParams = messageListParams
} else if self.customizedMessageListParams == nil {
let messageListParams = MessageListParams()
SBUGlobalCustomParams.messageListParamsBuilder?(messageListParams)
self.customizedMessageListParams = messageListParams
}
// TODO: loading
// self.delegate?.shouldUpdateLoadingState(true)
SendbirdUI.connectIfNeeded { [weak self] _, error in
if let error = error {
self?.delegate?.didReceiveError(error, isBlocker: true)
completionHandler?(nil, error)
return
}
SBULog.info("[Request] Load channel: \(String(channelURL))")
GroupChannel.getChannel(url: channelURL) { [weak self] channel, error in
guard let self = self else {
completionHandler?(nil, error)
return
}
guard self.canProceed(with: channel, error: error) else {
completionHandler?(nil, error)
return
}
self.channel = channel
self.channelURL = channel?.channelURL
SBULog.info("[Succeed] Load channel request: \(String(describing: self.channel))")
// background refresh to check if user is banned or not.
self.refreshChannel()
// for updating channel information when the connection state is closed at the time of initial load.
if SendbirdChat.getConnectState() == .closed {
let context = MessageContext(source: .eventChannelChanged, sendingStatus: .succeeded)
self.delegate?.baseChannelViewModel(
self,
didChangeChannel: channel,
withContext: context
)
completionHandler?(channel, nil)
}
let cachedMessages = self.flushCache(with: [])
self.loadInitialMessages(
startingPoint: self.startingPoint,
showIndicator: true,
initialMessages: cachedMessages
)
}
}
}
public override func refreshChannel() {
if let channel = self.channel as? GroupChannel {
channel.refresh { [weak self] error in
guard let self = self else { return }
guard self.canProceed(with: channel, error: error) == true else {
let context = MessageContext(source: .eventChannelChanged, sendingStatus: .failed)
self.delegate?.baseChannelViewModel(self, didChangeChannel: channel, withContext: context)
return
}
let context = MessageContext(source: .eventChannelChanged, sendingStatus: .succeeded)
self.delegate?.baseChannelViewModel(self, didChangeChannel: channel, withContext: context)
}
} else if let channelURL = self.channelURL {
self.loadChannel(channelURL: channelURL)
}
}
private func canProceed(with channel: GroupChannel?, error: SBError?) -> Bool {
if let error = error {
SBULog.error("[Failed] Load channel request: \(error.localizedDescription)")
if error.code == ChatError.nonAuthorized.rawValue {
self.delegate?.baseChannelViewModel(self, shouldDismissForChannel: nil)
} else {
if SendbirdChat.isLocalCachingEnabled &&
error.code == ChatError.networkError.rawValue &&
channel != nil {
return true
} else {
self.delegate?.didReceiveError(error, isBlocker: true)
}
}
return false
}
guard let channel = channel,
channel.myMemberState != .none
else {
self.delegate?.baseChannelViewModel(self, shouldDismissForChannel: channel)
return false
}
return true
}
private func belongsToChannel(error: SBError) -> Bool {
return error.code != ChatError.nonAuthorized.rawValue
}
// MARK: - Message
/// Sends a multiple files message.
/// - Parameters:
/// - fileInfoList: A list of `UploadableFileInfo` that contains information about the files to be included in the multiple files message.
/// - Since: 3.10.0
open func sendMultipleFilesMessage(fileInfoList: [UploadableFileInfo]) {
if let channel = self.channel as? GroupChannel {
let param = MultipleFilesMessageCreateParams(uploadableFileInfoList: fileInfoList)
SBUGlobalCustomParams.multipleFilesMessageParamsSendBuilder?(param)
let preSendMessage: MultipleFilesMessage?
preSendMessage = channel.sendMultipleFilesMessage(
params: param,
fileUploadHandler: { requestId, index, _, error in
if let error = error {
SBULog.error("Multiple files message - failed to upload file at index [\(index)]. \(error.localizedDescription)")
} else {
SBULog.info("Multiple files message - file at index [\(index)] upload completed.")
}
// Update the multipleFilesMessage collection view cell
// when the upload is complete.
self.updateMultipleFilesMessageCell(requestId: requestId, index: index)
},
completionHandler: { [weak self] multipleFilesMessage, error in
if let error = error {
SBULog.error(error.localizedDescription)
}
self?.sendMultipleFilesMessageCompletionHandler?(multipleFilesMessage, error)
})
// Save each file data to cache.
if let preSendMessage = preSendMessage {
for (index, fileInfo) in param.uploadableFileInfoList.enumerated() {
SBUCacheManager.Image.preSave(
multipleFilesMessage: preSendMessage,
uploadableFileInfo: fileInfo,
index: index
)
}
}
// Upsert pending message to fullMessageList.
if let preSendMessage = preSendMessage, self.messageListParams.belongsTo(preSendMessage) {
// Upsert pendingMessage.
self.pendingMessageManager.upsertPendingMessage(
channelURL: channel.channelURL,
message: preSendMessage
)
} else {
SBULog.info("A filtered file message has been sent.")
}
self.sortAllMessageList(needReload: true)
let context = MessageContext(source: .eventMessageSent, sendingStatus: .succeeded)
self.baseDelegate?.baseChannelViewModel(
self,
shouldUpdateScrollInMessageList: self.fullMessageList,
forContext: context,
keepsScroll: false
)
}
}
/// Updates a multiple files message cell of the given index of a multiple files message.
/// - Parameters:
/// - requestId: the requestId of the multiple files message.
/// - index: the index of the cell of a multiple files message to update.
/// - Since: 3.10.0
open func updateMultipleFilesMessageCell(requestId: String, index: Int) {
self.delegate?.groupChannelViewModel(
self,
didFinishUploadingFileAt: index,
multipleFilesMessageRequestId: requestId
)
}
// MARK: - Load Messages
public override func loadInitialMessages(startingPoint: Int64?,
showIndicator: Bool,
initialMessages: [BaseMessage]?) {
SBULog.info("""
loadInitialMessages,
startingPoint : \(String(describing: startingPoint)),
initialMessages : \(String(describing: initialMessages))
"""
)
// Caution in function call order
self.reset()
self.createCollectionIfNeeded(startingPoint: startingPoint ?? .max)
self.clearMessageList()
if self.hasNext() {
// Hold on to most recent messages in cache for smooth scrolling.
setupCache()
}
self.delegate?.shouldUpdateLoadingState(showIndicator)
self.messageCollection?.startCollection(
initPolicy: initPolicy,
cacheResultHandler: { [weak self] cacheResult, error in
guard let self = self else { return }
defer { self.displaysLocalCachedListFirst = false }
if let error = error {
self.delegate?.didReceiveError(error, isBlocker: false)
return
}
// prevent empty view showing
if cacheResult == nil || cacheResult?.isEmpty == true { return }
self.isInitialLoading = true
self.upsertMessagesInList(
messages: cacheResult,
needReload: self.displaysLocalCachedListFirst
)
}, apiResultHandler: { [weak self] apiResult, error in
guard let self = self else { return }
self.loadInitialPendingMessages()
if let error = error {
self.delegate?.shouldUpdateLoadingState(false)
// ignore error if using local caching
if !SendbirdChat.isLocalCachingEnabled {
self.delegate?.didReceiveError(error, isBlocker: false)
} else {
self.isInitialLoading = false
self.upsertMessagesInList(messages: nil, needReload: true)
}
return
}
if self.initPolicy == .cacheAndReplaceByApi {
self.clearMessageList()
}
self.isInitialLoading = false
self.upsertMessagesInList(messages: apiResult, needReload: true)
})
}
func loadInitialPendingMessages() {
let pendingMessages = self.messageCollection?.pendingMessages ?? []
let failedMessages = self.messageCollection?.failedMessages ?? []
let cachedTempMessages = pendingMessages + failedMessages
for message in cachedTempMessages {
if message.channelURL != self.channelURL { continue }
if message.parentMessageId > 0 { continue }
self.pendingMessageManager.upsertPendingMessage(
channelURL: self.channel?.channelURL,
message: message,
forMessageThread: self.isThreadMessageMode
)
if let fileMessage = message as? FileMessage,
let fileMessageParams = fileMessage.messageParams as? FileMessageCreateParams {
self.pendingMessageManager.addFileInfo(requestId: fileMessage.requestId, params: fileMessageParams)
}
}
}
public override func loadPrevMessages() {
guard let messageCollection = self.messageCollection else { return }
guard self.prevLock.try() else {
SBULog.info("Prev message already loading")
return
}
SBULog.info("[Request] Prev message list")
messageCollection.loadPrevious { [weak self] messages, error in
guard let self = self else { return }
defer {
self.prevLock.unlock()
}
if let error = error {
self.delegate?.didReceiveError(error, isBlocker: false)
return
}
guard let messages = messages, !messages.isEmpty else { return }
SBULog.info("[Prev message response] \(messages.count) messages")
self.delegate?.baseChannelViewModel(
self,
shouldUpdateScrollInMessageList: messages,
forContext: nil,
keepsScroll: false
)
self.upsertMessagesInList(messages: messages, needReload: true)
}
}
/// Loads next messages from `lastUpdatedTimestamp`.
public override func loadNextMessages() {
guard self.nextLock.try() else {
SBULog.info("Next message already loading")
return
}
guard let messageCollection = self.messageCollection else { return }
self.isLoadingNext = true
messageCollection.loadNext { [weak self] messages, error in
guard let self = self else { return }
defer {
self.nextLock.unlock()
self.isLoadingNext = false
}
if let error = error {
self.delegate?.didReceiveError(error, isBlocker: false)
return
}
guard let messages = messages else { return }
SBULog.info("[Next message Response] \(messages.count) messages")
self.delegate?.baseChannelViewModel(
self,
shouldUpdateScrollInMessageList: messages,
forContext: nil,
keepsScroll: true
)
self.upsertMessagesInList(messages: messages, needReload: true)
}
}
// MARK: - Resend
override public func deleteResendableMessage(_ message: BaseMessage, needReload: Bool) {
if self.channel is GroupChannel {
self.messageCollection?.removeFailed(messages: [message], completionHandler: nil)
}
super.deleteResendableMessage(message, needReload: needReload)
}
// MARK: - Message related
public func markAsRead() {
self.markAsRead(completionHandler: nil)
}
func markAsRead(completionHandler: SendbirdChatSDK.SBErrorHandler?) {
if let channel = self.channel as? GroupChannel {
channel.markAsRead(completionHandler: completionHandler)
}
}
// MARK: - Typing
public func startTypingMessage() {
guard let channel = self.channel as? GroupChannel else { return }
SBULog.info("[Request] Start typing")
channel.startTyping()
}
public func endTypingMessage() {
guard let channel = self.channel as? GroupChannel else { return }
SBULog.info("[Request] End typing")
channel.endTyping()
}
// MARK: - Typing Indicator Message
private func updateTypingIndicatorMessage() {
guard let channel = self.channel as? GroupChannel, let collection = self.messageCollection else { return }
// One or more user is typing.
if var typers = channel.getTypingUsers(),
typers.isEmpty == false,
let typingMessage = SBUTypingIndicatorMessage.make(["": ""]) {
// if hasNext is true, don't show typing bubble.
if collection.hasNext { return }
let truncatedTypers = Array(typers.prefix(3))
typingMessage.typingIndicatorInfo = SBUTypingIndicatorInfo(
typers: truncatedTypers,
numberOfTypers: typers.count
)
self.typingMessageManager.typingMessages[channel.channelURL] = typingMessage
}
// No user is typing.
else {
self.clearTypingMessage()
}
self.sortAllMessageList(needReload: false) // tableview reload is handled in GroupChannelVC
}
func clearTypingMessage() {
guard let channel = self.channel as? GroupChannel else { return }
self.typingMessageManager.typingMessages.removeValue(forKey: channel.channelURL)
}
// MARK: - Mention
/// Loads mentionable member list.
/// When the suggested list is received, it calls `groupChannelViewModel(_:didReceiveSuggestedMembers:)` delegate method.
/// - Parameter filterText: The text that is used as filter while searching for the suggested mentions.
public func loadSuggestedMentions(with filterText: String) {
self.debouncer?.add { [weak self] in
guard let self = self else { return }
if let channel = self.channel as? GroupChannel {
if channel.isSuper {
guard let config = SBUGlobals.userMentionConfig else {
SBULog.error("`SBUGlobals.userMentionConfig` is `nil`")
return
}
guard SendbirdUI.config.groupChannel.channel.isMentionEnabled else {
SBULog.error("User mention features are disabled. See `SBUGlobals.isMentionEnabled` for more information")
return
}
let params = MemberListQueryParams()
params.nicknameStartsWithFilter = filterText
// +1 is buffer for when the current user is included in the search results
params.limit = UInt(config.suggestionLimit) + 1
self.query = channel.createMemberListQuery(params: params)
self.query?.loadNextPage { [weak self] members, _ in
guard let self = self else { return }
self.suggestedMemberList = SBUUser.convertUsers(members)
self.delegate?.groupChannelViewModel(
self,
didReceiveSuggestedMentions: self.suggestedMemberList
)
}
} else {
guard channel.members.count > 0 else {
self.suggestedMemberList = nil
self.delegate?.groupChannelViewModel(self, didReceiveSuggestedMentions: nil)
return
}
let sortedMembers = channel.members.sorted { $0.nickname.lowercased() < $1.nickname.lowercased() }
let matchedMembers = sortedMembers.filter {
return $0.nickname.lowercased().hasPrefix(filterText.lowercased())
}
let memberCount = matchedMembers.count
// +1 is buffer for when the current user is included in the search results
let limit = (SBUGlobals.userMentionConfig?.suggestionLimit ?? 0) + 1
let splitCount = min(memberCount, Int(limit))
let resultMembers = Array(matchedMembers[0..<splitCount])
self.suggestedMemberList = SBUUser.convertUsers(resultMembers)
self.delegate?.groupChannelViewModel(
self,
didReceiveSuggestedMentions: self.suggestedMemberList
)
}
}
}
}
/// Cancels loading the suggested mentions.
public func cancelLoadingSuggestedMentions() {
self.debouncer?.cancel()
}
// MARK: - Common
private func createCollectionIfNeeded(startingPoint: Int64) {
// GroupChannel only
guard let channel = self.channel as? GroupChannel else { return }
self.messageCollection = SendbirdChat.createMessageCollection(
channel: channel,
startingPoint: startingPoint,
params: self.messageListParams
)
self.messageCollection?.delegate = self
}
public override func hasNext() -> Bool {
return self.messageCollection?.hasNext ?? (self.getStartingPoint() != nil)
}
public override func hasPrevious() -> Bool {
return self.messageCollection?.hasPrevious ?? true
}
public override func getStartingPoint() -> Int64? {
return self.messageCollection?.startingPoint
}
override func reset() {
self.markAsRead()
super.reset()
}
}
extension SBUGroupChannelViewModel: MessageCollectionDelegate {
open func messageCollection(_ collection: MessageCollection,
context: MessageContext,
channel: GroupChannel,
addedMessages messages: [BaseMessage]) {
// -> pending, -> receive new message
// message thread case exception
var existInPendingMessage = false
for addedMessage in messages {
if addedMessage.sendingStatus == .succeeded { continue }
let filteredMessages = self.pendingMessageManager
.getPendingMessages(
channelURL: self.channelURL,
forMessageThread: true
)
.filter { $0.requestId == addedMessage.requestId }
.filter { $0.isRequestIdValid }
if !filteredMessages.isEmpty {
existInPendingMessage = true
}
}
if existInPendingMessage { return }
SBULog.info("messageCollection addedMessages : \(messages.count)")
switch context.source {
case .eventMessageReceived:
self.markAsRead()
default: break
}
self.delegate?.baseChannelViewModel(
self,
shouldUpdateScrollInMessageList: messages,
forContext: context,
keepsScroll: true
)
self.upsertMessagesInList(messages: messages, needReload: true)
}
open func messageCollection(_ collection: MessageCollection,
context: MessageContext,
channel: GroupChannel,
updatedMessages messages: [BaseMessage]) {
// pending -> failed, pending -> succeded, failed -> Pending
// message thread case exception
var existInPendingMessage = false
for addedMessage in messages {
if addedMessage.sendingStatus == .succeeded { continue }
let filteredMessages = self.pendingMessageManager
.getPendingMessages(
channelURL: self.channelURL,
forMessageThread: true
)
.filter { $0.requestId == addedMessage.requestId }
.filter { $0.isRequestIdValid }
if !filteredMessages.isEmpty {
existInPendingMessage = true
}
}
if existInPendingMessage { return }
SBULog.info("messageCollection updatedMessages : \(messages.count)")
self.delegate?.baseChannelViewModel(
self,
shouldUpdateScrollInMessageList: messages,
forContext: context,
keepsScroll: false
)
self.upsertMessagesInList(
messages: messages,
needUpdateNewMessage: false,
needReload: true
)
}
open func messageCollection(_ collection: MessageCollection,
context: MessageContext,
channel: GroupChannel,
deletedMessages messages: [BaseMessage]) {
SBULog.info("messageCollection deletedMessages : \(messages.count)")
self.delegate?.baseChannelViewModel(self, deletedMessages: messages)
self.deleteMessagesInList(messageIds: messages.compactMap({ $0.messageId }), needReload: true)
}
open func messageCollection(_ collection: MessageCollection,
context: MessageContext,
updatedChannel channel: GroupChannel) {
SBULog.info("messageCollection changedChannel")
// Update typingMessageBubble.
if context.source == .eventTypingStatusUpdated,
SendbirdUI.config.groupChannel.channel.isTypingIndicatorEnabled,
SendbirdUI.config.groupChannel.channel.typingIndicatorTypes.contains(.bubble) {
updateTypingIndicatorMessage()
}
self.delegate?.baseChannelViewModel(self, didChangeChannel: channel, withContext: context)
}
open func messageCollection(_ collection: MessageCollection,
context: MessageContext,
deletedChannel channelURL: String) {
SBULog.info("messageCollection deletedChannel")
self.delegate?.baseChannelViewModel(self, didChangeChannel: nil, withContext: context)
}
open func didDetectHugeGap(_ collection: MessageCollection) {
SBULog.info("messageCollection didDetectHugeGap")
self.messageCollection?.dispose()
var startingPoint: Int64?
let indexPathsForStartingPoint = self.dataSource?.groupChannelViewModel(self, startingPointIndexPathsForChannel: self.channel as? GroupChannel)
let visibleRowCount = indexPathsForStartingPoint?.count ?? 0
let visibleCenterIdx = indexPathsForStartingPoint?[visibleRowCount / 2].row ?? 0
if visibleCenterIdx < self.fullMessageList.count {
startingPoint = self.fullMessageList[visibleCenterIdx].createdAt
}
self.loadInitialMessages(
startingPoint: startingPoint,
showIndicator: false,
initialMessages: nil
)
}
// MARK: - Submit Form.
/// This function is used to submit form data.
/// - Parameters:
/// - message: `BaseMessage` object to submit form.
/// - answer: set form asnwer.
/// - Since: 3.11.0
public func submitForm(message: BaseMessage, answer: SBUForm.Answer) {
SBULog.info("[Request] Submit Form")
message.submitForm(
formKey: answer.formKey,
answers: answer.data
) { error in
if let error = error {
SBULog.error("[Request] Submit Form - error: \(error.localizedDescription)")
self.delegate?.didReceiveError(error)
return
}
}
}
// MARK: - Updated cached form data.
/// This function is used to update cached form data.
/// - Parameters:
/// - message: `BaseMessage` object to submit form.
/// - form: for updating reload form.
/// - answer: for updating asnwer.
/// - Since: 3.11.0
public func updateForm(message: BaseMessage, answer: SBUForm.Answer) {
SBULog.info("[Request] Updated Cached Form data")
guard let cache = self.formCaches[message.messageId] else { return }
cache.updateForms(with: message.asForms)
cache.updateAnswer(with: answer)
}
}
// MARK: - ConnectionDelegate
extension SBUGroupChannelViewModel {
open override func didSucceedReconnection() {
super.didSucceedReconnection()
if self.hasNext() {
self.messageCache?.loadNext()
}
self.markAsRead { [weak self] _ in
self?.refreshChannel()
}
}
}
// MARK: - GroupChannelDelegate
extension SBUGroupChannelViewModel: GroupChannelDelegate {
// Received message
open override func channel(_ channel: BaseChannel, didReceive message: BaseMessage) {
guard self.channel?.channelURL == channel.channelURL else { return }
guard self.messageListParams.belongsTo(message) else { return }
super.channel(channel, didReceive: message)
let isScrollBottom = self.dataSource?.baseChannelViewModel(self, isScrollNearBottomInChannel: self.channel)
if (self.hasNext() == true || isScrollBottom == false) &&
(message is UserMessage || message is FileMessage) {
// let context = MessageContext(source: .eventMessageReceived, sendingStatus: .succeeded)
if let channel = self.channel {
self.delegate?.baseChannelViewModel(self, didReceiveNewMessage: message, forChannel: channel)
}
}
}
}