ChatViewController.swift 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813
  1. //
  2. // SPDX-FileCopyrightText: 2023 Nextcloud GmbH and Nextcloud contributors
  3. // SPDX-License-Identifier: GPL-3.0-or-later
  4. //
  5. import Foundation
  6. import NextcloudKit
  7. import PhotosUI
  8. import UIKit
  9. @objcMembers public class ChatViewController: BaseChatViewController {
  10. // MARK: - Public var
  11. public var presentedInCall = false
  12. public var chatController: NCChatController
  13. public var highlightMessageId = 0
  14. // MARK: - Private var
  15. private var hasPresentedLobby = false
  16. private var hasRequestedInitialHistory = false
  17. private var hasReceiveInitialHistory = false
  18. private var retrievingHistory = false
  19. private var hasJoinedRoom = false
  20. private var startReceivingMessagesAfterJoin = false
  21. private var offlineMode = false
  22. private var hasStoredHistory = true
  23. private var hasStopped = false
  24. private var chatViewPresentedTimestamp = Date().timeIntervalSince1970
  25. private lazy var unreadMessagesSeparator: NCChatMessage = {
  26. let message = NCChatMessage()
  27. message.messageId = kUnreadMessagesSeparatorIdentifier
  28. return message
  29. }()
  30. private lazy var lastReadMessage: Int = {
  31. return self.room.lastReadMessage
  32. }()
  33. private var lobbyCheckTimer: Timer?
  34. // MARK: - Call buttons in NavigationBar
  35. func getBarButton(forVideo video: Bool) -> BarButtonItemWithActivity {
  36. let symbolConfiguration = UIImage.SymbolConfiguration(pointSize: 20)
  37. let buttonImage = UIImage(systemName: video ? "video" : "phone", withConfiguration: symbolConfiguration)
  38. let button = BarButtonItemWithActivity(width: 50, with: buttonImage)
  39. button.innerButton.addAction { [unowned self] in
  40. button.showIndicator()
  41. startCall(withVideo: video, silently: false, button: button)
  42. }
  43. if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilitySilentCall, for: self.room) {
  44. let silentCall = UIAction(title: NSLocalizedString("Call without notification", comment: ""), image: UIImage(systemName: "bell.slash")) { [unowned self] _ in
  45. button.showIndicator()
  46. startCall(withVideo: video, silently: true, button: button)
  47. }
  48. button.innerButton.menu = UIMenu(children: [silentCall])
  49. }
  50. return button
  51. }
  52. func startCall(withVideo video: Bool, silently: Bool, button: BarButtonItemWithActivity) {
  53. if self.room.recordingConsent {
  54. let alert = UIAlertController(title: "⚠️" + NSLocalizedString("The call might be recorded", comment: ""),
  55. message: NSLocalizedString("The recording might include your voice, video from camera, and screen share. Your consent is required before joining the call.", comment: ""),
  56. preferredStyle: .alert)
  57. 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
  58. CallKitManager.sharedInstance().startCall(self.room.token, withVideoEnabled: video, andDisplayName: self.room.displayName, asInitiator: !self.room.hasCall, silently: silently, recordingConsent: true, withAccountId: self.room.accountId)
  59. })
  60. alert.addAction(.init(title: NSLocalizedString("Cancel", comment: ""), style: .cancel) { _ in
  61. button.hideIndicator()
  62. })
  63. NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
  64. } else {
  65. CallKitManager.sharedInstance().startCall(self.room.token, withVideoEnabled: video, andDisplayName: self.room.displayName, asInitiator: !self.room.hasCall, silently: silently, recordingConsent: false, withAccountId: self.room.accountId)
  66. }
  67. }
  68. private lazy var videoCallButton: BarButtonItemWithActivity = {
  69. let videoCallButton = self.getBarButton(forVideo: true)
  70. videoCallButton.accessibilityLabel = NSLocalizedString("Video call", comment: "")
  71. videoCallButton.accessibilityHint = NSLocalizedString("Double tap to start a video call", comment: "")
  72. return videoCallButton
  73. }()
  74. private lazy var voiceCallButton: BarButtonItemWithActivity = {
  75. let voiceCallButton = self.getBarButton(forVideo: false)
  76. voiceCallButton.accessibilityLabel = NSLocalizedString("Voice call", comment: "")
  77. voiceCallButton.accessibilityHint = NSLocalizedString("Double tap to start a voice call", comment: "")
  78. return voiceCallButton
  79. }()
  80. private var messageExpirationTimer: Timer?
  81. public override init?(for room: NCRoom) {
  82. self.chatController = NCChatController(for: room)
  83. super.init(for: room)
  84. NotificationCenter.default.addObserver(self, selector: #selector(didUpdateRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidUpdateRoom, object: nil)
  85. NotificationCenter.default.addObserver(self, selector: #selector(didJoinRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidJoinRoom, object: nil)
  86. NotificationCenter.default.addObserver(self, selector: #selector(didLeaveRoom(notification:)), name: NSNotification.Name.NCRoomsManagerDidLeaveRoom, object: nil)
  87. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveInitialChatHistory(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveInitialChatHistory, object: nil)
  88. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveInitialChatHistoryOffline(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveInitialChatHistoryOffline, object: nil)
  89. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatHistory(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatHistory, object: nil)
  90. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatMessages(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatMessages, object: nil)
  91. NotificationCenter.default.addObserver(self, selector: #selector(didSendChatMessage(notification:)), name: NSNotification.Name.NCChatControllerDidSendChatMessage, object: nil)
  92. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveChatBlocked(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveChatBlocked, object: nil)
  93. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveNewerCommonReadMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveNewerCommonReadMessage, object: nil)
  94. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveCallStartedMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveCallStartedMessage, object: nil)
  95. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveCallEndedMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveCallEndedMessage, object: nil)
  96. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveUpdateMessage(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveUpdateMessage, object: nil)
  97. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveHistoryCleared(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveHistoryCleared, object: nil)
  98. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveMessagesInBackground(notification:)), name: NSNotification.Name.NCChatControllerDidReceiveMessagesInBackground, object: nil)
  99. NotificationCenter.default.addObserver(self, selector: #selector(didChangeRoomCapabilities(notification:)), name: NSNotification.Name.NCDatabaseManagerRoomCapabilitiesChanged, object: nil)
  100. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveParticipantJoin(notification:)), name: NSNotification.Name.NCExternalSignalingControllerDidReceiveJoinOfParticipant, object: nil)
  101. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveParticipantLeave(notification:)), name: NSNotification.Name.NCExternalSignalingControllerDidReceiveLeaveOfParticipant, object: nil)
  102. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveStartedTyping(notification:)), name: NSNotification.Name.NCExternalSignalingControllerDidReceiveStartedTyping, object: nil)
  103. NotificationCenter.default.addObserver(self, selector: #selector(didReceiveStoppedTyping(notification:)), name: NSNotification.Name.NCExternalSignalingControllerDidReceiveStoppedTyping, object: nil)
  104. NotificationCenter.default.addObserver(self, selector: #selector(didFailRequestingCallTransaction(notification:)), name: NSNotification.Name.CallKitManagerDidFailRequestingCallTransaction, object: nil)
  105. NotificationCenter.default.addObserver(self, selector: #selector(didUpdateParticipants(notification:)), name: NSNotification.Name.NCExternalSignalingControllerDidUpdateParticipants, object: nil)
  106. NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(notification:)), name: UIApplication.didBecomeActiveNotification, object: nil)
  107. NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
  108. NotificationCenter.default.addObserver(self, selector: #selector(connectionStateHasChanged(notification:)), name: NSNotification.Name.NCConnectionStateHasChanged, object: nil)
  109. NotificationCenter.default.addObserver(self, selector: #selector(maintenanceModeActive(notification:)), name: NSNotification.Name.NCServerMaintenanceMode, object: nil)
  110. // Notifications when runing on Mac
  111. NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive(notification:)), name: NSNotification.Name(rawValue: "NSApplicationDidBecomeActiveNotification"), object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive(notification:)), name: NSNotification.Name(rawValue: "NSApplicationDidResignActiveNotification"), object: nil)
  113. }
  114. deinit {
  115. NotificationCenter.default.removeObserver(self)
  116. print("Dealloc NewChatViewController")
  117. }
  118. // MARK: - View lifecycle
  119. public override func viewDidLoad() {
  120. super.viewDidLoad()
  121. if room.supportsCalling {
  122. self.navigationItem.rightBarButtonItems = [videoCallButton, voiceCallButton]
  123. }
  124. // No sharing options in federation v1
  125. if room.isFederated {
  126. // When hiding the button it is still respected in the layout constraints
  127. // So we need to remove the image to remove the button for now
  128. self.leftButton.setImage(nil, for: .normal)
  129. }
  130. // Disable room info, input bar and call buttons until joining room
  131. self.disableRoomControls()
  132. }
  133. public override func viewWillAppear(_ animated: Bool) {
  134. super.viewWillAppear(animated)
  135. self.checkLobbyState()
  136. self.checkRoomControlsAvailability()
  137. self.startObservingExpiredMessages()
  138. // Workaround for open conversations:
  139. // We can't get initial chat history until we join the conversation (since we are not a participant until then)
  140. // 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.
  141. if !self.hasReceiveInitialHistory, !self.hasRequestedInitialHistory, self.room.lastReadMessage > 0 {
  142. self.hasRequestedInitialHistory = true
  143. self.chatController.getInitialChatHistory()
  144. }
  145. if !self.offlineMode {
  146. if self.room.token == nil {
  147. fatalTokenError()
  148. }
  149. NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
  150. }
  151. }
  152. private func fatalTokenError() {
  153. let capabilities = NCDatabaseManager.sharedInstance().serverCapabilities()
  154. switch capabilities.versionMajor {
  155. case 19:
  156. fatalError()
  157. case 20:
  158. fatalError()
  159. case 21:
  160. fatalError()
  161. case 22:
  162. fatalError()
  163. case 23:
  164. fatalError()
  165. case 24:
  166. fatalError()
  167. case 25:
  168. fatalError()
  169. case 26:
  170. fatalError()
  171. case 27:
  172. fatalError()
  173. case 28:
  174. fatalError()
  175. case 29:
  176. fatalError()
  177. case 30:
  178. fatalError()
  179. default:
  180. fatalError()
  181. }
  182. }
  183. public override func viewWillDisappear(_ animated: Bool) {
  184. super.viewWillDisappear(animated)
  185. self.saveLastReadMessage()
  186. self.stopVoiceMessagePlayer()
  187. }
  188. public override func viewDidDisappear(_ animated: Bool) {
  189. super.viewDidDisappear(animated)
  190. if self.isMovingFromParent {
  191. self.leaveChat()
  192. }
  193. self.videoCallButton.hideIndicator()
  194. self.voiceCallButton.hideIndicator()
  195. }
  196. required init?(coder decoder: NSCoder) {
  197. fatalError("init(coder:) has not been implemented")
  198. }
  199. // MARK: - App lifecycle
  200. func appDidBecomeActive(notification: Notification) {
  201. // Don't handle this event if the view is not loaded yet.
  202. // Otherwise we try to join the room and receive new messages while
  203. // viewDidLoad wasn't called, resulting in uninitialized dictionaries and crashes
  204. if !self.isViewLoaded {
  205. return
  206. }
  207. // If we stopped the chat, we don't want to resume it here
  208. if self.hasStopped {
  209. return
  210. }
  211. // Check if new messages were added while the app was inactive (eg. via background-refresh)
  212. self.checkForNewStoredMessages()
  213. if !self.offlineMode {
  214. if self.room.token == nil {
  215. fatalTokenError()
  216. }
  217. NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
  218. }
  219. self.startObservingExpiredMessages()
  220. }
  221. func appWillResignActive(notification: Notification) {
  222. // If we stopped the chat, we don't want to change anything here
  223. if self.hasStopped {
  224. return
  225. }
  226. self.startReceivingMessagesAfterJoin = true
  227. self.removeUnreadMessagesSeparator()
  228. self.savePendingMessage()
  229. self.chatController.stop()
  230. self.messageExpirationTimer?.invalidate()
  231. self.stopTyping(force: false)
  232. NCRoomsManager.sharedInstance().leaveChat(inRoom: self.room.token)
  233. }
  234. func connectionStateHasChanged(notification: Notification) {
  235. guard let rawConnectionState = notification.userInfo?["connectionState"] as? Int, let connectionState = ConnectionState(rawValue: rawConnectionState) else {
  236. return
  237. }
  238. switch connectionState {
  239. case .connected:
  240. if offlineMode {
  241. offlineMode = false
  242. startReceivingMessagesAfterJoin = true
  243. self.removeOfflineFooterView()
  244. NCRoomsManager.sharedInstance().joinRoom(self.room.token, forCall: false)
  245. }
  246. default:
  247. break
  248. }
  249. }
  250. func maintenanceModeActive(notification: Notification) {
  251. self.setOfflineMode()
  252. }
  253. // MARK: - User Interface
  254. func disableRoomControls() {
  255. self.titleView?.isUserInteractionEnabled = false
  256. self.videoCallButton.hideIndicator()
  257. self.videoCallButton.isEnabled = false
  258. self.voiceCallButton.hideIndicator()
  259. self.voiceCallButton.isEnabled = false
  260. self.rightButton.isEnabled = false
  261. self.leftButton.isEnabled = false
  262. }
  263. func checkRoomControlsAvailability() {
  264. if hasJoinedRoom, !offlineMode {
  265. // Enable room info and call buttons when we joined a room
  266. self.titleView?.isUserInteractionEnabled = true
  267. self.videoCallButton.isEnabled = true
  268. self.voiceCallButton.isEnabled = true
  269. }
  270. // Files/objects can only be send when we're not offline
  271. self.leftButton.isEnabled = !offlineMode
  272. // Always allow to start writing a message, even if we didn't join the room (yet)
  273. self.rightButton.isEnabled = self.canPressRightButton()
  274. self.textInputbar.isUserInteractionEnabled = true
  275. if !room.userCanStartCall, !room.hasCall {
  276. // Disable call buttons
  277. self.videoCallButton.isEnabled = false
  278. self.voiceCallButton.isEnabled = false
  279. }
  280. if room.readOnlyState == .readOnly || self.shouldPresentLobbyView() {
  281. // Hide text input
  282. self.setTextInputbarHidden(true, animated: self.isVisible)
  283. // Disable call buttons
  284. self.videoCallButton.isEnabled = false
  285. self.voiceCallButton.isEnabled = false
  286. } else if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityChatPermission, for: room), (room.permissions & NCPermission.chat.rawValue) == 0 {
  287. // Hide text input
  288. self.setTextInputbarHidden(true, animated: isVisible)
  289. } else if self.isTextInputbarHidden {
  290. // Show text input if it was hidden in a previous state
  291. self.setTextInputbarHidden(false, animated: isVisible)
  292. if self.tableView?.slk_isAtBottom ?? false {
  293. self.tableView?.slk_scrollToBottom(animated: true)
  294. }
  295. // Make sure the textinput has the correct height
  296. self.setChatMessage(self.textInputbar.textView.text)
  297. }
  298. if self.presentedInCall {
  299. // Create a close button and remove the call buttons
  300. let barButtonItem = UIBarButtonItem(title: nil, style: .plain, target: nil, action: nil)
  301. barButtonItem.primaryAction = UIAction(title: NSLocalizedString("Close", comment: ""), handler: { _ in
  302. NCRoomsManager.sharedInstance().callViewController?.toggleChatView()
  303. })
  304. self.navigationItem.rightBarButtonItems = [barButtonItem]
  305. }
  306. }
  307. func checkLobbyState() {
  308. if self.shouldPresentLobbyView() {
  309. self.hasPresentedLobby = true
  310. var placeholderText = NSLocalizedString("You are currently waiting in the lobby", comment: "")
  311. // Lobby timer
  312. if self.room.lobbyTimer > 0 {
  313. let date = Date(timeIntervalSince1970: TimeInterval(self.room.lobbyTimer))
  314. let meetingStart = NCUtils.readableDateTime(fromDate: date)
  315. 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)")
  316. placeholderText += "\n\n\(meetingStartPlaceholder)\n\(meetingStart)"
  317. }
  318. // Room description
  319. if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityRoomDescription, for: room), !self.room.roomDescription.isEmpty {
  320. placeholderText += "\n\n" + self.room.roomDescription
  321. }
  322. // Only set it when text changes to avoid flickering in links
  323. if chatBackgroundView.placeholderTextView.text != placeholderText {
  324. chatBackgroundView.placeholderTextView.text = placeholderText
  325. }
  326. self.chatBackgroundView.setImage(UIImage(named: "lobby-placeholder"))
  327. self.chatBackgroundView.placeholderView.isHidden = false
  328. self.chatBackgroundView.loadingView.stopAnimating()
  329. self.chatBackgroundView.loadingView.isHidden = true
  330. // Clear current chat since chat history will be retrieved when lobby is disabled
  331. self.cleanChat()
  332. } else {
  333. self.chatBackgroundView.setImage(UIImage(named: "chat-placeholder"))
  334. self.chatBackgroundView.placeholderTextView.text = NSLocalizedString("No messages yet, start the conversation!", comment: "")
  335. self.chatBackgroundView.placeholderView.isHidden = true
  336. self.chatBackgroundView.loadingView.startAnimating()
  337. self.chatBackgroundView.loadingView.isHidden = false
  338. // Stop checking lobby flag
  339. self.lobbyCheckTimer?.invalidate()
  340. // Retrieve initial chat history if lobby was enabled and we didn't retrieve it before
  341. if !hasReceiveInitialHistory, !hasRequestedInitialHistory, hasPresentedLobby {
  342. self.hasRequestedInitialHistory = true
  343. self.chatController.getInitialChatHistory()
  344. }
  345. self.hasPresentedLobby = false
  346. }
  347. }
  348. func setOfflineFooterView() {
  349. let isAtBottom = self.shouldScrollOnNewMessages()
  350. let footerLabel = UILabel(frame: .init(x: 0, y: 0, width: 350, height: 24))
  351. footerLabel.textAlignment = .center
  352. footerLabel.textColor = .label
  353. footerLabel.font = .systemFont(ofSize: 12)
  354. footerLabel.backgroundColor = .clear
  355. footerLabel.text = NSLocalizedString("Offline, only showing downloaded messages", comment: "")
  356. self.tableView?.tableFooterView = footerLabel
  357. self.tableView?.tableFooterView?.backgroundColor = .secondarySystemBackground
  358. if isAtBottom {
  359. self.tableView?.slk_scrollToBottom(animated: true)
  360. }
  361. }
  362. func removeOfflineFooterView() {
  363. DispatchQueue.main.async {
  364. self.tableView?.tableFooterView?.removeFromSuperview()
  365. self.tableView?.tableFooterView = nil
  366. // Scrolling after removing the tableFooterView won't scroll all the way to the bottom therefore just keep the current position
  367. // And don't try to call scrollToBottom
  368. }
  369. }
  370. func setOfflineMode() {
  371. self.offlineMode = true
  372. self.setOfflineFooterView()
  373. self.chatController.stopReceivingNewChatMessages()
  374. self.disableRoomControls()
  375. self.checkRoomControlsAvailability()
  376. }
  377. // MARK: - Message expiration
  378. func startObservingExpiredMessages() {
  379. self.messageExpirationTimer?.invalidate()
  380. self.removeExpiredMessages()
  381. self.messageExpirationTimer = Timer.scheduledTimer(withTimeInterval: 30.0, repeats: true, block: { [weak self] _ in
  382. self?.removeExpiredMessages()
  383. })
  384. }
  385. func removeExpiredMessages() {
  386. DispatchQueue.main.async {
  387. let currentTimestamp = Int(Date().timeIntervalSince1970)
  388. // Iterate backwards in case we need to delete multiple sections in one go
  389. for sectionIndex in self.dateSections.indices.reversed() {
  390. let section = self.dateSections[sectionIndex]
  391. guard let messages = self.messages[section] else { continue }
  392. let deleteMessages = messages.filter { message in
  393. return message.expirationTimestamp > 0 && message.expirationTimestamp <= currentTimestamp
  394. }
  395. if !deleteMessages.isEmpty {
  396. self.tableView?.beginUpdates()
  397. let filteredMessages = messages.filter { !deleteMessages.contains($0) }
  398. self.messages[section] = filteredMessages
  399. if !filteredMessages.isEmpty {
  400. self.tableView?.reloadSections(IndexSet(integer: sectionIndex), with: .top)
  401. } else {
  402. self.messages.removeValue(forKey: section)
  403. self.sortDateSections()
  404. self.tableView?.deleteSections(IndexSet(integer: sectionIndex), with: .top)
  405. }
  406. self.tableView?.endUpdates()
  407. }
  408. }
  409. self.chatController.removeExpiredMessages()
  410. }
  411. }
  412. // MARK: - Utils
  413. func presentJoinError(_ subtitle: String) {
  414. NotificationPresenter.shared().present(title: NSLocalizedString("Could not join conversation", comment: ""), subtitle: subtitle, includedStyle: .warning)
  415. NotificationPresenter.shared().dismiss(afterDelay: 8.0)
  416. }
  417. // MARK: - Action methods
  418. override func sendChatMessage(message: String, withParentMessage parentMessage: NCChatMessage?, messageParameters: String, silently: Bool) {
  419. // Create temporary message
  420. let temporaryMessage = self.createTemporaryMessage(message: message, replyTo: parentMessage, messageParameters: messageParameters, silently: silently)
  421. if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityChatReferenceId, for: room) {
  422. self.appendTemporaryMessage(temporaryMessage: temporaryMessage)
  423. }
  424. // Send message
  425. self.chatController.send(temporaryMessage)
  426. }
  427. public override func canPressRightButton() -> Bool {
  428. let canPress = super.canPressRightButton()
  429. if self.textInputbar.isEditing {
  430. // When we're editing, we can use the default implementation, as we don't want to save an empty message
  431. return canPress
  432. }
  433. // If in offline mode, we don't want to show the voice button
  434. if !offlineMode, !canPress, !presentedInCall,
  435. NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityVoiceMessage, for: room),
  436. !room.isFederated {
  437. self.showVoiceMessageRecordButton()
  438. return true
  439. }
  440. self.showSendMessageButton()
  441. return canPress
  442. }
  443. // MARK: - Voice message player
  444. // Override the default implementation to don't hijack the audio session when presented in a call
  445. override func playVoiceMessagePlayer() {
  446. if !self.presentedInCall {
  447. self.setSpeakerAudioSession()
  448. self.enableProximitySensor()
  449. }
  450. self.startVoiceMessagePlayerTimer()
  451. self.voiceMessagesPlayer?.play()
  452. }
  453. override func pauseVoiceMessagePlayer() {
  454. if !self.presentedInCall {
  455. self.disableProximitySensor()
  456. }
  457. self.stopVoiceMessagePlayerTimer()
  458. self.voiceMessagesPlayer?.pause()
  459. self.checkVisibleCellAudioPlayers()
  460. }
  461. override func stopVoiceMessagePlayer() {
  462. if !self.presentedInCall {
  463. self.disableProximitySensor()
  464. }
  465. self.stopVoiceMessagePlayerTimer()
  466. self.voiceMessagesPlayer?.stop()
  467. }
  468. override func sensorStateChange(notification: Notification) {
  469. if self.presentedInCall {
  470. return
  471. }
  472. if UIDevice.current.proximityState {
  473. self.setVoiceChatAudioSession()
  474. } else {
  475. self.pauseVoiceMessagePlayer()
  476. self.setSpeakerAudioSession()
  477. self.disableProximitySensor()
  478. }
  479. }
  480. // MARK: - UIScrollViewDelegate methods
  481. public override func scrollViewDidScroll(_ scrollView: UIScrollView) {
  482. super.scrollViewDidScroll(scrollView)
  483. guard scrollView == self.tableView,
  484. scrollView.contentOffset.y < 0,
  485. self.couldRetrieveHistory()
  486. else { return }
  487. if let firstMessage = self.getFirstRealMessage()?.message,
  488. self.chatController.hasHistory(fromMessageId: firstMessage.messageId) {
  489. self.retrievingHistory = true
  490. self.showLoadingHistoryView()
  491. if self.offlineMode {
  492. self.chatController.getHistoryBatchOffline(fromMessagesId: firstMessage.messageId)
  493. } else {
  494. self.chatController.getHistoryBatch(fromMessagesId: firstMessage.messageId)
  495. }
  496. }
  497. }
  498. public func stopChat() {
  499. self.hasStopped = true
  500. self.chatController.stop()
  501. self.cleanChat()
  502. }
  503. public func resumeChat() {
  504. self.hasStopped = false
  505. if !self.hasReceiveInitialHistory, !self.hasRequestedInitialHistory {
  506. self.hasRequestedInitialHistory = true
  507. self.chatController.getInitialChatHistory()
  508. }
  509. }
  510. public func leaveChat() {
  511. self.lobbyCheckTimer?.invalidate()
  512. self.messageExpirationTimer?.invalidate()
  513. self.chatController.stop()
  514. // Dismiss possible notifications
  515. // swiftlint:disable:next notification_center_detachment
  516. NotificationCenter.default.removeObserver(self)
  517. // In case we're typing when we leave the chat, make sure we notify everyone
  518. // The 'stopTyping' method makes sure to only send signaling messages when we were typing before
  519. self.stopTyping(force: false)
  520. // If this chat view controller is for the same room as the one owned by the rooms manager
  521. // then we should not try to leave the chat. Since we will leave the chat when the
  522. // chat view controller owned by rooms manager moves from parent view controller.
  523. if NCRoomsManager.sharedInstance().chatViewController?.room.token == self.room.token,
  524. NCRoomsManager.sharedInstance().chatViewController !== self {
  525. return
  526. }
  527. NCRoomsManager.sharedInstance().leaveChat(inRoom: self.room.token)
  528. // Remove chat view controller pointer if this chat is owned by rooms manager
  529. // and the chat view is moving from parent view controller
  530. if NCRoomsManager.sharedInstance().chatViewController === self {
  531. NCRoomsManager.sharedInstance().chatViewController = nil
  532. }
  533. }
  534. public override func cleanChat() {
  535. super.cleanChat()
  536. self.hasReceiveInitialHistory = false
  537. self.hasRequestedInitialHistory = false
  538. self.chatController.hasReceivedMessagesFromServer = false
  539. }
  540. func saveLastReadMessage() {
  541. NCRoomsManager.sharedInstance().updateLastReadMessage(self.lastReadMessage, for: self.room)
  542. }
  543. // MARK: - Room Manager notifications
  544. func didUpdateRoom(notification: Notification) {
  545. guard let room = notification.userInfo?["room"] as? NCRoom else { return }
  546. if room.token != self.room.token {
  547. return
  548. }
  549. self.room = room
  550. self.setTitleView()
  551. if !self.hasStopped {
  552. self.checkLobbyState()
  553. self.checkRoomControlsAvailability()
  554. }
  555. }
  556. func didJoinRoom(notification: Notification) {
  557. guard let token = notification.userInfo?["token"] as? String else { return }
  558. if token != self.room.token {
  559. return
  560. }
  561. if self.isVisible,
  562. notification.userInfo?["error"] != nil,
  563. let errorReason = notification.userInfo?["errorReason"] as? String {
  564. self.setOfflineMode()
  565. self.presentJoinError(errorReason)
  566. if let isBanned = notification.userInfo?["isBanned"] as? Bool, isBanned {
  567. // Usually we remove all notifications when the view disappears, but in this case, we want to keep it
  568. self.dismissNotificationsOnViewWillDisappear = false
  569. // We are not allowed to join this conversation -> Move back to the conversation list
  570. NCUserInterfaceController.sharedInstance().presentConversationsList()
  571. }
  572. return
  573. }
  574. if let room = notification.userInfo?["room"] as? NCRoom {
  575. self.room = room
  576. }
  577. self.hasJoinedRoom = true
  578. self.checkRoomControlsAvailability()
  579. if self.hasStopped {
  580. return
  581. }
  582. if self.startReceivingMessagesAfterJoin, self.hasReceiveInitialHistory {
  583. self.startReceivingMessagesAfterJoin = false
  584. self.chatController.startReceivingNewChatMessages()
  585. } else if !self.hasReceiveInitialHistory, !self.hasRequestedInitialHistory {
  586. self.hasRequestedInitialHistory = true
  587. self.chatController.getInitialChatHistory()
  588. }
  589. DispatchQueue.main.asyncAfter(deadline: .now() + 4) { [capturedToken = self.room.token] in
  590. // After we joined a room, check if there are offline messages for this particular room which need to be send
  591. NCRoomsManager.sharedInstance().resendOfflineMessages(forToken: capturedToken, withCompletionBlock: nil)
  592. }
  593. }
  594. func didLeaveRoom(notification: Notification) {
  595. guard let token = notification.userInfo?["token"] as? String else { return }
  596. if token != self.room.token {
  597. return
  598. }
  599. if notification.userInfo?["error"] != nil {
  600. // In case an error occurred when leaving the room, we assume we are still joined
  601. return
  602. }
  603. self.hasJoinedRoom = false
  604. self.disableRoomControls()
  605. self.checkRoomControlsAvailability()
  606. }
  607. // MARK: - CallKit Manager notifications
  608. func didFailRequestingCallTransaction(notification: Notification) {
  609. guard let token = notification.userInfo?["roomToken"] as? String else { return }
  610. if token != self.room.token {
  611. return
  612. }
  613. DispatchQueue.main.async {
  614. self.videoCallButton.hideIndicator()
  615. self.voiceCallButton.hideIndicator()
  616. }
  617. }
  618. // MARK: - Chat Controller notifications
  619. // swiftlint:disable:next cyclomatic_complexity
  620. func didReceiveInitialChatHistory(notification: Notification) {
  621. DispatchQueue.main.async {
  622. if notification.object as? NCChatController != self.chatController {
  623. return
  624. }
  625. if self.shouldPresentLobbyView() {
  626. self.hasRequestedInitialHistory = false
  627. self.startObservingRoomLobbyFlag()
  628. return
  629. }
  630. if let messages = notification.userInfo?["messages"] as? [NCChatMessage], !messages.isEmpty {
  631. var indexPathUnreadMessageSeparator: IndexPath?
  632. let lastMessage = messages.reversed().first(where: { !$0.isUpdateMessage })
  633. self.appendMessages(messages: messages)
  634. if let lastMessage, lastMessage.messageId > self.lastReadMessage {
  635. // Iterate backwards to find the correct location for the unread message separator
  636. for sectionIndex in self.dateSections.indices.reversed() {
  637. let dateSection: Date = self.dateSections[sectionIndex]
  638. guard var messages = self.messages[dateSection] else { continue }
  639. for messageIndex in messages.indices.reversed() {
  640. let message = messages[messageIndex]
  641. if message.messageId > self.lastReadMessage {
  642. continue
  643. }
  644. messages.insert(self.unreadMessagesSeparator, at: messageIndex + 1)
  645. self.messages[dateSection] = messages
  646. indexPathUnreadMessageSeparator = IndexPath(row: messageIndex + 1, section: sectionIndex)
  647. break
  648. }
  649. if indexPathUnreadMessageSeparator != nil {
  650. break
  651. }
  652. }
  653. self.lastReadMessage = lastMessage.messageId
  654. }
  655. let storedTemporaryMessages = self.chatController.getTemporaryMessages()
  656. if !storedTemporaryMessages.isEmpty {
  657. self.insertMessages(messages: storedTemporaryMessages)
  658. if indexPathUnreadMessageSeparator != nil {
  659. // It is possible that temporary messages are added which add new sections
  660. // In this case the indexPath of the unreadMessageSeparator would be invalid and could lead to a crash
  661. // Therefore we need to make sure we got the correct indexPath here
  662. indexPathUnreadMessageSeparator = self.indexPathForUnreadMessageSeparator()
  663. }
  664. }
  665. self.tableView?.reloadData()
  666. if let indexPathUnreadMessageSeparator {
  667. self.tableView?.scrollToRow(at: indexPathUnreadMessageSeparator, at: .middle, animated: false)
  668. } else {
  669. self.tableView?.slk_scrollToBottom(animated: false)
  670. }
  671. self.updateToolbar(animated: false)
  672. } else {
  673. self.chatBackgroundView.placeholderView.isHidden = false
  674. }
  675. self.hasReceiveInitialHistory = true
  676. if notification.userInfo?["error"] == nil {
  677. self.chatController.startReceivingNewChatMessages()
  678. } else {
  679. self.offlineMode = true
  680. self.chatController.getInitialChatHistoryForOfflineMode()
  681. }
  682. }
  683. }
  684. func didReceiveInitialChatHistoryOffline(notification: Notification) {
  685. DispatchQueue.main.async {
  686. if notification.object as? NCChatController != self.chatController {
  687. return
  688. }
  689. if let messages = notification.userInfo?["messages"] as? [NCChatMessage], !messages.isEmpty {
  690. self.appendMessages(messages: messages)
  691. self.setOfflineFooterView()
  692. self.tableView?.reloadData()
  693. self.tableView?.slk_scrollToBottom(animated: false)
  694. self.updateToolbar(animated: false)
  695. } else {
  696. self.chatBackgroundView.placeholderView.isHidden = false
  697. }
  698. let storedTemporaryMessages = self.chatController.getTemporaryMessages()
  699. if !storedTemporaryMessages.isEmpty {
  700. self.insertMessages(messages: storedTemporaryMessages)
  701. self.tableView?.reloadData()
  702. self.tableView?.slk_scrollToBottom(animated: false)
  703. self.updateToolbar(animated: false)
  704. }
  705. }
  706. }
  707. func didReceiveChatHistory(notification: Notification) {
  708. DispatchQueue.main.async {
  709. if notification.object as? NCChatController != self.chatController {
  710. return
  711. }
  712. if let messages = notification.userInfo?["messages"] as? [NCChatMessage], !messages.isEmpty {
  713. let shouldAddBlockSeparator = notification.userInfo?["shouldAddBlockSeparator"] as? Bool ?? false
  714. if let lastHistoryMessageIP = self.prependMessages(historyMessages: messages, addingBlockSeparator: shouldAddBlockSeparator),
  715. let tableView = self.tableView {
  716. self.tableView?.reloadData()
  717. if NCUtils.isValid(indexPath: lastHistoryMessageIP, forTableView: tableView) {
  718. self.tableView?.scrollToRow(at: lastHistoryMessageIP, at: .top, animated: false)
  719. }
  720. }
  721. }
  722. if notification.userInfo?["noMoreStoredHistory"] as? Bool == true {
  723. self.hasStoredHistory = false
  724. }
  725. self.retrievingHistory = false
  726. self.hideLoadingHistoryView()
  727. }
  728. }
  729. // swiftlint:disable:next cyclomatic_complexity
  730. func didReceiveChatMessages(notification: Notification) {
  731. // If we receive messages in the background, we should make sure that our update here completely run
  732. let bgTask = BGTaskHelper.startBackgroundTask(withName: "didReceiveChatMessages")
  733. DispatchQueue.main.async {
  734. if notification.object as? NCChatController != self.chatController || notification.userInfo?["error"] != nil {
  735. return
  736. }
  737. let firstNewMessagesAfterHistory = notification.userInfo?["firstNewMessagesAfterHistory"] as? Bool ?? false
  738. if let messages = notification.userInfo?["messages"] as? [NCChatMessage], let tableView = self.tableView, !messages.isEmpty {
  739. // Detect if we should scroll to new messages before we issue a reloadData
  740. // Otherwise longer messages will prevent scrolling
  741. let shouldScrollOnNewMessages = self.shouldScrollOnNewMessages()
  742. let newMessagesContainVisibleMessages = messages.containsVisibleMessages()
  743. // Use a Set here so we don't have to deal with duplicates
  744. var insertIndexPaths: Set<IndexPath> = []
  745. var insertSections: IndexSet = []
  746. var reloadIndexPaths: Set<IndexPath> = []
  747. var addedUnreadMessageSeparator = false
  748. // Check if unread messages separator should be added (only if it's not already shown)
  749. if firstNewMessagesAfterHistory, self.getLastRealMessage() != nil, self.indexPathForUnreadMessageSeparator() == nil, newMessagesContainVisibleMessages,
  750. let lastDateSection = self.dateSections.last, var messagesBeforeUpdate = self.messages[lastDateSection] {
  751. messagesBeforeUpdate.append(self.unreadMessagesSeparator)
  752. self.messages[lastDateSection] = messagesBeforeUpdate
  753. insertIndexPaths.insert(IndexPath(row: messagesBeforeUpdate.count - 1, section: self.dateSections.count - 1))
  754. addedUnreadMessageSeparator = true
  755. }
  756. self.appendMessages(messages: messages)
  757. for newMessage in messages {
  758. // If we don't get an indexPath here, something is wrong with our appendMessages function
  759. let indexPath = self.indexPath(for: newMessage)!
  760. if indexPath.section >= tableView.numberOfSections {
  761. // New section -> insert the section
  762. insertSections.insert(indexPath.section)
  763. }
  764. if indexPath.section < tableView.numberOfSections, indexPath.row < tableView.numberOfRows(inSection: indexPath.section) {
  765. // This is a already known indexPath, so we want to reload the cell
  766. reloadIndexPaths.insert(indexPath)
  767. } else {
  768. // New indexPath -> insert it
  769. insertIndexPaths.insert(indexPath)
  770. }
  771. if newMessage.isUpdateMessage, let parentMessage = newMessage.parent, let parentPath = self.indexPath(for: parentMessage) {
  772. if parentPath.section < tableView.numberOfSections, parentPath.row < tableView.numberOfRows(inSection: parentPath.section) {
  773. // We received an update message to a message which is already part of our current data, therefore we need to reload it
  774. reloadIndexPaths.insert(parentPath)
  775. }
  776. }
  777. if let collapsedByMessage = newMessage.collapsedBy, let collapsedPath = self.indexPath(for: collapsedByMessage) {
  778. if collapsedPath.section < tableView.numberOfSections, collapsedPath.row < tableView.numberOfRows(inSection: collapsedPath.section) {
  779. // The current message is collapsed, so we need to make sure that the collapsedBy message is reloaded
  780. reloadIndexPaths.insert(collapsedPath)
  781. }
  782. }
  783. }
  784. tableView.performBatchUpdates {
  785. if !insertSections.isEmpty {
  786. tableView.insertSections(insertSections, with: .automatic)
  787. }
  788. if !insertIndexPaths.isEmpty {
  789. tableView.insertRows(at: Array(insertIndexPaths), with: .automatic)
  790. }
  791. if !reloadIndexPaths.isEmpty {
  792. tableView.reloadRows(at: Array(reloadIndexPaths), with: .none)
  793. }
  794. } completion: { _ in
  795. // Remove unread messages separator when user writes a message
  796. if messages.containsUserMessage() {
  797. self.removeUnreadMessagesSeparator()
  798. }
  799. // Only scroll to unread message separator if we added it while processing the received messages
  800. // Otherwise we would scroll whenever a unread message separator is available
  801. if addedUnreadMessageSeparator, let indexPathUnreadMessageSeparator = self.indexPathForUnreadMessageSeparator() {
  802. tableView.scrollToRow(at: indexPathUnreadMessageSeparator, at: .middle, animated: true)
  803. } else if (shouldScrollOnNewMessages || messages.containsUserMessage()), let lastIndexPath = self.getLastRealMessage()?.indexPath {
  804. tableView.scrollToRow(at: lastIndexPath, at: .none, animated: true)
  805. } else if self.firstUnreadMessage == nil, newMessagesContainVisibleMessages, let firstNewMessage = messages.first {
  806. // This check is needed since several calls to receiveMessages API might be needed
  807. // (if the number of unread messages is bigger than the "limit" in receiveMessages request)
  808. // to receive all the unread messages.
  809. if firstNewMessage.timestamp >= Int(self.chatViewPresentedTimestamp) {
  810. self.showNewMessagesView(until: firstNewMessage)
  811. }
  812. }
  813. // Set last received message as last read message
  814. if let lastReceivedMessage = messages.last {
  815. self.lastReadMessage = lastReceivedMessage.messageId
  816. }
  817. }
  818. if firstNewMessagesAfterHistory {
  819. self.chatBackgroundView.loadingView.stopAnimating()
  820. self.chatBackgroundView.loadingView.isHidden = true
  821. }
  822. if self.highlightMessageId > 0, let indexPath = self.indexPathAndMessage(forMessageId: self.highlightMessageId)?.indexPath {
  823. self.highlightMessage(at: indexPath, with: .middle)
  824. self.highlightMessageId = 0
  825. }
  826. }
  827. bgTask.stopBackgroundTask()
  828. }
  829. }
  830. func didSendChatMessage(notification: Notification) {
  831. DispatchQueue.main.async {
  832. if notification.object as? NCChatController != self.chatController {
  833. return
  834. }
  835. if notification.userInfo?["error"] == nil {
  836. return
  837. }
  838. guard let message = notification.userInfo?["message"] as? String else { return }
  839. if let referenceId = notification.userInfo?["referenceId"] as? String {
  840. // Got a referenceId -> update the corresponding message
  841. let isOfflineMessage = notification.userInfo?["isOfflineMessage"] as? Bool ?? false
  842. self.modifyMessageWith(referenceId: referenceId) { message in
  843. message.sendingFailed = !isOfflineMessage
  844. message.isOfflineMessage = isOfflineMessage
  845. }
  846. } else {
  847. // No referenceId -> show generic error
  848. self.textView.text = message
  849. let alert = UIAlertController(title: NSLocalizedString("Could not send the message", comment: ""),
  850. message: NSLocalizedString("An error occurred while sending the message", comment: ""),
  851. preferredStyle: .alert)
  852. alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
  853. NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
  854. }
  855. }
  856. }
  857. func didReceiveChatBlocked(notification: Notification) {
  858. if notification.object as? NCChatController != self.chatController {
  859. return
  860. }
  861. self.startObservingRoomLobbyFlag()
  862. }
  863. func didReceiveNewerCommonReadMessage(notification: Notification) {
  864. if notification.object as? NCChatController != self.chatController {
  865. return
  866. }
  867. guard let lastCommonReadMessage = notification.userInfo?["lastCommonReadMessage"] as? Int else { return }
  868. if lastCommonReadMessage > self.room.lastCommonReadMessage {
  869. self.room.lastCommonReadMessage = lastCommonReadMessage
  870. }
  871. self.checkLastCommonReadMessage()
  872. }
  873. func didReceiveCallStartedMessage(notification: Notification) {
  874. if notification.object as? NCChatController != self.chatController {
  875. return
  876. }
  877. self.room.hasCall = true
  878. self.checkRoomControlsAvailability()
  879. }
  880. func didReceiveCallEndedMessage(notification: Notification) {
  881. if notification.object as? NCChatController != self.chatController {
  882. return
  883. }
  884. self.room.hasCall = false
  885. self.checkRoomControlsAvailability()
  886. }
  887. func didReceiveUpdateMessage(notification: Notification) {
  888. if notification.object as? NCChatController != self.chatController {
  889. return
  890. }
  891. guard let message = notification.userInfo?["updateMessage"] as? NCChatMessage,
  892. let updateMessage = message.parent
  893. else { return }
  894. self.updateMessage(withMessageId: updateMessage.messageId, updatedMessage: updateMessage)
  895. }
  896. func didReceiveHistoryCleared(notification: Notification) {
  897. if notification.object as? NCChatController != self.chatController {
  898. return
  899. }
  900. guard let message = notification.userInfo?["historyCleared"] as? NCChatMessage
  901. else { return }
  902. if self.chatController.hasOlderStoredMessagesThanMessageId(message.messageId) {
  903. self.cleanChat()
  904. self.chatController.clearHistoryAndResetChatController()
  905. self.hasRequestedInitialHistory = false
  906. self.chatController.getInitialChatHistory()
  907. }
  908. }
  909. func didReceiveMessagesInBackground(notification: Notification) {
  910. if notification.object as? NCChatController != self.chatController {
  911. return
  912. }
  913. print("didReceiveMessagesInBackground")
  914. self.checkForNewStoredMessages()
  915. }
  916. // MARK: - Database controller notifications
  917. func didChangeRoomCapabilities(notification: Notification) {
  918. guard let token = notification.userInfo?["roomToken"] as? String else { return }
  919. if token != self.room.token {
  920. return
  921. }
  922. self.tableView?.reloadData()
  923. self.checkRoomControlsAvailability()
  924. }
  925. // MARK: - External signaling controller notifications
  926. func didUpdateParticipants(notification: Notification) {
  927. guard let token = notification.userInfo?["roomToken"] as? String else { return }
  928. if token != self.room.token {
  929. return
  930. }
  931. let serverSupportsConversationPermissions = NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityConversationPermissions, for: room) ||
  932. NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityDirectMentionFlag, for: room)
  933. guard serverSupportsConversationPermissions else { return }
  934. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  935. // Retrieve the information about ourselves
  936. guard let userDict = notification.userInfo?["users"] as? [[String: String]],
  937. let appUserDict = userDict.first(where: { $0["userId"] == activeAccount.userId })
  938. else { return }
  939. // Check if we still have the same permissions
  940. if let permissionsString = appUserDict["participantPermissions"],
  941. let permissions = Int(permissionsString),
  942. permissions != self.room.permissions {
  943. // Need to update the room from the api because otherwise "canStartCall" is not updated correctly
  944. NCRoomsManager.sharedInstance().updateRoom(self.room.token, withCompletionBlock: nil)
  945. }
  946. }
  947. func processTypingNotification(notification: Notification, startedTyping started: Bool) {
  948. guard let token = notification.userInfo?["roomToken"] as? String,
  949. let sessionId = notification.userInfo?["sessionId"] as? String,
  950. token == self.room.token
  951. else { return }
  952. // Waiting for https://github.com/nextcloud/spreed/issues/9726 to receive the correct displayname for guests
  953. let displayName = notification.userInfo?["displayName"] as? String ?? NSLocalizedString("Guest", comment: "")
  954. // Don't show a typing indicator for ourselves or if typing indicator setting is disabled
  955. // Workaround: TypingPrivacy should be checked locally, not from the remote server, use serverCapabilities for now
  956. // TODO: Remove workaround for federated typing indicators.
  957. guard let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId)
  958. else { return }
  959. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  960. let userId = notification.userInfo?["userId"] as? String
  961. let isFederated = notification.userInfo?["isFederated"] as? Bool ?? false
  962. // Since our own userId can exist on other servers, only suppress the notification if it's not federated
  963. if (userId == activeAccount.userId && !isFederated) || serverCapabilities.typingPrivacy {
  964. return
  965. }
  966. // For guests we use the sessionId as an identifier, for users we use the userId
  967. var userIdentifier = sessionId
  968. if let userId, !userId.isEmpty {
  969. userIdentifier = userId
  970. }
  971. if started {
  972. self.addTypingIndicator(withUserIdentifier: userIdentifier, andDisplayName: displayName)
  973. } else {
  974. self.removeTypingIndicator(withUserIdentifier: userIdentifier)
  975. }
  976. }
  977. func didReceiveStartedTyping(notification: Notification) {
  978. self.processTypingNotification(notification: notification, startedTyping: true)
  979. }
  980. func didReceiveStoppedTyping(notification: Notification) {
  981. self.processTypingNotification(notification: notification, startedTyping: false)
  982. }
  983. func didReceiveParticipantJoin(notification: Notification) {
  984. guard let token = notification.userInfo?["roomToken"] as? String,
  985. let sessionId = notification.userInfo?["sessionId"] as? String,
  986. token == self.room.token
  987. else { return }
  988. DispatchQueue.main.async {
  989. if self.isTyping {
  990. self.sendStartedTypingMessage(to: sessionId)
  991. }
  992. }
  993. }
  994. func didReceiveParticipantLeave(notification: Notification) {
  995. guard let token = notification.userInfo?["roomToken"] as? String,
  996. let sessionId = notification.userInfo?["sessionId"] as? String,
  997. token == self.room.token
  998. else { return }
  999. // For guests we use the sessionId as an identifier, for users we use the userId
  1000. var userIdentifier = sessionId
  1001. if let userId = notification.userInfo?["userId"] as? String, !userId.isEmpty {
  1002. userIdentifier = userId
  1003. }
  1004. self.removeTypingIndicator(withUserIdentifier: userIdentifier)
  1005. }
  1006. // MARK: - Lobby functions
  1007. func startObservingRoomLobbyFlag() {
  1008. self.updateRoomInformation()
  1009. DispatchQueue.main.async {
  1010. self.lobbyCheckTimer?.invalidate()
  1011. self.lobbyCheckTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(self.updateRoomInformation), userInfo: nil, repeats: true)
  1012. }
  1013. }
  1014. func updateRoomInformation() {
  1015. NCRoomsManager.sharedInstance().updateRoom(self.room.token, withCompletionBlock: nil)
  1016. }
  1017. func shouldPresentLobbyView() -> Bool {
  1018. let serverSupportsConversationPermissions =
  1019. NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityConversationPermissions, for: room) ||
  1020. NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityDirectMentionFlag, for: room)
  1021. if serverSupportsConversationPermissions, (self.room.permissions & NCPermission.canIgnoreLobby.rawValue) != 0 {
  1022. return false
  1023. }
  1024. return self.room.lobbyState == .moderatorsOnly && !self.room.canModerate
  1025. }
  1026. // MARK: - Chat functions
  1027. func couldRetrieveHistory() -> Bool {
  1028. return self.hasReceiveInitialHistory &&
  1029. !self.retrievingHistory &&
  1030. !self.dateSections.isEmpty
  1031. && self.hasStoredHistory
  1032. }
  1033. func checkLastCommonReadMessage() {
  1034. DispatchQueue.main.async {
  1035. guard let tableView = self.tableView,
  1036. let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows
  1037. else { return }
  1038. var reloadCells: [IndexPath] = []
  1039. for visibleIndexPath in indexPathsForVisibleRows {
  1040. if let message = self.message(for: visibleIndexPath),
  1041. message.messageId > 0,
  1042. message.messageId <= self.room.lastCommonReadMessage {
  1043. reloadCells.append(visibleIndexPath)
  1044. }
  1045. }
  1046. if !reloadCells.isEmpty {
  1047. self.tableView?.beginUpdates()
  1048. self.tableView?.reloadRows(at: reloadCells, with: .none)
  1049. self.tableView?.endUpdates()
  1050. }
  1051. }
  1052. }
  1053. func checkForNewStoredMessages() {
  1054. // Get the last "real" message. For temporary messages the messageId would be 0
  1055. // which would load all stored messages of the current conversation
  1056. if let lastMessage = self.getLastRealMessage()?.message {
  1057. self.chatController.checkForNewMessages(fromMessageId: lastMessage.messageId)
  1058. self.checkLastCommonReadMessage()
  1059. }
  1060. }
  1061. // MARK: - Editing support
  1062. public override func didCommitTextEditing(_ sender: Any) {
  1063. if let editingMessage {
  1064. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1065. let messageParametersJSONString = NCMessageParameter.messageParametersJSONString(from: self.mentionsDict) ?? ""
  1066. editingMessage.message = self.replaceMentionsDisplayNamesWithMentionsKeysInMessage(message: self.textView.text, parameters: messageParametersJSONString)
  1067. editingMessage.messageParametersJSONString = messageParametersJSONString
  1068. NCAPIController.sharedInstance().editChatMessage(inRoom: editingMessage.token, withMessageId: editingMessage.messageId, withMessage: editingMessage.sendingMessage, for: activeAccount) { messageDict, error, _ in
  1069. if error != nil {
  1070. NotificationPresenter.shared().present(text: NSLocalizedString("Error occurred while editing a message", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1071. return
  1072. }
  1073. guard let messageDict,
  1074. let parent = messageDict["parent"] as? [AnyHashable: Any],
  1075. let updatedMessage = NCChatMessage(dictionary: parent, andAccountId: activeAccount.accountId)
  1076. else { return }
  1077. self.updateMessage(withMessageId: editingMessage.messageId, updatedMessage: updatedMessage)
  1078. }
  1079. }
  1080. super.didCommitTextEditing(sender)
  1081. }
  1082. // MARK: - ChatMessageTableViewCellDelegate delegate
  1083. override public func cellDidSelectedReaction(_ reaction: NCChatReaction!, for message: NCChatMessage!) {
  1084. self.addOrRemoveReaction(reaction: reaction, in: message)
  1085. }
  1086. // MARK: - ContextMenu (Long press on message)
  1087. func isMessageReplyable(message: NCChatMessage) -> Bool {
  1088. return message.isReplyable && !message.isDeleting
  1089. }
  1090. func isMessageReactable(message: NCChatMessage) -> Bool {
  1091. var isReactable = NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityReactions, for: room)
  1092. isReactable = isReactable && !self.offlineMode
  1093. isReactable = isReactable && self.room.readOnlyState != .readOnly
  1094. isReactable = isReactable && !message.isDeletedMessage && !message.isCommandMessage && !message.sendingFailed && !message.isTemporary
  1095. return isReactable
  1096. }
  1097. func getSetReminderOptions(for message: NCChatMessage) -> [UIMenuElement] {
  1098. var reminderOptions: [UIMenuElement] = []
  1099. let now = Date()
  1100. let sunday = 1
  1101. let monday = 2
  1102. let friday = 6
  1103. let saturday = 7
  1104. let formatter = DateFormatter()
  1105. formatter.dateFormat = "EEE"
  1106. let setReminderCompletion: SetReminderForMessage = { (error: Error?) in
  1107. if error != nil {
  1108. NotificationPresenter.shared().present(text: NSLocalizedString("Error occurred when creating a reminder", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1109. } else {
  1110. NotificationPresenter.shared().present(text: NSLocalizedString("Reminder was successfully set", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
  1111. }
  1112. }
  1113. // Today
  1114. let laterTodayTime = NCUtils.today(withHour: 18, withMinute: 0, withSecond: 0)!
  1115. let laterToday = UIAction(title: NSLocalizedString("Later today", comment: "Remind me later today about that message"), subtitle: NCUtils.getTime(fromDate: laterTodayTime)) { _ in
  1116. let timestamp = String(Int(laterTodayTime.timeIntervalSince1970))
  1117. NCAPIController.sharedInstance().setReminderFor(message, withTimestamp: timestamp, withCompletionBlock: setReminderCompletion)
  1118. }
  1119. // Tomorrow
  1120. var tomorrowTime = NCUtils.today(withHour: 8, withMinute: 0, withSecond: 0)!
  1121. tomorrowTime = Calendar.current.date(byAdding: .day, value: 1, to: tomorrowTime)!
  1122. let tomorrow = UIAction(title: NSLocalizedString("Tomorrow", comment: "Remind me tomorrow about that message")) { _ in
  1123. let timestamp = String(Int(tomorrowTime.timeIntervalSince1970))
  1124. NCAPIController.sharedInstance().setReminderFor(message, withTimestamp: timestamp, withCompletionBlock: setReminderCompletion)
  1125. }
  1126. tomorrow.subtitle = "\(formatter.string(from: tomorrowTime)), \(NCUtils.getTime(fromDate: tomorrowTime))"
  1127. // This weekend
  1128. var weekendTime = NCUtils.today(withHour: 8, withMinute: 0, withSecond: 0)!
  1129. weekendTime = NCUtils.setWeekday(saturday, withDate: weekendTime)
  1130. let thisWeekend = UIAction(title: NSLocalizedString("This weekend", comment: "Remind me this weekend about that message")) { _ in
  1131. let timestamp = String(Int(weekendTime.timeIntervalSince1970))
  1132. NCAPIController.sharedInstance().setReminderFor(message, withTimestamp: timestamp, withCompletionBlock: setReminderCompletion)
  1133. }
  1134. thisWeekend.subtitle = "\(formatter.string(from: weekendTime)), \(NCUtils.getTime(fromDate: weekendTime))"
  1135. // Next week
  1136. var nextWeekTime = NCUtils.today(withHour: 8, withMinute: 0, withSecond: 0)!
  1137. nextWeekTime = Calendar.current.date(byAdding: .weekOfYear, value: 1, to: nextWeekTime)!
  1138. nextWeekTime = NCUtils.setWeekday(monday, withDate: nextWeekTime)
  1139. let nextWeek = UIAction(title: NSLocalizedString("Next week", comment: "Remind me next week about that message")) { _ in
  1140. let timestamp = String(Int(nextWeekTime.timeIntervalSince1970))
  1141. NCAPIController.sharedInstance().setReminderFor(message, withTimestamp: timestamp, withCompletionBlock: setReminderCompletion)
  1142. }
  1143. nextWeek.subtitle = "\(formatter.string(from: nextWeekTime)), \(NCUtils.getTime(fromDate: nextWeekTime))"
  1144. // Custom reminder
  1145. let customReminderAction = UIAction(title: NSLocalizedString("Pick date & time", comment: ""), image: .init(systemName: "calendar.badge.clock")) { [weak self] _ in
  1146. DispatchQueue.main.async {
  1147. guard let self else { return }
  1148. self.interactingMessage = message
  1149. self.lastMessageBeforeInteraction = self.tableView?.indexPathsForVisibleRows?.last
  1150. let startingDate = Calendar.current.date(byAdding: .hour, value: 1, to: now)
  1151. let minimumDate = Calendar.current.date(byAdding: .minute, value: 15, to: now)
  1152. self.datePickerTextField.getDate(startingDate: startingDate, minimumDate: minimumDate) { selectedDate in
  1153. let timestamp = String(Int(selectedDate.timeIntervalSince1970))
  1154. NCAPIController.sharedInstance().setReminderFor(message, withTimestamp: timestamp, withCompletionBlock: setReminderCompletion)
  1155. }
  1156. }
  1157. }
  1158. let customReminder = UIMenu(options: .displayInline, children: [customReminderAction])
  1159. // Hide "Later today" when it's past 5pm
  1160. if Calendar.current.component(.hour, from: now) < 17 {
  1161. reminderOptions.append(laterToday)
  1162. }
  1163. reminderOptions.append(tomorrow)
  1164. // Only show "This weekend" for Mon-Tue
  1165. let nowWeekday = Calendar.current.component(.weekday, from: now)
  1166. if nowWeekday != friday && nowWeekday != saturday && nowWeekday != sunday {
  1167. reminderOptions.append(thisWeekend)
  1168. }
  1169. // "Next week" should be hidden on sunday
  1170. if nowWeekday != sunday {
  1171. reminderOptions.append(nextWeek)
  1172. }
  1173. reminderOptions.append(customReminder)
  1174. return reminderOptions
  1175. }
  1176. override func getContextMenuAccessoryView(forMessage message: NCChatMessage, forIndexPath indexPath: IndexPath, withCellHeight cellHeight: CGFloat) -> UIView? {
  1177. let hasChatPermissions = !NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityChatPermission, for: room) || (self.room.permissions & NCPermission.chat.rawValue) != 0
  1178. guard hasChatPermissions && self.isMessageReactable(message: message) else { return nil }
  1179. let reactionViewPadding = 10
  1180. let emojiButtonPadding = 10
  1181. let emojiButtonSize = 48
  1182. let frequentlyUsedEmojis = NCDatabaseManager.sharedInstance().activeAccount().frequentlyUsedEmojis
  1183. let totalEmojiButtonWidth = frequentlyUsedEmojis.count * emojiButtonSize
  1184. let totalEmojiButtonPadding = frequentlyUsedEmojis.count * emojiButtonPadding
  1185. let addButtonWidth = emojiButtonSize + emojiButtonPadding
  1186. // We need to add an extra padding to the right so the buttons are correctly padded
  1187. let reactionViewWidth = totalEmojiButtonWidth + totalEmojiButtonPadding + addButtonWidth + emojiButtonPadding
  1188. let reactionView = UIView(frame: .init(x: 0, y: Int(cellHeight) + reactionViewPadding, width: reactionViewWidth, height: emojiButtonSize))
  1189. var positionX = emojiButtonPadding
  1190. for emoji in frequentlyUsedEmojis {
  1191. let emojiShortcutButton = UIButton(type: .system)
  1192. emojiShortcutButton.frame = CGRect(x: positionX, y: 0, width: emojiButtonSize, height: emojiButtonSize)
  1193. emojiShortcutButton.layer.cornerRadius = CGFloat(emojiButtonSize) / 2
  1194. emojiShortcutButton.titleLabel?.font = .systemFont(ofSize: 20)
  1195. emojiShortcutButton.setTitle(emoji, for: .normal)
  1196. emojiShortcutButton.backgroundColor = .systemBackground
  1197. emojiShortcutButton.addAction { [weak self] in
  1198. guard let self else { return }
  1199. self.tableView?.contextMenuInteraction?.dismissMenu()
  1200. self.contextMenuActionBlock = {
  1201. self.addReaction(reaction: emoji, to: message)
  1202. }
  1203. }
  1204. // Disable shortcuts, if we already reacted with that emoji
  1205. for reaction in message.reactionsArray() {
  1206. if reaction.reaction == emoji && reaction.userReacted {
  1207. emojiShortcutButton.isEnabled = false
  1208. emojiShortcutButton.alpha = 0.4
  1209. break
  1210. }
  1211. }
  1212. reactionView.addSubview(emojiShortcutButton)
  1213. positionX += emojiButtonSize + emojiButtonPadding
  1214. }
  1215. let addReactionButton = UIButton(type: .system)
  1216. addReactionButton.frame = CGRect(x: positionX, y: 0, width: emojiButtonSize, height: emojiButtonSize)
  1217. addReactionButton.layer.cornerRadius = CGFloat(emojiButtonSize) / 2
  1218. addReactionButton.titleLabel?.font = .systemFont(ofSize: 22)
  1219. addReactionButton.setImage(.init(systemName: "plus"), for: .normal)
  1220. addReactionButton.tintColor = .label
  1221. addReactionButton.backgroundColor = .systemBackground
  1222. addReactionButton.addAction { [weak self] in
  1223. guard let self else { return }
  1224. self.tableView?.contextMenuInteraction?.dismissMenu()
  1225. self.contextMenuActionBlock = {
  1226. self.didPressAddReaction(for: message, at: indexPath)
  1227. }
  1228. }
  1229. reactionView.addSubview(addReactionButton)
  1230. // The reactionView will be shown after the animation finishes, otherwise we see the view already when animating and this looks odd
  1231. reactionView.alpha = 0
  1232. reactionView.layer.cornerRadius = CGFloat(emojiButtonSize) / 2
  1233. reactionView.backgroundColor = .systemBackground
  1234. return reactionView
  1235. }
  1236. // swiftlint:disable:next cyclomatic_complexity
  1237. public override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  1238. if tableView == self.autoCompletionView {
  1239. return nil
  1240. }
  1241. let cell = tableView.cellForRow(at: indexPath)
  1242. // Show reactionSummary for legacy cells
  1243. if let cell = cell as? ChatTableViewCell {
  1244. let pointInCell = tableView.convert(point, to: cell)
  1245. let reactionView = cell.contentView.subviews.first(where: { $0 is ReactionsView && $0.frame.contains(pointInCell) })
  1246. if reactionView != nil {
  1247. self.showReactionsSummary(of: cell.message)
  1248. return nil
  1249. }
  1250. }
  1251. if let cell = cell as? BaseChatTableViewCell {
  1252. let pointInCell = tableView.convert(point, to: cell)
  1253. let pointInReactionPart = cell.convert(pointInCell, to: cell.reactionPart)
  1254. let reactionView = cell.reactionPart.subviews.first(where: { $0 is ReactionsView && $0.frame.contains(pointInReactionPart) })
  1255. if reactionView != nil, let message = cell.message {
  1256. self.showReactionsSummary(of: message)
  1257. return nil
  1258. }
  1259. }
  1260. guard let message = self.message(for: indexPath) else { return nil }
  1261. if message.isSystemMessage || message.isDeletedMessage || message.messageId == kUnreadMessagesSeparatorIdentifier {
  1262. return nil
  1263. }
  1264. var actions: [UIMenuElement] = []
  1265. var informationalActions: [UIMenuElement] = []
  1266. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1267. let hasChatPermissions = !NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityChatPermission, for: room) || (self.room.permissions & NCPermission.chat.rawValue) != 0
  1268. // Show edit information
  1269. if let lastEditActorDisplayName = message.lastEditActorDisplayName, message.lastEditTimestamp > 0 {
  1270. let timestampDate = Date(timeIntervalSince1970: TimeInterval(message.lastEditTimestamp))
  1271. let editInfo = UIAction(title: NSLocalizedString("Edited by", comment: "A message was edited by ...") + " " + lastEditActorDisplayName, attributes: [.disabled], handler: {_ in })
  1272. editInfo.subtitle = NCUtils.readableTimeAndDate(fromDate: timestampDate)
  1273. informationalActions.append(editInfo)
  1274. }
  1275. // Show silent send information
  1276. if message.isSilent {
  1277. let silentInfo = UIAction(title: NSLocalizedString("Sent without notification", comment: "A message has been sent without notifications"), attributes: [.disabled], handler: {_ in })
  1278. silentInfo.image = UIImage(systemName: "bell.slash")
  1279. informationalActions.append(silentInfo)
  1280. }
  1281. if !informationalActions.isEmpty {
  1282. actions.append(UIMenu(options: [.displayInline], children: informationalActions))
  1283. }
  1284. // Reply option
  1285. if self.isMessageReplyable(message: message), hasChatPermissions, !self.textInputbar.isEditing {
  1286. actions.append(UIAction(title: NSLocalizedString("Reply", comment: ""), image: .init(systemName: "arrowshape.turn.up.left")) { _ in
  1287. self.didPressReply(for: message)
  1288. })
  1289. }
  1290. // Show "Add reaction" when running on MacOS because we don't have an accessory view
  1291. if self.isMessageReactable(message: message), hasChatPermissions, NCUtils.isiOSAppOnMac() {
  1292. actions.append(UIAction(title: NSLocalizedString("Add reaction", comment: ""), image: .init(systemName: "face.smiling")) { _ in
  1293. self.didPressAddReaction(for: message, at: indexPath)
  1294. })
  1295. }
  1296. // Reply-privately option (only to other users and not in one-to-one)
  1297. if self.isMessageReplyable(message: message), self.room.type != .oneToOne, message.actorType == "users", message.actorId != activeAccount.userId {
  1298. actions.append(UIAction(title: NSLocalizedString("Reply privately", comment: ""), image: .init(systemName: "person")) { _ in
  1299. self.didPressReplyPrivately(for: message)
  1300. })
  1301. }
  1302. // Forward option (only normal messages for now)
  1303. if message.file() == nil, message.poll == nil, !message.isDeletedMessage {
  1304. actions.append(UIAction(title: NSLocalizedString("Forward", comment: ""), image: .init(systemName: "arrowshape.turn.up.right")) { _ in
  1305. self.didPressForward(for: message)
  1306. })
  1307. }
  1308. // Note to self
  1309. if message.file() == nil, message.poll == nil, !message.isDeletedMessage, room.type != .noteToSelf,
  1310. NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityNoteToSelf, for: room) {
  1311. actions.append(UIAction(title: NSLocalizedString("Note to self", comment: ""), image: .init(systemName: "square.and.pencil")) { _ in
  1312. self.didPressNoteToSelf(for: message)
  1313. })
  1314. }
  1315. // Remind me later
  1316. if !message.sendingFailed, !message.isOfflineMessage, NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityRemindMeLater, for: room) {
  1317. let deferredMenuElement = UIDeferredMenuElement.uncached { [weak self] completion in
  1318. NCAPIController.sharedInstance().getReminderFor(message) { [weak self] response, error in
  1319. guard let self else { return }
  1320. var menuOptions: [UIMenuElement] = []
  1321. menuOptions.append(contentsOf: self.getSetReminderOptions(for: message))
  1322. if error == nil,
  1323. let responseDict = response as? [String: Any],
  1324. let timestamp = responseDict["timestamp"] as? Int {
  1325. // There's already an existing reminder set for this message
  1326. // -> offer a delete option
  1327. let timestampDate = Date(timeIntervalSince1970: TimeInterval(timestamp))
  1328. let clearAction = UIAction(title: NSLocalizedString("Clear reminder", comment: ""), image: .init(systemName: "trash")) { _ in
  1329. NCAPIController.sharedInstance().deleteReminder(for: message) { error in
  1330. if error == nil {
  1331. NotificationPresenter.shared().present(text: NSLocalizedString("Reminder was successfully cleared", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
  1332. } else {
  1333. NotificationPresenter.shared().present(text: NSLocalizedString("Failed to clear reminder", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1334. }
  1335. }
  1336. }
  1337. clearAction.subtitle = NCUtils.readableDateTime(fromDate: timestampDate)
  1338. clearAction.attributes = .destructive
  1339. menuOptions.append(UIMenu(options: .displayInline, children: [clearAction]))
  1340. }
  1341. completion(menuOptions)
  1342. }
  1343. }
  1344. actions.append(UIMenu(title: NSLocalizedString("Set reminder", comment: "Remind me later about that message"),
  1345. image: .init(systemName: "alarm"),
  1346. children: [deferredMenuElement]))
  1347. }
  1348. // Re-send option
  1349. if (message.sendingFailed || message.isOfflineMessage) && hasChatPermissions {
  1350. actions.append(UIAction(title: NSLocalizedString("Resend", comment: ""), image: .init(systemName: "arrow.clockwise")) { _ in
  1351. self.didPressResend(for: message)
  1352. })
  1353. }
  1354. // Copy option
  1355. actions.append(UIAction(title: NSLocalizedString("Copy", comment: ""), image: .init(systemName: "square.on.square")) { _ in
  1356. self.didPressCopy(for: message)
  1357. })
  1358. // Translate
  1359. if !self.offlineMode, NCDatabaseManager.sharedInstance().hasAvailableTranslations(forAccountId: activeAccount.accountId) {
  1360. actions.append(UIAction(title: NSLocalizedString("Translate", comment: ""), image: .init(systemName: "character.book.closed")) { _ in
  1361. self.didPressTranslate(for: message)
  1362. })
  1363. }
  1364. // Open in nextcloud option
  1365. if !self.offlineMode, message.file() != nil {
  1366. let openInNextcloudTitle = String(format: NSLocalizedString("Open in %@", comment: ""), filesAppName)
  1367. actions.append(UIAction(title: openInNextcloudTitle, image: .init(named: "logo-action")?.withRenderingMode(.alwaysTemplate)) { _ in
  1368. self.didPressOpenInNextcloud(for: message)
  1369. })
  1370. }
  1371. // Transcribe voice-message
  1372. if message.messageType == kMessageTypeVoiceMessage {
  1373. let transcribeTitle = NSLocalizedString("Transcribe", comment: "TRANSLATORS this is for transcribing a voice message to text")
  1374. actions.append(UIAction(title: transcribeTitle, image: .init(systemName: "text.bubble")) { _ in
  1375. self.didPressTranscribeVoiceMessage(for: message)
  1376. })
  1377. }
  1378. var destructiveMenuActions: [UIMenuElement] = []
  1379. // Edit option
  1380. if message.isEditable(for: activeAccount, in: self.room) && hasChatPermissions {
  1381. destructiveMenuActions.append(UIAction(title: NSLocalizedString("Edit", comment: "Edit a message or room participants"), image: .init(systemName: "pencil")) { _ in
  1382. self.didPressEdit(for: message)
  1383. })
  1384. }
  1385. // Delete option
  1386. if message.sendingFailed || message.isOfflineMessage || (message.isDeletable(for: activeAccount, in: self.room) && hasChatPermissions) {
  1387. destructiveMenuActions.append(UIAction(title: NSLocalizedString("Delete", comment: ""), image: .init(systemName: "trash"), attributes: .destructive) { _ in
  1388. self.didPressDelete(for: message)
  1389. })
  1390. }
  1391. if !destructiveMenuActions.isEmpty {
  1392. actions.append(UIMenu(options: [.displayInline], children: destructiveMenuActions))
  1393. }
  1394. let menu = UIMenu(children: actions)
  1395. let configuration = UIContextMenuConfiguration(identifier: indexPath as NSIndexPath) {
  1396. return nil
  1397. } actionProvider: { _ in
  1398. return menu
  1399. }
  1400. return configuration
  1401. }
  1402. // MARK: - NCChatTitleViewDelegate
  1403. public override func chatTitleViewTapped(_ titleView: NCChatTitleView!) {
  1404. guard let roomInfoVC = RoomInfoTableViewController(for: self.room, from: self) else { return }
  1405. roomInfoVC.hideDestructiveActions = self.presentedInCall
  1406. if let splitViewController = NCUserInterfaceController.sharedInstance().mainViewController {
  1407. if !splitViewController.isCollapsed {
  1408. roomInfoVC.modalPresentationStyle = .pageSheet
  1409. let navController = UINavigationController(rootViewController: roomInfoVC)
  1410. self.present(navController, animated: true)
  1411. } else {
  1412. self.navigationController?.pushViewController(roomInfoVC, animated: true)
  1413. }
  1414. } else {
  1415. self.navigationController?.pushViewController(roomInfoVC, animated: true)
  1416. }
  1417. // When returning from RoomInfoTableViewController the default keyboard will be shown, so the height might be wrong -> make sure the keyboard is hidden
  1418. self.dismissKeyboard(true)
  1419. }
  1420. }