-
Notifications
You must be signed in to change notification settings - Fork 73
/
SBUGroupChannelModule.Input.swift
1029 lines (880 loc) · 46.1 KB
/
SBUGroupChannelModule.Input.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
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
//
// SBUGroupChannelModule.Input.swift
// SendbirdUIKit
//
// Created by Jaesung Lee on 2022/01/16.
// Copyright © 2022 Sendbird, Inc. All rights reserved.
//
import UIKit
import PhotosUI
import SendbirdChatSDK
/// Event methods for the views updates and performing actions from the input component in the group channel.
public protocol SBUGroupChannelModuleInputDelegate: SBUBaseChannelModuleInputDelegate {
/// Called when a file was picked to send a file message.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - fileData: A data of a picked file.
/// - mimeType: A MIME type of a picked file.
/// - parentMessage: A message that will be a parent message. Please refer to *quote reply* features.
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
didPickFileData fileData: Data?,
fileName: String,
mimeType: String,
parentMessage: BaseMessage?
)
/// Called when multiple files were picked to send a multiple files message.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - didPickMultipleFiles: A list of `UploadableFileInfo` for the picked files.
/// - parentMessage: A message that will be a parent message. Please refer to *quote reply* features.
/// - Since: 3.10.0
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
didPickMultipleFiles fileInfoList: [UploadableFileInfo]?,
parentMessage: BaseMessage?
)
/// Called when the send button was tapped.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - text: The normal text.
/// - mentionedMessageTemplate: The mentioned text that is generated by `text` and `mentionUsers`.
/// - mentionedUserIds: The mentioned userIds.
/// - parentMessage: The parent message of the message representing `text`.
/// ```swift
/// print(text) // "Hi @Nickname"
/// print(mentionedMessageTemplate) // "Hi @{UserID}"
/// print(mentionedUserIds) // ["{UserID}"]
/// ```
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
didTapSend text: String,
mentionedMessageTemplate: String,
mentionedUserIds: [String],
parentMessage: BaseMessage?
)
/// Called when the edit button was tapped.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - text: The normal text
/// - mentionedMessageTemplate: The mentioned text that is generated by `text` and `mentionUsers`.
/// - mentionedUserIds: The mentioned userIds.
/// ```swift
/// print(text) // "Hi @Nickname"
/// print(mentionedMessageTemplate) // "Hi @{UserID}"
/// print(mentionedUserIds) // ["{UserID}"]
/// ```
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
didTapEdit text: String,
mentionedMessageTemplate: String,
mentionedUserIds: [String]
)
/// Called when the `SBUMessageInputMode` will be changed.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - mode: `SBUMessageInputMode` value.
/// - mentionedMessageTemplate: The mentioned text that is generated by `mentionUsers`.
/// - mentionedUserIds: The mentioned userIds.
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
willChangeMode mode: SBUMessageInputMode,
message: BaseMessage?,
mentionedMessageTemplate: String,
mentionedUserIds: [String]
)
/// Called when the suggested mentions should be loaded. Please refer to `loadSuggestedMentions(with:)` function in `SBUGroupChannelViewModel`.
/// - Parameters:
/// - inputComponent: `SBUGroupChannelModule.Input` object.
/// - filterText: The text that is used as a filter while loading the suggested mentions.
func groupChannelModule(
_ inputComponent: SBUGroupChannelModule.Input,
shouldLoadSuggestedMentions filterText: String
)
/// Called when it the suggested mentions are no longer valid.
/// - Parameter inputComponent: `SBUGroupChannelModule.Input` object.
func groupChannelModuleShouldStopSuggestingMention(
_ inputComponent: SBUGroupChannelModule.Input
)
/// Called when it the voice message button tabbed.
/// - Parameter inputComponent: `SBUGroupChannelModule.Input` object.
/// - Since: 3.4.0
func groupChannelModuleDidTapVoiceMessage(_ inputComponent: SBUGroupChannelModule.Input)
}
/// Methods to get data source for the input component in the group channel.
public protocol SBUGroupChannelModuleInputDataSource: SBUBaseChannelModuleInputDataSource { }
extension SBUGroupChannelModule {
/// The `SBUGroupChannelModule`'s component class that represents input
@objc(SBUGroupChannelModuleInput)
@objcMembers
open class Input: SBUBaseChannelModule.Input, SBUMentionManagerDelegate, SBUSuggestedMentionListDelegate {
public var suggestedMentionList: SBUSuggestedMentionList?
/// A current quoted message in message input view. This value is only available when the `messageInputView` is type of `SBUMessageInputView` that supports the message replying feature.
public var currentQuotedMessage: BaseMessage? {
guard let messageInputView = messageInputView as? SBUMessageInputView else { return nil }
var parentMessage: BaseMessage?
switch messageInputView.option {
case .quoteReply(let message):
parentMessage = message
default: break
}
return parentMessage
}
/// The group channel object casted from `baseChannel`.
public var channel: GroupChannel? {
self.baseChannel as? GroupChannel
}
/// The object that acts as the delegate of the input component. The delegate must adopt the `SBUGroupChannelModuleInputDelegate`.
public weak var delegate: SBUGroupChannelModuleInputDelegate? {
get { self.baseDelegate as? SBUGroupChannelModuleInputDelegate }
set { self.baseDelegate = newValue }
}
/// The object that acts as the data source of the input component. The data source must adopt the `SBUGroupChannelModuleInputDataSource`.
public weak var dataSource: SBUGroupChannelModuleInputDataSource? {
get { self.baseDataSource as? SBUGroupChannelModuleInputDataSource }
set { self.baseDataSource = newValue }
}
/// The object that acts as the data source of the mention manager. The data source must adopt the `SBUMentionManagerDataSource`.
public weak var mentionManagerDataSource: SBUMentionManagerDataSource?
/// String constants used when sending a multiple files message.
/// - Since: 3.10.0
struct MultipleFilesConstants {
static let fileInfoList = "uploadableFileInfoList"
static let image = "image"
static let gif = "gif"
static let video = "video"
}
/// The OperationQueue that manages the order of messages when sending.
/// - Since: 3.10.0
lazy var messageOperationQueue: OperationQueue = {
let operationQueue = OperationQueue()
operationQueue.name = SBUConstant.messageOperationQueueName
operationQueue.maxConcurrentOperationCount = 1
return operationQueue
}()
// MARK: Mention
public var mentionManager: SBUMentionManager?
/// Configures component with parameters.
/// - Parameters:
/// - delegate: `SBUGroupChannelModuleListDelegate` type listener
/// - dataSource: The data source that is type of `SBUGroupChannelModuleInputDataSource`
/// - theme: `SBUChannelTheme` object
open func configure(
delegate: SBUGroupChannelModuleInputDelegate,
dataSource: SBUGroupChannelModuleInputDataSource,
mentionManagerDataSource: SBUMentionManagerDataSource? = nil,
theme: SBUChannelTheme
) {
self.delegate = delegate
self.dataSource = dataSource
self.mentionManagerDataSource = mentionManagerDataSource
self.theme = theme
self.setupViews()
self.setupLayouts()
self.setupStyles()
if SendbirdUI.config.groupChannel.channel.isMentionEnabled {
self.setupMentionManager()
}
}
open override func setupViews() {
super.setupViews()
}
open override func setupLayouts() {
super.setupLayouts()
}
open override func pickImageFile(info: [UIImagePickerController.InfoKey: Any]) {
var tempImageURL: URL?
if let imageURL = info[.imageURL] as? URL {
// file:https:///~~~
tempImageURL = imageURL
}
guard let imageURL = tempImageURL else {
let originalImage = info[.originalImage] as? UIImage
// TODO: need to improved. (mimetype)
// for Camera capture
guard let image = originalImage?.fixedOrientation(),
let imageData = image.sbu_convertToData() else { return }
self.delegate?.groupChannelModule(
self,
didPickFileData: imageData,
fileName: "\(Date().sbu_toString(dateFormat: SBUDateFormatSet.Message.fileNameFormat, localizedFormat: false)).jpg",
mimeType: "image/jpeg",
parentMessage: self.currentQuotedMessage
)
return
}
let imageName = imageURL.lastPathComponent
guard let mimeType = SBUUtils.getMimeType(url: imageURL) else {
SBULog.error("Failed to get mimeType")
return
}
switch mimeType {
case "image/gif":
let gifData = try? Data(contentsOf: imageURL)
self.delegate?.groupChannelModule(
self,
didPickFileData: gifData,
fileName: imageName,
mimeType: mimeType,
parentMessage: self.currentQuotedMessage
)
default:
let originalImage = info[.originalImage] as? UIImage
guard let image = originalImage?.fixedOrientation(),
let imageData = image.sbu_convertToData() else { return }
self.delegate?.groupChannelModule(
self,
didPickFileData: imageData,
fileName: imageName,
mimeType: mimeType,
parentMessage: self.currentQuotedMessage
)
}
}
open override func pickVideoFile(info: [UIImagePickerController.InfoKey: Any]) {
do {
guard let videoURL = info[.mediaURL] as? URL else { return }
let videoFileData = try Data(contentsOf: videoURL)
let videoName = videoURL.lastPathComponent
guard let mimeType = SBUUtils.getMimeType(url: videoURL) else { return }
let parentMessage = self.currentQuotedMessage
self.delegate?.groupChannelModule(
self,
didPickFileData: videoFileData,
fileName: videoName,
mimeType: mimeType,
parentMessage: parentMessage
)
} catch {
SBULog.error(error.localizedDescription)
let sbError = SBError(domain: (error as NSError).domain, code: (error as NSError).code)
self.delegate?.didReceiveError(sbError, isBlocker: false)
}
}
// MARK: PHPicker
/// Loads image files from the NSItemProvider and sends a multiple files message.
/// - Parameters:
/// - itemProviders: An array of NSItemProvider
/// - Since: 3.10.0
@available(iOS 14.0, *)
open func pickMultipleImageFiles(itemProviders: [NSItemProvider]) {
// Define and add a blocking operation to the message queue.
// This blocking operation will be executed after all images/gifs are finished loading.
let operation = BlockingOperation(asyncTask: { operation in
defer { operation.complete() }
guard let fileInfoList = operation.userInfo[MultipleFilesConstants.fileInfoList] as? [UploadableFileInfo],
fileInfoList.isEmpty == false else {
return
}
DispatchQueue.main.async { [self, fileInfoList] in
self.delegate?.groupChannelModule(
self,
didPickMultipleFiles: fileInfoList,
parentMessage: self.currentQuotedMessage
)
}
}, requireExplicity: true)
messageOperationQueue.addOperation(operation)
// Load images and GIFs.
var fileInfoList: [UploadableFileInfo?] = Array(repeating: nil, count: itemProviders.count)
let group = DispatchGroup()
for (index, itemProvider) in itemProviders.enumerated() {
group.enter()
/// !! Warining !!
/// Since the image identifier includes the gif identifier, the check of the gif type should take precedence over the image type comparison.
// GIF
if itemProvider.hasItemConformingToTypeIdentifier(UTType.gif.identifier) {
self.loadGIFfile(itemProvider: itemProvider, index: index) { gifData, fileName, mimeType in
defer {
group.leave()
}
guard let gifData = gifData, let fileName = fileName, let mimeType = mimeType else {
return
}
// Create UploadableFileInfo.
let fileInfo = UploadableFileInfo(file: gifData)
fileInfo.mimeType = mimeType
fileInfo.fileName = fileName
// GIF thumbnail should be static, not animated.
if let image = UIImage(data: gifData) {
let thumbnailSize = ThumbnailSize.make(maxSize: image.size)
fileInfo.thumbnailSizes = [thumbnailSize]
}
fileInfoList[index] = fileInfo
}
}
// Image
else if itemProvider.hasItemConformingToTypeIdentifier(UTType.image.identifier) {
self.loadImageFile(itemProvider: itemProvider, index: index) { imageData, fileName, mimeType in
defer {
group.leave()
}
guard let imageData = imageData, let fileName = fileName, let mimeType = mimeType else {
return
}
// Create UploadableFileInfo.
let fileInfo = UploadableFileInfo(file: imageData)
fileInfo.mimeType = mimeType
fileInfo.fileName = fileName
if let image = UIImage(data: imageData) {
let thumbnailSize = ThumbnailSize.make(maxSize: image.size)
fileInfo.thumbnailSizes = [thumbnailSize]
}
fileInfoList[index] = fileInfo
}
}
}
// Finally, execute the blocking operation.
group.notify(queue: .main) {
operation.userInfo[MultipleFilesConstants.fileInfoList] = fileInfoList
operation.markReady()
}
}
@available(iOS 14.0, *)
open override func pickImageFile(itemProvider: NSItemProvider) {
let operation = BlockingOperation(asyncTask: { operation in
defer { operation.complete() }
// swiftlint:disable large_tuple
guard let (imageData, fileName, mimeType) = operation.userInfo[MultipleFilesConstants.image] as? (Data, String, String) else {
return
}
// swiftlint:enable large_tuple
DispatchQueue.main.async { [self, imageData, fileName, mimeType] in
self.delegate?.groupChannelModule(
self,
didPickFileData: imageData,
fileName: fileName,
mimeType: mimeType,
parentMessage: self.currentQuotedMessage
)
}
}, requireExplicity: true)
messageOperationQueue.addOperation(operation)
loadImageFile(itemProvider: itemProvider) { imageData, fileName, mimeType in
defer { operation.markReady() }
guard let imageData = imageData, let fileName = fileName, let mimeType = mimeType else { return }
operation.userInfo[MultipleFilesConstants.image] = (imageData, fileName, mimeType)
}
}
@available(iOS 14.0, *)
open override func pickGIFFile(itemProvider: NSItemProvider) {
let operation = BlockingOperation(asyncTask: { operation in
defer { operation.complete() }
// swiftlint:disable large_tuple
guard let (gifData, fileName, mimeType) = operation.userInfo[MultipleFilesConstants.gif] as? (Data, String, String) else {
return
}
// swiftlint:enable large_tuple
DispatchQueue.main.async { [self, gifData, fileName, mimeType] in
self.delegate?.groupChannelModule(
self,
didPickFileData: gifData,
fileName: fileName,
mimeType: mimeType,
parentMessage: self.currentQuotedMessage
)
}
}, requireExplicity: true)
messageOperationQueue.addOperation(operation)
loadGIFfile(itemProvider: itemProvider) { gifData, fileName, mimeType in
defer {
operation.markReady()
}
guard let gifData = gifData, let fileName = fileName, let mimeType = mimeType else { return }
operation.userInfo[MultipleFilesConstants.gif] = (gifData, fileName, mimeType)
}
}
@available(iOS 14.0, *)
open override func pickVideoFile(itemProvider: NSItemProvider) {
let operation = BlockingOperation(asyncTask: { operation in
defer { operation.complete() }
// swiftlint:disable large_tuple
guard let (videoFileData, videoName, mimeType) = operation.userInfo[MultipleFilesConstants.video] as? (Data, String, String) else {
return
}
// swiftlint:enable large_tuple
DispatchQueue.main.async { [self, videoFileData, videoName, mimeType] in
// load전에 operation 등록을 미리해야함. 등록은 async로 감싸면 X
self.delegate?.groupChannelModule(
self,
didPickFileData: videoFileData,
fileName: videoName,
mimeType: mimeType,
parentMessage: self.currentQuotedMessage
)
}
}, requireExplicity: true)
messageOperationQueue.addOperation(operation)
itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.movie.identifier) { url, error in
guard let videoURL = url else { return }
do {
defer {
operation.markReady()
}
guard videoURL.isFileSizeUploadable else {
return
}
let videoFileData = try Data(contentsOf: videoURL)
let videoName = videoURL.lastPathComponent
guard let mimeType = SBUUtils.getMimeType(url: videoURL) else { return }
operation.userInfo[MultipleFilesConstants.video] = (videoFileData, videoName, mimeType)
} catch {
SBULog.error(error.localizedDescription)
}
}
}
open override func pickDocumentFile(documentURLs: [URL]) {
do {
guard let documentURL = documentURLs.first else { return }
let documentData = try Data(contentsOf: documentURL)
let documentName = documentURL.lastPathComponent
guard let mimeType = SBUUtils.getMimeType(url: documentURL) else { return }
let parentMessage = self.currentQuotedMessage
self.delegate?.groupChannelModule(
self,
didPickFileData: documentData,
fileName: documentName,
mimeType: mimeType,
parentMessage: parentMessage
)
} catch {
SBULog.error(error.localizedDescription)
let sbError = SBError(domain: (error as NSError).domain, code: (error as NSError).code)
self.delegate?.didReceiveError(sbError, isBlocker: false)
}
}
open override func pickImageData(_ data: Data, fileName: String? = nil, mimeType: String? = nil) {
let tempFileName = "\(Date().sbu_toString(dateFormat: SBUDateFormatSet.Message.fileNameFormat, localizedFormat: false)).jpg"
self.delegate?.groupChannelModule(
self,
didPickFileData: data,
fileName: fileName ?? tempFileName,
mimeType: mimeType ?? "image/jpeg",
parentMessage: self.currentQuotedMessage
)
}
open override func pickVideoURL(_ url: URL) {
do {
let videoFileData = try Data(contentsOf: url)
let videoName = url.lastPathComponent
guard let mimeType = SBUUtils.getMimeType(url: url) else { return }
let parentMessage = self.currentQuotedMessage
self.delegate?.groupChannelModule(
self,
didPickFileData: videoFileData,
fileName: videoName,
mimeType: mimeType,
parentMessage: parentMessage
)
} catch {
SBULog.error(error.localizedDescription)
let sbError = SBError(domain: (error as NSError).domain, code: (error as NSError).code)
self.delegate?.didReceiveError(sbError, isBlocker: false)
}
}
open override func updateMessageInputMode(_ mode: SBUMessageInputMode, message: BaseMessage? = nil) {
super.updateMessageInputMode(mode, message: message)
if mode == .edit {
guard SendbirdUI.config.groupChannel.channel.isMentionEnabled else { return }
guard let messageInputView = self.messageInputView as? SBUMessageInputView else { return }
guard let mentionedUsers = message?.mentionedUsers else { return }
guard let mentionedMessageTemplate = message?.mentionedMessageTemplate,
mentionedMessageTemplate != "" else { return }
if let mentionManager = mentionManager {
mentionManager.reset()
} else {
self.mentionManager = SBUMentionManager()
self.mentionManager?.configure(
delegate: self,
dataSource: self.mentionManagerDataSource,
defaultTextAttributes: messageInputView.defaultAttributes,
mentionTextAttributes: messageInputView.mentionedAttributes
)
}
let attributedText = self.mentionManager!.generateMentionedMessage(
with: mentionedMessageTemplate,
mentionedUsers: SBUUser.convertUsers(mentionedUsers)
)
messageInputView.textView?.attributedText = attributedText
}
}
/// Updates state of `messageInputView`.
open override func updateMessageInputModeState() {
if channel != nil {
self.updateBroadcastModeState()
self.updateFrozenModeState()
self.updateMutedModeState()
self.updateNotificationModeState()
} else {
if let messageInputView = self.messageInputView as? SBUMessageInputView {
messageInputView.setErrorState()
}
}
}
/// This is used to update frozen mode of `messageInputView`. This will call `SBUBaseChannelModuleInputDelegate baseChannelModule(_:didUpdateFrozenState:)`
open override func updateFrozenModeState() {
let isOperator = self.channel?.myRole == .operator
let isBroadcast = self.channel?.isBroadcast ?? false
let isFrozen = self.channel?.isFrozen ?? false
if !isBroadcast {
if let messageInputView = self.messageInputView as? SBUMessageInputView {
messageInputView.setFrozenModeState(!isOperator && isFrozen)
}
}
self.delegate?.baseChannelModule(self, didUpdateFrozenState: isFrozen)
}
/// Updates the mode of `messageInputView` according to broadcast state of the channel.
open func updateBroadcastModeState() {
let isOperator = self.channel?.myRole == .operator
let isBroadcast = self.channel?.isBroadcast ?? false
self.messageInputView?.isHidden = !isOperator && isBroadcast
}
/// Updates the mode of `messageInputView` according to frozen and muted state of the channel.
open func updateMutedModeState() {
let isOperator = self.channel?.myRole == .operator
let isFrozen = self.channel?.isFrozen ?? false
let isMuted = self.channel?.myMutedState == .muted
if !isFrozen || (isFrozen && isOperator) {
if let messageInputView = self.messageInputView as? SBUMessageInputView {
messageInputView.setMutedModeState(isMuted)
}
}
}
/// Updates the mode of `messageInputView` according to notification state of the channel.
/// - Since: 3.5.0
open func updateNotificationModeState() {
let isChatNotification = self.channel?.isChatNotification ?? false
self.messageInputView?.isHidden = isChatNotification
}
// MARK: PHPicker utils
/// Loads image data from a NSItemProvider.
/// - Parameters:
/// - itemProvider: the NSItemProvider to load the image data from
/// - index: the index of the image file in a multiple files message. `nil` in a single file message
/// - completionHandler: returns image data, fileName, and mimeType
/// - Since: 3.10.0
@available(iOS 14.0, *)
private func loadImageFile(
itemProvider: NSItemProvider,
index: Int? = nil,
completion: @escaping (Data?, String?, String?) -> Void
) {
itemProvider.loadItem(forTypeIdentifier: UTType.image.identifier, options: [:]) { url, _ in
guard let imageURL = url as? URL,
imageURL.isFileSizeUploadable else {
completion(nil, nil, nil)
return
}
if itemProvider.canLoadObject(ofClass: UIImage.self) {
itemProvider.loadObject(ofClass: UIImage.self) { imageItem, _ in
DispatchQueue.main.async {
guard let originalImage = imageItem as? UIImage,
let mimeType = SBUUtils.getMimeType(url: imageURL),
let imageData = originalImage.fixedOrientation().sbu_convertToData() else {
completion(nil, nil, nil)
return
}
let fileExtension = imageURL.pathExtension
/// If multiple files message, fileName is `date_index.fileExtension`
/// If single file message, fileName is `date.fileExtension`
var fileName = Date().sbu_toString(
dateFormat: SBUDateFormatSet.Message.fileNameFormat,
localizedFormat: false
)
if let index = index {
fileName = "\(fileName)_\(index)"
}
fileName = "\(fileName).\(fileExtension)"
completion(imageData, fileName, mimeType)
}
}
} else {
completion(nil, nil, nil)
}
}
}
/// Loads GIF data from a NSItemProvider.
/// - Parameters:
/// - itemProvider: the NSItemProvider to load the image data from
/// - index: the index of the image file in a multiple files message. `nil` in a single file message
/// - completionHandler: returns image data, fileName, and mimeType
/// - Since: 3.10.0
@available(iOS 14.0, *)
private func loadGIFfile(
itemProvider: NSItemProvider,
index: Int? = nil,
completion: @escaping (Data?, String?, String?) -> Void
) {
itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.gif.identifier) { url, _ in
guard let imageURL = url,
imageURL.isFileSizeUploadable else {
completion(nil, nil, nil)
return
}
guard let mimeType = SBUUtils.getMimeType(url: imageURL) else {
completion(nil, nil, nil)
return
}
let gifData = try? Data(contentsOf: imageURL)
let fileExtension = imageURL.pathExtension
/// If multiple files message, fileName is `date_index.fileExtension`
/// If single file message, fileName is `date.fileExtension`
var fileName = Date().sbu_toString(
dateFormat: SBUDateFormatSet.Message.fileNameFormat,
localizedFormat: false
)
if let index = index {
fileName = "\(fileName)_\(index)"
}
fileName = "\(fileName).\(fileExtension)"
completion(gifData, fileName, mimeType)
}
}
// MARK: Mention
/// Initializes `SBUMentionManager` instance and configure with attributes.
/// The `messageInputView` updates to use its `defaultAttributes` and `mentionedAttributes`.
open func setupMentionManager() {
guard SendbirdUI.config.groupChannel.channel.isMentionEnabled else { return }
if mentionManager == nil {
self.mentionManager = SBUMentionManager()
}
guard let messageInputView = self.messageInputView as? SBUMessageInputView,
let mentionManager = self.mentionManager else { return }
mentionManager.configure(
delegate: self,
dataSource: self.mentionManagerDataSource,
defaultTextAttributes: messageInputView.defaultAttributes,
mentionTextAttributes: messageInputView.mentionedAttributes
)
messageInputView.textView?.typingAttributes = mentionManager.defaultTextAttributes
messageInputView.textView?.linkTextAttributes = mentionManager.mentionTextAttributes
}
/// Handles pending mention suggestion. This calls when the channel view model receives member list from callback.
open func handlePendingMentionSuggestion(with members: [SBUUser]?) {
self.mentionManager?.handlePendingMentionSuggestion()
}
/// Updates `suggestedMentionList` with `members`
open func updateSuggestedMentionList(with members: [SBUUser]) {
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
}
var filteredMembers = members.filter {
($0.user?.isActive == true) &&
($0.userId != SBUGlobals.currentUser?.userId)
}
if filteredMembers.count > config.suggestionLimit {
// Remove buffer member
filteredMembers.removeLast()
}
if self.suggestedMentionList?.superview == nil, filteredMembers.count > 0 {
self.presentSuggestedMentionList()
}
guard let suggestedMentionList = suggestedMentionList else { return }
let mentionLimit = SBUGlobals.userMentionConfig?.mentionLimit ?? 10
if let mentionedList = mentionManager?.mentionedList, mentionedList.count < mentionLimit {
suggestedMentionList.isLimitGuideEnabled = false
} else {
suggestedMentionList.isLimitGuideEnabled = true
}
suggestedMentionList.reloadData(with: filteredMembers)
let height = CGFloat(44 * filteredMembers.count)
let maxHeight: CGFloat
switch UIDevice.current.orientation {
case .landscapeRight, .landscapeLeft:
maxHeight = 164
default:
maxHeight = 196
}
suggestedMentionList.heightConstraint?.constant = suggestedMentionList.isLimitGuideEnabled
? 44
: min(height, maxHeight)
self.layoutIfNeeded()
}
/// Presents `suggestedMentionList`
open func presentSuggestedMentionList() {
if suggestedMentionList == nil {
self.suggestedMentionList = SBUSuggestedMentionList()
self.suggestedMentionList?.delegate = self
}
guard let suggestedMentionList = suggestedMentionList else { return }
guard let messageInputView = self.messageInputView else { return }
self.addSubview(suggestedMentionList)
suggestedMentionList.translatesAutoresizingMaskIntoConstraints = false
suggestedMentionList.heightConstraint?.isActive = false
suggestedMentionList.heightConstraint = suggestedMentionList.heightAnchor.constraint(equalToConstant: 0)
suggestedMentionList.heightConstraint?.isActive = true
suggestedMentionList
.sbu_constraint(equalTo: self, leading: 0, trailing: 0)
.sbu_constraint_equalTo(
bottomAnchor:
(messageInputView as? SBUMessageInputView)?.contentHStackView.topAnchor
?? messageInputView.topAnchor,
bottom: 0
)
.sbu_constraint_lessThan(height: 196)
}
/// Dismiss `suggestedMentionList` and remove from super view.
open func dismissSuggestedMentionList() {
guard let suggestedMentionList = self.suggestedMentionList else { return }
suggestedMentionList.reloadData(with: [])
suggestedMentionList.removeFromSuperview()
self.suggestedMentionList = nil
self.setupLayouts()
}
open override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard let suggestedMentionList = suggestedMentionList, suggestedMentionList.superview != nil else {
return super.point(inside: point, with: event)
}
let tounchedInside = bounds
.insetBy(dx: 0, dy: -suggestedMentionList.bounds.height)
.contains(point)
if !tounchedInside {
self.dismissSuggestedMentionList()
}
return tounchedInside
}
open override func messageInputView(_ messageInputView: SBUMessageInputView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
guard let textView = messageInputView.textView else { return false }
return self.mentionManager?.shouldChangeText(
on: textView,
in: range,
replacementText: text
) ?? true
}
open override func messageInputView(_ messageInputView: SBUMessageInputView, shouldInteractWith url: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
// TODO: Mention tap action
return true
}
open override func messageInputView(_ messageInputView: SBUMessageInputView, didChangeSelection range: NSRange) {
guard let textView = messageInputView.textView else { return }
guard let mentionManager = self.mentionManager else { return }
guard !mentionManager.needToSkipSelection(textView) else { return }
guard self.channel?.isBroadcast == false else { return }
self.mentionManager?.handleMentionSuggestion(on: textView, range: range)
}
/// Called when the send button was selected.
/// - Parameters:
/// - messageInputView: `SBUMessageinputView` object.
/// - text: The sent text.
/// - NOTE: If there's mentions in `mentionManager.mentionedList`, It invokes ``messageInputView(_:didSelectSend:mentionManager:)`` instead.
open override func messageInputView(_ messageInputView: SBUMessageInputView, didSelectSend text: String) {
if let textView = messageInputView.textView,
let mentionManager = mentionManager,
mentionManager.mentionedList.isEmpty == false {
self.messageInputView(messageInputView, didSelectSend: textView.attributedText, mentionManager: mentionManager)
} else {
super.messageInputView(messageInputView, didSelectSend: text)
}
}
/// Called when the message input mode will be changed via `setMode(_:message:)` method.
/// - Parameters:
/// - messageInputView: `SBUMessageinputView` object.
/// - mode: `SBUMessageInputMode` value. The `messageInputView` changes its mode to this value.
/// - message: `BaseMessage` object. It's `nil` when the `mode` is `none`.
/// - NOTE: If there's mentions in `mentionManager.mentionedList`, It invokes ``messageInputView(_:willChangeMode:message:mentionManager:)`` instead.
open override func messageInputView(_ messageInputView: SBUMessageInputView, willChangeMode mode: SBUMessageInputMode, message: BaseMessage?) {
if let mentionManager = mentionManager,
mentionManager.mentionedList.isEmpty == false {
self.messageInputView(messageInputView, willChangeMode: mode, message: message, mentionManager: mentionManager)
} else {
super.messageInputView(messageInputView, willChangeMode: mode, message: message)
}
}
/// Called when the message input mode will be changed via `setMode(_:message:)` method and need to reset the `mentionManager`.
open func messageInputView(_ messageInputView: SBUMessageInputView, willChangeMode mode: SBUMessageInputMode, message: BaseMessage?, mentionManager: SBUMentionManager) {
let mentionedMessageTemplate: String
if let text = messageInputView.textView?.attributedText {
mentionedMessageTemplate = mentionManager.generateTemplate(
with: text,
mentions: mentionManager.mentionedList
)
} else {
mentionedMessageTemplate = ""
}
self.delegate?.groupChannelModule(
self,
willChangeMode: mode,
message: message,
mentionedMessageTemplate: mentionedMessageTemplate,
mentionedUserIds: mentionManager.mentionedList.compactMap { $0.user.userId }
)
mentionManager.reset()
}
open func messageInputView(_ messageInputView: SBUMessageInputView, didSelectSend text: NSAttributedString, mentionManager: SBUMentionManager) {
var parentMessage: BaseMessage?
switch messageInputView.option {
case .quoteReply(let message):
parentMessage = message
default:
break
}
self.delegate?.groupChannelModule(
self,
didTapSend: text.string,
mentionedMessageTemplate: mentionManager.generateTemplate(
with: text,
mentions: mentionManager.mentionedList
),
mentionedUserIds: mentionManager.mentionedList.compactMap { $0.user.userId },
parentMessage: parentMessage
)
messageInputView.setMode(.none)
mentionManager.reset()
}
open override func messageInputView(_ messageInputView: SBUMessageInputView, didSelectEdit text: String) {
if let textView = messageInputView.textView,
let mentionManager = mentionManager,
mentionManager.mentionedList.isEmpty == false {
self.messageInputView(messageInputView, didSelectEdit: textView.attributedText, mentionManager: mentionManager)
} else {
super.messageInputView(messageInputView, didSelectEdit: text)
}
}
open func messageInputView(_ messageInputView: SBUMessageInputView, didSelectEdit text: NSAttributedString, mentionManager: SBUMentionManager) {
self.delegate?.groupChannelModule(
self,
didTapEdit: text.string,
mentionedMessageTemplate: mentionManager.generateTemplate(
with: text,
mentions: mentionManager.mentionedList
),
mentionedUserIds: mentionManager.mentionedList.compactMap { $0.user.userId }
)
mentionManager.reset()
}
open override func messageInputViewDidTapVoiceMessage(_ messageInputView: SBUMessageInputView) {
self.delegate?.groupChannelModuleDidTapVoiceMessage(self)
}
// MARK: SBUMentionManagerDelegate
open func mentionManager(_ manager: SBUMentionManager,
didChangeSuggestedMention members: [SBUUser],