-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathChatViewController.swift
More file actions
2684 lines (2107 loc) Β· 118 KB
/
ChatViewController.swift
File metadata and controls
2684 lines (2107 loc) Β· 118 KB
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 SwiftyAttributes
import SwiftUI
@objcMembers public class ChatViewController: BaseChatViewController {
// MARK: - Public var
public var presentedInCall = false
public var presentKeyboardOnAppear = false
public var chatController: NCChatController
public var highlightMessageId = 0
public var presentThreadOnAppear = 0
// MARK: - Private var
private var hasPresentedLobby = false
private var hasRequestedInitialHistory = false
private var hasReceiveInitialHistory = false
private var retrievingHistory = false
private var hasJoinedRoom = false
private var startReceivingMessagesAfterJoin = false
private var offlineMode = false
private var hasStoredHistory = true
private var hasStopped = false
private var hasCheckedOutOfOfficeStatus = false
private var chatViewPresentedTimestamp = Date().timeIntervalSince1970
private var generateSummaryFromMessageId: Int?
private var generateSummaryTimer: Timer?
private var startCallSilently: Bool = false
private lazy var unreadMessagesSeparator: NCChatMessage = {
let message = NCChatMessage()
message.messageId = MessageSeparatorTableViewCell.unreadMessagesSeparatorId
// We decide at this point if the unread marker should be with/without summary button, so it doesn't get changed when the room is updated
if !self.room.isFederated, NCDatabaseManager.sharedInstance().serverHasTalkCapability(kCapabilityChatSummary, forAccountId: self.room.accountId),
let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId),
serverCapabilities.summaryThreshold <= self.room.unreadMessages {
message.messageId = MessageSeparatorTableViewCell.unreadMessagesWithSummarySeparatorId
}
return message
}()
private lazy var lastReadMessage: Int = {
return self.room.lastReadMessage
}()
private var lobbyCheckTimer: Timer?
public var isThreadViewController: Bool {
return thread != nil
}
// MARK: - Thread notification levels
enum NotificationLevelOption: Int, CaseIterable {
case room
case allMessages
case mentions
case off
var value: Int { rawValue }
var title: String {
switch self {
case .room:
return NSLocalizedString("Default", comment: "")
case .allMessages:
return NSLocalizedString("All messages", comment: "")
case .mentions:
return NSLocalizedString("@-mentions only", comment: "")
case .off:
return NSLocalizedString("Off", comment: "")
}
}
var subtitle: String? {
switch self {
case .room:
return NSLocalizedString("Follow conversation settings", comment: "")
default:
return nil
}
}
var image: UIImage? {
let config = UIImage.SymbolConfiguration(pointSize: 16)
switch self {
case .room:
return UIImage(systemName: "bell", withConfiguration: config)
case .allMessages:
return UIImage(systemName: "bell.and.waves.left.and.right", withConfiguration: config)
case .mentions:
return UIImage(systemName: "bell", withConfiguration: config)
case .off:
return UIImage(systemName: "bell.slash", withConfiguration: config)
}
}
}
// MARK: - Buttons in NavigationBar
func getCallOptionsBarButton() -> BarButtonItemWithActivity {
let button = BarButtonItemWithActivity(image: UIImage())
configureCallButtonAsInCall(button: button, inCall: room.hasCall)
setupCallOptionsBarButtonMenu(button: button)
return button
}
func configureCallButtonAsInCall(button: BarButtonItemWithActivity, inCall: Bool) {
let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 16)
let imageName = inCall ? "phone.fill" : "phone"
let image = UIImage(systemName: imageName, withConfiguration: symbolConfiguration) ?? UIImage()
button.setImage(image)
let callButtonColor: UIColor = inCall ? .systemGreen : .clear
if #available(iOS 26.0, *) {
button.tintColor = callButtonColor
button.style = inCall ? .prominent : .plain
} else {
button.setBackgroundColor(callButtonColor)
}
}
func setupCallOptionsBarButtonMenu(button: BarButtonItemWithActivity) {
let audioCallAction = UIAction(title: NSLocalizedString("Start call", comment: ""),
subtitle: NSLocalizedString("Only audio and screen shares", comment: ""),
image: UIImage(systemName: "phone")) { [unowned self] _ in
startCall(withVideo: false, silently: startCallSilently, button: button)
}
audioCallAction.accessibilityIdentifier = "Voice only call"
audioCallAction.accessibilityHint = NSLocalizedString("Double tap to start a voice only call", comment: "")
let videoCallAction = UIAction(title: NSLocalizedString("Start video call", comment: ""),
subtitle: NSLocalizedString("Audio, video and screen shares", comment: ""),
image: UIImage(systemName: "video")) { [unowned self] _ in
startCall(withVideo: true, silently: startCallSilently, button: button)
}
videoCallAction.accessibilityIdentifier = "Video call"
videoCallAction.accessibilityHint = NSLocalizedString("Double tap to start a video call", comment: "")
if self.room.hasCall {
audioCallAction.title = NSLocalizedString("Join call", comment: "")
videoCallAction.title = NSLocalizedString("Join video call", comment: "")
} else if self.startCallSilently {
audioCallAction.title = NSLocalizedString("Start call silently", comment: "")
videoCallAction.title = NSLocalizedString("Start video call silently", comment: "")
}
var callOptions: [UIMenuElement] = [audioCallAction, videoCallAction]
// Only show silent call option when starting a call (not when joining)
if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilitySilentCall, for: self.room), !room.hasCall {
var silentImage = UIImage(systemName: "bell.slash")
if startCallSilently {
silentImage = UIImage(systemName: "bell.slash.fill")?.withTintColor(.systemRed, renderingMode: .alwaysOriginal)
}
let silentCallAction = UIAction(title: NSLocalizedString("Call without notification", comment: ""),
image: silentImage) { [unowned self] _ in
startCallSilently.toggle()
setupCallOptionsBarButtonMenu(button: button)
}
silentCallAction.attributes = [.keepsMenuPresented]
silentCallAction.accessibilityIdentifier = "Call without notification"
silentCallAction.accessibilityHint = NSLocalizedString("Double tap to enable or disable 'Call without notification' option", comment: "")
let silentMenu = UIMenu(title: "", options: [.displayInline], children: [silentCallAction])
callOptions.append(silentMenu)
}
button.innerButton.menu = UIMenu(title: "", children: callOptions)
button.innerButton.showsMenuAsPrimaryAction = true
}
func startCall(withVideo video: Bool, silently: Bool, button: BarButtonItemWithActivity) {
button.showIndicator()
if self.room.recordingConsent {
let alert = UIAlertController(title: "β οΈ" + NSLocalizedString("The call might be recorded", comment: ""),
message: NSLocalizedString("The recording might include your voice, video from camera, and screen share. Your consent is required before joining the call.", comment: ""),
preferredStyle: .alert)
alert.addAction(.init(title: NSLocalizedString("Give consent and join call", comment: "Give consent to the recording of the call and join that call"), style: .default) { _ in
CallKitManager.sharedInstance().startCall(self.room.token, withVideoEnabled: video, andDisplayName: self.room.displayName, asInitiator: !self.room.hasCall, silently: silently, recordingConsent: true, withAccountId: self.room.accountId)
})
alert.addAction(.init(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in
button.hideIndicator()
})
NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
} else {
CallKitManager.sharedInstance().startCall(self.room.token, withVideoEnabled: video, andDisplayName: self.room.displayName, asInitiator: !self.room.hasCall, silently: silently, recordingConsent: false, withAccountId: self.room.accountId)
}
}
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
closeButton.primaryAction = UIAction(title: NSLocalizedString("Close", comment: ""), handler: { [unowned self] _ in
if self.presentedInCall {
NCRoomsManager.sharedInstance().callViewController?.toggleChatView()
} else {
self.leaveChat()
self.dismiss(animated: true)
}
})
closeButton.accessibilityIdentifier = "closeChatButton"
return closeButton
}()
private lazy var threadNotificationButton: UIBarButtonItem = {
let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 16)
let buttonImage = UIImage(systemName: "bell", withConfiguration: symbolConfiguration) ?? UIImage()
let button = BarButtonItemWithActivity(image: buttonImage)
self.setupThreadNotificationButtonMenu(button: button)
button.accessibilityLabel = NSLocalizedString("Thread notification level button", comment: "")
button.accessibilityHint = NSLocalizedString("Double tap to display thread notification level options", comment: "")
return button
}()
func setupThreadNotificationButtonMenu(button: BarButtonItemWithActivity) {
guard let thread = thread else { return }
let options = NotificationLevelOption.allCases.map { option in
UIAction(
title: option.title,
subtitle: option.subtitle,
image: option.image,
state: option.value == thread.notificationLevel ? .on : .off
) { [weak self] _ in
guard let self else { return }
button.showIndicator()
NCAPIController.sharedInstance().setNotificationLevelForThread(
for: self.account.accountId,
in: self.room.token,
threadId: thread.threadId,
level: option.value
) { updatedThread in
DispatchQueue.main.async {
button.hideIndicator()
if let updatedThread {
self.thread = updatedThread
self.setupThreadNotificationButtonMenu(button: button)
if updatedThread.notificationLevel != NotificationLevelOption.off.rawValue {
NCDatabaseManager.sharedInstance().updateHasThreads(forAccountId: self.account.accountId, with: true)
}
}
}
}
}
}
if let currentOption = NotificationLevelOption.allCases.first(where: { $0.value == thread.notificationLevel }),
let currentOptionImage = currentOption.image {
button.setImage(currentOptionImage)
}
button.innerButton.menu = UIMenu(options: .displayInline, children: options)
button.innerButton.showsMenuAsPrimaryAction = true
}
private lazy var threadDetailsEditButton: UIBarButtonItem = {
let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 16)
let buttonImage = UIImage(systemName: "ellipsis.circle", withConfiguration: symbolConfiguration) ?? UIImage()
let button = BarButtonItemWithActivity(image: buttonImage)
let editAction = UIAction(
title: NSLocalizedString("Edit thread details", comment: ""),
image: UIImage(systemName: "pencil")
) { [weak self] _ in
guard let self else { return }
self.presentThreadEditDialog()
}
button.innerButton.menu = UIMenu(children: [editAction])
button.innerButton.showsMenuAsPrimaryAction = true
return button
}()
private func presentThreadEditDialog() {
let alert = UIAlertController(
title: NSLocalizedString("Edit thread details", comment: ""),
message: NSLocalizedString("Thread title", comment: ""),
preferredStyle: .alert
)
alert.addTextField { [weak self] textField in
guard let self else { return }
textField.text = self.thread?.title
textField.placeholder = NSLocalizedString("Thread title", comment: "")
}
let saveAction = UIAlertAction(
title: NSLocalizedString("Save", comment: ""),
style: .default
) { [weak self] _ in
guard let self,
let thread,
let title = alert.textFields?.first?.text,
!title.isEmpty, title != thread.title
else { return }
NCAPIController.sharedInstance().renameThread(
with: title,
for: self.account.accountId,
in: self.room.token,
threadId: thread.threadId
) { updatedThread in
DispatchQueue.main.async {
if let updatedThread {
self.thread = updatedThread
}
}
}
}
let cancelAction = UIAlertAction(
title: NSLocalizedString("Cancel", comment: ""),
style: .cancel,
handler: nil
)
alert.addAction(saveAction)
alert.addAction(cancelAction)
present(alert, animated: true)
}
private lazy var callOptionsButton: BarButtonItemWithActivity = {
let callOptionsButton = self.getCallOptionsBarButton()
callOptionsButton.accessibilityLabel = NSLocalizedString("Call options", comment: "")
callOptionsButton.accessibilityHint = NSLocalizedString("Double tap to display call options", comment: "")
return callOptionsButton
}()
private lazy var optionMenuButton: BarButtonItemWithActivity = {
let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 16)
let buttonImage = UIImage(systemName: "ellipsis.circle", withConfiguration: symbolConfiguration) ?? UIImage()
let button = BarButtonItemWithActivity(image: buttonImage)
button.innerButton.menu = createOptionsRoomMenu()
button.innerButton.showsMenuAsPrimaryAction = true
button.accessibilityLabel = NSLocalizedString("Option menu", comment: "A menu to show additional options for the current conversation")
button.accessibilityHint = NSLocalizedString("Double tap to display option menu", comment: "A menu to show additional options for the current conversation")
return button
}()
private func createOptionsRoomMenu() -> UIMenu {
var menuElements: [UIMenuElement] = []
if room.supportsUpcomingEvents {
menuElements.append(self.createEventsMenu())
}
if room.supportsThreading {
menuElements.append(self.createThreadingRoomMenu())
}
return UIMenu(options: [.displayInline], children: menuElements)
}
private func createThreadingRoomMenu() -> UIMenu {
let deferredMenuElement = UIDeferredMenuElement.uncached { [weak self] completion in
guard let self else { return }
NCAPIController.sharedInstance().getThreads(for: self.account.accountId, in: self.room.token, withLimit: 5) { threads in
guard let threads, !threads.isEmpty else {
completion([UIAction(title: NSLocalizedString("No recent threads", comment: ""), attributes: .disabled, handler: { _ in })])
return
}
var actions: [UIAction] = []
let menuCreationGroup = DispatchGroup()
for thread in threads {
menuCreationGroup.enter()
let message = thread.lastMessage() ?? thread.firstMessage()
let action = UIAction(title: thread.title, handler: { _ in
guard let message else { return }
self.didPressShowThread(for: message)
})
actions.append(action)
guard let message else {
menuCreationGroup.leave()
continue
}
action.subtitle = message.lastMessagePreview()?.string
if let image = AvatarManager.shared.getThreadAvatar(for: thread, with: self.traitCollection.userInterfaceStyle) {
action.image = NCUtils.roundedImage(fromImage: image)
}
menuCreationGroup.leave()
}
// TODO: Add a "More threads" button if the limit was returned and open a dedicated view?
menuCreationGroup.notify(queue: .main) {
completion(actions)
}
}
}
return UIMenu(title: NSLocalizedString("Recent threads", comment: ""), options: [.displayInline], children: [deferredMenuElement])
}
private func createEventsMenu() -> UIMenu {
if self.room.isEvent {
return self.createEventsRoomMenu()
} else {
return self.createUpcomingEventsMenu()
}
}
private func createEventsRoomMenu() -> UIMenu {
guard let calendarEvent = self.room.calendarEvent else {
return UIMenu(children: [UIAction(title: NSLocalizedString("No upcoming events", comment: ""), attributes: .disabled, handler: { _ in })])
}
var menuElements: [UIMenuElement] = []
menuElements.append(UIAction(title: NSLocalizedString("Schedule", comment: "Noun. 'Schedule' of a meeting"), subtitle: calendarEvent.readableStartTime(), handler: { _ in }))
if self.room.canModerate, calendarEvent.isPastEvent {
let deleteConversation = UIAction(title: NSLocalizedString("Delete conversation", comment: ""), image: .init(systemName: "trash")) { [unowned self] _ in
NCRoomsManager.sharedInstance().deleteRoom(withConfirmation: self.room, withStartedBlock: nil)
}
deleteConversation.attributes = .destructive
let deleteMenu = UIMenu(title: "", options: [.displayInline], children: [deleteConversation])
menuElements.append(deleteMenu)
}
return UIMenu(title: "", options: [.displayInline], children: menuElements)
}
private func createUpcomingEventsMenu() -> UIMenu {
let deferredUpcomingEvents = UIDeferredMenuElement { [weak self] completion in
guard let self = self else { return }
NCAPIController.sharedInstance().upcomingEvents(self.room, forAccount: self.account) { events in
let actions: [UIAction]
if !events.isEmpty {
actions = events.map { event in
UIAction(title: event.summary, subtitle: event.readableStartTime(), handler: { _ in })
}
} else {
actions = [UIAction(title: NSLocalizedString("No upcoming events", comment: ""), attributes: .disabled, handler: { _ in })]
}
completion(actions)
}
}
var menuElements: [UIMenuElement] = [deferredUpcomingEvents]
if self.room.canModerate || self.room.type == .oneToOne {
let scheduleMeetingAction = UIAction(title: NSLocalizedString("Schedule a meeting", comment: ""), image: UIImage(systemName: "calendar.badge.plus")) { [unowned self] _ in
let scheduleMeetingView = ScheduleMeetingSwiftUIView(account: self.account, room: self.room) {
self.handleMeetingCreationSuccess()
}
let hostingController = UIHostingController(rootView: scheduleMeetingView)
self.present(hostingController, animated: true)
}
menuElements.append(scheduleMeetingAction)
}
return UIMenu(title: NSLocalizedString("Meetings", comment: "Headline for a 'meeting section'"), options: [.displayInline], children: menuElements)
}
private func handleMeetingCreationSuccess() {
// Re-create menu so upcoming events are refetched
optionMenuButton.innerButton.menu = createOptionsRoomMenu()
}
private var messageExpirationTimer: Timer?
override func setTitleView() {
super.setTitleView()
if isThreadViewController {
self.titleView?.update(for: thread)
self.titleView?.longPressGestureRecognizer.isEnabled = false
}
}
public override init?(forRoom room: NCRoom, withAccount account: TalkAccount) {
self.chatController = NCChatController(for: room)
super.init(forRoom: room, withAccount: account)
self.addCommonNotificationObservers()
}
public init?(forThread thread: NCThread, inRoom room: NCRoom, withAccount account: TalkAccount) {
self.chatController = NCChatController(forThreadId: thread.threadId, in: room)
super.init(forRoom: room, withAccount: account)
self.thread = thread
self.addCommonNotificationObservers()
}
func addCommonNotificationObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(didUpdateRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidUpdateRoom, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didJoinRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidJoinRoom, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didLeaveRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidLeaveRoom, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveInitialChatHistory(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveInitialChatHistory, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveInitialChatHistoryOffline(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveInitialChatHistoryOffline, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatHistory(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatHistory, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatMessages(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatMessages, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didSendChatMessage(notification:)), name: NSNotification.Name.NCChatControllerDidSendChatMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatBlocked(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatBlocked, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNewerCommonReadMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveNewerCommonReadMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveCallStartedMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveCallStartedMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveCallEndedMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveCallEndedMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveUpdateMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveUpdateMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveThreadMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveThreadMessage, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveHistoryCleared(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveHistoryCleared, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveMessagesInBackground(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveMessagesInBackground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeRoomCapabilities(notification:)), name: NSNotification.Name.NCDatabaseManagerRoomCapabilitiesChanged, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveParticipantJoin(notification:)), name: .extSignalingDidReceiveJoinOfParticipant, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveParticipantLeave(notification:)), name: .extSignalingDidReceiveLeaveOfParticipant, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveStartedTyping(notification:)), name: .extSignalingDidReceiveStartedTyping, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveStoppedTyping(notification:)), name: .extSignalingDidReceiveStoppedTyping, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didFailRequestingCallTransaction(notification:)), name: NSNotification.Name.CallKitManagerDidFailRequestingCallTransaction, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didUpdateParticipants(notification:)), name: .extSignalingDidUpdateParticipants, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(connectionStateHasChanged(notification:)), name: NSNotification.Name.NCConnectionStateHasChangedNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(maintenanceModeActive(notification:)), name: NSNotification.Name.NCServerMaintenanceMode, object: nil)
// Notifications when runing on Mac
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(notification:)), name: NSNotification.Name(rawValue: "NSApplicationDidBecomeActiveNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(notification:)), name: NSNotification.Name(rawValue: "NSApplicationDidResignActiveNotification"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
print("Dealloc NewChatViewController")
}
// MARK: - View lifecycle
public override func viewDidLoad() {
super.viewDidLoad()
// Right bar button items
var barButtonsItems: [UIBarButtonItem] = []
if presentedInCall {
barButtonsItems = [closeButton]
} else if isThreadViewController {
barButtonsItems = [closeButton]
// Thread edit menu
if let thread, thread.isThreadOwner(NCDatabaseManager.sharedInstance().activeAccount()) || room.canModerate {
barButtonsItems.append(threadDetailsEditButton)
}
// Thread notifications
barButtonsItems.append(threadNotificationButton)
} else {
// Option menu
if room.supportsUpcomingEvents || room.supportsThreading {
barButtonsItems.append(optionMenuButton)
}
// Call options
if room.supportsCalling {
barButtonsItems.append(callOptionsButton)
}
}
self.navigationItem.rightBarButtonItems = barButtonsItems
// No sharing options in federation v1 (or thread view until implemented)
if room.isFederated {
// When hiding the button it is still respected in the layout constraints
// So we need to remove the image to remove the button for now
self.leftButton.setImage(nil, for: .normal)
}
// Disable room info, input bar and call buttons until joining room
self.disableRoomControls()
}
public override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.checkLobbyState()
self.checkRoomControlsAvailability()
self.checkOutOfOfficeAbsence()
self.checkPinnedMessage()
self.checkRetention()
self.startObservingExpiredMessages()
// Workaround for open conversations:
// We can't get initial chat history until we join the conversation (since we are not a participant until then)
// So for rooms that we don't know the last read message we wait until we join the room to get the initial chat history.
if !self.hasReceiveInitialHistory, !self.hasRequestedInitialHistory, self.room.lastReadMessage > 0 {
self.hasRequestedInitialHistory = true
self.chatController.getInitialChatHistory()
}
if !self.offlineMode {
NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
}
// Check if there are summary tasks still running, but not yet finished
if !AiSummaryController.shared.getSummaryTaskIds(forRoomInternalId: self.room.internalId).isEmpty {
self.showGeneratingSummaryNotification()
self.scheduleSummaryTaskCheck()
}
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.presentKeyboardOnAppear {
self.presentKeyboard(true)
self.presentKeyboardOnAppear = false
}
if self.presentThreadOnAppear != 0 {
self.presentThreadView(for: presentThreadOnAppear)
self.presentThreadOnAppear = 0
}
}
public override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.saveLastReadMessage()
self.stopVoiceMessagePlayer()
}
public override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.isMovingFromParent {
self.leaveChat()
}
self.callOptionsButton.hideIndicator()
}
required init?(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - App lifecycle
func appDidBecomeActive(notification: Notification) {
// Don't handle this event if the view is not loaded yet.
// Otherwise we try to join the room and receive new messages while
// viewDidLoad wasn't called, resulting in uninitialized dictionaries and crashes
if !self.isViewLoaded {
return
}
// If we stopped the chat, we don't want to resume it here
if self.hasStopped {
return
}
// Check if new messages were added while the app was inactive (eg. via background-refresh)
self.checkForNewStoredMessages()
if !self.offlineMode {
NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
}
self.startObservingExpiredMessages()
}
func appWillResignActive(notification: Notification) {
// If we stopped the chat, we don't want to change anything here
if self.hasStopped {
return
}
self.startReceivingMessagesAfterJoin = true
self.removeUnreadMessagesSeparator()
self.savePendingMessage()
self.chatController.stop()
self.messageExpirationTimer?.invalidate()
self.stopTyping(force: false)
NCRoomsManager.sharedInstance().leaveChat(inRoom: self.room.token)
}
func connectionStateHasChanged(notification: Notification) {
guard let rawConnectionState = notification.userInfo?["connectionState"] as? Int, let connectionState = ConnectionState(rawValue: rawConnectionState) else {
return
}
switch connectionState {
case .connected:
if offlineMode {
offlineMode = false
startReceivingMessagesAfterJoin = true
self.removeOfflineFooterView()
NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
}
default:
break
}
}
func maintenanceModeActive(notification: Notification) {
self.setOfflineMode()
}
// MARK: - User Interface
func disableRoomControls() {
self.titleView?.isUserInteractionEnabled = false
self.callOptionsButton.hideIndicator()
self.callOptionsButton.isEnabled = false
self.rightButton.isEnabled = false
self.leftButton.isEnabled = false
}
func checkRoomControlsAvailability() {
if hasJoinedRoom, !offlineMode {
// Enable room info and call buttons when we joined a room
self.titleView?.isUserInteractionEnabled = true
self.callOptionsButton.isEnabled = true
}
// Files/objects can only be send when we're not offline
self.leftButton.isEnabled = !offlineMode
// Always allow to start writing a message, even if we didn't join the room (yet)
self.rightButton.isEnabled = self.canPressRightButton()
self.textInputbar.isUserInteractionEnabled = true
if !room.userCanStartCall, !room.hasCall {
// Disable call buttons
self.callOptionsButton.isEnabled = false
}
// Configure inCall state for call button
self.configureCallButtonAsInCall(button: callOptionsButton, inCall: room.hasCall)
if room.readOnlyState == .readOnly || self.shouldPresentLobbyView() {
// Hide text input
self.setTextInputbarHidden(true, animated: self.isVisible)
// Disable call buttons
self.callOptionsButton.isEnabled = false
} else if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityChatPermission, for: room), !room.permissions.contains(.chat) {
// Hide text input
self.setTextInputbarHidden(true, animated: isVisible)
} else if self.isTextInputbarHidden {
// Show text input if it was hidden in a previous state
self.setTextInputbarHidden(false, animated: isVisible)
if self.tableView?.slk_isAtBottom ?? false {
self.tableView?.slk_scrollToBottom(animated: true)
}
// Make sure the textinput has the correct height
self.setChatMessage(self.textInputbar.textView.text)
}
// Rebuild the call menu to reflect the current call state
self.setupCallOptionsBarButtonMenu(button: self.callOptionsButton)
}
func checkLobbyState() {
if self.shouldPresentLobbyView() {
self.hasPresentedLobby = true
var placeholderText = NSLocalizedString("You are currently waiting in the lobby", comment: "")
// Lobby timer
if self.room.lobbyTimer > 0 {
let date = Date(timeIntervalSince1970: TimeInterval(self.room.lobbyTimer))
let meetingStart = NCUtils.readableDateTime(fromDate: date)
let meetingStartPlaceholder = NSLocalizedString("This meeting is scheduled for", comment: "The meeting start time will be displayed after this text e.g (This meeting is scheduled for tomorrow at 10:00)")
placeholderText += "\n\n\(meetingStartPlaceholder)\n\(meetingStart)"
}
// Room description
if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityRoomDescription, for: room), !self.room.roomDescription.isEmpty {
placeholderText += "\n\n" + self.room.roomDescription
}
// Only set it when text changes to avoid flickering in links
if chatBackgroundView.placeholderTextView.text != placeholderText {
chatBackgroundView.placeholderTextView.text = placeholderText
}
self.chatBackgroundView.setImage(UIImage(named: "lobby-placeholder"))
self.chatBackgroundView.placeholderView.isHidden = false
self.chatBackgroundView.loadingView.stopAnimating()
self.chatBackgroundView.loadingView.isHidden = true
// Clear current chat since chat history will be retrieved when lobby is disabled
self.cleanChat()
} else {
self.chatBackgroundView.setImage(UIImage(named: "chat-placeholder"))
self.chatBackgroundView.placeholderTextView.text = NSLocalizedString("No messages yet, start the conversation!", comment: "")
self.chatBackgroundView.placeholderView.isHidden = true
self.chatBackgroundView.loadingView.startAnimating()
self.chatBackgroundView.loadingView.isHidden = false
// Stop checking lobby flag
self.lobbyCheckTimer?.invalidate()
// Retrieve initial chat history if lobby was enabled and we didn't retrieve it before
if !hasReceiveInitialHistory, !hasRequestedInitialHistory, hasPresentedLobby {
self.hasRequestedInitialHistory = true
self.chatController.getInitialChatHistory()
}
self.hasPresentedLobby = false
}
}
func setOfflineFooterView() {
let isAtBottom = self.shouldScrollOnNewMessages()
let footerLabel = UILabel(frame: .init(x: 0, y: 0, width: 350, height: 24))
footerLabel.textAlignment = .center
footerLabel.textColor = .label
footerLabel.font = .systemFont(ofSize: 12)
footerLabel.backgroundColor = .clear
footerLabel.text = NSLocalizedString("Offline, only showing downloaded messages", comment: "")
self.tableView?.tableFooterView = footerLabel
self.tableView?.tableFooterView?.backgroundColor = .secondarySystemBackground
if isAtBottom {
self.tableView?.slk_scrollToBottom(animated: true)
}
}
func removeOfflineFooterView() {
DispatchQueue.main.async {
self.tableView?.tableFooterView?.removeFromSuperview()
self.tableView?.tableFooterView = nil
// Scrolling after removing the tableFooterView won't scroll all the way to the bottom therefore just keep the current position
// And don't try to call scrollToBottom
}
}
func setOfflineMode() {
self.offlineMode = true
self.setOfflineFooterView()
self.chatController.stopReceivingNewChatMessages()
self.disableRoomControls()
self.checkRoomControlsAvailability()
}
// MARK: - Out Of Office
func checkOutOfOfficeAbsence() {
// Only check once, and only for 1:1 on DND right now
guard self.hasCheckedOutOfOfficeStatus == false,
self.room.type == .oneToOne,
self.room.status == kUserStatusDND,
let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId),
serverCapabilities.absenceSupported
else { return }
self.hasCheckedOutOfOfficeStatus = true
NCAPIController.sharedInstance().getCurrentUserAbsence(forAccountId: self.room.accountId, forUserId: self.room.name) { absenceData in
guard let absenceData else { return }
let oooView = OutOfOfficeView()
oooView.setupAbsence(withData: absenceData, inRoom: self.room)
oooView.alpha = 0
self.view.addSubview(oooView)
NSLayoutConstraint.activate([
oooView.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
oooView.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
oooView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
])
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut]) {
oooView.alpha = 1.0
}
}
}
// MARK: - Pinned messages
private var pinnedMessageView: PinnedMessageView?
func checkPinnedMessage() {
if let pinnedMessageView {
if self.room.lastPinnedId != pinnedMessageView.message?.messageId {
// Remove pinned message in case there's now a different message pinned or it was unpinned in the meantime
self.removePinnedMessageView()
} else {
// Nothing to do if it's still the same message
return
}
}
guard self.room.lastPinnedId > 0,
self.room.lastPinnedId != self.room.hiddenPinnedId
else { return }
self.chatController.getSingleMessage(withMessageId: self.room.lastPinnedId) { message in
guard let message else { return }
let view = PinnedMessageView()
self.pinnedMessageView = view
view.delegate = self
view.setupPinnedMessage(withMessage: message, inRoom: self.room)
view.alpha = 0
self.view.addSubview(view)
NSLayoutConstraint.activate([
view.leadingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.leadingAnchor),
view.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor),
view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor)
])
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut]) {
view.alpha = 1.0
}
}
}
func removePinnedMessageView() {
guard let pinnedMessageView else { return }
self.pinnedMessageView = nil
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseInOut]) {
pinnedMessageView.alpha = 0.0
} completion: { _ in
pinnedMessageView.removeFromSuperview()
}
}
// MARK: - Room retention
var retentionView: ChatInfoView? = nil
func checkRetention() {
// Only check for event conversations that have ended
// TODO: check if there are end_call messages
guard self.room.isEvent,
self.room.isPastEvent,
let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId),
serverCapabilities.retentionEvent > 0
else {
self.retentionView?.removeFromSuperview()
return
}