-
Notifications
You must be signed in to change notification settings - Fork 93
/
Copy pathBaseChatViewController.swift
3610 lines (2871 loc) Β· 163 KB
/
BaseChatViewController.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
//
// SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
// SPDX-License-Identifier: GPL-3.0-or-later
//
import Foundation
import NextcloudKit
import PhotosUI
import UIKit
import Realm
import ContactsUI
import QuickLook
import SwiftUI
@objcMembers public class BaseChatViewController: InputbarViewController,
UITextFieldDelegate,
UIImagePickerControllerDelegate,
PHPickerViewControllerDelegate,
UINavigationControllerDelegate,
PollCreationViewControllerDelegate,
ShareLocationViewControllerDelegate,
CNContactPickerDelegate,
UIDocumentPickerDelegate,
VLCKitVideoViewControllerDelegate,
ShareViewControllerDelegate,
QLPreviewControllerDelegate,
QLPreviewControllerDataSource,
NCChatFileControllerDelegate,
ShareConfirmationViewControllerDelegate,
AVAudioRecorderDelegate,
AVAudioPlayerDelegate,
SystemMessageTableViewCellDelegate,
BaseChatTableViewCellDelegate,
UITableViewDataSourcePrefetching {
// MARK: - Internal var
internal var messages: [Date: [NCChatMessage]] = [:]
internal var dateSections: [Date] = []
internal var isVisible = false
internal var isTyping = false
internal var firstUnreadMessage: NCChatMessage?
internal var dismissNotificationsOnViewWillDisappear = true
internal var replyMessageView: ReplyMessageView?
internal var voiceMessagesPlayer: AVAudioPlayer?
internal var interactingMessage: NCChatMessage?
internal var lastMessageBeforeInteraction: IndexPath?
internal var contextMenuActionBlock: (() -> Void)?
internal var editingMessage: NCChatMessage?
internal lazy var emojiTextField: EmojiTextField = {
let emojiTextField = EmojiTextField()
emojiTextField.delegate = self
self.view.addSubview(emojiTextField)
return emojiTextField
}()
internal lazy var datePickerTextField: DatePickerTextField = {
let datePicker = DatePickerTextField()
datePicker.delegate = self
self.view.addSubview(datePicker)
return datePicker
}()
internal lazy var chatBackgroundView: PlaceholderView = {
let chatBackgroundView = PlaceholderView()
chatBackgroundView.placeholderView.isHidden = true
chatBackgroundView.loadingView.startAnimating()
chatBackgroundView.placeholderTextView.text = NSLocalizedString("No messages yet, start the conversation!", comment: "")
chatBackgroundView.setImage(UIImage(named: "chat-placeholder"))
return chatBackgroundView
}()
// MARK: - Private var
private var sendButtonTagMessage = 99
private var sendButtonTagVoice = 98
private var isVoiceRecordingLocked = false
private var actionTypeTranscribeVoiceMessage = "transcribe-voice-message"
private var imagePicker: UIImagePickerController?
private var stopTypingTimer: Timer?
private var typingTimer: Timer?
private var voiceMessageLongPressGesture: UILongPressGestureRecognizer?
private var recorder: AVAudioRecorder?
private var voiceMessageRecordingView: VoiceMessageRecordingView?
private var expandedUIHostingController: UIHostingController<ExpandedVoiceMessageRecordingView>?
private var longPressStartingPoint: CGPoint?
private var cancelHintLabelInitialPositionX: CGFloat?
private var recordCancelled: Bool = false
private var animationDispatchGroup = DispatchGroup()
private var animationDispatchQueue = DispatchQueue(label: "\(groupIdentifier).animationQueue")
private var loadingHistoryView: UIActivityIndicatorView?
private var isPreviewControllerShown: Bool = false
private var previewControllerFilePath: String?
private var playerProgressTimer: Timer?
private var playerAudioFileStatus: NCChatFileStatus?
private var photoPicker: PHPickerViewController?
private var contextMenuAccessoryView: UIView?
private var contextMenuMessageView: UIView?
private lazy var inputbarBorderView: UIView = {
let inputbarBorderView = UIView()
inputbarBorderView.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
inputbarBorderView.frame = .init(x: 0, y: 0, width: self.textInputbar.frame.size.width, height: 1)
inputbarBorderView.isHidden = true
inputbarBorderView.backgroundColor = .systemGray6
self.textInputbar.addSubview(inputbarBorderView)
return inputbarBorderView
}()
private lazy var unreadMessageButton: UIButton = {
let unreadMessageButton = UIButton(frame: .init(x: 0, y: 0, width: 126, height: 24))
unreadMessageButton.backgroundColor = NCAppBranding.themeColor()
unreadMessageButton.setTitleColor(NCAppBranding.themeTextColor(), for: .normal)
unreadMessageButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
unreadMessageButton.layer.cornerRadius = 12
unreadMessageButton.clipsToBounds = true
unreadMessageButton.isHidden = true
unreadMessageButton.translatesAutoresizingMaskIntoConstraints = false
unreadMessageButton.contentEdgeInsets = .init(top: 0, left: 10, bottom: 0, right: 10)
unreadMessageButton.titleLabel?.minimumScaleFactor = 0.9
unreadMessageButton.titleLabel?.numberOfLines = 1
unreadMessageButton.titleLabel?.adjustsFontSizeToFitWidth = true
unreadMessageButton.setTitle(NSLocalizedString("β New messages", comment: ""), for: .normal)
unreadMessageButton.addAction { [weak self] in
guard let self,
let firstUnreadMessage = self.firstUnreadMessage,
let indexPath = self.indexPath(for: firstUnreadMessage)
else { return }
self.tableView?.scrollToRow(at: indexPath, at: .none, animated: true)
}
self.view.addSubview(unreadMessageButton)
return unreadMessageButton
}()
private lazy var scrollToBottomButton: UIButton = {
let button = UIButton(frame: .init(x: 0, y: 0, width: 44, height: 44), primaryAction: UIAction { [weak self] _ in
self?.tableView?.slk_scrollToBottom(animated: true)
})
button.backgroundColor = .secondarySystemBackground
button.tintColor = .systemBlue
button.layer.cornerRadius = button.frame.size.height / 2
button.clipsToBounds = true
button.alpha = 0
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(systemName: "chevron.down"), for: .normal)
self.view.addSubview(button)
return button
}()
private lazy var voiceRecordingLockButton: UIButton = {
let button = UIButton(frame: .init(x: 0, y: 0, width: 44, height: 44))
button.backgroundColor = .secondarySystemBackground
button.tintColor = .systemBlue
button.layer.cornerRadius = button.frame.size.height / 2
button.clipsToBounds = true
button.alpha = 0
button.translatesAutoresizingMaskIntoConstraints = false
button.setImage(UIImage(systemName: "lock.open"), for: .normal)
self.view.addSubview(button)
return button
}()
// MARK: - Init/Deinit
public init?(for room: NCRoom) {
super.init(for: room, tableViewStyle: .plain)
self.hidesBottomBarWhenPushed = true
self.tableView?.estimatedRowHeight = 0
self.tableView?.estimatedSectionHeaderHeight = 0
self.tableView?.prefetchDataSource = self
FilePreviewImageView.setSharedImageDownloader(NCAPIController.sharedInstance().imageDownloader)
NotificationCenter.default.addObserver(self, selector: #selector(willShowKeyboard(notification:)), name: UIWindow.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(willHideKeyboard(notification:)), name: UIWindow.keyboardWillHideNotification, object: nil)
AllocationTracker.shared.addAllocation("ChatViewController")
}
// Not using an optional here, because it is not available from ObjC
// Pass "0" as highlightMessageId to not highlight a message
public convenience init?(for room: NCRoom, withMessage messages: [NCChatMessage], withHighlightId highlightMessageId: Int) {
self.init(for: room)
// When we pass in a fixed number of messages, we hide the inputbar by default
self.textInputbar.isHidden = true
// Scroll to bottom manually after hiding the textInputbar, otherwise the
// scrollToBottom button might be briefly visible even if not needed
self.tableView?.slk_scrollToBottom(animated: false)
self.appendMessages(messages: messages)
self.tableView?.performBatchUpdates({
self.tableView?.reloadData()
}, completion: { _ in
self.highlightMessageWithContentOffset(messageId: highlightMessageId)
})
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
AllocationTracker.shared.removeAllocation("ChatViewController")
NSLog("Dealloc BaseChatViewController")
}
// MARK: - View lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
self.shouldScrollToBottomAfterKeyboardShows = false
self.isInverted = false
self.showSendMessageButton()
self.leftButton.setImage(UIImage(systemName: "paperclip"), for: .normal)
self.leftButton.accessibilityLabel = NSLocalizedString("Share a file from your Nextcloud", comment: "")
self.leftButton.accessibilityHint = NSLocalizedString("Double tap to open file browser", comment: "")
// Set delegate to retrieve typing events
self.tableView?.separatorStyle = .none
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatGroupedMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatReplyMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: fileMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: fileGroupedMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: locationMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: locationGroupedMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: voiceMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: voiceGroupedMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: pollMessageCellIdentifier)
self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: pollGroupedMessageCellIdentifier)
self.tableView?.register(SystemMessageTableViewCell.self, forCellReuseIdentifier: SystemMessageCellIdentifier)
self.tableView?.register(SystemMessageTableViewCell.self, forCellReuseIdentifier: InvisibleSystemMessageCellIdentifier)
self.tableView?.register(MessageSeparatorTableViewCell.self, forCellReuseIdentifier: MessageSeparatorCellIdentifier)
let newMessagesButtonText = NSLocalizedString("β New messages", comment: "")
// Need to move down to NSLayout
let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
let textSize = NSString(string: newMessagesButtonText).boundingRect(with: .init(width: 300, height: 24), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let buttonWidth = textSize.size.width + 20
let views = [
"unreadMessageButton": self.unreadMessageButton,
"textInputbar": self.textInputbar,
"scrollToBottomButton": self.scrollToBottomButton,
"autoCompletionView": self.autoCompletionView,
"voiceRecordingLockButton": self.voiceRecordingLockButton
]
let metrics = [
"buttonWidth": buttonWidth
]
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[unreadMessageButton(24)]-5-[autoCompletionView]", metrics: metrics, views: views))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[unreadMessageButton(buttonWidth)]-(>=0)-|", metrics: metrics, views: views))
if let view = self.view {
self.view.addConstraint(NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: self.unreadMessageButton, attribute: .centerX, multiplier: 1, constant: 0))
}
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[scrollToBottomButton(44)]-10-[autoCompletionView]", metrics: metrics, views: views))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[scrollToBottomButton(44)]-(>=0)-|", metrics: metrics, views: views))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[voiceRecordingLockButton(44)]-64-[autoCompletionView]", metrics: metrics, views: views))
self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[voiceRecordingLockButton(44)]-(>=0)-|", metrics: metrics, views: views))
self.scrollToBottomButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
self.voiceRecordingLockButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
self.addMenuToLeftButton()
self.replyMessageView?.addObserver(self, forKeyPath: "visible", options: .new, context: nil)
}
// swiftlint:disable:next block_based_kvo
public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
guard let object = object as? ReplyMessageView,
object == self.replyMessageView else { return }
// When the visible state of the replyMessageView changes, we need to update the toolbar to show the correct border
// Only do this if we are not already at the bottom, otherwise we briefly show the scroll button directly after sending a message
self.updateToolbar(animated: true)
}
public func updateToolbar(animated: Bool) {
guard let tableView else { return }
let animations = {
let minimumOffset = (tableView.contentSize.height - tableView.frame.size.height) - 10
if tableView.contentOffset.y < minimumOffset {
// Scrolled -> show top border
// When a reply view is visible, we show the border of that view
if let replyMessageView = self.replyMessageView {
replyMessageView.topBorder.isHidden = !replyMessageView.isVisible
self.inputbarBorderView.isHidden = replyMessageView.isVisible
} else {
self.inputbarBorderView.isHidden = false
}
} else {
// At the bottom -> no top border
self.inputbarBorderView.isHidden = true
if let replyMessageView = self.replyMessageView {
replyMessageView.topBorder.isHidden = true
}
}
}
let animationsScrollButton = {
let minimumOffset = (tableView.contentSize.height - tableView.frame.size.height) - 10
if tableView.contentOffset.y < minimumOffset {
// Scrolled -> show button
self.scrollToBottomButton.alpha = 1
} else {
// At the bottom -> hide button
self.scrollToBottomButton.alpha = 0
}
}
if animated {
self.animationDispatchQueue.async {
self.animationDispatchGroup.enter()
self.animationDispatchGroup.enter()
DispatchQueue.main.async {
UIView.transition(with: self.textInputbar,
duration: 0.3,
options: .transitionCrossDissolve,
animations: animations) { _ in
self.animationDispatchGroup.leave()
}
}
DispatchQueue.main.async {
UIView.animate(withDuration: 0.3,
animations: animationsScrollButton) { _ in
self.animationDispatchGroup.leave()
}
}
_ = self.animationDispatchGroup.wait(timeout: .distantFuture)
}
} else {
DispatchQueue.main.async {
animations()
animationsScrollButton()
}
}
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.isVisible = true
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.isVisible = false
if !self.textInputbar.isHidden {
self.savePendingMessage()
}
if dismissNotificationsOnViewWillDisappear {
NotificationPresenter.shared().dismiss(animated: false)
}
}
public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
self.updateToolbar(animated: true)
}
}
// MARK: - Keyboard notifications
func willShowKeyboard(notification: Notification) {
guard let currentResponder = UIResponder.slk_currentFirst() else { return }
// Skip if it's not the emoji/date text field
if !currentResponder.isKind(of: EmojiTextField.self) && !currentResponder.isKind(of: DatePickerTextField.self) {
return
}
guard let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
let keyboardRect = keyboardFrame.cgRectValue
self.updateView(toShowOrHideEmojiKeyboard: keyboardRect.size.height)
guard let interactingMessage,
let indexPath = self.indexPath(for: interactingMessage) else {
return
}
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
if let tableView = self.tableView {
let cellRect = tableView.rectForRow(at: indexPath)
if !tableView.bounds.contains(cellRect) {
self.tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
}
}
}
func willHideKeyboard(notification: Notification) {
guard let currentResponder = UIResponder.slk_currentFirst() else { return }
// Skip if it's not the emoji/date text field
if !currentResponder.isKind(of: EmojiTextField.self) && !currentResponder.isKind(of: DatePickerTextField.self) {
return
}
self.updateView(toShowOrHideEmojiKeyboard: 0.0)
guard let lastMessageBeforeInteraction, let tableView else { return }
if NCUtils.isValid(indexPath: lastMessageBeforeInteraction, forTableView: tableView) {
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
tableView.scrollToRow(at: lastMessageBeforeInteraction, at: .bottom, animated: true)
}
}
}
// MARK: - Utils
internal func getHeaderString(fromDate date: Date) -> String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.doesRelativeDateFormatting = true
return formatter.string(from: date)
}
internal func presentWithNavigation(_ viewControllerToPresent: UIViewController, animated flag: Bool) {
self.present(NCNavigationController(rootViewController: viewControllerToPresent), animated: flag)
}
// MARK: - Temporary messages
internal func createTemporaryMessage(message: String, replyTo parentMessage: NCChatMessage?, messageParameters: String, silently: Bool) -> NCChatMessage {
let temporaryMessage = NCChatMessage()
let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
temporaryMessage.accountId = activeAccount.accountId
temporaryMessage.actorDisplayName = activeAccount.userDisplayName
temporaryMessage.actorId = activeAccount.userId
temporaryMessage.actorType = "users"
temporaryMessage.timestamp = Int(Date().timeIntervalSince1970)
temporaryMessage.token = room.token
temporaryMessage.message = self.replaceMentionsDisplayNamesWithMentionsKeysInMessage(message: message, parameters: messageParameters)
let referenceId = "temp-\(Date().timeIntervalSince1970 * 1000)"
temporaryMessage.referenceId = NCUtils.sha1(fromString: referenceId)
temporaryMessage.internalId = referenceId
temporaryMessage.isTemporary = true
temporaryMessage.parentId = parentMessage?.internalId
temporaryMessage.messageParametersJSONString = messageParameters
temporaryMessage.isSilent = silently
temporaryMessage.isMarkdownMessage = NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityMarkdownMessages, for: self.room)
let realm = RLMRealm.default()
try? realm.transaction {
realm.add(temporaryMessage)
}
let unmanagedTemporaryMessage = NCChatMessage(value: temporaryMessage)
return unmanagedTemporaryMessage
}
internal func replaceMessageMentionsKeysWithMentionsDisplayNames(message: String, parameters: String) -> String {
var resultMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
guard let messageParametersDict = NCMessageParameter.messageParametersDict(fromJSONString: parameters) else { return resultMessage }
for (parameterKey, parameter) in messageParametersDict {
let parameterKeyString = "{\(parameterKey)}"
resultMessage = resultMessage.replacingOccurrences(of: parameterKeyString, with: parameter.mentionDisplayName)
}
return resultMessage
}
internal func appendTemporaryMessage(temporaryMessage: NCChatMessage) {
DispatchQueue.main.async {
let lastSectionBeforeUpdate = self.dateSections.count - 1
self.appendMessages(messages: [temporaryMessage])
if let lastDateSection = self.dateSections.last, let messagesForLastDate = self.messages[lastDateSection] {
let lastMessageIndexPath = IndexPath(row: messagesForLastDate.count - 1, section: self.dateSections.count - 1)
self.tableView?.beginUpdates()
let newLastSection = self.dateSections.count - 1
if lastSectionBeforeUpdate != newLastSection {
self.tableView?.insertSections(.init(integer: newLastSection), with: .none)
} else {
self.tableView?.insertRows(at: [lastMessageIndexPath], with: .none)
}
self.tableView?.endUpdates()
self.tableView?.scrollToRow(at: lastMessageIndexPath, at: .none, animated: true)
}
}
}
internal func removePermanentlyTemporaryMessage(temporaryMessage: NCChatMessage) {
let realm = RLMRealm.default()
try? realm.transaction {
if let managedTemporaryMessage = NCChatMessage.objects(where: "referenceId = %@ AND isTemporary = true", temporaryMessage.referenceId).firstObject() {
realm.delete(managedTemporaryMessage)
}
}
self.removeTemporaryMessages(temporaryMessages: [temporaryMessage])
}
internal func removeTemporaryMessages(temporaryMessages: [NCChatMessage]) {
DispatchQueue.main.async {
for temporaryMessage in temporaryMessages {
if let indexPath = self.indexPath(for: temporaryMessage) {
self.removeMessage(at: indexPath)
}
}
}
}
// MARK: - Message updates
internal func modifyMessageWith(referenceId: String, block: (NCChatMessage) -> Void) {
guard let (indexPath, message) = self.indexPathAndMessage(forReferenceId: referenceId)
else { return }
block(message)
self.tableView?.beginUpdates()
self.tableView?.reloadRows(at: [indexPath], with: .none)
self.tableView?.endUpdates()
}
internal func updateMessage(withMessageId messageId: Int, updatedMessage: NCChatMessage) {
DispatchQueue.main.async {
guard let (indexPath, message) = self.indexPathAndMessage(forMessageId: messageId) else { return }
var reloadIndexPaths = [indexPath]
let isAtBottom = self.shouldScrollOnNewMessages()
let keyDate = self.dateSections[indexPath.section]
updatedMessage.isGroupMessage = message.isGroupMessage && message.actorType != "bots" && updatedMessage.lastEditTimestamp == 0
self.messages[keyDate]?[indexPath.row] = updatedMessage
// Check if there are any messages that reference our message as a parent -> these need to be reloaded as well
if let visibleIndexPaths = self.tableView?.indexPathsForVisibleRows {
let referencingIndexPaths = visibleIndexPaths.filter({
guard let message = self.message(for: $0),
let parentMessage = message.parent
else { return false }
return parentMessage.messageId == messageId
})
reloadIndexPaths.append(contentsOf: referencingIndexPaths)
}
self.tableView?.beginUpdates()
self.tableView?.reloadRows(at: reloadIndexPaths, with: .none)
self.tableView?.endUpdates()
if isAtBottom {
// Make sure we're really at the bottom after updating a message
DispatchQueue.main.async {
self.tableView?.slk_scrollToBottom(animated: false)
self.updateToolbar(animated: false)
}
}
}
}
// MARK: - User interface
func showVoiceMessageRecordButton() {
self.rightButton.setTitle("", for: .normal)
self.rightButton.setImage(UIImage(systemName: "mic"), for: .normal)
self.rightButton.tag = sendButtonTagVoice
self.rightButton.accessibilityLabel = NSLocalizedString("Record voice message", comment: "")
self.rightButton.accessibilityHint = NSLocalizedString("Tap and hold to record a voice message", comment: "")
self.addGestureRecognizerToRightButton()
}
func showSendMessageButton() {
self.rightButton.setTitle("", for: .normal)
self.rightButton.setImage(UIImage(systemName: "paperplane"), for: .normal)
self.rightButton.tag = sendButtonTagMessage
self.rightButton.accessibilityLabel = NSLocalizedString("Send message", comment: "")
self.rightButton.accessibilityHint = NSLocalizedString("Double tap to send message", comment: "")
self.addMenuToRightButton()
}
// MARK: - Action methods
func sendChatMessage(message: String, withParentMessage parentMessage: NCChatMessage?, messageParameters: String, silently: Bool) {
// Overridden in sub class
}
func sendCurrentMessage(silently: Bool) {
var replyToMessage: NCChatMessage?
if let replyMessageView, replyMessageView.isVisible {
replyToMessage = replyMessageView.message
}
let messageParameters = NCMessageParameter.messageParametersJSONString(from: self.mentionsDict) ?? ""
self.sendChatMessage(message: self.textView.text, withParentMessage: replyToMessage, messageParameters: messageParameters, silently: silently)
self.mentionsDict.removeAll()
self.replyMessageView?.dismiss()
super.didPressRightButton(self)
self.clearPendingMessage()
self.stopTyping(force: true)
}
public override func didPressRightButton(_ sender: Any?) {
guard let button = sender as? UIButton else { return }
switch button.tag {
case sendButtonTagMessage:
self.sendCurrentMessage(silently: false)
super.didPressRightButton(sender)
case sendButtonTagVoice:
self.showVoiceMessageRecordHint()
default:
break
}
}
func addGestureRecognizerToRightButton() {
// Remove a potential menu so it does not interfere with the long gesture recognizer
self.rightButton.menu = nil
// Add long press gesture recognizer for voice message recording button
self.voiceMessageLongPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressInVoiceMessageRecordButton(gestureRecognizer:)))
if let voiceMessageLongPressGesture {
voiceMessageLongPressGesture.delegate = self
self.rightButton.addGestureRecognizer(voiceMessageLongPressGesture)
}
}
func addMenuToRightButton() {
// Remove a gesture recognizer to not interfere with our menu
if let voiceMessageLongPressGesture = self.voiceMessageLongPressGesture {
self.rightButton.removeGestureRecognizer(voiceMessageLongPressGesture)
self.voiceMessageLongPressGesture = nil
}
let silentSendAction = UIAction(title: NSLocalizedString("Send without notification", comment: ""), image: UIImage(systemName: "bell.slash")) { [unowned self] _ in
self.sendCurrentMessage(silently: true)
}
self.rightButton.menu = UIMenu(children: [silentSendAction])
}
func addMenuToLeftButton() {
// The keyboard will be hidden when an action is invoked. Depending on what
// attachment is shared, not resigning might lead to a currupted chat view
var items: [UIAction] = []
let cameraAction = UIAction(title: NSLocalizedString("Camera", comment: ""), image: UIImage(systemName: "camera")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.checkAndPresentCamera()
}
let photoLibraryAction = UIAction(title: NSLocalizedString("Photo Library", comment: ""), image: UIImage(systemName: "photo")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentPhotoLibrary()
}
let shareLocationAction = UIAction(title: NSLocalizedString("Location", comment: ""), image: UIImage(systemName: "location")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentShareLocation()
}
let contactShareAction = UIAction(title: NSLocalizedString("Contacts", comment: ""), image: UIImage(systemName: "person")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentShareContact()
}
let filesAction = UIAction(title: NSLocalizedString("Files", comment: ""), image: UIImage(systemName: "doc")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentDocumentPicker()
}
let ncFilesAction = UIAction(title: filesAppName, image: UIImage(named: "logo-action")?.withRenderingMode(.alwaysTemplate)) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentNextcloudFilesBrowser()
}
let pollAction = UIAction(title: NSLocalizedString("Poll", comment: ""), image: UIImage(systemName: "chart.bar")) { [unowned self] _ in
self.textView.resignFirstResponder()
self.presentPollCreation()
}
// Add actions (inverted)
items.append(ncFilesAction)
items.append(filesAction)
items.append(contactShareAction)
if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityLocationSharing, for: self.room) {
items.append(shareLocationAction)
}
if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityTalkPolls, for: self.room),
self.room.type != .oneToOne, self.room.type != .noteToSelf {
items.append(pollAction)
}
items.append(photoLibraryAction)
if UIImagePickerController.isSourceTypeAvailable(.camera) {
items.append(cameraAction)
}
self.leftButton.menu = UIMenu(children: items)
self.leftButton.showsMenuAsPrimaryAction = true
}
func presentNextcloudFilesBrowser() {
let directoryVC = DirectoryTableViewController(path: "", inRoom: self.room.token)
self.presentWithNavigation(directoryVC, animated: true)
}
func checkAndPresentCamera() {
// https://stackoverflow.com/a/20464727/2512312
let mediaType = AVMediaType.video
let authStatus = AVCaptureDevice.authorizationStatus(for: mediaType)
if authStatus == AVAuthorizationStatus.authorized {
self.presentCamera()
return
} else if authStatus == AVAuthorizationStatus.notDetermined {
AVCaptureDevice.requestAccess(for: mediaType, completionHandler: { (granted: Bool) in
if granted {
self.presentCamera()
}
})
return
}
let alert = UIAlertController(title: NSLocalizedString("Could not access camera", comment: ""),
message: NSLocalizedString("Camera access is not allowed. Check your settings.", comment: ""),
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
}
func presentCamera() {
DispatchQueue.main.async {
self.imagePicker = UIImagePickerController()
if let imagePicker = self.imagePicker,
let sourceType = UIImagePickerController.availableMediaTypes(for: imagePicker.sourceType) {
imagePicker.sourceType = .camera
imagePicker.cameraFlashMode = UIImagePickerController.CameraFlashMode(rawValue: NCUserDefaults.preferredCameraFlashMode()) ?? .off
imagePicker.mediaTypes = sourceType
imagePicker.delegate = self
self.present(imagePicker, animated: true)
}
}
}
func presentPhotoLibrary() {
DispatchQueue.main.async {
var pickerConfig = PHPickerConfiguration()
pickerConfig.selectionLimit = 5
pickerConfig.filter = PHPickerFilter.any(of: [.images, .videos])
self.photoPicker = PHPickerViewController(configuration: pickerConfig)
if let photoPicker = self.photoPicker {
photoPicker.delegate = self
self.present(photoPicker, animated: true)
}
}
}
func presentPollCreation() {
let pollCreationVC = PollCreationViewController(style: .insetGrouped)
pollCreationVC.pollCreationDelegate = self
self.presentWithNavigation(pollCreationVC, animated: true)
}
func presentShareLocation() {
let shareLocationVC = ShareLocationViewController()
shareLocationVC.delegate = self
self.presentWithNavigation(shareLocationVC, animated: true)
}
func presentShareContact() {
let contactPicker = CNContactPickerViewController()
contactPicker.delegate = self
self.present(contactPicker, animated: true)
}
func presentDocumentPicker() {
DispatchQueue.main.async {
let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
documentPicker.delegate = self
self.present(documentPicker, animated: true)
}
}
func showReplyView(for message: NCChatMessage) {
let isAtBottom = self.shouldScrollOnNewMessages()
let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
if let replyProxyView = self.replyProxyView as? ReplyMessageView {
self.replyMessageView = replyProxyView
replyProxyView.presentReply(with: message, withUserId: activeAccount.userId)
self.presentKeyboard(true)
// Make sure we're really at the bottom after showing the replyMessageView
if isAtBottom {
self.tableView?.slk_scrollToBottom(animated: false)
self.updateToolbar(animated: false)
}
}
}
func didPressReply(for message: NCChatMessage) {
// Make sure we get a smooth animation after dismissing the context menu
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
self.showReplyView(for: message)
}
}
func didPressReplyPrivately(for message: NCChatMessage) {
var userInfo: [String: String] = [:]
userInfo["actorId"] = message.actorId
NotificationCenter.default.post(name: .NCChatViewControllerReplyPrivatelyNotification, object: self, userInfo: userInfo)
}
func didPressAddReaction(for message: NCChatMessage, at indexPath: IndexPath) {
// Hide the keyboard because we are going to present the emoji keyboard
DispatchQueue.main.async {
self.textView.resignFirstResponder()
}
DispatchQueue.main.async {
self.interactingMessage = message
self.lastMessageBeforeInteraction = self.tableView?.indexPathsForVisibleRows?.last
if NCUtils.isiOSAppOnMac() {
// Move the emojiTextField to the position of the cell
if let rowRect = self.tableView?.rectForRow(at: indexPath),
var convertedRowRect = self.tableView?.convert(rowRect, to: self.view) {
// Show the emoji picker at the textView location of the cell
convertedRowRect.origin.y += convertedRowRect.size.height - 16
convertedRowRect.origin.x += 54
// We don't want to have a clickable textField floating around
convertedRowRect.size.width = 0
convertedRowRect.size.height = 0
// Remove and add the emojiTextField to the view, so the Mac OS emoji picker is always at the right location
self.emojiTextField.removeFromSuperview()
self.emojiTextField.frame = convertedRowRect
self.view.addSubview(self.emojiTextField)
}
}
self.emojiTextField.becomeFirstResponder()
}
}
func didPressForward(for message: NCChatMessage) {
var shareViewController: ShareViewController
if message.isObjectShare {
shareViewController = ShareViewController(toForwardObjectShare: message, fromChatViewController: self)
} else {
shareViewController = ShareViewController(toForwardMessage: message.parsedMessage().string, fromChatViewController: self)
}
shareViewController.delegate = self
self.presentWithNavigation(shareViewController, animated: true)
}
func didPressNoteToSelf(for message: NCChatMessage) {
let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
NCAPIController.sharedInstance().getNoteToSelfRoom(forAccount: activeAccount) { roomDict, error in
if error == nil, let room = NCRoom(dictionary: roomDict, andAccountId: activeAccount.accountId) {
if message.isObjectShare {
NCAPIController.sharedInstance().shareRichObject(message.richObjectFromObjectShare, inRoom: room.token, for: activeAccount) { error in
if error == nil {
NotificationPresenter.shared().present(text: NSLocalizedString("Added note to self", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
} else {
NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
}
}
} else {
NCAPIController.sharedInstance().sendChatMessage(message.parsedMessage().string, toRoom: room.token, displayName: nil, replyTo: -1, referenceId: nil, silently: false, for: activeAccount) { error in
if error == nil {
NotificationPresenter.shared().present(text: NSLocalizedString("Added note to self", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
} else {
NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
}
}
}
} else {
NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
}
}
}
func didPressResend(for message: NCChatMessage) {
// Make sure there's no unread message separator, as the indexpath could be invalid after removing a message
self.removeUnreadMessagesSeparator()
self.removePermanentlyTemporaryMessage(temporaryMessage: message)
let originalMessage = self.replaceMessageMentionsKeysWithMentionsDisplayNames(message: message.message, parameters: message.messageParametersJSONString ?? "")
self.sendChatMessage(message: originalMessage, withParentMessage: message.parent, messageParameters: message.messageParametersJSONString ?? "", silently: message.isSilent)
}
func didPressCopy(for message: NCChatMessage) {
let pasteboard = UIPasteboard.general
pasteboard.string = message.parsedMessage().string
NotificationPresenter.shared().present(text: NSLocalizedString("Message copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
}
func didPressCopyLink(for message: NCChatMessage) {
guard let link = room.linkURL else {
return
}
let url = "\(link)#message_\(message.messageId)"
let pasteboard = UIPasteboard.general
pasteboard.string = url