BaseChatViewController.swift 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483
  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. import Realm
  10. import ContactsUI
  11. import QuickLook
  12. @objcMembers public class BaseChatViewController: InputbarViewController,
  13. UITextFieldDelegate,
  14. UIImagePickerControllerDelegate,
  15. PHPickerViewControllerDelegate,
  16. UINavigationControllerDelegate,
  17. PollCreationViewControllerDelegate,
  18. ShareLocationViewControllerDelegate,
  19. CNContactPickerDelegate,
  20. UIDocumentPickerDelegate,
  21. VLCKitVideoViewControllerDelegate,
  22. ShareViewControllerDelegate,
  23. QLPreviewControllerDelegate,
  24. QLPreviewControllerDataSource,
  25. NCChatFileControllerDelegate,
  26. ShareConfirmationViewControllerDelegate,
  27. AVAudioRecorderDelegate,
  28. AVAudioPlayerDelegate,
  29. SystemMessageTableViewCellDelegate,
  30. BaseChatTableViewCellDelegate,
  31. UITableViewDataSourcePrefetching {
  32. // MARK: - Internal var
  33. internal var messages: [Date: [NCChatMessage]] = [:]
  34. internal var dateSections: [Date] = []
  35. internal var isVisible = false
  36. internal var isTyping = false
  37. internal var firstUnreadMessage: NCChatMessage?
  38. internal var dismissNotificationsOnViewWillDisappear = true
  39. internal var replyMessageView: ReplyMessageView?
  40. internal var voiceMessagesPlayer: AVAudioPlayer?
  41. internal var interactingMessage: NCChatMessage?
  42. internal var lastMessageBeforeInteraction: IndexPath?
  43. internal var contextMenuActionBlock: (() -> Void)?
  44. internal var editingMessage: NCChatMessage?
  45. internal lazy var emojiTextField: EmojiTextField = {
  46. let emojiTextField = EmojiTextField()
  47. emojiTextField.delegate = self
  48. self.view.addSubview(emojiTextField)
  49. return emojiTextField
  50. }()
  51. internal lazy var datePickerTextField: DatePickerTextField = {
  52. let datePicker = DatePickerTextField()
  53. datePicker.delegate = self
  54. self.view.addSubview(datePicker)
  55. return datePicker
  56. }()
  57. internal lazy var chatBackgroundView: PlaceholderView = {
  58. let chatBackgroundView = PlaceholderView()
  59. chatBackgroundView.placeholderView.isHidden = true
  60. chatBackgroundView.loadingView.startAnimating()
  61. chatBackgroundView.placeholderTextView.text = NSLocalizedString("No messages yet, start the conversation!", comment: "")
  62. chatBackgroundView.setImage(UIImage(named: "chat-placeholder"))
  63. return chatBackgroundView
  64. }()
  65. // MARK: - Private var
  66. private var sendButtonTagMessage = 99
  67. private var sendButtonTagVoice = 98
  68. private var actionTypeTranscribeVoiceMessage = "transcribe-voice-message"
  69. private var imagePicker: UIImagePickerController?
  70. private var stopTypingTimer: Timer?
  71. private var typingTimer: Timer?
  72. private var voiceMessageLongPressGesture: UILongPressGestureRecognizer?
  73. private var recorder: AVAudioRecorder?
  74. private var voiceMessageRecordingView: VoiceMessageRecordingView?
  75. private var longPressStartingPoint: CGPoint?
  76. private var cancelHintLabelInitialPositionX: CGFloat?
  77. private var recordCancelled: Bool = false
  78. private var animationDispatchGroup = DispatchGroup()
  79. private var animationDispatchQueue = DispatchQueue(label: "\(groupIdentifier).animationQueue")
  80. private var loadingHistoryView: UIActivityIndicatorView?
  81. private var isPreviewControllerShown: Bool = false
  82. private var previewControllerFilePath: String?
  83. private var playerProgressTimer: Timer?
  84. private var playerAudioFileStatus: NCChatFileStatus?
  85. private var photoPicker: PHPickerViewController?
  86. private var contextMenuAccessoryView: UIView?
  87. private var contextMenuMessageView: UIView?
  88. private lazy var inputbarBorderView: UIView = {
  89. let inputbarBorderView = UIView()
  90. inputbarBorderView.autoresizingMask = [.flexibleWidth, .flexibleBottomMargin]
  91. inputbarBorderView.frame = .init(x: 0, y: 0, width: self.textInputbar.frame.size.width, height: 1)
  92. inputbarBorderView.isHidden = true
  93. inputbarBorderView.backgroundColor = .systemGray6
  94. self.textInputbar.addSubview(inputbarBorderView)
  95. return inputbarBorderView
  96. }()
  97. private lazy var unreadMessageButton: UIButton = {
  98. let unreadMessageButton = UIButton(frame: .init(x: 0, y: 0, width: 126, height: 24))
  99. unreadMessageButton.backgroundColor = NCAppBranding.themeColor()
  100. unreadMessageButton.setTitleColor(NCAppBranding.themeTextColor(), for: .normal)
  101. unreadMessageButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
  102. unreadMessageButton.layer.cornerRadius = 12
  103. unreadMessageButton.clipsToBounds = true
  104. unreadMessageButton.isHidden = true
  105. unreadMessageButton.translatesAutoresizingMaskIntoConstraints = false
  106. unreadMessageButton.contentEdgeInsets = .init(top: 0, left: 10, bottom: 0, right: 10)
  107. unreadMessageButton.titleLabel?.minimumScaleFactor = 0.9
  108. unreadMessageButton.titleLabel?.numberOfLines = 1
  109. unreadMessageButton.titleLabel?.adjustsFontSizeToFitWidth = true
  110. unreadMessageButton.setTitle(NSLocalizedString("↓ New messages", comment: ""), for: .normal)
  111. unreadMessageButton.addAction { [weak self] in
  112. guard let self,
  113. let firstUnreadMessage = self.firstUnreadMessage,
  114. let indexPath = self.indexPath(for: firstUnreadMessage)
  115. else { return }
  116. self.tableView?.scrollToRow(at: indexPath, at: .none, animated: true)
  117. }
  118. self.view.addSubview(unreadMessageButton)
  119. return unreadMessageButton
  120. }()
  121. private lazy var scrollToBottomButton: UIButton = {
  122. let button = UIButton(frame: .init(x: 0, y: 0, width: 44, height: 44), primaryAction: UIAction { [weak self] _ in
  123. self?.tableView?.slk_scrollToBottom(animated: true)
  124. })
  125. button.backgroundColor = .secondarySystemBackground
  126. button.tintColor = .systemBlue
  127. button.layer.cornerRadius = button.frame.size.height / 2
  128. button.clipsToBounds = true
  129. button.alpha = 0
  130. button.translatesAutoresizingMaskIntoConstraints = false
  131. button.setImage(UIImage(systemName: "chevron.down"), for: .normal)
  132. self.view.addSubview(button)
  133. return button
  134. }()
  135. // MARK: - Init/Deinit
  136. public init?(for room: NCRoom) {
  137. super.init(for: room, tableViewStyle: .plain)
  138. self.hidesBottomBarWhenPushed = true
  139. self.tableView?.estimatedRowHeight = 0
  140. self.tableView?.estimatedSectionHeaderHeight = 0
  141. self.tableView?.prefetchDataSource = self
  142. FilePreviewImageView.setSharedImageDownloader(NCAPIController.sharedInstance().imageDownloader)
  143. NotificationCenter.default.addObserver(self, selector: #selector(willShowKeyboard(notification:)), name: UIWindow.keyboardWillShowNotification, object: nil)
  144. NotificationCenter.default.addObserver(self, selector: #selector(willHideKeyboard(notification:)), name: UIWindow.keyboardWillHideNotification, object: nil)
  145. AllocationTracker.shared.addAllocation("ChatViewController")
  146. }
  147. // Not using an optional here, because it is not available from ObjC
  148. // Pass "0" as highlightMessageId to not highlight a message
  149. public convenience init?(for room: NCRoom, withMessage messages: [NCChatMessage], withHighlightId highlightMessageId: Int) {
  150. self.init(for: room)
  151. // When we pass in a fixed number of messages, we hide the inputbar by default
  152. self.textInputbar.isHidden = true
  153. // Scroll to bottom manually after hiding the textInputbar, otherwise the
  154. // scrollToBottom button might be briefly visible even if not needed
  155. self.tableView?.slk_scrollToBottom(animated: false)
  156. self.appendMessages(messages: messages)
  157. self.tableView?.performBatchUpdates({
  158. self.tableView?.reloadData()
  159. }, completion: { _ in
  160. self.highlightMessageWithContentOffset(messageId: highlightMessageId)
  161. })
  162. }
  163. required init?(coder decoder: NSCoder) {
  164. fatalError("init(coder:) has not been implemented")
  165. }
  166. deinit {
  167. NotificationCenter.default.removeObserver(self)
  168. AllocationTracker.shared.removeAllocation("ChatViewController")
  169. NSLog("Dealloc BaseChatViewController")
  170. }
  171. // MARK: - View lifecycle
  172. public override func viewDidLoad() {
  173. super.viewDidLoad()
  174. self.shouldScrollToBottomAfterKeyboardShows = false
  175. self.isInverted = false
  176. self.showSendMessageButton()
  177. self.leftButton.setImage(UIImage(systemName: "paperclip"), for: .normal)
  178. self.leftButton.accessibilityLabel = NSLocalizedString("Share a file from your Nextcloud", comment: "")
  179. self.leftButton.accessibilityHint = NSLocalizedString("Double tap to open file browser", comment: "")
  180. // Set delegate to retrieve typing events
  181. self.tableView?.separatorStyle = .none
  182. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatMessageCellIdentifier)
  183. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatGroupedMessageCellIdentifier)
  184. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: chatReplyMessageCellIdentifier)
  185. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: fileMessageCellIdentifier)
  186. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: fileGroupedMessageCellIdentifier)
  187. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: locationMessageCellIdentifier)
  188. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: locationGroupedMessageCellIdentifier)
  189. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: voiceMessageCellIdentifier)
  190. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: voiceGroupedMessageCellIdentifier)
  191. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: pollMessageCellIdentifier)
  192. self.tableView?.register(UINib(nibName: "BaseChatTableViewCell", bundle: nil), forCellReuseIdentifier: pollGroupedMessageCellIdentifier)
  193. self.tableView?.register(SystemMessageTableViewCell.self, forCellReuseIdentifier: SystemMessageCellIdentifier)
  194. self.tableView?.register(SystemMessageTableViewCell.self, forCellReuseIdentifier: InvisibleSystemMessageCellIdentifier)
  195. self.tableView?.register(MessageSeparatorTableViewCell.self, forCellReuseIdentifier: MessageSeparatorCellIdentifier)
  196. let newMessagesButtonText = NSLocalizedString("↓ New messages", comment: "")
  197. // Need to move down to NSLayout
  198. let attributes = [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)]
  199. let textSize = NSString(string: newMessagesButtonText).boundingRect(with: .init(width: 300, height: 24), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
  200. let buttonWidth = textSize.size.width + 20
  201. let views = [
  202. "unreadMessageButton": self.unreadMessageButton,
  203. "textInputbar": self.textInputbar,
  204. "scrollToBottomButton": self.scrollToBottomButton,
  205. "autoCompletionView": self.autoCompletionView
  206. ]
  207. let metrics = [
  208. "buttonWidth": buttonWidth
  209. ]
  210. self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[unreadMessageButton(24)]-5-[autoCompletionView]", metrics: metrics, views: views))
  211. self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[unreadMessageButton(buttonWidth)]-(>=0)-|", metrics: metrics, views: views))
  212. if let view = self.view {
  213. self.view.addConstraint(NSLayoutConstraint(item: view, attribute: .centerX, relatedBy: .equal, toItem: self.unreadMessageButton, attribute: .centerX, multiplier: 1, constant: 0))
  214. }
  215. self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[scrollToBottomButton(44)]-10-[autoCompletionView]", metrics: metrics, views: views))
  216. self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(>=0)-[scrollToBottomButton(44)]-(>=0)-|", metrics: metrics, views: views))
  217. self.scrollToBottomButton.trailingAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.trailingAnchor, constant: -10).isActive = true
  218. self.addMenuToLeftButton()
  219. self.replyMessageView?.addObserver(self, forKeyPath: "visible", options: .new, context: nil)
  220. }
  221. // swiftlint:disable:next block_based_kvo
  222. public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
  223. super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
  224. guard let object = object as? ReplyMessageView,
  225. object == self.replyMessageView else { return }
  226. // When the visible state of the replyMessageView changes, we need to update the toolbar to show the correct border
  227. // Only do this if we are not already at the bottom, otherwise we briefly show the scroll button directly after sending a message
  228. self.updateToolbar(animated: true)
  229. }
  230. public func updateToolbar(animated: Bool) {
  231. guard let tableView else { return }
  232. let animations = {
  233. let minimumOffset = (tableView.contentSize.height - tableView.frame.size.height) - 10
  234. if tableView.contentOffset.y < minimumOffset {
  235. // Scrolled -> show top border
  236. // When a reply view is visible, we show the border of that view
  237. if let replyMessageView = self.replyMessageView {
  238. replyMessageView.topBorder.isHidden = !replyMessageView.isVisible
  239. self.inputbarBorderView.isHidden = replyMessageView.isVisible
  240. } else {
  241. self.inputbarBorderView.isHidden = false
  242. }
  243. } else {
  244. // At the bottom -> no top border
  245. self.inputbarBorderView.isHidden = true
  246. if let replyMessageView = self.replyMessageView {
  247. replyMessageView.topBorder.isHidden = true
  248. }
  249. }
  250. }
  251. let animationsScrollButton = {
  252. let minimumOffset = (tableView.contentSize.height - tableView.frame.size.height) - 10
  253. if tableView.contentOffset.y < minimumOffset {
  254. // Scrolled -> show button
  255. self.scrollToBottomButton.alpha = 1
  256. } else {
  257. // At the bottom -> hide button
  258. self.scrollToBottomButton.alpha = 0
  259. }
  260. }
  261. if animated {
  262. self.animationDispatchQueue.async {
  263. self.animationDispatchGroup.enter()
  264. self.animationDispatchGroup.enter()
  265. DispatchQueue.main.async {
  266. UIView.transition(with: self.textInputbar,
  267. duration: 0.3,
  268. options: .transitionCrossDissolve,
  269. animations: animations) { _ in
  270. self.animationDispatchGroup.leave()
  271. }
  272. }
  273. DispatchQueue.main.async {
  274. UIView.animate(withDuration: 0.3,
  275. animations: animationsScrollButton) { _ in
  276. self.animationDispatchGroup.leave()
  277. }
  278. }
  279. _ = self.animationDispatchGroup.wait(timeout: .distantFuture)
  280. }
  281. } else {
  282. DispatchQueue.main.async {
  283. animations()
  284. animationsScrollButton()
  285. }
  286. }
  287. }
  288. public override func viewWillAppear(_ animated: Bool) {
  289. super.viewWillAppear(animated)
  290. self.isVisible = true
  291. }
  292. public override func viewWillDisappear(_ animated: Bool) {
  293. super.viewWillDisappear(animated)
  294. self.isVisible = false
  295. if !self.textInputbar.isHidden {
  296. self.savePendingMessage()
  297. }
  298. if dismissNotificationsOnViewWillDisappear {
  299. NotificationPresenter.shared().dismiss(animated: false)
  300. }
  301. }
  302. public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  303. super.traitCollectionDidChange(previousTraitCollection)
  304. if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
  305. self.updateToolbar(animated: true)
  306. }
  307. }
  308. // MARK: - Keyboard notifications
  309. func willShowKeyboard(notification: Notification) {
  310. guard let currentResponder = UIResponder.slk_currentFirst() else { return }
  311. // Skip if it's not the emoji/date text field
  312. if !currentResponder.isKind(of: EmojiTextField.self) && !currentResponder.isKind(of: DatePickerTextField.self) {
  313. return
  314. }
  315. guard let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
  316. return
  317. }
  318. let keyboardRect = keyboardFrame.cgRectValue
  319. self.updateView(toShowOrHideEmojiKeyboard: keyboardRect.size.height)
  320. guard let interactingMessage,
  321. let indexPath = self.indexPath(for: interactingMessage) else {
  322. return
  323. }
  324. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
  325. if let tableView = self.tableView {
  326. let cellRect = tableView.rectForRow(at: indexPath)
  327. if !tableView.bounds.contains(cellRect) {
  328. self.tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
  329. }
  330. }
  331. }
  332. }
  333. func willHideKeyboard(notification: Notification) {
  334. guard let currentResponder = UIResponder.slk_currentFirst() else { return }
  335. // Skip if it's not the emoji/date text field
  336. if !currentResponder.isKind(of: EmojiTextField.self) && !currentResponder.isKind(of: DatePickerTextField.self) {
  337. return
  338. }
  339. self.updateView(toShowOrHideEmojiKeyboard: 0.0)
  340. guard let lastMessageBeforeInteraction, let tableView else { return }
  341. if NCUtils.isValid(indexPath: lastMessageBeforeInteraction, forTableView: tableView) {
  342. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
  343. tableView.scrollToRow(at: lastMessageBeforeInteraction, at: .bottom, animated: true)
  344. }
  345. }
  346. }
  347. // MARK: - Utils
  348. internal func getHeaderString(fromDate date: Date) -> String {
  349. let formatter = DateFormatter()
  350. formatter.dateStyle = .medium
  351. formatter.doesRelativeDateFormatting = true
  352. return formatter.string(from: date)
  353. }
  354. internal func presentWithNavigation(_ viewControllerToPresent: UIViewController, animated flag: Bool) {
  355. self.present(NCNavigationController(rootViewController: viewControllerToPresent), animated: flag)
  356. }
  357. // MARK: - Temporary messages
  358. internal func createTemporaryMessage(message: String, replyTo parentMessage: NCChatMessage?, messageParameters: String, silently: Bool) -> NCChatMessage {
  359. let temporaryMessage = NCChatMessage()
  360. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  361. temporaryMessage.accountId = activeAccount.accountId
  362. temporaryMessage.actorDisplayName = activeAccount.userDisplayName
  363. temporaryMessage.actorId = activeAccount.userId
  364. temporaryMessage.actorType = "users"
  365. temporaryMessage.timestamp = Int(Date().timeIntervalSince1970)
  366. temporaryMessage.token = room.token
  367. temporaryMessage.message = self.replaceMentionsDisplayNamesWithMentionsKeysInMessage(message: message, parameters: messageParameters)
  368. let referenceId = "temp-\(Date().timeIntervalSince1970 * 1000)"
  369. temporaryMessage.referenceId = NCUtils.sha1(fromString: referenceId)
  370. temporaryMessage.internalId = referenceId
  371. temporaryMessage.isTemporary = true
  372. temporaryMessage.parentId = parentMessage?.internalId
  373. temporaryMessage.messageParametersJSONString = messageParameters
  374. temporaryMessage.isSilent = silently
  375. temporaryMessage.isMarkdownMessage = NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityMarkdownMessages, for: self.room)
  376. let realm = RLMRealm.default()
  377. try? realm.transaction {
  378. realm.add(temporaryMessage)
  379. }
  380. let unmanagedTemporaryMessage = NCChatMessage(value: temporaryMessage)
  381. return unmanagedTemporaryMessage
  382. }
  383. internal func replaceMessageMentionsKeysWithMentionsDisplayNames(message: String, parameters: String) -> String {
  384. var resultMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
  385. guard let messageParametersDict = NCMessageParameter.messageParametersDict(fromJSONString: parameters) else { return resultMessage }
  386. for (parameterKey, parameter) in messageParametersDict {
  387. let parameterKeyString = "{\(parameterKey)}"
  388. resultMessage = resultMessage.replacingOccurrences(of: parameterKeyString, with: parameter.mentionDisplayName)
  389. }
  390. return resultMessage
  391. }
  392. internal func appendTemporaryMessage(temporaryMessage: NCChatMessage) {
  393. DispatchQueue.main.async {
  394. let lastSectionBeforeUpdate = self.dateSections.count - 1
  395. self.appendMessages(messages: [temporaryMessage])
  396. if let lastDateSection = self.dateSections.last, let messagesForLastDate = self.messages[lastDateSection] {
  397. let lastMessageIndexPath = IndexPath(row: messagesForLastDate.count - 1, section: self.dateSections.count - 1)
  398. self.tableView?.beginUpdates()
  399. let newLastSection = self.dateSections.count - 1
  400. if lastSectionBeforeUpdate != newLastSection {
  401. self.tableView?.insertSections(.init(integer: newLastSection), with: .none)
  402. } else {
  403. self.tableView?.insertRows(at: [lastMessageIndexPath], with: .none)
  404. }
  405. self.tableView?.endUpdates()
  406. self.tableView?.scrollToRow(at: lastMessageIndexPath, at: .none, animated: true)
  407. }
  408. }
  409. }
  410. internal func removePermanentlyTemporaryMessage(temporaryMessage: NCChatMessage) {
  411. let realm = RLMRealm.default()
  412. try? realm.transaction {
  413. if let managedTemporaryMessage = NCChatMessage.objects(where: "referenceId = %@ AND isTemporary = true", temporaryMessage.referenceId).firstObject() {
  414. realm.delete(managedTemporaryMessage)
  415. }
  416. }
  417. self.removeTemporaryMessages(temporaryMessages: [temporaryMessage])
  418. }
  419. internal func removeTemporaryMessages(temporaryMessages: [NCChatMessage]) {
  420. DispatchQueue.main.async {
  421. for temporaryMessage in temporaryMessages {
  422. if let indexPath = self.indexPath(for: temporaryMessage) {
  423. self.removeMessage(at: indexPath)
  424. }
  425. }
  426. }
  427. }
  428. // MARK: - Message updates
  429. internal func modifyMessageWith(referenceId: String, block: (NCChatMessage) -> Void) {
  430. guard let (indexPath, message) = self.indexPathAndMessage(forReferenceId: referenceId)
  431. else { return }
  432. block(message)
  433. self.tableView?.beginUpdates()
  434. self.tableView?.reloadRows(at: [indexPath], with: .none)
  435. self.tableView?.endUpdates()
  436. }
  437. internal func updateMessage(withMessageId messageId: Int, updatedMessage: NCChatMessage) {
  438. DispatchQueue.main.async {
  439. guard let (indexPath, message) = self.indexPathAndMessage(forMessageId: messageId) else { return }
  440. var reloadIndexPaths = [indexPath]
  441. let isAtBottom = self.shouldScrollOnNewMessages()
  442. let keyDate = self.dateSections[indexPath.section]
  443. updatedMessage.isGroupMessage = message.isGroupMessage && message.actorType != "bots" && updatedMessage.lastEditTimestamp == 0
  444. self.messages[keyDate]?[indexPath.row] = updatedMessage
  445. // Check if there are any messages that reference our message as a parent -> these need to be reloaded as well
  446. if let visibleIndexPaths = self.tableView?.indexPathsForVisibleRows {
  447. let referencingIndexPaths = visibleIndexPaths.filter({
  448. guard let message = self.message(for: $0),
  449. let parentMessage = message.parent
  450. else { return false }
  451. return parentMessage.messageId == messageId
  452. })
  453. reloadIndexPaths.append(contentsOf: referencingIndexPaths)
  454. }
  455. self.tableView?.beginUpdates()
  456. self.tableView?.reloadRows(at: reloadIndexPaths, with: .none)
  457. self.tableView?.endUpdates()
  458. if isAtBottom {
  459. // Make sure we're really at the bottom after updating a message
  460. DispatchQueue.main.async {
  461. self.tableView?.slk_scrollToBottom(animated: false)
  462. self.updateToolbar(animated: false)
  463. }
  464. }
  465. }
  466. }
  467. // MARK: - User interface
  468. func showVoiceMessageRecordButton() {
  469. self.rightButton.setTitle("", for: .normal)
  470. self.rightButton.setImage(UIImage(systemName: "mic"), for: .normal)
  471. self.rightButton.tag = sendButtonTagVoice
  472. self.rightButton.accessibilityLabel = NSLocalizedString("Record voice message", comment: "")
  473. self.rightButton.accessibilityHint = NSLocalizedString("Tap and hold to record a voice message", comment: "")
  474. self.addGestureRecognizerToRightButton()
  475. }
  476. func showSendMessageButton() {
  477. self.rightButton.setTitle("", for: .normal)
  478. self.rightButton.setImage(UIImage(systemName: "paperplane"), for: .normal)
  479. self.rightButton.tag = sendButtonTagMessage
  480. self.rightButton.accessibilityLabel = NSLocalizedString("Send message", comment: "")
  481. self.rightButton.accessibilityHint = NSLocalizedString("Double tap to send message", comment: "")
  482. self.addMenuToRightButton()
  483. }
  484. // MARK: - Action methods
  485. func sendChatMessage(message: String, withParentMessage parentMessage: NCChatMessage?, messageParameters: String, silently: Bool) {
  486. // Overridden in sub class
  487. }
  488. func sendCurrentMessage(silently: Bool) {
  489. var replyToMessage: NCChatMessage?
  490. if let replyMessageView, replyMessageView.isVisible {
  491. replyToMessage = replyMessageView.message
  492. }
  493. let messageParameters = NCMessageParameter.messageParametersJSONString(from: self.mentionsDict) ?? ""
  494. self.sendChatMessage(message: self.textView.text, withParentMessage: replyToMessage, messageParameters: messageParameters, silently: silently)
  495. self.mentionsDict.removeAll()
  496. self.replyMessageView?.dismiss()
  497. super.didPressRightButton(self)
  498. self.clearPendingMessage()
  499. self.stopTyping(force: true)
  500. }
  501. public override func didPressRightButton(_ sender: Any?) {
  502. guard let button = sender as? UIButton else { return }
  503. switch button.tag {
  504. case sendButtonTagMessage:
  505. self.sendCurrentMessage(silently: false)
  506. super.didPressRightButton(sender)
  507. case sendButtonTagVoice:
  508. self.showVoiceMessageRecordHint()
  509. default:
  510. break
  511. }
  512. }
  513. func addGestureRecognizerToRightButton() {
  514. // Remove a potential menu so it does not interfere with the long gesture recognizer
  515. self.rightButton.menu = nil
  516. // Add long press gesture recognizer for voice message recording button
  517. self.voiceMessageLongPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressInVoiceMessageRecordButton(gestureRecognizer:)))
  518. if let voiceMessageLongPressGesture {
  519. voiceMessageLongPressGesture.delegate = self
  520. self.rightButton.addGestureRecognizer(voiceMessageLongPressGesture)
  521. }
  522. }
  523. func addMenuToRightButton() {
  524. // Remove a gesture recognizer to not interfere with our menu
  525. if let voiceMessageLongPressGesture = self.voiceMessageLongPressGesture {
  526. self.rightButton.removeGestureRecognizer(voiceMessageLongPressGesture)
  527. self.voiceMessageLongPressGesture = nil
  528. }
  529. let silentSendAction = UIAction(title: NSLocalizedString("Send without notification", comment: ""), image: UIImage(systemName: "bell.slash")) { [unowned self] _ in
  530. self.sendCurrentMessage(silently: true)
  531. }
  532. self.rightButton.menu = UIMenu(children: [silentSendAction])
  533. }
  534. func addMenuToLeftButton() {
  535. // The keyboard will be hidden when an action is invoked. Depending on what
  536. // attachment is shared, not resigning might lead to a currupted chat view
  537. var items: [UIAction] = []
  538. let cameraAction = UIAction(title: NSLocalizedString("Camera", comment: ""), image: UIImage(systemName: "camera")) { [unowned self] _ in
  539. self.textView.resignFirstResponder()
  540. self.checkAndPresentCamera()
  541. }
  542. let photoLibraryAction = UIAction(title: NSLocalizedString("Photo Library", comment: ""), image: UIImage(systemName: "photo")) { [unowned self] _ in
  543. self.textView.resignFirstResponder()
  544. self.presentPhotoLibrary()
  545. }
  546. let shareLocationAction = UIAction(title: NSLocalizedString("Location", comment: ""), image: UIImage(systemName: "location")) { [unowned self] _ in
  547. self.textView.resignFirstResponder()
  548. self.presentShareLocation()
  549. }
  550. let contactShareAction = UIAction(title: NSLocalizedString("Contacts", comment: ""), image: UIImage(systemName: "person")) { [unowned self] _ in
  551. self.textView.resignFirstResponder()
  552. self.presentShareContact()
  553. }
  554. let filesAction = UIAction(title: NSLocalizedString("Files", comment: ""), image: UIImage(systemName: "doc")) { [unowned self] _ in
  555. self.textView.resignFirstResponder()
  556. self.presentDocumentPicker()
  557. }
  558. let ncFilesAction = UIAction(title: filesAppName, image: UIImage(named: "logo-action")?.withRenderingMode(.alwaysTemplate)) { [unowned self] _ in
  559. self.textView.resignFirstResponder()
  560. self.presentNextcloudFilesBrowser()
  561. }
  562. let pollAction = UIAction(title: NSLocalizedString("Poll", comment: ""), image: UIImage(systemName: "chart.bar")) { [unowned self] _ in
  563. self.textView.resignFirstResponder()
  564. self.presentPollCreation()
  565. }
  566. // Add actions (inverted)
  567. items.append(ncFilesAction)
  568. items.append(filesAction)
  569. items.append(contactShareAction)
  570. if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityLocationSharing, for: self.room) {
  571. items.append(shareLocationAction)
  572. }
  573. if NCDatabaseManager.sharedInstance().roomHasTalkCapability(kCapabilityTalkPolls, for: self.room),
  574. self.room.type != .oneToOne, self.room.type != .noteToSelf {
  575. items.append(pollAction)
  576. }
  577. items.append(photoLibraryAction)
  578. if UIImagePickerController.isSourceTypeAvailable(.camera) {
  579. items.append(cameraAction)
  580. }
  581. self.leftButton.menu = UIMenu(children: items)
  582. self.leftButton.showsMenuAsPrimaryAction = true
  583. }
  584. func presentNextcloudFilesBrowser() {
  585. let directoryVC = DirectoryTableViewController(path: "", inRoom: self.room.token)
  586. self.presentWithNavigation(directoryVC, animated: true)
  587. }
  588. func checkAndPresentCamera() {
  589. // https://stackoverflow.com/a/20464727/2512312
  590. let mediaType = AVMediaType.video
  591. let authStatus = AVCaptureDevice.authorizationStatus(for: mediaType)
  592. if authStatus == AVAuthorizationStatus.authorized {
  593. self.presentCamera()
  594. return
  595. } else if authStatus == AVAuthorizationStatus.notDetermined {
  596. AVCaptureDevice.requestAccess(for: mediaType, completionHandler: { (granted: Bool) in
  597. if granted {
  598. self.presentCamera()
  599. }
  600. })
  601. return
  602. }
  603. let alert = UIAlertController(title: NSLocalizedString("Could not access camera", comment: ""),
  604. message: NSLocalizedString("Camera access is not allowed. Check your settings.", comment: ""),
  605. preferredStyle: .alert)
  606. alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
  607. NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
  608. }
  609. func presentCamera() {
  610. DispatchQueue.main.async {
  611. self.imagePicker = UIImagePickerController()
  612. if let imagePicker = self.imagePicker,
  613. let sourceType = UIImagePickerController.availableMediaTypes(for: imagePicker.sourceType) {
  614. imagePicker.sourceType = .camera
  615. imagePicker.cameraFlashMode = UIImagePickerController.CameraFlashMode(rawValue: NCUserDefaults.preferredCameraFlashMode()) ?? .off
  616. imagePicker.mediaTypes = sourceType
  617. imagePicker.delegate = self
  618. self.present(imagePicker, animated: true)
  619. }
  620. }
  621. }
  622. func presentPhotoLibrary() {
  623. DispatchQueue.main.async {
  624. var pickerConfig = PHPickerConfiguration()
  625. pickerConfig.selectionLimit = 5
  626. pickerConfig.filter = PHPickerFilter.any(of: [.images, .videos])
  627. self.photoPicker = PHPickerViewController(configuration: pickerConfig)
  628. if let photoPicker = self.photoPicker {
  629. photoPicker.delegate = self
  630. self.present(photoPicker, animated: true)
  631. }
  632. }
  633. }
  634. func presentPollCreation() {
  635. let pollCreationVC = PollCreationViewController(style: .insetGrouped)
  636. pollCreationVC.pollCreationDelegate = self
  637. self.presentWithNavigation(pollCreationVC, animated: true)
  638. }
  639. func presentShareLocation() {
  640. let shareLocationVC = ShareLocationViewController()
  641. shareLocationVC.delegate = self
  642. self.presentWithNavigation(shareLocationVC, animated: true)
  643. }
  644. func presentShareContact() {
  645. let contactPicker = CNContactPickerViewController()
  646. contactPicker.delegate = self
  647. self.present(contactPicker, animated: true)
  648. }
  649. func presentDocumentPicker() {
  650. DispatchQueue.main.async {
  651. let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.item], asCopy: true)
  652. documentPicker.delegate = self
  653. self.present(documentPicker, animated: true)
  654. }
  655. }
  656. func showReplyView(for message: NCChatMessage) {
  657. let isAtBottom = self.shouldScrollOnNewMessages()
  658. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  659. if let replyProxyView = self.replyProxyView as? ReplyMessageView {
  660. self.replyMessageView = replyProxyView
  661. replyProxyView.presentReply(with: message, withUserId: activeAccount.userId)
  662. self.presentKeyboard(true)
  663. // Make sure we're really at the bottom after showing the replyMessageView
  664. if isAtBottom {
  665. self.tableView?.slk_scrollToBottom(animated: false)
  666. self.updateToolbar(animated: false)
  667. }
  668. }
  669. }
  670. func didPressReply(for message: NCChatMessage) {
  671. // Make sure we get a smooth animation after dismissing the context menu
  672. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
  673. self.showReplyView(for: message)
  674. }
  675. }
  676. func didPressReplyPrivately(for message: NCChatMessage) {
  677. var userInfo: [String: String] = [:]
  678. userInfo["actorId"] = message.actorId
  679. NotificationCenter.default.post(name: .NCChatViewControllerReplyPrivatelyNotification, object: self, userInfo: userInfo)
  680. }
  681. func didPressAddReaction(for message: NCChatMessage, at indexPath: IndexPath) {
  682. // Hide the keyboard because we are going to present the emoji keyboard
  683. DispatchQueue.main.async {
  684. self.textView.resignFirstResponder()
  685. }
  686. DispatchQueue.main.async {
  687. self.interactingMessage = message
  688. self.lastMessageBeforeInteraction = self.tableView?.indexPathsForVisibleRows?.last
  689. if NCUtils.isiOSAppOnMac() {
  690. // Move the emojiTextField to the position of the cell
  691. if let rowRect = self.tableView?.rectForRow(at: indexPath),
  692. var convertedRowRect = self.tableView?.convert(rowRect, to: self.view) {
  693. // Show the emoji picker at the textView location of the cell
  694. convertedRowRect.origin.y += convertedRowRect.size.height - 16
  695. convertedRowRect.origin.x += 54
  696. // We don't want to have a clickable textField floating around
  697. convertedRowRect.size.width = 0
  698. convertedRowRect.size.height = 0
  699. // Remove and add the emojiTextField to the view, so the Mac OS emoji picker is always at the right location
  700. self.emojiTextField.removeFromSuperview()
  701. self.emojiTextField.frame = convertedRowRect
  702. self.view.addSubview(self.emojiTextField)
  703. }
  704. }
  705. self.emojiTextField.becomeFirstResponder()
  706. }
  707. }
  708. func didPressForward(for message: NCChatMessage) {
  709. var shareViewController: ShareViewController
  710. if message.isObjectShare {
  711. shareViewController = ShareViewController(toForwardObjectShare: message, fromChatViewController: self)
  712. } else {
  713. shareViewController = ShareViewController(toForwardMessage: message.parsedMessage().string, fromChatViewController: self)
  714. }
  715. shareViewController.delegate = self
  716. self.presentWithNavigation(shareViewController, animated: true)
  717. }
  718. func didPressNoteToSelf(for message: NCChatMessage) {
  719. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  720. NCAPIController.sharedInstance().getNoteToSelfRoom(forAccount: activeAccount) { roomDict, error in
  721. if error == nil, let room = NCRoom(dictionary: roomDict, andAccountId: activeAccount.accountId) {
  722. if message.isObjectShare {
  723. NCAPIController.sharedInstance().shareRichObject(message.richObjectFromObjectShare, inRoom: room.token, for: activeAccount) { error in
  724. if error == nil {
  725. NotificationPresenter.shared().present(text: NSLocalizedString("Added note to self", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
  726. } else {
  727. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  728. }
  729. }
  730. } else {
  731. NCAPIController.sharedInstance().sendChatMessage(message.parsedMessage().string, toRoom: room.token, displayName: nil, replyTo: -1, referenceId: nil, silently: false, for: activeAccount) { error in
  732. if error == nil {
  733. NotificationPresenter.shared().present(text: NSLocalizedString("Added note to self", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
  734. } else {
  735. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  736. }
  737. }
  738. }
  739. } else {
  740. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding note", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  741. }
  742. }
  743. }
  744. func didPressResend(for message: NCChatMessage) {
  745. // Make sure there's no unread message separator, as the indexpath could be invalid after removing a message
  746. self.removeUnreadMessagesSeparator()
  747. self.removePermanentlyTemporaryMessage(temporaryMessage: message)
  748. let originalMessage = self.replaceMessageMentionsKeysWithMentionsDisplayNames(message: message.message, parameters: message.messageParametersJSONString ?? "")
  749. self.sendChatMessage(message: originalMessage, withParentMessage: message.parent, messageParameters: message.messageParametersJSONString ?? "", silently: message.isSilent)
  750. }
  751. func didPressCopy(for message: NCChatMessage) {
  752. let pasteboard = UIPasteboard.general
  753. pasteboard.string = message.parsedMessage().string
  754. NotificationPresenter.shared().present(text: NSLocalizedString("Message copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
  755. }
  756. func didPressCopyLink(for message: NCChatMessage) {
  757. guard let link = room.linkURL else {
  758. return
  759. }
  760. let url = "\(link)#message_\(message.messageId)"
  761. let pasteboard = UIPasteboard.general
  762. pasteboard.string = url
  763. NotificationPresenter.shared().present(text: NSLocalizedString("Message link copied", comment: ""), dismissAfterDelay: 5.0, includedStyle: .dark)
  764. }
  765. func didPressTranslate(for message: NCChatMessage) {
  766. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  767. let translateMessageVC = MessageTranslationViewController(message: message.parsedMessage().string, availableTranslations: NCDatabaseManager.sharedInstance().availableTranslations(forAccountId: activeAccount.accountId))
  768. self.presentWithNavigation(translateMessageVC, animated: true)
  769. }
  770. func didPressTranscribeVoiceMessage(for message: NCChatMessage) {
  771. let downloader = NCChatFileController()
  772. downloader.delegate = self
  773. downloader.messageType = kMessageTypeVoiceMessage
  774. downloader.actionType = actionTypeTranscribeVoiceMessage
  775. downloader.downloadFile(fromMessage: message.file())
  776. }
  777. func didPressEdit(for message: NCChatMessage) {
  778. self.savePendingMessage()
  779. let warningString = NSLocalizedString("Adding a mention will only notify users that did not read the message yet", comment: "")
  780. let warningView = UIView()
  781. let warningLabel = UILabel()
  782. warningView.addSubview(warningLabel)
  783. warningLabel.translatesAutoresizingMaskIntoConstraints = false
  784. NSLayoutConstraint.activate([
  785. warningLabel.leftAnchor.constraint(equalTo: warningView.safeAreaLayoutGuide.leftAnchor, constant: 8),
  786. warningLabel.rightAnchor.constraint(equalTo: warningView.safeAreaLayoutGuide.rightAnchor, constant: -8),
  787. warningLabel.topAnchor.constraint(equalTo: warningView.safeAreaLayoutGuide.topAnchor, constant: 4),
  788. warningLabel.bottomAnchor.constraint(equalTo: warningView.safeAreaLayoutGuide.bottomAnchor)
  789. ])
  790. let attributedWarningString = warningString.withFont(.systemFont(ofSize: 14)).withTextColor(.secondaryLabel)
  791. warningLabel.attributedText = attributedWarningString
  792. warningLabel.numberOfLines = 0
  793. // Calculate the height needed to completely show the text
  794. let maxWidth = self.autoCompletionView.frame.width - autoCompletionView.safeAreaInsets.left - autoCompletionView.safeAreaInsets.right - 16
  795. let contraintRect = CGSize(width: maxWidth, height: .greatestFiniteMagnitude)
  796. let size = attributedWarningString.boundingRect(with: contraintRect, options: .usesLineFragmentOrigin, context: nil)
  797. // Update the frame for the new height and include the top padding
  798. warningView.frame = .init(x: 0, y: 0, width: size.width, height: ceil(size.height) + 4)
  799. self.autoCompletionView.tableHeaderView = warningView
  800. DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
  801. // Show the message to edit in the reply view
  802. self.showReplyView(for: message)
  803. self.replyMessageView!.hideCloseButton()
  804. self.mentionsDict = [:]
  805. // Try to reconstruct the mentionsDict
  806. for (key, value) in message.messageParameters {
  807. if let key = key as? String,
  808. key.hasPrefix("mention-"),
  809. let value = value as? [String: String] {
  810. guard let parameter = NCMessageParameter(dictionary: value),
  811. let paramaterDisplayName = parameter.name,
  812. let parameterId = parameter.parameterId
  813. else { continue }
  814. // For mentions the displayName is in the parameter "name", in our mentionsDict we use
  815. // "mentionsDisplayName" for the displayName with the prefix "@", so we need to construct
  816. // that manually here, so mentions are correctly removed while editing.
  817. // The same needs to happen for "mentionId" -> userId with a prefixed "@"
  818. parameter.mentionDisplayName = "@\(paramaterDisplayName)"
  819. parameter.mentionId = "@\(parameterId)"
  820. self.mentionsDict[key] = parameter
  821. }
  822. }
  823. self.editingMessage = message
  824. // For files without a caption we start with an empty text instead of "{file}"
  825. if message.message == "{file}", message.file() != nil {
  826. self.editText("")
  827. } else {
  828. self.editText(message.parsedMessage().string)
  829. }
  830. }
  831. }
  832. func didPressDelete(for message: NCChatMessage) {
  833. if message.sendingFailed || message.isOfflineMessage {
  834. self.removePermanentlyTemporaryMessage(temporaryMessage: message)
  835. return
  836. }
  837. if let deletingMessage = message.copy() as? NCChatMessage {
  838. deletingMessage.message = NSLocalizedString("Deleting message", comment: "")
  839. deletingMessage.isDeleting = true
  840. self.updateMessage(withMessageId: deletingMessage.messageId, updatedMessage: deletingMessage)
  841. }
  842. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  843. NCAPIController.sharedInstance().deleteChatMessage(inRoom: self.room.token, withMessageId: message.messageId, for: activeAccount) { messageDict, error, statusCode in
  844. if error == nil,
  845. let messageDict,
  846. let parent = messageDict["parent"] as? [AnyHashable: Any] {
  847. if statusCode == 202 {
  848. self.view.makeToast(NSLocalizedString("Message deleted successfully, but Matterbridge is configured and the message might already be distributed to other services", comment: ""), duration: 5, position: CSToastPositionCenter)
  849. } else if statusCode == 200 {
  850. NotificationPresenter.shared().present(text: NSLocalizedString("Message deleted successfully", comment: ""), dismissAfterDelay: 5.0, includedStyle: .success)
  851. }
  852. if let deleteMessage = NCChatMessage(dictionary: parent, andAccountId: activeAccount.accountId) {
  853. self.updateMessage(withMessageId: deleteMessage.messageId, updatedMessage: deleteMessage)
  854. }
  855. } else if error != nil {
  856. switch statusCode {
  857. case 400:
  858. NotificationPresenter.shared().present(text: NSLocalizedString("Message could not be deleted because it is too old", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  859. case 405:
  860. NotificationPresenter.shared().present(text: NSLocalizedString("Only normal chat messages can be deleted", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  861. default:
  862. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while deleting the message", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  863. }
  864. self.updateMessage(withMessageId: message.messageId, updatedMessage: message)
  865. }
  866. }
  867. }
  868. func didPressOpenInNextcloud(for message: NCChatMessage) {
  869. if let file = message.file(), let path = file.path, let link = file.link {
  870. NCUtils.openFileInNextcloudAppOrBrowser(path: path, withFileLink: link)
  871. }
  872. }
  873. // MARK: - Editing support
  874. public override func didCancelTextEditing(_ sender: Any) {
  875. super.didCancelTextEditing(sender)
  876. self.autoCompletionView.tableHeaderView = nil
  877. self.replyMessageView?.dismiss()
  878. self.mentionsDict.removeAll()
  879. self.editingMessage = nil
  880. self.restorePendingMessage()
  881. }
  882. public override func didCommitTextEditing(_ sender: Any) {
  883. super.didCommitTextEditing(sender)
  884. self.autoCompletionView.tableHeaderView = nil
  885. self.replyMessageView?.dismiss()
  886. self.mentionsDict.removeAll()
  887. self.editingMessage = nil
  888. self.restorePendingMessage()
  889. }
  890. // MARK: - UITextField delegate
  891. public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  892. if textField == self.emojiTextField, self.interactingMessage != nil {
  893. self.interactingMessage = nil
  894. textField.resignFirstResponder()
  895. }
  896. return true
  897. }
  898. public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  899. if textField == self.emojiTextField, string.isSingleEmoji, let interactingMessage = self.interactingMessage {
  900. self.addReaction(reaction: string, to: interactingMessage)
  901. textField.resignFirstResponder()
  902. }
  903. return true
  904. }
  905. // MARK: - UITextViewDelegate
  906. public override func textViewDidChange(_ textView: UITextView) {
  907. self.startTyping()
  908. }
  909. // MARK: - TypingIndicator support
  910. func sendStartedTypingMessage(to sessionId: String) {
  911. // Workaround: TypingPrivacy should be checked locally, not from the remote server, use serverCapabilities for now
  912. // TODO: Remove workaround for federated typing indicators.
  913. guard let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId)
  914. else { return }
  915. if serverCapabilities.typingPrivacy {
  916. return
  917. }
  918. if let signalingController = NCSettingsController.sharedInstance().externalSignalingController(forAccountId: self.room.accountId) {
  919. let mySessionId = signalingController.sessionId()
  920. let message = NCStartedTypingMessage(from: mySessionId, sendTo: sessionId, withPayload: [:], forRoomType: "")
  921. signalingController.sendCall(message)
  922. }
  923. }
  924. func sendStartedTypingMessageToAll() {
  925. // Workaround: TypingPrivacy should be checked locally, not from the remote server, use serverCapabilities for now
  926. // TODO: Remove workaround for federated typing indicators.
  927. guard let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: self.room.accountId),
  928. !serverCapabilities.typingPrivacy,
  929. let signalingController = NCSettingsController.sharedInstance().externalSignalingController(forAccountId: self.room.accountId)
  930. else { return }
  931. let participantMap = signalingController.getParticipantMap()
  932. let mySessionId = signalingController.sessionId()
  933. for (key, _) in participantMap {
  934. if let sessionId = key as? String {
  935. let message = NCStartedTypingMessage(from: mySessionId, sendTo: sessionId, withPayload: [:], forRoomType: "")
  936. signalingController.sendCall(message)
  937. }
  938. }
  939. }
  940. func sendStoppedTypingMessageToAll() {
  941. guard let serverCapabilities = NCDatabaseManager.sharedInstance().roomTalkCapabilities(for: self.room),
  942. !serverCapabilities.typingPrivacy,
  943. let signalingController = NCSettingsController.sharedInstance().externalSignalingController(forAccountId: self.room.accountId)
  944. else { return }
  945. let participantMap = signalingController.getParticipantMap()
  946. let mySessionId = signalingController.sessionId()
  947. for (key, _) in participantMap {
  948. if let sessionId = key as? String {
  949. let message = NCStoppedTypingMessage(from: mySessionId, sendTo: sessionId, withPayload: [:], forRoomType: "")
  950. signalingController.sendCall(message)
  951. }
  952. }
  953. }
  954. func startTyping() {
  955. if !self.isTyping {
  956. self.isTyping = true
  957. self.sendStartedTypingMessageToAll()
  958. self.setTypingTimer()
  959. }
  960. self.setStopTypingTimer()
  961. }
  962. func stopTyping(force: Bool) {
  963. if self.isTyping || force {
  964. self.isTyping = false
  965. self.sendStoppedTypingMessageToAll()
  966. self.invalidateStopTypingTimer()
  967. self.invalidateTypingTimer()
  968. }
  969. }
  970. // TypingTimer is used to continously send "startedTyping" messages, while we are typing
  971. func setTypingTimer() {
  972. self.invalidateTypingTimer()
  973. self.typingTimer = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: false, block: { [weak self] _ in
  974. guard let self else { return }
  975. if self.isTyping {
  976. // We're still typing, send signaling message again to all participants
  977. self.sendStartedTypingMessageToAll()
  978. self.setTypingTimer()
  979. } else {
  980. // We stopped typing, we don't send anything to the participants, we just remove our timer
  981. self.invalidateTypingTimer()
  982. }
  983. })
  984. }
  985. func invalidateTypingTimer() {
  986. self.typingTimer?.invalidate()
  987. self.typingTimer = nil
  988. }
  989. // StopTypingTimer is used to detect when we stop typing (locally)
  990. func setStopTypingTimer() {
  991. self.invalidateStopTypingTimer()
  992. self.stopTypingTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: false, block: { [weak self] _ in
  993. guard let self else { return }
  994. if self.isTyping {
  995. self.isTyping = false
  996. self.invalidateStopTypingTimer()
  997. }
  998. })
  999. }
  1000. func invalidateStopTypingTimer() {
  1001. self.stopTypingTimer?.invalidate()
  1002. self.stopTypingTimer = nil
  1003. }
  1004. func addTypingIndicator(withUserIdentifier userIdentifier: String, andDisplayName displayName: String) {
  1005. DispatchQueue.main.async {
  1006. if let view = self.textInputbar.typingView as? TypingIndicatorView {
  1007. view.addTyping(userIdentifier: userIdentifier, displayName: displayName)
  1008. }
  1009. }
  1010. }
  1011. func removeTypingIndicator(withUserIdentifier userIdentifier: String) {
  1012. DispatchQueue.main.async {
  1013. if let view = self.textInputbar.typingView as? TypingIndicatorView {
  1014. view.removeTyping(userIdentifier: userIdentifier)
  1015. }
  1016. }
  1017. }
  1018. // MARK: - ShareConfirmationViewController delegate & helper
  1019. public func shareConfirmationViewControllerDidFailed(_ viewController: ShareConfirmationViewController) {
  1020. self.dismiss(animated: true) {
  1021. if viewController.forwardingMessage {
  1022. NotificationPresenter.shared().present(text: NSLocalizedString("Failed to forward message", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1023. }
  1024. }
  1025. }
  1026. public func shareConfirmationViewControllerDidFinish(_ viewController: ShareConfirmationViewController) {
  1027. self.dismiss(animated: true) {
  1028. if viewController.forwardingMessage {
  1029. var userInfo: [String: String] = [:]
  1030. userInfo["token"] = viewController.room.token
  1031. userInfo["accountId"] = viewController.account.accountId
  1032. NotificationCenter.default.post(name: .NCChatViewControllerForwardNotification, object: self, userInfo: userInfo)
  1033. }
  1034. }
  1035. }
  1036. internal func createShareConfirmationViewController() -> (shareConfirmationVC: ShareConfirmationViewController, navController: NCNavigationController) {
  1037. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1038. let serverCapabilities = NCDatabaseManager.sharedInstance().serverCapabilities(forAccountId: activeAccount.accountId)
  1039. let shareConfirmationVC = ShareConfirmationViewController(room: self.room, account: activeAccount, serverCapabilities: serverCapabilities!)!
  1040. shareConfirmationVC.delegate = self
  1041. shareConfirmationVC.isModal = true
  1042. let navigationController = NCNavigationController(rootViewController: shareConfirmationVC)
  1043. return (shareConfirmationVC, navigationController)
  1044. }
  1045. // MARK: - ShareViewController Delegate
  1046. public func shareViewControllerDidCancel(_ viewController: ShareViewController) {
  1047. self.dismiss(animated: true)
  1048. }
  1049. // MARK: - PHPhotoPicker Delegate
  1050. public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
  1051. if results.isEmpty {
  1052. picker.dismiss(animated: true)
  1053. return
  1054. }
  1055. let (shareConfirmationVC, navigationController) = self.createShareConfirmationViewController()
  1056. picker.dismiss(animated: true) {
  1057. self.present(navigationController, animated: true) {
  1058. for result in results {
  1059. result.itemProvider.loadItem(forTypeIdentifier: "public.image", options: nil) { item, error in
  1060. guard error == nil, let item = item as? URL else { return }
  1061. var fileName: String
  1062. if let suggestedFileName = result.itemProvider.suggestedName {
  1063. fileName = "\(suggestedFileName).jpg"
  1064. } else {
  1065. fileName = "IMG_\(String(Date().timeIntervalSince1970 * 1000)).jpg"
  1066. }
  1067. shareConfirmationVC.shareItemController.addItem(withURLAndName: item, withName: fileName)
  1068. }
  1069. result.itemProvider.loadItem(forTypeIdentifier: "public.movie", options: nil) { item, error in
  1070. guard error == nil, let item = item as? URL else { return }
  1071. var fileName: String
  1072. if let suggestedFileName = result.itemProvider.suggestedName {
  1073. fileName = "\(suggestedFileName).mov"
  1074. } else {
  1075. fileName = "VID_\(String(Date().timeIntervalSince1970 * 1000)).mov"
  1076. }
  1077. shareConfirmationVC.shareItemController.addItem(withURLAndName: item, withName: fileName)
  1078. }
  1079. }
  1080. }
  1081. }
  1082. }
  1083. // MARK: - UIImagePickerController delegate
  1084. public func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
  1085. self.saveImagePickerSettings(picker)
  1086. let (shareConfirmationVC, navigationController) = self.createShareConfirmationViewController()
  1087. guard let mediaType = info[.mediaType] as? String else { return }
  1088. if mediaType == "public.image" {
  1089. guard let image = info[.originalImage] as? UIImage else { return }
  1090. self.dismiss(animated: true) {
  1091. self.present(navigationController, animated: true) {
  1092. shareConfirmationVC.shareItemController.addItem(with: image)
  1093. }
  1094. }
  1095. } else if mediaType == "public.movie" {
  1096. guard let imageUrl = info[.mediaURL] as? URL else { return }
  1097. self.dismiss(animated: true) {
  1098. self.present(navigationController, animated: true) {
  1099. shareConfirmationVC.shareItemController.addItem(with: imageUrl)
  1100. }
  1101. }
  1102. }
  1103. }
  1104. public func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
  1105. self.saveImagePickerSettings(picker)
  1106. self.dismiss(animated: true)
  1107. }
  1108. public func saveImagePickerSettings(_ picker: UIImagePickerController) {
  1109. if picker.sourceType == .camera && picker.cameraCaptureMode == .photo {
  1110. NCUserDefaults.setPreferredCameraFlashMode(picker.cameraFlashMode.rawValue)
  1111. }
  1112. }
  1113. // MARK: - UIDocumentPickerViewController Delegate
  1114. public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
  1115. let (shareConfirmationVC, navigationController) = self.createShareConfirmationViewController()
  1116. self.present(navigationController, animated: true) {
  1117. for url in urls {
  1118. shareConfirmationVC.shareItemController.addItem(with: url)
  1119. }
  1120. }
  1121. }
  1122. // MARK: - ShareLocationViewController Delegate
  1123. public func shareLocationViewController(_ viewController: ShareLocationViewController, didSelectLocationWithLatitude latitude: Double, longitude: Double, andName name: String) {
  1124. let richObject = GeoLocationRichObject(latitude: latitude, longitude: longitude, name: name)
  1125. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1126. NCAPIController.sharedInstance().shareRichObject(richObject.richObjectDictionary(), inRoom: self.room.token, for: activeAccount) { error in
  1127. if let error {
  1128. print("Error sharing rich object: \(error)")
  1129. }
  1130. }
  1131. viewController.dismiss(animated: true)
  1132. }
  1133. // MARK: - CNContactPickerViewController Delegate
  1134. public func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
  1135. guard let vCardData = try? CNContactVCardSerialization.data(with: [contact]) else { return }
  1136. var vcString = String(data: vCardData, encoding: .utf8)
  1137. if let imageData = contact.imageData {
  1138. let base64Image = imageData.base64EncodedString()
  1139. let vcardImageString = "PHOTO;TYPE=JPEG;ENCODING=BASE64:\(base64Image)\n"
  1140. vcString = vcString?.replacingOccurrences(of: "END:VCARD", with: vcardImageString + "END:VCARD")
  1141. }
  1142. let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  1143. let folderPath = paths[0]
  1144. let filePath = (folderPath as NSString).appendingPathComponent("contact.vcf")
  1145. do {
  1146. try vcString?.write(toFile: filePath, atomically: true, encoding: .utf8)
  1147. let url = URL(fileURLWithPath: filePath)
  1148. let contactFileName = "\(contact.identifier).vcf"
  1149. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1150. NCAPIController.sharedInstance().uniqueNameForFileUpload(withName: contactFileName, originalName: true, for: activeAccount) { fileServerURL, fileServerPath, _, _ in
  1151. if let fileServerURL, let fileServerPath {
  1152. self.uploadFileAtPath(localPath: url.path, withFileServerURL: fileServerURL, andFileServerPath: fileServerPath, withMetaData: nil)
  1153. } else {
  1154. print("Could not find unique name for contact file")
  1155. }
  1156. }
  1157. } catch {
  1158. print("Could not write contact file")
  1159. }
  1160. }
  1161. // MARK: - Voice messages recording
  1162. func showVoiceMessageRecordHint() {
  1163. let toastPosition = CGPoint(x: self.textInputbar.center.x, y: self.textInputbar.center.y - self.textInputbar.frame.size.height)
  1164. self.view.makeToast(NSLocalizedString("Tap and hold to record a voice message, release the button to send it.", comment: ""), duration: 3, position: toastPosition)
  1165. }
  1166. func showVoiceMessageRecordingView() {
  1167. self.voiceMessageRecordingView = VoiceMessageRecordingView()
  1168. guard let voiceMessageRecordingView = self.voiceMessageRecordingView else { return }
  1169. voiceMessageRecordingView.translatesAutoresizingMaskIntoConstraints = false
  1170. self.textInputbar.addSubview(voiceMessageRecordingView)
  1171. self.textInputbar.bringSubviewToFront(voiceMessageRecordingView)
  1172. let views = [
  1173. "voiceMessageRecordingView": voiceMessageRecordingView
  1174. ]
  1175. let metrics = [
  1176. "buttonWidth": self.rightButton.frame.size.width
  1177. ]
  1178. self.textInputbar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[voiceMessageRecordingView]|", metrics: metrics, views: views))
  1179. self.textInputbar.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[voiceMessageRecordingView(>=0)]-(buttonWidth)-|", metrics: metrics, views: views))
  1180. }
  1181. func hideVoiceMessageRecordingView() {
  1182. self.voiceMessageRecordingView?.isHidden = true
  1183. }
  1184. func setupAudioRecorder() {
  1185. guard let userDocumentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last,
  1186. let outputFileURL = NSURL.fileURL(withPathComponents: [userDocumentDirectory, "voice-message-recording.m4a"])
  1187. else { return }
  1188. let session = AVAudioSession.sharedInstance()
  1189. try? session.setCategory(.playAndRecord)
  1190. let settings = [
  1191. AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
  1192. AVSampleRateKey: 44100,
  1193. AVNumberOfChannelsKey: 2
  1194. ]
  1195. self.recorder = try? AVAudioRecorder(url: outputFileURL, settings: settings)
  1196. self.recorder?.delegate = self
  1197. self.recorder?.isMeteringEnabled = true
  1198. self.recorder?.prepareToRecord()
  1199. }
  1200. func checkPermissionAndRecordVoiceMessage() {
  1201. let mediaType = AVMediaType.audio
  1202. let authStatus = AVCaptureDevice.authorizationStatus(for: mediaType)
  1203. if authStatus == AVAuthorizationStatus.authorized {
  1204. self.startRecordingVoiceMessage()
  1205. return
  1206. } else if authStatus == AVAuthorizationStatus.notDetermined {
  1207. AVCaptureDevice.requestAccess(for: mediaType, completionHandler: { granted in
  1208. NSLog("Microphone permission granted: %@", granted ? "YES" : "NO")
  1209. })
  1210. return
  1211. }
  1212. let alert = UIAlertController(title: NSLocalizedString("Could not access microphone", comment: ""),
  1213. message: NSLocalizedString("Microphone access is not allowed. Check your settings.", comment: ""),
  1214. preferredStyle: .alert)
  1215. alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
  1216. NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
  1217. }
  1218. func startRecordingVoiceMessage() {
  1219. self.setupAudioRecorder()
  1220. self.showVoiceMessageRecordingView()
  1221. if let recorder = self.recorder, !recorder.isRecording {
  1222. let session = AVAudioSession.sharedInstance()
  1223. try? session.setActive(true)
  1224. recorder.record()
  1225. }
  1226. }
  1227. func stopRecordingVoiceMessage() {
  1228. self.hideVoiceMessageRecordingView()
  1229. if let recorder = self.recorder, recorder.isRecording {
  1230. recorder.stop()
  1231. let session = AVAudioSession.sharedInstance()
  1232. try? session.setActive(false)
  1233. }
  1234. }
  1235. func shareVoiceMessage() {
  1236. let dateFormatter = DateFormatter()
  1237. dateFormatter.dateFormat = "yyyy-MM-dd HH-mm-ss"
  1238. let dateString = dateFormatter.string(from: Date())
  1239. // Replace chars that are not allowed on the filesystem
  1240. let notAllowedCharSet = CharacterSet(charactersIn: "\\/:%")
  1241. var roomString = self.room.displayName.components(separatedBy: notAllowedCharSet).joined(separator: " ")
  1242. // Replace multiple spaces with 1
  1243. if let regex = try? NSRegularExpression(pattern: " +") {
  1244. roomString = regex.stringByReplacingMatches(in: roomString, range: .init(location: 0, length: roomString.count), withTemplate: " ")
  1245. }
  1246. var audioFileName = "Talk recording from \(dateString) (\(roomString))"
  1247. // Trim the file name if too long
  1248. if audioFileName.count > 146 {
  1249. audioFileName = String(audioFileName.prefix(146))
  1250. }
  1251. audioFileName += ".mp3"
  1252. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1253. NCAPIController.sharedInstance().uniqueNameForFileUpload(withName: audioFileName, originalName: true, for: activeAccount, withCompletionBlock: { fileServerURL, fileServerPath, _, _ in
  1254. if let fileServerURL, let fileServerPath, let recorder = self.recorder {
  1255. let talkMetaData: [String: String] = ["messageType": "voice-message"]
  1256. self.uploadFileAtPath(localPath: recorder.url.path, withFileServerURL: fileServerURL, andFileServerPath: fileServerPath, withMetaData: talkMetaData)
  1257. } else {
  1258. NSLog("Could not find unique name for voice message file.")
  1259. }
  1260. })
  1261. }
  1262. func uploadFileAtPath(localPath: String, withFileServerURL fileServerURL: String, andFileServerPath fileServerPath: String, withMetaData talkMetaData: [String: String]?) {
  1263. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1264. NCAPIController.sharedInstance().setupNCCommunication(for: activeAccount)
  1265. NextcloudKit.shared.upload(serverUrlFileName: fileServerURL, fileNameLocalPath: localPath, taskHandler: { _ in
  1266. NSLog("Upload task")
  1267. }, progressHandler: { progress in
  1268. NSLog("Progress:%f", progress.fractionCompleted)
  1269. }, completionHandler: { _, _, _, _, _, _, _, error in
  1270. NSLog("Upload completed with error code: %ld", error.errorCode)
  1271. if error.errorCode == 0 {
  1272. NCAPIController.sharedInstance().shareFileOrFolder(for: activeAccount, atPath: fileServerPath, toRoom: self.room.token, talkMetaData: talkMetaData, withCompletionBlock: { error in
  1273. if error != nil {
  1274. NSLog("Failed to share voice message")
  1275. }
  1276. })
  1277. } else if error.errorCode == 404 || error.errorCode == 409 {
  1278. NCAPIController.sharedInstance().checkOrCreateAttachmentFolder(for: activeAccount, withCompletionBlock: { created, _ in
  1279. if created {
  1280. self.uploadFileAtPath(localPath: localPath, withFileServerURL: fileServerURL, andFileServerPath: fileServerPath, withMetaData: talkMetaData)
  1281. } else {
  1282. NSLog("Failed to check or create attachment folder")
  1283. }
  1284. })
  1285. } else {
  1286. NSLog("Failed upload voice message")
  1287. }
  1288. })
  1289. }
  1290. // MARK: - AVAudioRecorder Delegate
  1291. public func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
  1292. if flag, recorder == self.recorder, !self.recordCancelled {
  1293. self.shareVoiceMessage()
  1294. }
  1295. }
  1296. // MARK: - Voice Messages Transcribe
  1297. func transcribeVoiceMessage(with fileStatus: NCChatFileStatus) {
  1298. guard let fileLocalPath = fileStatus.fileLocalPath else { return }
  1299. DispatchQueue.main.async {
  1300. let audioFileURL = URL(fileURLWithPath: fileLocalPath)
  1301. let viewController = VoiceMessageTranscribeViewController(audiofileUrl: audioFileURL)
  1302. let navController = NCNavigationController(rootViewController: viewController)
  1303. self.present(navController, animated: true)
  1304. }
  1305. }
  1306. // MARK: - Voice Message Player
  1307. func setupVoiceMessagePlayer(with fileStatus: NCChatFileStatus) {
  1308. guard let fileLocalPath = fileStatus.fileLocalPath,
  1309. let data = try? Data(contentsOf: URL(fileURLWithPath: fileLocalPath)),
  1310. let player = try? AVAudioPlayer(data: data)
  1311. else { return }
  1312. self.voiceMessagesPlayer = player
  1313. self.playerAudioFileStatus = fileStatus
  1314. player.delegate = self
  1315. self.playVoiceMessagePlayer()
  1316. }
  1317. func playVoiceMessagePlayer() {
  1318. self.setSpeakerAudioSession()
  1319. self.enableProximitySensor()
  1320. self.startVoiceMessagePlayerTimer()
  1321. self.voiceMessagesPlayer?.play()
  1322. }
  1323. func pauseVoiceMessagePlayer() {
  1324. self.disableProximitySensor()
  1325. self.stopVoiceMessagePlayerTimer()
  1326. self.voiceMessagesPlayer?.pause()
  1327. self.checkVisibleCellAudioPlayers()
  1328. }
  1329. func stopVoiceMessagePlayer() {
  1330. self.disableProximitySensor()
  1331. self.stopVoiceMessagePlayerTimer()
  1332. self.voiceMessagesPlayer?.stop()
  1333. }
  1334. func enableProximitySensor() {
  1335. NotificationCenter.default.addObserver(self, selector: #selector(sensorStateChange(notification:)), name: UIDevice.proximityStateDidChangeNotification, object: nil)
  1336. UIDevice.current.isProximityMonitoringEnabled = true
  1337. }
  1338. func disableProximitySensor() {
  1339. if UIDevice.current.proximityState == false {
  1340. // Only disable monitoring if proximity sensor state is not active.
  1341. // If not proximity sensor state is cached as active and next time we enable monitoring
  1342. // sensorStateChange won't be trigger until proximity sensor state changes to inactive.
  1343. NotificationCenter.default.removeObserver(self, name: UIDevice.proximityStateDidChangeNotification, object: nil)
  1344. UIDevice.current.isProximityMonitoringEnabled = false
  1345. }
  1346. }
  1347. func setSpeakerAudioSession() {
  1348. let session = AVAudioSession.sharedInstance()
  1349. try? session.setCategory(AVAudioSession.Category.playback)
  1350. try? session.setActive(true)
  1351. }
  1352. func setVoiceChatAudioSession() {
  1353. let session = AVAudioSession.sharedInstance()
  1354. try? session.setCategory(AVAudioSession.Category.playAndRecord, mode: AVAudioSession.Mode.voiceChat)
  1355. try? session.setActive(true)
  1356. }
  1357. func sensorStateChange(notification: Notification) {
  1358. if UIDevice.current.proximityState {
  1359. self.setVoiceChatAudioSession()
  1360. } else {
  1361. self.pauseVoiceMessagePlayer()
  1362. self.setSpeakerAudioSession()
  1363. self.disableProximitySensor()
  1364. }
  1365. }
  1366. func checkVisibleCellAudioPlayers() {
  1367. guard let tableView = self.tableView,
  1368. let indexPaths = tableView.indexPathsForVisibleRows,
  1369. let playerAudioFileStatus = self.playerAudioFileStatus,
  1370. let voiceMessagesPlayer = self.voiceMessagesPlayer
  1371. else { return }
  1372. for indexPath in indexPaths {
  1373. let sectionDate = self.dateSections[indexPath.section]
  1374. if let messages = self.messages[sectionDate] {
  1375. let message = messages[indexPath.row]
  1376. if message.isVoiceMessage {
  1377. guard let cell = tableView.cellForRow(at: indexPath) as? BaseChatTableViewCell,
  1378. let file = message.file()
  1379. else { continue }
  1380. if file.parameterId == playerAudioFileStatus.fileId, file.path == playerAudioFileStatus.filePath {
  1381. cell.audioPlayerView?.setPlayerProgress(voiceMessagesPlayer.currentTime, isPlaying: voiceMessagesPlayer.isPlaying, maximumValue: voiceMessagesPlayer.duration)
  1382. continue
  1383. }
  1384. cell.audioPlayerView?.resetPlayer()
  1385. }
  1386. }
  1387. }
  1388. }
  1389. func startVoiceMessagePlayerTimer() {
  1390. self.stopVoiceMessagePlayerTimer()
  1391. self.playerProgressTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: #selector(checkVisibleCellAudioPlayers), userInfo: nil, repeats: true)
  1392. }
  1393. func stopVoiceMessagePlayerTimer() {
  1394. self.playerProgressTimer?.invalidate()
  1395. self.playerProgressTimer = nil
  1396. }
  1397. // MARK: - AVAudioPlayer Delegate
  1398. public func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  1399. self.stopVoiceMessagePlayerTimer()
  1400. self.checkVisibleCellAudioPlayers()
  1401. self.disableProximitySensor()
  1402. }
  1403. // MARK: - Gesture recognizer
  1404. public override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
  1405. if gestureRecognizer == self.voiceMessageLongPressGesture {
  1406. return true
  1407. }
  1408. return super.gestureRecognizerShouldBegin(gestureRecognizer)
  1409. }
  1410. func handleLongPressInVoiceMessageRecordButton(gestureRecognizer: UILongPressGestureRecognizer) {
  1411. if self.rightButton.tag != sendButtonTagVoice {
  1412. return
  1413. }
  1414. let point = gestureRecognizer.location(in: self.view)
  1415. if gestureRecognizer.state == .began {
  1416. print("Start recording audio message")
  1417. // 'Pop' feedback (strong boom)
  1418. AudioServicesPlaySystemSound(1520)
  1419. self.checkPermissionAndRecordVoiceMessage()
  1420. self.shouldLockInterfaceOrientation(lock: true)
  1421. self.recordCancelled = false
  1422. self.longPressStartingPoint = point
  1423. self.cancelHintLabelInitialPositionX = voiceMessageRecordingView?.slideToCancelHintLabel?.frame.origin.x
  1424. } else if gestureRecognizer.state == .ended {
  1425. print("Stop recording audio message")
  1426. self.shouldLockInterfaceOrientation(lock: false)
  1427. if let recordingTime = self.recorder?.currentTime {
  1428. // Mark record as cancelled if audio message is no longer than one second
  1429. self.recordCancelled = recordingTime < 1
  1430. }
  1431. self.stopRecordingVoiceMessage()
  1432. } else if gestureRecognizer.state == .changed {
  1433. guard let longPressStartingPoint,
  1434. let cancelHintLabelInitialPositionX,
  1435. let voiceMessageRecordingView,
  1436. let slideToCancelHintLabel = voiceMessageRecordingView.slideToCancelHintLabel
  1437. else { return }
  1438. let slideX = longPressStartingPoint.x - point.x
  1439. // Only slide view to the left
  1440. if slideX > 0 {
  1441. let maxSlideX = 100.0
  1442. var labelFrame = slideToCancelHintLabel.frame
  1443. labelFrame = .init(x: cancelHintLabelInitialPositionX - slideX, y: labelFrame.origin.y, width: labelFrame.size.width, height: labelFrame.size.height)
  1444. slideToCancelHintLabel.frame = labelFrame
  1445. slideToCancelHintLabel.alpha = (maxSlideX - slideX) / 100
  1446. // Cancel recording if slided more than maxSlideX
  1447. if slideX > maxSlideX, !self.recordCancelled {
  1448. print("Cancel recording audio message")
  1449. // 'Cancelled' feedback (three sequential weak booms)
  1450. AudioServicesPlaySystemSound(1521)
  1451. self.recordCancelled = true
  1452. self.stopRecordingVoiceMessage()
  1453. }
  1454. }
  1455. } else if gestureRecognizer.state == .cancelled || gestureRecognizer.state == .failed {
  1456. print("Gesture cancelled or failed -> Cancel recording audio message")
  1457. self.shouldLockInterfaceOrientation(lock: false)
  1458. self.recordCancelled = false
  1459. self.stopRecordingVoiceMessage()
  1460. }
  1461. }
  1462. func shouldLockInterfaceOrientation(lock: Bool) {
  1463. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  1464. appDelegate.shouldLockInterfaceOrientation = lock
  1465. }
  1466. }
  1467. // MARK: - UIScrollViewDelegate methods
  1468. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  1469. super.scrollViewDidEndDecelerating(scrollView)
  1470. guard scrollView == self.tableView
  1471. else { return }
  1472. if self.firstUnreadMessage != nil {
  1473. self.checkUnreadMessagesVisibility()
  1474. }
  1475. self.updateToolbar(animated: true)
  1476. }
  1477. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  1478. super.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate)
  1479. guard scrollView == self.tableView
  1480. else { return }
  1481. if !decelerate, self.firstUnreadMessage != nil {
  1482. self.checkUnreadMessagesVisibility()
  1483. }
  1484. self.updateToolbar(animated: true)
  1485. }
  1486. public override func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
  1487. guard scrollView == self.tableView
  1488. else { return }
  1489. if self.firstUnreadMessage != nil {
  1490. self.checkUnreadMessagesVisibility()
  1491. }
  1492. self.updateToolbar(animated: true)
  1493. }
  1494. // MARK: - UITextViewDelegate methods
  1495. public override func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  1496. // Do not allow to type while recording
  1497. if let voiceMessageLongPressGesture,
  1498. voiceMessageLongPressGesture.state != .possible {
  1499. return false
  1500. }
  1501. return super.textView(textView, shouldChangeTextIn: range, replacementText: text)
  1502. }
  1503. // MARK: - Chat functions
  1504. func prependMessages(historyMessages: [NCChatMessage], addingBlockSeparator shouldAddBlockSeparator: Bool) -> IndexPath? {
  1505. var historyDict: [Date: [NCChatMessage]] = [:]
  1506. self.internalAppendMessages(messages: historyMessages, inDictionary: &historyDict)
  1507. var chatSection: Date?
  1508. var historyMessagesForSection: [NCChatMessage]?
  1509. // Sort history sections
  1510. let historySections = historyDict.keys.sorted()
  1511. // Add every section in history that can't be merged with current chat messages
  1512. for historySection in historySections {
  1513. historyMessagesForSection = historyDict[historySection]
  1514. chatSection = self.getKeyForDate(date: historySection, inDictionary: self.messages)
  1515. if chatSection == nil {
  1516. self.messages[historySection] = historyMessagesForSection
  1517. }
  1518. }
  1519. self.sortDateSections()
  1520. if shouldAddBlockSeparator {
  1521. // Chat block separator
  1522. let blockSeparatorMessage = NCChatMessage()
  1523. blockSeparatorMessage.messageId = kChatBlockSeparatorIdentifier
  1524. historyMessagesForSection?.append(blockSeparatorMessage)
  1525. }
  1526. if let lastSection = historySections.last,
  1527. let lastHistoryMessages = historyDict[lastSection] {
  1528. let lastHistoryMessageIP = IndexPath(row: lastHistoryMessages.count - 1, section: historySections.count - 1)
  1529. // Merge last section of history messages with first section in current chat
  1530. if let chatSection,
  1531. let chatMessages = self.messages[chatSection] {
  1532. if var historyMessagesForSection,
  1533. let lastHistoryMessage = historyMessagesForSection.last,
  1534. let firstChatMessage = chatMessages.first {
  1535. firstChatMessage.isGroupMessage = self.shouldGroupMessage(newMessage: firstChatMessage, withMessage: lastHistoryMessage)
  1536. historyMessagesForSection.append(contentsOf: chatMessages)
  1537. self.messages[chatSection] = historyMessagesForSection
  1538. }
  1539. }
  1540. return lastHistoryMessageIP
  1541. }
  1542. return nil
  1543. }
  1544. func insertMessages(messages: [NCChatMessage]) {
  1545. for newMessage in messages {
  1546. let newMessageDate = Date(timeIntervalSince1970: TimeInterval(newMessage.timestamp))
  1547. if let keyDate = self.getKeyForDate(date: newMessageDate, inDictionary: self.messages),
  1548. var messagesForDate = self.messages[keyDate] {
  1549. for messageIndex in messagesForDate.indices {
  1550. let currentMessage = messagesForDate[messageIndex]
  1551. if currentMessage.timestamp > newMessage.timestamp {
  1552. // Message inserted in between other messages
  1553. if messageIndex > 0 {
  1554. let previousMessage = messagesForDate[messageIndex - 1]
  1555. newMessage.isGroupMessage = self.shouldGroupMessage(newMessage: newMessage, withMessage: previousMessage)
  1556. }
  1557. currentMessage.isGroupMessage = self.shouldGroupMessage(newMessage: currentMessage, withMessage: newMessage)
  1558. messagesForDate.insert(newMessage, at: messageIndex)
  1559. break
  1560. } else if messageIndex == (messagesForDate.count - 1) {
  1561. // Message inserted at the end of a date section
  1562. newMessage.isGroupMessage = self.shouldGroupMessage(newMessage: newMessage, withMessage: currentMessage)
  1563. messagesForDate.append(newMessage)
  1564. break
  1565. }
  1566. }
  1567. self.messages[keyDate] = messagesForDate
  1568. } else {
  1569. // We don't have messages for that date in our dictionary right now, so add this message as the first one
  1570. self.messages[newMessageDate] = [newMessage]
  1571. }
  1572. }
  1573. self.sortDateSections()
  1574. }
  1575. func appendMessages(messages: [NCChatMessage]) {
  1576. // Because of the inout parameter, we can't call self.sortDateSections() inside the append function
  1577. // Therefore we wrap it in this append function
  1578. self.internalAppendMessages(messages: messages, inDictionary: &self.messages)
  1579. self.sortDateSections()
  1580. }
  1581. private func internalAppendMessages(messages: [NCChatMessage], inDictionary dictionary: inout [Date: [NCChatMessage]]) {
  1582. for newMessage in messages {
  1583. let newMessageDate = Date(timeIntervalSince1970: TimeInterval(newMessage.timestamp))
  1584. let keyDate = self.getKeyForDate(date: newMessageDate, inDictionary: dictionary)
  1585. if let keyDate, let messagesForDate = dictionary[keyDate] {
  1586. var messageUpdated = false
  1587. // Check if we can update the message instead of adding a new one
  1588. for messageIndex in messagesForDate.indices {
  1589. let currentMessage = messagesForDate[messageIndex]
  1590. if currentMessage.isSameMessage(newMessage) {
  1591. // The newly received message either already exists or its temporary counterpart exists -> update
  1592. // If the user type a command the newMessage.actorType will be "bots", then we should not group those messages
  1593. // even if the original message was grouped.
  1594. // Edited messages should not be grouped to make it clear, that the message was edited
  1595. newMessage.isGroupMessage = currentMessage.isGroupMessage && newMessage.actorType != "bots" && newMessage.lastEditTimestamp == 0
  1596. dictionary[keyDate]?[messageIndex] = newMessage
  1597. messageUpdated = true
  1598. break
  1599. }
  1600. }
  1601. if !messageUpdated, let lastMessage = messagesForDate.last {
  1602. newMessage.isGroupMessage = self.shouldGroupMessage(newMessage: newMessage, withMessage: lastMessage)
  1603. dictionary[keyDate]?.append(newMessage)
  1604. }
  1605. } else {
  1606. // Section not found, create new section and add message
  1607. dictionary[newMessageDate] = [newMessage]
  1608. }
  1609. }
  1610. }
  1611. func removeMessage(at indexPath: IndexPath) {
  1612. guard indexPath.section < self.dateSections.count else { return }
  1613. let sectionKey = self.dateSections[indexPath.section]
  1614. if var messages = self.messages[sectionKey], indexPath.row < messages.count {
  1615. if messages.count == 1 {
  1616. // Remove section
  1617. self.messages.removeValue(forKey: sectionKey)
  1618. self.sortDateSections()
  1619. self.tableView?.beginUpdates()
  1620. self.tableView?.deleteSections([indexPath.section], with: .none)
  1621. self.tableView?.endUpdates()
  1622. } else {
  1623. // Remove message
  1624. let isLastMessage = indexPath.row == (messages.count - 1)
  1625. messages.remove(at: indexPath.row)
  1626. self.messages[sectionKey] = messages
  1627. self.tableView?.beginUpdates()
  1628. self.tableView?.deleteRows(at: [indexPath], with: .none)
  1629. self.tableView?.endUpdates()
  1630. if !isLastMessage {
  1631. // Update the message next to removed message
  1632. let nextMessage = messages[indexPath.row]
  1633. nextMessage.isGroupMessage = false
  1634. if indexPath.row > 0 {
  1635. let previousMessage = messages[indexPath.row - 1]
  1636. nextMessage.isGroupMessage = self.shouldGroupMessage(newMessage: nextMessage, withMessage: previousMessage)
  1637. }
  1638. self.tableView?.beginUpdates()
  1639. self.tableView?.reloadRows(at: [indexPath], with: .none)
  1640. self.tableView?.endUpdates()
  1641. }
  1642. }
  1643. }
  1644. }
  1645. func sortDateSections() {
  1646. self.dateSections = self.messages.keys.sorted()
  1647. }
  1648. // MARK: - Message grouping
  1649. func shouldGroupMessage(newMessage: NCChatMessage, withMessage lastMessage: NCChatMessage) -> Bool {
  1650. let sameActor = newMessage.actorId == lastMessage.actorId
  1651. let sameType = newMessage.isSystemMessage == lastMessage.isSystemMessage
  1652. let timeDiff = (newMessage.timestamp - lastMessage.timestamp) < kChatMessageGroupTimeDifference
  1653. let notEdited = newMessage.lastEditTimestamp == 0
  1654. // Try to collapse system messages if the new message is not already collapsing some messages
  1655. // Disable swiftlint -> not supported on Realm object
  1656. // swiftlint:disable:next empty_count
  1657. if newMessage.isSystemMessage, lastMessage.isSystemMessage, newMessage.collapsedMessages.count == 0 {
  1658. self.tryToGroupSystemMessage(newMessage: newMessage, withMessage: lastMessage)
  1659. }
  1660. return sameActor && sameType && timeDiff && notEdited
  1661. }
  1662. func tryToGroupSystemMessage(newMessage: NCChatMessage, withMessage lastMessage: NCChatMessage) {
  1663. if newMessage.systemMessage == lastMessage.systemMessage {
  1664. if newMessage.actorId == lastMessage.actorId {
  1665. // Same action and actor
  1666. if ["user_added", "user_removed", "moderator_promoted", "moderator_demoted"].contains(newMessage.systemMessage) {
  1667. self.collapseSystemMessage(newMessage, withMessage: lastMessage, withAction: newMessage.systemMessage)
  1668. }
  1669. } else {
  1670. // Same action, different actor
  1671. if ["call_joined", "call_left"].contains(newMessage.systemMessage) {
  1672. self.collapseSystemMessage(newMessage, withMessage: lastMessage, withAction: newMessage.systemMessage)
  1673. }
  1674. }
  1675. } else if newMessage.actorId == lastMessage.actorId {
  1676. if lastMessage.systemMessage == "call_left", newMessage.systemMessage == "call_joined" {
  1677. self.collapseSystemMessage(newMessage, withMessage: lastMessage, withAction: "call_reconnected")
  1678. }
  1679. }
  1680. }
  1681. // swiftlint:disable:next cyclomatic_complexity
  1682. func collapseSystemMessage(_ newMessage: NCChatMessage, withMessage lastMessage: NCChatMessage, withAction action: String) {
  1683. var collapseByMessage = lastMessage
  1684. if let lastCollapsedByMessage = lastMessage.collapsedBy {
  1685. collapseByMessage = lastCollapsedByMessage
  1686. collapseByMessage.collapsedBy = nil
  1687. self.tryToGroupSystemMessage(newMessage: newMessage, withMessage: collapseByMessage)
  1688. return
  1689. }
  1690. newMessage.collapsedBy = collapseByMessage
  1691. newMessage.isCollapsed = true
  1692. collapseByMessage.collapsedMessages.add(newMessage.messageId as NSNumber)
  1693. collapseByMessage.isCollapsed = true
  1694. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1695. var isUser0Self = false
  1696. var isUser1Self = false
  1697. if let userDict = collapseByMessage.messageParameters["user"] as? [String: Any] {
  1698. isUser0Self = userDict["id"] as? String == activeAccount.userId && userDict["type"] as? String == "user"
  1699. }
  1700. if let userDict = newMessage.messageParameters["user"] as? [String: Any] {
  1701. isUser1Self = userDict["id"] as? String == activeAccount.userId && userDict["type"] as? String == "user"
  1702. }
  1703. let isActor0Self = collapseByMessage.actorId == activeAccount.userId && collapseByMessage.actorType == "users"
  1704. let isActor1Self = newMessage.actorId == activeAccount.userId && newMessage.actorType == "users"
  1705. let isActor0Admin = collapseByMessage.actorId == "cli" && collapseByMessage.actorType == "guests"
  1706. collapseByMessage.collapsedIncludesUserSelf = isUser0Self || isUser1Self
  1707. collapseByMessage.collapsedIncludesActorSelf = isActor0Self || isActor1Self
  1708. var collapsedMessageParameters: [String: Any] = [:]
  1709. if let actor0Dict = collapseByMessage.messageParameters["actor"],
  1710. let actor1Dict = newMessage.messageParameters["actor"] {
  1711. collapsedMessageParameters["actor0"] = isActor0Self ? actor1Dict : actor0Dict
  1712. collapsedMessageParameters["actor1"] = actor1Dict
  1713. }
  1714. if let user0Dict = collapseByMessage.messageParameters["user"],
  1715. let user1Dict = newMessage.messageParameters["user"] {
  1716. collapsedMessageParameters["user0"] = isUser0Self ? user1Dict : user0Dict
  1717. collapsedMessageParameters["user1"] = user1Dict
  1718. }
  1719. collapseByMessage.setCollapsedMessageParameters(collapsedMessageParameters)
  1720. if action == "user_added" {
  1721. if isActor0Self {
  1722. if collapseByMessage.collapsedMessages.count == 1 {
  1723. collapseByMessage.collapsedMessage = NSLocalizedString("You added {user0} and {user1}", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1724. } else {
  1725. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You added {user0} and %ld more participants", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1726. }
  1727. } else if isActor0Admin {
  1728. if collapseByMessage.collapsedMessages.count == 1 {
  1729. if collapseByMessage.collapsedIncludesUserSelf {
  1730. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator added you and {user0}", comment: "Please put {user0} placeholder in the correct position on the translated text but do not translate it")
  1731. } else {
  1732. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator added {user0} and {user1}", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them"))
  1733. }
  1734. } else {
  1735. if collapseByMessage.collapsedIncludesUserSelf {
  1736. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator added you and %ld more participants", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1737. } else {
  1738. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator added {user0} and %ld more participants", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1739. }
  1740. }
  1741. } else {
  1742. if collapseByMessage.collapsedMessages.count == 1 {
  1743. if collapseByMessage.collapsedIncludesUserSelf {
  1744. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} added you and {user0}", comment: "Please put {actor0} and {user0} placeholders in the correct position on the translated text but do not translate them")
  1745. } else {
  1746. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} added {user0} and {user1}", comment: "Please put {actor0}, {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1747. }
  1748. } else {
  1749. if collapseByMessage.collapsedIncludesUserSelf {
  1750. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} added you and %ld more participants", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1751. } else {
  1752. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} added {user0} and %ld more participants", comment: "Please put {actor0}, {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1753. }
  1754. }
  1755. }
  1756. } else if action == "user_removed" {
  1757. if isActor0Self {
  1758. if collapseByMessage.collapsedMessages.count == 1 {
  1759. collapseByMessage.collapsedMessage = NSLocalizedString("You removed {user0} and {user1}", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1760. } else {
  1761. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You removed {user0} and %ld more participants", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1762. }
  1763. } else if isActor0Admin {
  1764. if collapseByMessage.collapsedMessages.count == 1 {
  1765. if collapseByMessage.collapsedIncludesUserSelf {
  1766. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator removed you and {user0}", comment: "Please put {user0} placeholder in the correct position on the translated text but do not translate it")
  1767. } else {
  1768. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator removed {user0} and {user1}", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1769. }
  1770. } else {
  1771. if collapseByMessage.collapsedIncludesUserSelf {
  1772. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator removed you and %ld more participants", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1773. } else {
  1774. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator removed {user0} and %ld more participants", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1775. }
  1776. }
  1777. } else {
  1778. if collapseByMessage.collapsedMessages.count == 1 {
  1779. if collapseByMessage.collapsedIncludesUserSelf {
  1780. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} removed you and {user0}", comment: "Please put {actor0} and {user0} placeholders in the correct position on the translated text but do not translate them")
  1781. } else {
  1782. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} removed {user0} and {user1}", comment: "Please put {actor0}, {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1783. }
  1784. } else {
  1785. if collapseByMessage.collapsedIncludesUserSelf {
  1786. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} removed you and %ld more participants", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1787. } else {
  1788. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} removed {user0} and %ld more participants", comment: "Please put {actor0}, {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1789. }
  1790. }
  1791. }
  1792. } else if action == "moderator_promoted" {
  1793. if isActor0Self {
  1794. if collapseByMessage.collapsedMessages.count == 1 {
  1795. collapseByMessage.collapsedMessage = NSLocalizedString("You promoted {user0} and {user1} to moderators", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1796. } else {
  1797. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You promoted {user0} and %ld more participants to moderators", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1798. }
  1799. } else if isActor0Admin {
  1800. if collapseByMessage.collapsedMessages.count == 1 {
  1801. if collapseByMessage.collapsedIncludesUserSelf {
  1802. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator promoted you and {user0} to moderators", comment: "Please put {user0} placeholder in the correct position on the translated text but do not translate it")
  1803. } else {
  1804. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator promoted {user0} and {user1} to moderators", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1805. }
  1806. } else {
  1807. if collapseByMessage.collapsedIncludesUserSelf {
  1808. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator promoted you and %ld more participants to moderators", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1809. } else {
  1810. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator promoted {user0} and %ld more participants to moderators", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1811. }
  1812. }
  1813. } else {
  1814. if collapseByMessage.collapsedMessages.count == 1 {
  1815. if collapseByMessage.collapsedIncludesUserSelf {
  1816. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} promoted you and {user0} to moderators", comment: "Please put {actor0} and {user0} placeholders in the correct position on the translated text but do not translate them")
  1817. } else {
  1818. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} promoted {user0} and {user1} to moderators", comment: "Please put {actor0}, {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1819. }
  1820. } else {
  1821. if collapseByMessage.collapsedIncludesUserSelf {
  1822. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} promoted you and %ld more participants to moderators", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1823. } else {
  1824. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} promoted {user0} and %ld more participants to moderators", comment: "Please put {actor0}, {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1825. }
  1826. }
  1827. }
  1828. } else if action == "moderator_demoted" {
  1829. if isActor0Self {
  1830. if collapseByMessage.collapsedMessages.count == 1 {
  1831. collapseByMessage.collapsedMessage = NSLocalizedString("You demoted {user0} and {user1} from moderators", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1832. } else {
  1833. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You demoted {user0} and %ld more participants from moderators", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1834. }
  1835. } else if isActor0Admin {
  1836. if collapseByMessage.collapsedMessages.count == 1 {
  1837. if collapseByMessage.collapsedIncludesUserSelf {
  1838. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator demoted you and {user0} from moderators", comment: "Please put {user0} placeholder in the correct position on the translated text but do not translate it")
  1839. } else {
  1840. collapseByMessage.collapsedMessage = NSLocalizedString("An administrator demoted {user0} and {user1} from moderators", comment: "Please put {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1841. }
  1842. } else {
  1843. if collapseByMessage.collapsedIncludesUserSelf {
  1844. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator demoted you and %ld more participants from moderators", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1845. } else {
  1846. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("An administrator demoted {user0} and %ld more participants from moderators", comment: "Please put {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1847. }
  1848. }
  1849. } else {
  1850. if collapseByMessage.collapsedMessages.count == 1 {
  1851. if collapseByMessage.collapsedIncludesUserSelf {
  1852. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} demoted you and {user0} from moderators", comment: "Please put {actor0} and {user0} placeholders in the correct position on the translated text but do not translate them")
  1853. } else {
  1854. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} demoted {user0} and {user1} from moderators", comment: "Please put {actor0}, {user0} and {user1} placeholders in the correct position on the translated text but do not translate them")
  1855. }
  1856. } else {
  1857. if collapseByMessage.collapsedIncludesUserSelf {
  1858. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} demoted you and %ld more participants from moderators", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1859. } else {
  1860. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} demoted {user0} and %ld more participants from moderators", comment: "Please put {actor0}, {user0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1861. }
  1862. }
  1863. }
  1864. } else if action == "call_joined" {
  1865. if collapseByMessage.collapsedIncludesActorSelf {
  1866. if collapseByMessage.collapsedMessages.count == 1 {
  1867. collapseByMessage.collapsedMessage = NSLocalizedString("You and {actor0} joined the call", comment: "Please put {actor0} placeholder in the correct position on the translated text but do not translate it")
  1868. } else {
  1869. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You and %ld more participants joined the call", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1870. }
  1871. } else {
  1872. if collapseByMessage.collapsedMessages.count == 1 {
  1873. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} and {actor1} joined the call", comment: "Please put {actor0} and {actor1} placeholders in the correct position on the translated text but do not translate them")
  1874. } else {
  1875. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} and %ld more participants joined the call", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1876. }
  1877. }
  1878. } else if action == "call_left" {
  1879. if collapseByMessage.collapsedIncludesActorSelf {
  1880. if collapseByMessage.collapsedMessages.count == 1 {
  1881. collapseByMessage.collapsedMessage = NSLocalizedString("You and {actor0} left the call", comment: "Please put {actor0} placeholder in the correct position on the translated text but do not translate it")
  1882. } else {
  1883. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("You and %ld more participants left the call", comment: "Please put %ld placeholder in the correct position on the translated text but do not translate it"), collapseByMessage.collapsedMessages.count)
  1884. }
  1885. } else {
  1886. if collapseByMessage.collapsedMessages.count == 1 {
  1887. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} and {actor1} left the call", comment: "Please put {actor0} and {actor1} placeholders in the correct position on the translated text but do not translate them")
  1888. } else {
  1889. collapseByMessage.collapsedMessage = String(format: NSLocalizedString("{actor0} and %ld more participants left the call", comment: "Please put {actor0} and %ld placeholders in the correct position on the translated text but do not translate them"), collapseByMessage.collapsedMessages.count)
  1890. }
  1891. }
  1892. } else if action == "call_reconnected" {
  1893. if collapseByMessage.collapsedIncludesActorSelf {
  1894. collapseByMessage.collapsedMessage = NSLocalizedString("You reconnected to the call", comment: "")
  1895. } else {
  1896. collapseByMessage.collapsedMessage = NSLocalizedString("{actor0} reconnected to the call", comment: "Please put {actor0} placeholder in the correct position on the translated text but do not translate it")
  1897. }
  1898. }
  1899. }
  1900. // MARK: - Reactions
  1901. func addReaction(reaction: String, to message: NCChatMessage) {
  1902. if message.reactionsArray().contains(where: {$0.reaction == reaction && $0.userReacted }) {
  1903. // We can't add reaction twice
  1904. return
  1905. }
  1906. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1907. self.setTemporaryReaction(reaction: reaction, withState: .adding, toMessage: message)
  1908. NCDatabaseManager.sharedInstance().increaseEmojiUsage(forEmoji: reaction, forAccount: activeAccount.accountId)
  1909. NCAPIController.sharedInstance().addReaction(reaction, toMessage: message.messageId, inRoom: self.room.token, for: activeAccount) { _, error, _ in
  1910. if error != nil {
  1911. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while adding a reaction to a message", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1912. self.removeTemporaryReaction(reaction: reaction, forMessageId: message.messageId)
  1913. }
  1914. }
  1915. }
  1916. func removeReaction(reaction: String, from message: NCChatMessage) {
  1917. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1918. self.setTemporaryReaction(reaction: reaction, withState: .removing, toMessage: message)
  1919. NCAPIController.sharedInstance().removeReaction(reaction, fromMessage: message.messageId, inRoom: self.room.token, for: activeAccount) { _, error, _ in
  1920. if error != nil {
  1921. NotificationPresenter.shared().present(text: NSLocalizedString("An error occurred while removing a reaction from a message", comment: ""), dismissAfterDelay: 5.0, includedStyle: .error)
  1922. self.removeTemporaryReaction(reaction: reaction, forMessageId: message.messageId)
  1923. }
  1924. }
  1925. }
  1926. func addOrRemoveReaction(reaction: NCChatReaction, in message: NCChatMessage) {
  1927. if message.isReactionBeingModified(reaction.reaction) {
  1928. return
  1929. }
  1930. if reaction.userReacted {
  1931. self.removeReaction(reaction: reaction.reaction, from: message)
  1932. } else {
  1933. self.addReaction(reaction: reaction.reaction, to: message)
  1934. }
  1935. }
  1936. func removeTemporaryReaction(reaction: String, forMessageId messageId: Int) {
  1937. DispatchQueue.main.async {
  1938. guard let (indexPath, message) = self.indexPathAndMessage(forMessageId: messageId) else { return }
  1939. message.removeReactionTemporarily(reaction)
  1940. self.tableView?.beginUpdates()
  1941. self.tableView?.reloadRows(at: [indexPath], with: .none)
  1942. self.tableView?.endUpdates()
  1943. }
  1944. }
  1945. func setTemporaryReaction(reaction: String, withState state: NCChatReactionState, toMessage message: NCChatMessage) {
  1946. DispatchQueue.main.async {
  1947. let isAtBottom = self.shouldScrollOnNewMessages()
  1948. guard let (indexPath, message) = self.indexPathAndMessage(forMessageId: message.messageId) else { return }
  1949. if state == .adding {
  1950. message.addTemporaryReaction(reaction)
  1951. } else if state == .removing {
  1952. message.removeReactionTemporarily(reaction)
  1953. }
  1954. self.tableView?.performBatchUpdates({
  1955. self.tableView?.reloadRows(at: [indexPath], with: .none)
  1956. }, completion: { _ in
  1957. if !isAtBottom {
  1958. return
  1959. }
  1960. if let (indexPath, _) = self.getLastNonUpdateMessage() {
  1961. self.tableView?.scrollToRow(at: indexPath, at: .bottom, animated: true)
  1962. }
  1963. })
  1964. }
  1965. }
  1966. func showReactionsSummary(of message: NCChatMessage) {
  1967. // Actuate `Peek` feedback (weak boom)
  1968. AudioServicesPlaySystemSound(1519)
  1969. let reactionsVC = ReactionsSummaryView(style: .insetGrouped)
  1970. reactionsVC.room = self.room
  1971. self.presentWithNavigation(reactionsVC, animated: true)
  1972. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  1973. NCAPIController.sharedInstance().getReactions(nil, fromMessage: message.messageId, inRoom: self.room.token, for: activeAccount) { reactionsDict, error, _ in
  1974. if error == nil,
  1975. let reactions = reactionsDict as? [String: [[String: AnyObject]]] {
  1976. reactionsVC.updateReactions(reactions: reactions)
  1977. }
  1978. }
  1979. }
  1980. // MARK: - UITableViewDataSource methods
  1981. public override func numberOfSections(in tableView: UITableView) -> Int {
  1982. if tableView != self.tableView {
  1983. return super.numberOfSections(in: tableView)
  1984. }
  1985. // TODO: There should be a better place to do this
  1986. if tableView == self.tableView, !self.dateSections.isEmpty {
  1987. tableView.backgroundView = nil
  1988. } else {
  1989. tableView.backgroundView = self.chatBackgroundView
  1990. }
  1991. return self.dateSections.count
  1992. }
  1993. public override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  1994. if tableView != self.tableView {
  1995. return super.tableView(tableView, numberOfRowsInSection: section)
  1996. }
  1997. let dateKey = self.dateSections[section]
  1998. return self.messages[dateKey]?.count ?? 0
  1999. }
  2000. public override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  2001. if tableView != self.tableView {
  2002. return super.tableView(tableView, titleForHeaderInSection: section)
  2003. }
  2004. let date = self.dateSections[section]
  2005. return self.getHeaderString(fromDate: date)
  2006. }
  2007. public override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
  2008. if tableView != self.tableView {
  2009. return super.tableView(tableView, heightForHeaderInSection: section)
  2010. }
  2011. let date = self.dateSections[section]
  2012. if let messages = self.messages[date], !messages.containsVisibleMessages() {
  2013. return 0
  2014. }
  2015. return kDateHeaderViewHeight
  2016. }
  2017. public override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  2018. if tableView != self.tableView {
  2019. return super.tableView(tableView, viewForHeaderInSection: section)
  2020. }
  2021. let headerView = DateHeaderView()
  2022. headerView.dateLabel.text = self.tableView(tableView, titleForHeaderInSection: section)
  2023. headerView.dateLabel.layer.cornerRadius = 12
  2024. headerView.dateLabel.clipsToBounds = true
  2025. if let headerLabel = headerView.dateLabel as? DateLabelCustom {
  2026. headerLabel.tableView = tableView
  2027. }
  2028. return headerView
  2029. }
  2030. public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {
  2031. guard tableView == self.tableView else { return }
  2032. for indexPath in indexPaths {
  2033. guard let message = self.message(for: indexPath) else { continue }
  2034. DispatchQueue.global(qos: .userInitiated).async {
  2035. guard message.messageId != kUnreadMessagesSeparatorIdentifier,
  2036. message.messageId != kChatBlockSeparatorIdentifier
  2037. else { return }
  2038. if message.containsURL() {
  2039. message.getReferenceData()
  2040. }
  2041. }
  2042. }
  2043. }
  2044. public override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  2045. if tableView != self.autoCompletionView,
  2046. let message = self.message(for: indexPath) {
  2047. return self.getCell(for: message)
  2048. }
  2049. return super.tableView(tableView, cellForRowAt: indexPath)
  2050. }
  2051. // swiftlint:disable:next cyclomatic_complexity
  2052. func getCell(for message: NCChatMessage) -> UITableViewCell {
  2053. if message.messageId == kUnreadMessagesSeparatorIdentifier,
  2054. let cell = self.tableView?.dequeueReusableCell(withIdentifier: MessageSeparatorCellIdentifier) as? MessageSeparatorTableViewCell {
  2055. cell.messageId = message.messageId
  2056. cell.separatorLabel.text = NSLocalizedString("Unread messages", comment: "")
  2057. return cell
  2058. }
  2059. if message.messageId == kChatBlockSeparatorIdentifier,
  2060. let cell = self.tableView?.dequeueReusableCell(withIdentifier: MessageSeparatorCellIdentifier) as? MessageSeparatorTableViewCell {
  2061. cell.messageId = message.messageId
  2062. cell.separatorLabel.text = NSLocalizedString("Some messages not shown, will be downloaded when online", comment: "")
  2063. return cell
  2064. }
  2065. if message.isUpdateMessage,
  2066. let cell = self.tableView?.dequeueReusableCell(withIdentifier: InvisibleSystemMessageCellIdentifier) as? SystemMessageTableViewCell {
  2067. return cell
  2068. }
  2069. if message.isSystemMessage,
  2070. let cell = self.tableView?.dequeueReusableCell(withIdentifier: SystemMessageCellIdentifier) as? SystemMessageTableViewCell {
  2071. cell.delegate = self
  2072. cell.setup(for: message)
  2073. return cell
  2074. }
  2075. if message.isVoiceMessage {
  2076. let cellIdentifier = message.isGroupMessage ? voiceGroupedMessageCellIdentifier : voiceMessageCellIdentifier
  2077. if let cell = self.tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) as? BaseChatTableViewCell {
  2078. cell.delegate = self
  2079. cell.setup(for: message, withLastCommonReadMessage: self.room.lastCommonReadMessage)
  2080. if let playerAudioFileStatus = self.playerAudioFileStatus,
  2081. let voiceMessagesPlayer = self.voiceMessagesPlayer {
  2082. if message.file().parameterId == playerAudioFileStatus.fileId, message.file().path == playerAudioFileStatus.filePath {
  2083. cell.audioPlayerView?.setPlayerProgress(voiceMessagesPlayer.currentTime, isPlaying: voiceMessagesPlayer.isPlaying, maximumValue: voiceMessagesPlayer.duration)
  2084. } else {
  2085. cell.audioPlayerView?.resetPlayer()
  2086. }
  2087. } else {
  2088. cell.audioPlayerView?.resetPlayer()
  2089. }
  2090. return cell
  2091. }
  2092. }
  2093. if message.file() != nil {
  2094. let cellIdentifier = message.isGroupMessage ? fileGroupedMessageCellIdentifier : fileMessageCellIdentifier
  2095. if let cell = self.tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) as? BaseChatTableViewCell {
  2096. cell.delegate = self
  2097. cell.setup(for: message, withLastCommonReadMessage: self.room.lastCommonReadMessage)
  2098. return cell
  2099. }
  2100. }
  2101. if message.geoLocation() != nil {
  2102. let cellIdentifier = message.isGroupMessage ? locationGroupedMessageCellIdentifier : locationMessageCellIdentifier
  2103. if let cell = self.tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) as? BaseChatTableViewCell {
  2104. cell.delegate = self
  2105. cell.setup(for: message, withLastCommonReadMessage: self.room.lastCommonReadMessage)
  2106. return cell
  2107. }
  2108. }
  2109. if message.poll != nil {
  2110. let cellIdentifier = message.isGroupMessage ? pollGroupedMessageCellIdentifier : pollMessageCellIdentifier
  2111. if let cell = self.tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) as? BaseChatTableViewCell {
  2112. cell.delegate = self
  2113. cell.setup(for: message, withLastCommonReadMessage: self.room.lastCommonReadMessage)
  2114. return cell
  2115. }
  2116. }
  2117. var cellIdentifier = chatMessageCellIdentifier
  2118. if message.isGroupMessage {
  2119. cellIdentifier = chatGroupedMessageCellIdentifier
  2120. } else if message.parent != nil {
  2121. cellIdentifier = chatReplyMessageCellIdentifier
  2122. }
  2123. if let cell = self.tableView?.dequeueReusableCell(withIdentifier: cellIdentifier) as? BaseChatTableViewCell {
  2124. cell.delegate = self
  2125. cell.setup(for: message, withLastCommonReadMessage: self.room.lastCommonReadMessage)
  2126. return cell
  2127. }
  2128. return UITableViewCell()
  2129. }
  2130. public override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  2131. if tableView == self.autoCompletionView {
  2132. return super.tableView(tableView, heightForRowAt: indexPath)
  2133. }
  2134. if let message = self.message(for: indexPath) {
  2135. return self.getCellHeight(for: message)
  2136. }
  2137. return chatMessageCellMinimumHeight
  2138. }
  2139. func getCellHeight(for message: NCChatMessage) -> CGFloat {
  2140. guard let tableView = self.tableView else { return chatMessageCellMinimumHeight }
  2141. var width = tableView.frame.width - kChatCellAvatarHeight
  2142. width -= tableView.safeAreaInsets.left + tableView.safeAreaInsets.right
  2143. return self.getCellHeight(for: message, with: width)
  2144. }
  2145. lazy var textViewForSizing: UITextView = {
  2146. return MessageBodyTextView()
  2147. }()
  2148. // swiftlint:disable:next cyclomatic_complexity
  2149. func getCellHeight(for message: NCChatMessage, with originalWidth: CGFloat) -> CGFloat {
  2150. // Chat separators
  2151. if message.messageId == kUnreadMessagesSeparatorIdentifier ||
  2152. message.messageId == kChatBlockSeparatorIdentifier {
  2153. return kMessageSeparatorCellHeight
  2154. }
  2155. // Update messages (the ones that notify about an update in one message, they should not be displayed)
  2156. if message.message.isEmpty || message.isUpdateMessage || (message.isCollapsed && message.collapsedBy != nil) {
  2157. return 0.0
  2158. }
  2159. // Chat messages
  2160. let messageString = message.parsedMarkdownForChat() ?? NSMutableAttributedString()
  2161. var width = originalWidth
  2162. width -= message.isSystemMessage ? 80.0 : 30.0 // *right(10) + dateLabel(40) : 3*right(10)
  2163. self.textViewForSizing.attributedText = messageString
  2164. let bodyBounds = self.textViewForSizing.sizeThatFits(CGSize(width: width, height: CGFLOAT_MAX))
  2165. var height = ceil(bodyBounds.height)
  2166. if message.poll != nil {
  2167. height = PollMessageView().pollMessageBodyHeight(with: messageString.string, width: width)
  2168. }
  2169. if (message.isGroupMessage && message.parent == nil) || message.isSystemMessage {
  2170. height += 10 // 2*left(5)
  2171. if height < chatGroupedMessageCellMinimumHeight {
  2172. height = chatGroupedMessageCellMinimumHeight
  2173. }
  2174. } else {
  2175. height += kChatCellAvatarHeight
  2176. height += 20.0 // right(10) + 2*left(5)
  2177. if height < chatMessageCellMinimumHeight {
  2178. height = chatMessageCellMinimumHeight
  2179. }
  2180. }
  2181. if !message.reactionsArray().isEmpty {
  2182. height += 40 // reactionsView(40)
  2183. }
  2184. if message.containsURL() {
  2185. height += 105
  2186. }
  2187. if message.parent != nil {
  2188. height += 60 // quoteView(60)
  2189. }
  2190. // Voice message should be before message.file check since it contains a file
  2191. if message.isVoiceMessage {
  2192. height -= ceil(bodyBounds.height)
  2193. height += voiceMessageCellPlayerHeight
  2194. } else if let file = message.file() {
  2195. if file.previewImageHeight > 0 {
  2196. height += CGFloat(file.previewImageHeight)
  2197. } else if case let estimatedHeight = BaseChatTableViewCell.getEstimatedPreviewSize(for: message), estimatedHeight > 0 {
  2198. height += estimatedHeight
  2199. message.setPreviewImageHeight(estimatedHeight)
  2200. } else {
  2201. height += fileMessageCellFileMaxPreviewHeight
  2202. }
  2203. height += 10 // right(10)
  2204. // if the message is a media file, reduce the message height by the bodyTextView height to hide it since it usually just contains an autogenerated file name (e.g. IMG_1234.jpg)
  2205. if NCUtils.isImage(fileType: file.mimetype) || NCUtils.isVideo(fileType: file.mimetype) {
  2206. // Only hide the filename if there's a preview available and we didn't receive a file caption
  2207. if file.previewAvailable && message.message == "{file}" {
  2208. height -= ceil(bodyBounds.height)
  2209. }
  2210. }
  2211. }
  2212. if message.geoLocation() != nil {
  2213. height += locationMessageCellPreviewHeight + 10 // right(10)
  2214. }
  2215. return height
  2216. }
  2217. public override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  2218. if tableView == self.tableView {
  2219. self.emojiTextField.resignFirstResponder()
  2220. self.datePickerTextField.resignFirstResponder()
  2221. // Disable swiftlint -> not supported on a Realm object
  2222. // swiftlint:disable:next empty_count
  2223. if let message = self.message(for: indexPath), message.collapsedMessages.count > 0 {
  2224. self.cellWantsToCollapseMessages(with: message)
  2225. }
  2226. tableView.deselectRow(at: indexPath, animated: true)
  2227. } else {
  2228. super.tableView(tableView, didSelectRowAt: indexPath)
  2229. }
  2230. }
  2231. // MARK: - ContextMenu (Long press on message)
  2232. public override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
  2233. if tableView == self.autoCompletionView {
  2234. return nil
  2235. }
  2236. let cell = tableView.cellForRow(at: indexPath)
  2237. // Show reactionSummary for legacy cells
  2238. if let cell = cell as? ChatTableViewCell {
  2239. let pointInCell = tableView.convert(point, to: cell)
  2240. let reactionView = cell.contentView.subviews.first(where: { $0 is ReactionsView && $0.frame.contains(pointInCell) })
  2241. if reactionView != nil {
  2242. self.showReactionsSummary(of: cell.message)
  2243. return nil
  2244. }
  2245. }
  2246. if let cell = cell as? BaseChatTableViewCell {
  2247. let pointInCell = tableView.convert(point, to: cell)
  2248. let pointInReactionPart = cell.convert(pointInCell, to: cell.reactionPart)
  2249. let reactionView = cell.reactionPart.subviews.first(where: { $0 is ReactionsView && $0.frame.contains(pointInReactionPart) })
  2250. if reactionView != nil, let message = cell.message {
  2251. self.showReactionsSummary(of: message)
  2252. return nil
  2253. }
  2254. }
  2255. guard let message = self.message(for: indexPath) else { return nil }
  2256. if message.isSystemMessage || message.isDeletedMessage || message.messageId == kUnreadMessagesSeparatorIdentifier {
  2257. return nil
  2258. }
  2259. var actions: [UIMenuElement] = []
  2260. // Copy option
  2261. actions.append(UIAction(title: NSLocalizedString("Copy", comment: ""), image: .init(systemName: "square.on.square")) { _ in
  2262. self.didPressCopy(for: message)
  2263. })
  2264. // Copy Link
  2265. actions.append(UIAction(title: NSLocalizedString("Copy message link", comment: ""), image: .init(systemName: "link")) { _ in
  2266. self.didPressCopyLink(for: message)
  2267. })
  2268. let menu = UIMenu(children: actions)
  2269. let configuration = UIContextMenuConfiguration(identifier: indexPath as NSIndexPath) {
  2270. return nil
  2271. } actionProvider: { _ in
  2272. return menu
  2273. }
  2274. return configuration
  2275. }
  2276. public override func tableView(_ tableView: UITableView, willDisplayContextMenu configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  2277. animator?.addAnimations {
  2278. // Only set these, when the context menu is fully visible
  2279. self.contextMenuAccessoryView?.alpha = 1
  2280. self.contextMenuMessageView?.layer.cornerRadius = 10
  2281. self.contextMenuMessageView?.layer.mask = nil
  2282. }
  2283. }
  2284. public override func tableView(_ tableView: UITableView, willEndContextMenuInteraction configuration: UIContextMenuConfiguration, animator: UIContextMenuInteractionAnimating?) {
  2285. animator?.addCompletion {
  2286. // Wait until the context menu is completely hidden before we execute any method
  2287. if let contextMenuActionBlock = self.contextMenuActionBlock {
  2288. contextMenuActionBlock()
  2289. self.contextMenuActionBlock = nil
  2290. }
  2291. }
  2292. }
  2293. internal func getContextMenuAccessoryView(forMessage message: NCChatMessage, forIndexPath indexPath: IndexPath, withCellHeight cellHeight: CGFloat) -> UIView? {
  2294. // We don't provide a accessory view in the BaseChatViewController, but can add it in a subclass
  2295. return nil
  2296. }
  2297. public override func tableView(_ tableView: UITableView, previewForHighlightingContextMenuWithConfiguration configuration: UIContextMenuConfiguration) -> UITargetedPreview? {
  2298. guard let indexPath = configuration.identifier as? NSIndexPath,
  2299. let message = self.message(for: indexPath as IndexPath)
  2300. else { return nil }
  2301. let maxPreviewWidth = self.view.bounds.size.width - self.view.safeAreaInsets.left - self.view.safeAreaInsets.right
  2302. let maxPreviewHeight = self.view.bounds.size.height * 0.6
  2303. // TODO: Take padding into account
  2304. let maxTextWidth = maxPreviewWidth - kChatCellAvatarHeight
  2305. // We need to get the height of the original cell to center the preview correctly (as the preview is always non-grouped)
  2306. let heightOfOriginalCell = self.getCellHeight(for: message, with: maxTextWidth)
  2307. // Remember grouped-status -> Create a previewView which always is a non-grouped-message
  2308. let isGroupMessage = message.isGroupMessage
  2309. message.isGroupMessage = false
  2310. let previewTableViewCell = self.getCell(for: message)
  2311. var cellHeight = self.getCellHeight(for: message, with: maxTextWidth)
  2312. // Cut the height if bigger than max height
  2313. if cellHeight > maxPreviewHeight {
  2314. cellHeight = maxPreviewHeight
  2315. }
  2316. // Use the contentView of the UITableViewCell as a preview view
  2317. let previewMessageView = previewTableViewCell.contentView
  2318. previewMessageView.frame = CGRect(x: 0, y: 0, width: maxPreviewWidth, height: cellHeight)
  2319. previewMessageView.layer.masksToBounds = true
  2320. // Create a mask to not show the avatar part when showing a grouped messages while animating
  2321. // The mask will be reset in willDisplayContextMenuWithConfiguration so the avatar is visible when the context menu is shown
  2322. let maskLayer = CAShapeLayer()
  2323. let maskRect = CGRect(x: 0, y: previewMessageView.frame.size.height - heightOfOriginalCell, width: previewMessageView.frame.size.width, height: heightOfOriginalCell)
  2324. maskLayer.path = CGPath(rect: maskRect, transform: nil)
  2325. previewMessageView.layer.mask = maskLayer
  2326. previewMessageView.backgroundColor = .systemBackground
  2327. self.contextMenuMessageView = previewMessageView
  2328. // Restore grouped-status
  2329. message.isGroupMessage = isGroupMessage
  2330. var containerView: UIView
  2331. var cellCenter = CGPoint()
  2332. if let accessoryView = self.getContextMenuAccessoryView(forMessage: message, forIndexPath: indexPath as IndexPath, withCellHeight: cellHeight) {
  2333. self.contextMenuAccessoryView = accessoryView
  2334. // maxY = height + y
  2335. let totalAccessoryFrameHeight = accessoryView.frame.maxY - cellHeight
  2336. containerView = UIView(frame: .init(x: 0, y: 0, width: Int(maxPreviewWidth), height: Int(cellHeight + totalAccessoryFrameHeight)))
  2337. containerView.backgroundColor = .clear
  2338. containerView.addSubview(previewMessageView)
  2339. containerView.addSubview(accessoryView)
  2340. if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
  2341. // On large iPhones (with regular landscape size, like iPhone X) we need to take the safe area into account when calculating the center
  2342. let cellCenterX = cell.center.x + self.view.safeAreaInsets.left / 2 - self.view.safeAreaInsets.right / 2
  2343. let cellCenterY = cell.center.y + (totalAccessoryFrameHeight) / 2 - (cellHeight - heightOfOriginalCell) / 2
  2344. cellCenter = CGPoint(x: cellCenterX, y: cellCenterY)
  2345. }
  2346. } else {
  2347. containerView = UIView(frame: .init(x: 0, y: 0, width: maxPreviewWidth, height: cellHeight))
  2348. containerView.backgroundColor = .clear
  2349. containerView.addSubview(previewMessageView)
  2350. if let cell = tableView.cellForRow(at: indexPath as IndexPath) {
  2351. // On large iPhones (with regular landscape size, like iPhone X) we need to take the safe area into account when calculating the center
  2352. let cellCenterX = cell.center.x + self.view.safeAreaInsets.left / 2 - self.view.safeAreaInsets.right / 2
  2353. let cellCenterY = cell.center.y - (cellHeight - heightOfOriginalCell) / 2
  2354. cellCenter = CGPoint(x: cellCenterX, y: cellCenterY)
  2355. }
  2356. }
  2357. // Create a preview target which allows us to have a transparent background
  2358. let previewTarget = UIPreviewTarget(container: tableView, center: cellCenter)
  2359. let previewParameter = UIPreviewParameters()
  2360. // Remove the background and the drop shadow from our custom preview view
  2361. previewParameter.backgroundColor = .clear
  2362. previewParameter.shadowPath = UIBezierPath()
  2363. return UITargetedPreview(view: containerView, parameters: previewParameter, target: previewTarget)
  2364. }
  2365. // MARK: - Chat functions
  2366. public func showLoadingHistoryView() {
  2367. self.loadingHistoryView = UIActivityIndicatorView(frame: .init(x: 0, y: 0, width: 30, height: 30))
  2368. self.loadingHistoryView?.color = .darkGray
  2369. self.loadingHistoryView?.startAnimating()
  2370. self.tableView?.tableHeaderView = self.loadingHistoryView
  2371. }
  2372. func hideLoadingHistoryView() {
  2373. self.loadingHistoryView = nil
  2374. self.tableView?.tableHeaderView = nil
  2375. }
  2376. func shouldScrollOnNewMessages() -> Bool {
  2377. guard self.isVisible, let tableView = self.tableView else { return false }
  2378. // Scroll if table view is at the bottom (or 80px up)
  2379. let minimumOffset = (tableView.contentSize.height - tableView.frame.size.height) - 80
  2380. if tableView.contentOffset.y >= minimumOffset {
  2381. return true
  2382. }
  2383. return false
  2384. }
  2385. public func cleanChat() {
  2386. self.messages = [:]
  2387. self.dateSections = []
  2388. self.hideNewMessagesView()
  2389. self.tableView?.reloadData()
  2390. }
  2391. public func savePendingMessage() {
  2392. if self.textInputbar.isEditing {
  2393. // We don't want to save a message that we are editing
  2394. return
  2395. }
  2396. self.room.pendingMessage = self.textView.text
  2397. NCRoomsManager.sharedInstance().updatePendingMessage(self.room.pendingMessage, for: self.room)
  2398. }
  2399. public func clearPendingMessage() {
  2400. self.room.pendingMessage = ""
  2401. NCRoomsManager.sharedInstance().updatePendingMessage("", for: self.room)
  2402. }
  2403. private func getKeyForDate(date: Date, inDictionary dict: [Date: [NCChatMessage]]) -> Date? {
  2404. let currentCalendar = NSCalendar.current
  2405. return dict.first(where: { currentCalendar.isDate(date, inSameDayAs: $0.key) })?.key
  2406. }
  2407. internal func message(for indexPath: IndexPath) -> NCChatMessage? {
  2408. let sectionDate = self.dateSections[indexPath.section]
  2409. if let message = self.messages[sectionDate]?[indexPath.row] {
  2410. return message
  2411. }
  2412. return nil
  2413. }
  2414. internal func indexPath(for message: NCChatMessage) -> IndexPath? {
  2415. let messageDate = Date(timeIntervalSince1970: TimeInterval(message.timestamp))
  2416. guard let keyDate = self.getKeyForDate(date: messageDate, inDictionary: self.messages),
  2417. let dateSection = dateSections.firstIndex(of: keyDate),
  2418. let messages = messages[keyDate]
  2419. else { return nil }
  2420. for i in messages.indices {
  2421. let chatMessage = messages[i]
  2422. if chatMessage.isSameMessage(message) {
  2423. return IndexPath(row: i, section: dateSection)
  2424. }
  2425. }
  2426. return nil
  2427. }
  2428. /// Iterate through all messages starting with the first message and returns the first message that fulfills the predicate
  2429. private func indexPathAndMessageFromStart(with predicate: (NCChatMessage) -> Bool) -> (indexPath: IndexPath, message: NCChatMessage)? {
  2430. for sectionIndex in dateSections.indices {
  2431. let section = dateSections[sectionIndex]
  2432. guard let messages = messages[section] else { continue }
  2433. for messageIndex in messages.indices {
  2434. let message = messages[messageIndex]
  2435. if predicate(message) {
  2436. return (IndexPath(row: messageIndex, section: sectionIndex), message)
  2437. }
  2438. }
  2439. }
  2440. return nil
  2441. }
  2442. /// Iterate through all messages starting with the last message and returns the first message that fulfills the predicate
  2443. private func indexPathAndMessageFromEnd(with predicate: (NCChatMessage) -> Bool) -> (indexPath: IndexPath, message: NCChatMessage)? {
  2444. for sectionIndex in dateSections.indices.reversed() {
  2445. let section = dateSections[sectionIndex]
  2446. guard let messages = messages[section] else { continue }
  2447. for messageIndex in messages.indices.reversed() {
  2448. let message = messages[messageIndex]
  2449. if predicate(message) {
  2450. return (IndexPath(row: messageIndex, section: sectionIndex), message)
  2451. }
  2452. }
  2453. }
  2454. return nil
  2455. }
  2456. internal func indexPathAndMessage(forMessageId messageId: Int) -> (indexPath: IndexPath, message: NCChatMessage)? {
  2457. return self.indexPathAndMessageFromEnd(with: { $0.messageId == messageId })
  2458. }
  2459. internal func indexPathAndMessage(forReferenceId referenceId: String) -> (indexPath: IndexPath, message: NCChatMessage)? {
  2460. return self.indexPathAndMessageFromEnd(with: { $0.referenceId == referenceId })
  2461. }
  2462. internal func indexPathForUnreadMessageSeparator() -> IndexPath? {
  2463. return self.indexPathAndMessageFromEnd(with: { $0.messageId == kUnreadMessagesSeparatorIdentifier })?.indexPath
  2464. }
  2465. internal func getLastNonUpdateMessage() -> (indexPath: IndexPath, message: NCChatMessage)? {
  2466. return self.indexPathAndMessageFromEnd(with: { !$0.isUpdateMessage })
  2467. }
  2468. internal func getLastRealMessage() -> (indexPath: IndexPath, message: NCChatMessage)? {
  2469. // Ignore temporary messages
  2470. return self.indexPathAndMessageFromEnd(with: { $0.messageId > 0 })
  2471. }
  2472. internal func getFirstRealMessage() -> (indexPath: IndexPath, message: NCChatMessage)? {
  2473. // Ignore temporary messages
  2474. return self.indexPathAndMessageFromStart(with: { $0.messageId > 0 })
  2475. }
  2476. internal func indexPathForLastMessage() -> IndexPath? {
  2477. return self.indexPathAndMessageFromEnd(with: { _ in return true })?.indexPath
  2478. }
  2479. internal func removeUnreadMessagesSeparator() {
  2480. if let indexPath = self.indexPathForUnreadMessageSeparator() {
  2481. let separatorDate = self.dateSections[indexPath.section]
  2482. self.messages[separatorDate]?.remove(at: indexPath.row)
  2483. self.tableView?.deleteRows(at: [indexPath], with: .fade)
  2484. }
  2485. }
  2486. internal func checkUnreadMessagesVisibility() {
  2487. DispatchQueue.main.async {
  2488. if let firstUnreadMessage = self.firstUnreadMessage,
  2489. let indexPath = self.indexPath(for: firstUnreadMessage) {
  2490. if self.tableView?.indexPathsForVisibleRows?.contains(indexPath) ?? false {
  2491. self.hideNewMessagesView()
  2492. }
  2493. }
  2494. }
  2495. }
  2496. internal func highlightMessage(at indexPath: IndexPath, with scrollPosition: UITableView.ScrollPosition) {
  2497. self.tableView?.selectRow(at: indexPath, animated: true, scrollPosition: scrollPosition)
  2498. DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
  2499. self.tableView?.deselectRow(at: indexPath, animated: true)
  2500. }
  2501. }
  2502. internal func highlightMessageWithContentOffset(messageId: Int) {
  2503. guard messageId > 0,
  2504. let tableView = self.tableView,
  2505. let (indexPath, _) = self.indexPathAndMessage(forMessageId: messageId)
  2506. else { return }
  2507. self.highlightMessage(at: indexPath, with: .none)
  2508. let rect = tableView.rectForRow(at: indexPath)
  2509. // ContentOffset when the cell is at the top of the tableView
  2510. let contentOffsetTop = rect.origin.y - tableView.safeAreaInsets.top
  2511. // ContentOffset when the cell is at the middle of the tableView
  2512. let contentOffsetMiddle = contentOffsetTop - tableView.frame.height / 2 + rect.height / 2
  2513. // Fallback to the top offset in case the top of the cell would be scrolled outside of the view
  2514. let newContentOffset = min(contentOffsetTop, contentOffsetMiddle)
  2515. tableView.contentOffset.y = newContentOffset
  2516. }
  2517. public func reloadDataAndHighlightMessage(messageId: Int) {
  2518. self.tableView?.reloadData()
  2519. self.highlightMessageWithContentOffset(messageId: messageId)
  2520. }
  2521. func showNewMessagesView(until message: NCChatMessage) {
  2522. self.firstUnreadMessage = message
  2523. self.unreadMessageButton.isHidden = false
  2524. // Check if unread messages are already visible
  2525. self.checkUnreadMessagesVisibility()
  2526. }
  2527. func hideNewMessagesView() {
  2528. self.firstUnreadMessage = nil
  2529. self.unreadMessageButton.isHidden = true
  2530. }
  2531. // MARK: - FileMessageTableViewCellDelegate
  2532. public func cellWants(toDownloadFile fileParameter: NCMessageFileParameter, for message: NCChatMessage) {
  2533. if NCUtils.isImage(fileType: fileParameter.mimetype) {
  2534. let mediaViewController = NCMediaViewerViewController(initialMessage: message)
  2535. let navController = CustomPresentableNavigationController(rootViewController: mediaViewController)
  2536. self.present(navController, interactiveDismissalType: .standard)
  2537. return
  2538. }
  2539. if fileParameter.fileStatus != nil && fileParameter.fileStatus?.isDownloading ?? false {
  2540. print("File already downloading -> skipping new download")
  2541. return
  2542. }
  2543. let downloader = NCChatFileController()
  2544. downloader.delegate = self
  2545. downloader.downloadFile(fromMessage: fileParameter)
  2546. }
  2547. public func cellHasDownloadedImagePreview(withHeight height: CGFloat, for message: NCChatMessage) {
  2548. if message.file().previewImageHeight == Int(height) {
  2549. return
  2550. }
  2551. let isAtBottom = self.shouldScrollOnNewMessages()
  2552. message.setPreviewImageHeight(height)
  2553. CATransaction.begin()
  2554. CATransaction.setCompletionBlock {
  2555. DispatchQueue.main.async {
  2556. // make sure we're really at the bottom after updating a message since the file previews could grow in size if they contain a media file preview, thus giving the effect of not being at the bottom of the chat
  2557. if isAtBottom, !(self.tableView?.isDecelerating ?? false) {
  2558. self.tableView?.slk_scrollToBottom(animated: true)
  2559. self.updateToolbar(animated: true)
  2560. }
  2561. }
  2562. }
  2563. self.tableView?.beginUpdates()
  2564. self.tableView?.endUpdates()
  2565. CATransaction.commit()
  2566. }
  2567. // MARK: - VoiceMessageTableViewCellDelegate
  2568. public func cellWants(toPlayAudioFile fileParameter: NCMessageFileParameter) {
  2569. if fileParameter.fileStatus != nil && fileParameter.fileStatus?.isDownloading ?? false {
  2570. print("File already downloading -> skipping new download")
  2571. return
  2572. }
  2573. if let voiceMessagesPlayer = self.voiceMessagesPlayer,
  2574. let playerAudioFileStatus = self.playerAudioFileStatus,
  2575. !voiceMessagesPlayer.isPlaying,
  2576. fileParameter.parameterId == playerAudioFileStatus.fileId,
  2577. fileParameter.path == playerAudioFileStatus.filePath {
  2578. self.playVoiceMessagePlayer()
  2579. return
  2580. }
  2581. let downloader = NCChatFileController()
  2582. downloader.delegate = self
  2583. downloader.messageType = kMessageTypeVoiceMessage
  2584. downloader.downloadFile(fromMessage: fileParameter)
  2585. }
  2586. public func cellWants(toPauseAudioFile fileParameter: NCMessageFileParameter) {
  2587. if let voiceMessagesPlayer = self.voiceMessagesPlayer,
  2588. let playerAudioFileStatus = self.playerAudioFileStatus,
  2589. voiceMessagesPlayer.isPlaying,
  2590. fileParameter.parameterId == playerAudioFileStatus.fileId,
  2591. fileParameter.path == playerAudioFileStatus.filePath {
  2592. self.pauseVoiceMessagePlayer()
  2593. }
  2594. }
  2595. public func cellWants(toChangeProgress progress: CGFloat, fromAudioFile fileParameter: NCMessageFileParameter) {
  2596. if let playerAudioFileStatus = self.playerAudioFileStatus,
  2597. fileParameter.parameterId == playerAudioFileStatus.fileId,
  2598. fileParameter.path == playerAudioFileStatus.filePath {
  2599. self.pauseVoiceMessagePlayer()
  2600. self.voiceMessagesPlayer?.currentTime = progress
  2601. self.checkVisibleCellAudioPlayers()
  2602. }
  2603. }
  2604. // MARK: - LocationMessageTableViewCell
  2605. public func cellWants(toOpenLocation geoLocationRichObject: GeoLocationRichObject) {
  2606. self.presentWithNavigation(MapViewController(geoLocationRichObject: geoLocationRichObject), animated: true)
  2607. }
  2608. // MARK: - ObjectShareMessageTableViewCell
  2609. public func cellWants(toOpenPoll poll: NCMessageParameter) {
  2610. let pollVC = PollVotingView(style: .insetGrouped)
  2611. pollVC.room = self.room
  2612. self.presentWithNavigation(pollVC, animated: true)
  2613. if let pollId = Int(poll.parameterId) {
  2614. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  2615. NCAPIController.sharedInstance().getPollWithId(pollId, inRoom: self.room.token, for: activeAccount) { poll, error, _ in
  2616. if error == nil, let poll {
  2617. pollVC.updatePoll(poll: poll)
  2618. }
  2619. }
  2620. }
  2621. }
  2622. // MARK: - PollCreationViewControllerDelegate
  2623. func pollCreationViewControllerWantsToCreatePoll(pollCreationViewController: PollCreationViewController, question: String, options: [String], resultMode: NCPollResultMode, maxVotes: Int) {
  2624. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  2625. NCAPIController.sharedInstance().createPoll(withQuestion: question, options: options, resultMode: resultMode, maxVotes: maxVotes, inRoom: self.room.token, for: activeAccount) { _, error, _ in
  2626. if error != nil {
  2627. pollCreationViewController.showCreationError()
  2628. } else {
  2629. pollCreationViewController.close()
  2630. }
  2631. }
  2632. }
  2633. // MARK: - SystemMessageTableViewCellDelegate
  2634. public func cellWantsToCollapseMessages(with message: NCChatMessage!) {
  2635. DispatchQueue.main.async {
  2636. guard let messageIds = message.collapsedMessages.value(forKey: "self") as? [NSNumber] else { return }
  2637. let collapse = !message.isCollapsed
  2638. var reloadIndexPath: [IndexPath] = []
  2639. if let indexPath = self.indexPath(for: message) {
  2640. reloadIndexPath.append(indexPath)
  2641. message.isCollapsed = collapse
  2642. }
  2643. for messageId in messageIds {
  2644. if let (indexPath, message) = self.indexPathAndMessage(forMessageId: messageId.intValue) {
  2645. reloadIndexPath.append(indexPath)
  2646. message.isCollapsed = collapse
  2647. }
  2648. }
  2649. self.tableView?.beginUpdates()
  2650. self.tableView?.reloadRows(at: reloadIndexPath, with: .automatic)
  2651. self.tableView?.endUpdates()
  2652. }
  2653. }
  2654. // MARK: - ChatMessageTableViewCellDelegate
  2655. public func cellWantsToScroll(to message: NCChatMessage) {
  2656. DispatchQueue.main.async {
  2657. if let indexPath = self.indexPath(for: message) {
  2658. self.highlightMessage(at: indexPath, with: .top)
  2659. }
  2660. }
  2661. }
  2662. public func cellDidSelectedReaction(_ reaction: NCChatReaction!, for message: NCChatMessage) {
  2663. // Do nothing -> override in subclass
  2664. }
  2665. public func cellWantsToReply(to message: NCChatMessage) {
  2666. if self.textInputbar.isEditing {
  2667. return
  2668. }
  2669. self.didPressReply(for: message)
  2670. }
  2671. // MARK: - NCChatFileControllerDelegate
  2672. public func fileControllerDidLoadFile(_ fileController: NCChatFileController, with fileStatus: NCChatFileStatus) {
  2673. if fileController.messageType == kMessageTypeVoiceMessage {
  2674. if fileController.actionType == actionTypeTranscribeVoiceMessage {
  2675. self.transcribeVoiceMessage(with: fileStatus)
  2676. } else {
  2677. self.setupVoiceMessagePlayer(with: fileStatus)
  2678. }
  2679. return
  2680. }
  2681. if self.isPreviewControllerShown {
  2682. // We are showing a file already, no need to open another one
  2683. return
  2684. }
  2685. guard let tableView = self.tableView else { return }
  2686. var isFileCellStillVisible = false
  2687. if let indexPathsForVisibleRows = tableView.indexPathsForVisibleRows {
  2688. for indexPath in indexPathsForVisibleRows {
  2689. guard let message = self.message(for: indexPath), let file = message.file() else { continue }
  2690. if file.parameterId == fileStatus.fileId && file.path == fileStatus.filePath {
  2691. isFileCellStillVisible = true
  2692. break
  2693. }
  2694. }
  2695. }
  2696. if !isFileCellStillVisible {
  2697. // Only open file when the corresponding cell is still visible on the screen
  2698. return
  2699. }
  2700. DispatchQueue.main.async {
  2701. self.isPreviewControllerShown = true
  2702. self.previewControllerFilePath = fileStatus.fileLocalPath
  2703. // When the keyboard is not dismissed, dismissing the previewController might result in a corrupted keyboardView
  2704. self.dismissKeyboard(false)
  2705. guard let fileLocalPath = fileStatus.fileLocalPath else { return }
  2706. let fileExtension = URL(fileURLWithPath: fileLocalPath).pathExtension.lowercased()
  2707. // Use VLCKitVideoViewController for file formats unsupported by the native PreviewController
  2708. if VLCKitVideoViewController.supportedFileExtensions.contains(fileExtension) {
  2709. let vlcKitViewController = VLCKitVideoViewController(filePath: fileLocalPath)
  2710. vlcKitViewController.delegate = self
  2711. vlcKitViewController.modalPresentationStyle = .fullScreen
  2712. self.present(vlcKitViewController, animated: true)
  2713. return
  2714. }
  2715. let preview = QLPreviewController()
  2716. preview.dataSource = self
  2717. preview.delegate = self
  2718. preview.navigationController?.navigationBar.tintColor = NCAppBranding.themeTextColor()
  2719. preview.navigationController?.navigationBar.barTintColor = NCAppBranding.themeColor()
  2720. preview.tabBarController?.tabBar.tintColor = NCAppBranding.themeColor()
  2721. let appearance = UINavigationBarAppearance()
  2722. appearance.configureWithOpaqueBackground()
  2723. appearance.titleTextAttributes = [.foregroundColor: NCAppBranding.themeTextColor()]
  2724. appearance.backgroundColor = NCAppBranding.themeColor()
  2725. self.navigationItem.standardAppearance = appearance
  2726. self.navigationItem.compactAppearance = appearance
  2727. self.navigationItem.scrollEdgeAppearance = appearance
  2728. self.present(preview, animated: true)
  2729. }
  2730. }
  2731. public func fileControllerDidFailLoadingFile(_ fileController: NCChatFileController, withErrorDescription errorDescription: String) {
  2732. let alert = UIAlertController(title: NSLocalizedString("Unable to load file", comment: ""),
  2733. message: errorDescription,
  2734. preferredStyle: .alert)
  2735. alert.addAction(UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default))
  2736. NCUserInterfaceController.sharedInstance().presentAlertViewController(alert)
  2737. }
  2738. // MARK: - QLPreviewControllerDelegate/DataSource
  2739. public func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
  2740. return 1
  2741. }
  2742. public func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
  2743. if let filePath = self.previewControllerFilePath {
  2744. return URL(fileURLWithPath: filePath) as QLPreviewItem
  2745. }
  2746. return URL(fileURLWithPath: "") as QLPreviewItem
  2747. }
  2748. public func previewControllerDidDismiss(_ controller: QLPreviewController) {
  2749. self.isPreviewControllerShown = false
  2750. }
  2751. // MARK: - VLCVideoViewControllerDelegate
  2752. func vlckitVideoViewControllerDismissed(_ controller: VLCKitVideoViewController) {
  2753. self.isPreviewControllerShown = false
  2754. }
  2755. }
  2756. extension Sequence where Iterator.Element == NCChatMessage {
  2757. func containsUserMessage() -> Bool {
  2758. let activeAccount = NCDatabaseManager.sharedInstance().activeAccount()
  2759. return self.contains(where: { !$0.isSystemMessage && $0.actorId == activeAccount.userId })
  2760. }
  2761. func containsVisibleMessages() -> Bool {
  2762. return self.contains(where: { !$0.isUpdateMessage })
  2763. }
  2764. }