ChatViewController.swift 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. protocol MediaSendHandler {
  7. func onSuccess()
  8. }
  9. extension ChatViewController: MediaSendHandler {
  10. func onSuccess() {
  11. refreshMessages()
  12. }
  13. }
  14. class ChatViewController: MessagesViewController {
  15. var dcContext: DcContext
  16. weak var coordinator: ChatViewCoordinator?
  17. let outgoingAvatarOverlap: CGFloat = 17.5
  18. let loadCount = 30
  19. let chatId: Int
  20. let refreshControl = UIRefreshControl()
  21. var messageList: [DcMsg] = []
  22. var msgChangedObserver: Any?
  23. var incomingMsgObserver: Any?
  24. lazy var navBarTap: UITapGestureRecognizer = {
  25. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  26. }()
  27. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and udpate audio cell UI accordingly.
  28. open lazy var audioController = BasicAudioController(messageCollectionView: messagesCollectionView)
  29. var disableWriting = false
  30. var showCustomNavBar = true
  31. var previewView: UIView?
  32. var previewController: PreviewController?
  33. override var inputAccessoryView: UIView? {
  34. if disableWriting {
  35. return nil
  36. }
  37. return messageInputBar
  38. }
  39. init(dcContext: DcContext, chatId: Int) {
  40. self.dcContext = dcContext
  41. self.chatId = chatId
  42. super.init(nibName: nil, bundle: nil)
  43. hidesBottomBarWhenPushed = true
  44. }
  45. required init?(coder _: NSCoder) {
  46. fatalError("init(coder:) has not been implemented")
  47. }
  48. override func viewDidLoad() {
  49. dcContext.marknoticedChat(chatId: chatId)
  50. messagesCollectionView.register(CustomMessageCell.self)
  51. super.viewDidLoad()
  52. if !DcConfig.configured {
  53. // TODO: display message about nothing being configured
  54. return
  55. }
  56. configureMessageCollectionView()
  57. if !disableWriting {
  58. configureMessageInputBar()
  59. messageInputBar.inputTextView.text = textDraft
  60. messageInputBar.inputTextView.becomeFirstResponder()
  61. }
  62. loadFirstMessages()
  63. }
  64. override func viewWillAppear(_ animated: Bool) {
  65. super.viewWillAppear(animated)
  66. // this will be removed in viewWillDisappear
  67. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  68. let chat = DcChat(id: chatId)
  69. if showCustomNavBar {
  70. let titleView = ChatTitleView()
  71. var subtitle = "ErrSubtitle"
  72. let chatContactIds = chat.contactIds
  73. if chat.isGroup {
  74. subtitle = String.localizedStringWithFormat(NSLocalizedString("n_members", comment: ""), chatContactIds.count)
  75. } else if chatContactIds.count >= 1 {
  76. if chat.isSelfTalk {
  77. subtitle = String.localized("chat_self_talk_subtitle")
  78. } else {
  79. subtitle = DcContact(id: chatContactIds[0]).email
  80. }
  81. }
  82. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  83. navigationItem.titleView = titleView
  84. let badge: InitialsBadge
  85. if let image = chat.profileImage {
  86. badge = InitialsBadge(image: image, size: 28)
  87. } else {
  88. badge = InitialsBadge(name: chat.name, color: chat.color, size: 28)
  89. }
  90. badge.setVerified(chat.isVerified)
  91. navigationItem.rightBarButtonItem = UIBarButtonItem(customView: badge)
  92. }
  93. configureMessageMenu()
  94. let nc = NotificationCenter.default
  95. msgChangedObserver = nc.addObserver(
  96. forName: dcNotificationChanged,
  97. object: nil,
  98. queue: OperationQueue.main
  99. ) { notification in
  100. if let ui = notification.userInfo {
  101. if self.disableWriting {
  102. // always refresh, as we can't check currently
  103. self.refreshMessages()
  104. } else if let id = ui["message_id"] as? Int {
  105. if id > 0 {
  106. self.updateMessage(id)
  107. }
  108. }
  109. }
  110. }
  111. incomingMsgObserver = nc.addObserver(
  112. forName: dcNotificationIncoming,
  113. object: nil, queue: OperationQueue.main
  114. ) { notification in
  115. if let ui = notification.userInfo {
  116. if self.chatId == ui["chat_id"] as? Int {
  117. if let id = ui["message_id"] as? Int {
  118. if id > 0 {
  119. self.insertMessage(DcMsg(id: id))
  120. }
  121. }
  122. }
  123. }
  124. }
  125. }
  126. override func viewWillDisappear(_ animated: Bool) {
  127. super.viewWillDisappear(animated)
  128. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  129. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  130. let array = DcArray(arrayPointer: dc_get_fresh_msgs(mailboxPointer))
  131. UIApplication.shared.applicationIconBadgeNumber = array.count
  132. }
  133. override func viewDidDisappear(_ animated: Bool) {
  134. super.viewDidDisappear(animated)
  135. setTextDraft()
  136. let nc = NotificationCenter.default
  137. if let msgChangedObserver = self.msgChangedObserver {
  138. nc.removeObserver(msgChangedObserver)
  139. }
  140. if let incomingMsgObserver = self.incomingMsgObserver {
  141. nc.removeObserver(incomingMsgObserver)
  142. }
  143. audioController.stopAnyOngoingPlaying()
  144. }
  145. @objc
  146. private func loadMoreMessages() {
  147. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  148. DispatchQueue.main.async {
  149. self.messageList = self.getMessageIds(self.loadCount, from: self.messageList.count) + self.messageList
  150. self.messagesCollectionView.reloadDataAndKeepOffset()
  151. self.refreshControl.endRefreshing()
  152. }
  153. }
  154. }
  155. @objc
  156. private func refreshMessages() {
  157. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  158. DispatchQueue.main.async {
  159. self.messageList = self.getMessageIds(self.messageList.count)
  160. self.messagesCollectionView.reloadDataAndKeepOffset()
  161. self.refreshControl.endRefreshing()
  162. if self.isLastSectionVisible() {
  163. self.messagesCollectionView.scrollToBottom(animated: true)
  164. }
  165. }
  166. }
  167. }
  168. private func loadFirstMessages() {
  169. DispatchQueue.global(qos: .userInitiated).async {
  170. DispatchQueue.main.async {
  171. self.messageList = self.getMessageIds(self.loadCount)
  172. self.messagesCollectionView.reloadData()
  173. self.refreshControl.endRefreshing()
  174. self.messagesCollectionView.scrollToBottom(animated: false)
  175. }
  176. }
  177. }
  178. private var textDraft: String? {
  179. if let draft = dc_get_draft(mailboxPointer, UInt32(chatId)) {
  180. if let cString = dc_msg_get_text(draft) {
  181. let swiftString = String(cString: cString)
  182. dc_str_unref(cString)
  183. dc_msg_unref(draft)
  184. return swiftString
  185. }
  186. dc_msg_unref(draft)
  187. return nil
  188. }
  189. return nil
  190. }
  191. private func getMessageIds(_ count: Int, from: Int? = nil) -> [DcMsg] {
  192. let cMessageIds = dc_get_chat_msgs(mailboxPointer, UInt32(chatId), 0, 0)
  193. let ids: [Int]
  194. if let from = from {
  195. ids = Utils.copyAndFreeArrayWithOffset(inputArray: cMessageIds, len: count, skipEnd: from)
  196. } else {
  197. ids = Utils.copyAndFreeArrayWithLen(inputArray: cMessageIds, len: count)
  198. }
  199. let markIds: [UInt32] = ids.map { UInt32($0) }
  200. dc_markseen_msgs(mailboxPointer, UnsafePointer(markIds), Int32(ids.count))
  201. return ids.map {
  202. DcMsg(id: $0)
  203. }
  204. }
  205. private func setTextDraft() {
  206. if let text = self.messageInputBar.inputTextView.text {
  207. let draft = dc_msg_new(mailboxPointer, DC_MSG_TEXT)
  208. dc_msg_set_text(draft, text.cString(using: .utf8))
  209. dc_set_draft(mailboxPointer, UInt32(chatId), draft)
  210. // cleanup
  211. dc_msg_unref(draft)
  212. }
  213. }
  214. private func configureMessageMenu() {
  215. var menuItems: [UIMenuItem]
  216. if disableWriting {
  217. menuItems = [
  218. UIMenuItem(title: String.localized("start_chat"), action: #selector(MessageCollectionViewCell.messageStartChat(_:))),
  219. UIMenuItem(title: String.localized("dismiss"), action: #selector(MessageCollectionViewCell.messageDismiss(_:))),
  220. UIMenuItem(title: String.localized("menu_block_contact"), action: #selector(MessageCollectionViewCell.messageBlock(_:))),
  221. ]
  222. } else {
  223. // Configures the UIMenu which is shown when selecting a message
  224. menuItems = [
  225. UIMenuItem(title: String.localized("info"), action: #selector(MessageCollectionViewCell.messageInfo(_:))),
  226. ]
  227. }
  228. UIMenuController.shared.menuItems = menuItems
  229. }
  230. private func configureMessageCollectionView() {
  231. messagesCollectionView.messagesDataSource = self
  232. messagesCollectionView.messageCellDelegate = self
  233. scrollsToBottomOnKeyboardBeginsEditing = true // default false
  234. maintainPositionOnKeyboardFrameChanged = true // default false
  235. messagesCollectionView.backgroundColor = DcColors.chatBackgroundColor
  236. messagesCollectionView.addSubview(refreshControl)
  237. refreshControl.addTarget(self, action: #selector(loadMoreMessages), for: .valueChanged)
  238. let layout = messagesCollectionView.collectionViewLayout as? MessagesCollectionViewFlowLayout
  239. layout?.sectionInset = UIEdgeInsets(top: 0, left: 8, bottom: 2, right: 8)
  240. // Hide the outgoing avatar and adjust the label alignment to line up with the messages
  241. layout?.setMessageOutgoingAvatarSize(.zero)
  242. layout?.setMessageOutgoingMessageTopLabelAlignment(LabelAlignment(textAlignment: .right,
  243. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  244. layout?.setMessageOutgoingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .right,
  245. textInsets: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 8)))
  246. // Set outgoing avatar to overlap with the message bubble
  247. layout?.setMessageIncomingMessageTopLabelAlignment(LabelAlignment(textAlignment: .left,
  248. textInsets: UIEdgeInsets(top: 0, left: 18, bottom: 0, right: 0)))
  249. layout?.setMessageIncomingAvatarSize(CGSize(width: 30, height: 30))
  250. layout?.setMessageIncomingMessagePadding(UIEdgeInsets(
  251. top: 0, left: -18, bottom: 0, right: 0))
  252. layout?.setMessageIncomingMessageBottomLabelAlignment(LabelAlignment(textAlignment: .left,
  253. textInsets: UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 0)))
  254. layout?.setMessageIncomingAccessoryViewSize(CGSize(width: 30, height: 30))
  255. layout?.setMessageIncomingAccessoryViewPadding(HorizontalEdgeInsets(left: 8, right: 0))
  256. layout?.setMessageOutgoingAccessoryViewSize(CGSize(width: 30, height: 30))
  257. layout?.setMessageOutgoingAccessoryViewPadding(HorizontalEdgeInsets(left: 0, right: 8))
  258. messagesCollectionView.messagesLayoutDelegate = self
  259. messagesCollectionView.messagesDisplayDelegate = self
  260. }
  261. private func configureMessageInputBar() {
  262. messageInputBar.delegate = self
  263. messageInputBar.inputTextView.tintColor = DcColors.primary
  264. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  265. messageInputBar.isTranslucent = true
  266. messageInputBar.separatorLine.isHidden = true
  267. messageInputBar.inputTextView.tintColor = DcColors.primary
  268. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  269. messageInputBar.backgroundView.backgroundColor = .black
  270. messageInputBar.isTranslucent = false
  271. //messageInputBar.backgroundColor = DcColors.chatBackgroundColor
  272. scrollsToBottomOnKeyboardBeginsEditing = true
  273. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  274. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  275. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  276. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  277. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  278. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  279. messageInputBar.inputTextView.layer.borderWidth = 1.0
  280. messageInputBar.inputTextView.layer.cornerRadius = 16.0
  281. messageInputBar.inputTextView.layer.masksToBounds = true
  282. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  283. configureInputBarItems()
  284. }
  285. private func configureInputBarItems() {
  286. messageInputBar.setLeftStackViewWidthConstant(to: 30, animated: false)
  287. messageInputBar.setRightStackViewWidthConstant(to: 30, animated: false)
  288. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  289. messageInputBar.sendButton.image = sendButtonImage
  290. messageInputBar.sendButton.title = nil
  291. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  292. messageInputBar.sendButton.layer.cornerRadius = 15
  293. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 10)
  294. // this adds a padding between textinputfield and send button
  295. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  296. messageInputBar.sendButton.setSize(CGSize(width: 30, height: 30), animated: false)
  297. let leftItems = [
  298. InputBarButtonItem()
  299. .configure {
  300. $0.spacing = .fixed(0)
  301. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  302. $0.image = clipperIcon
  303. $0.tintColor = DcColors.colorDisabled
  304. $0.setSize(CGSize(width: 30, height: 30), animated: false)
  305. }.onSelected {
  306. $0.tintColor = DcColors.primary
  307. }.onDeselected {
  308. $0.tintColor = DcColors.colorDisabled
  309. }.onTouchUpInside { _ in
  310. self.clipperButtonPressed()
  311. }
  312. ]
  313. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  314. // This just adds some more flare
  315. messageInputBar.sendButton
  316. .onEnabled { item in
  317. UIView.animate(withDuration: 0.3, animations: {
  318. item.backgroundColor = DcColors.primary
  319. })
  320. }.onDisabled { item in
  321. UIView.animate(withDuration: 0.3, animations: {
  322. item.backgroundColor = DcColors.colorDisabled
  323. })
  324. }
  325. }
  326. @objc private func chatProfilePressed() {
  327. coordinator?.showChatDetail(chatId: chatId)
  328. }
  329. // MARK: - UICollectionViewDataSource
  330. public override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  331. guard let messagesCollectionView = collectionView as? MessagesCollectionView else {
  332. fatalError("notMessagesCollectionView")
  333. }
  334. guard let messagesDataSource = messagesCollectionView.messagesDataSource else {
  335. fatalError("nilMessagesDataSource")
  336. }
  337. let message = messagesDataSource.messageForItem(at: indexPath, in: messagesCollectionView)
  338. switch message.kind {
  339. case .text, .attributedText, .emoji:
  340. let cell = messagesCollectionView.dequeueReusableCell(TextMessageCell.self, for: indexPath)
  341. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  342. return cell
  343. case .photo, .video:
  344. let cell = messagesCollectionView.dequeueReusableCell(MediaMessageCell.self, for: indexPath)
  345. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  346. return cell
  347. case .photoText, .videoText, .fileText:
  348. let cell = messagesCollectionView.dequeueReusableCell(TextMediaMessageCell.self, for: indexPath)
  349. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  350. return cell
  351. case .location:
  352. let cell = messagesCollectionView.dequeueReusableCell(LocationMessageCell.self, for: indexPath)
  353. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  354. return cell
  355. case .contact:
  356. let cell = messagesCollectionView.dequeueReusableCell(ContactMessageCell.self, for: indexPath)
  357. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  358. return cell
  359. case .custom:
  360. let cell = messagesCollectionView.dequeueReusableCell(CustomMessageCell.self, for: indexPath)
  361. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  362. return cell
  363. case .audio:
  364. let cell = messagesCollectionView.dequeueReusableCell(AudioMessageCell.self, for: indexPath)
  365. cell.configure(with: message, at: indexPath, and: messagesCollectionView)
  366. return cell
  367. }
  368. }
  369. override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  370. if action == NSSelectorFromString("messageInfo:") ||
  371. action == NSSelectorFromString("messageBlock:") ||
  372. action == NSSelectorFromString("messageDismiss:") ||
  373. action == NSSelectorFromString("messageStartChat:") {
  374. return true
  375. } else {
  376. return super.collectionView(collectionView, canPerformAction: action, forItemAt: indexPath, withSender: sender)
  377. }
  378. }
  379. override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
  380. switch action {
  381. case NSSelectorFromString("messageInfo:"):
  382. let msg = messageList[indexPath.section]
  383. logger.info("message: View info \(msg.messageId)")
  384. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  385. if let ctrl = navigationController {
  386. ctrl.pushViewController(msgViewController, animated: true)
  387. }
  388. case NSSelectorFromString("messageStartChat:"):
  389. let msg = messageList[indexPath.section]
  390. logger.info("message: Start Chat \(msg.messageId)")
  391. let chat = msg.createChat()
  392. // TODO: figure out how to properly show the chat after creation
  393. refreshMessages()
  394. coordinator?.showChat(chatId: chat.id)
  395. case NSSelectorFromString("messageBlock:"):
  396. let msg = messageList[indexPath.section]
  397. logger.info("message: Block \(msg.messageId)")
  398. msg.fromContact.block()
  399. refreshMessages()
  400. case NSSelectorFromString("messageDismiss:"):
  401. let msg = messageList[indexPath.section]
  402. logger.info("message: Dismiss \(msg.messageId)")
  403. msg.fromContact.marknoticed()
  404. refreshMessages()
  405. default:
  406. super.collectionView(collectionView, performAction: action, forItemAt: indexPath, withSender: sender)
  407. }
  408. }
  409. }
  410. // MARK: - MessagesDataSource
  411. extension ChatViewController: MessagesDataSource {
  412. func numberOfSections(in _: MessagesCollectionView) -> Int {
  413. return messageList.count
  414. }
  415. func currentSender() -> SenderType {
  416. let currentSender = Sender(senderId: "1", displayName: "Alice")
  417. return currentSender
  418. }
  419. func messageForItem(at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageType {
  420. return messageList[indexPath.section]
  421. }
  422. func avatar(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> Avatar {
  423. let message = messageList[indexPath.section]
  424. let contact = message.fromContact
  425. return Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.displayName))
  426. }
  427. func cellTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  428. if isInfoMessage(at: indexPath) {
  429. return nil
  430. }
  431. if isTimeLabelVisible(at: indexPath) {
  432. return NSAttributedString(
  433. string: MessageKitDateFormatter.shared.string(from: message.sentDate),
  434. attributes: [
  435. NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 10),
  436. NSAttributedString.Key.foregroundColor: DcColors.grayTextColor,
  437. ]
  438. )
  439. }
  440. return nil
  441. }
  442. func messageTopLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  443. var attributedString: NSMutableAttributedString?
  444. if !isPreviousMessageSameSender(at: indexPath) {
  445. let name = message.sender.displayName
  446. let m = messageList[indexPath.section]
  447. attributedString = NSMutableAttributedString(string: name, attributes: [
  448. .font: UIFont.systemFont(ofSize: 14),
  449. .foregroundColor: m.fromContact.color,
  450. ])
  451. }
  452. if isMessageForwarded(at: indexPath) {
  453. let forwardedString = NSMutableAttributedString(string: String.localized("forwarded_message"), attributes: [
  454. .font: UIFont.systemFont(ofSize: 14),
  455. .foregroundColor: DcColors.grayTextColor,
  456. ])
  457. if attributedString == nil {
  458. attributedString = forwardedString
  459. } else {
  460. attributedString?.append(NSAttributedString(string: "\n", attributes: nil))
  461. attributedString?.append(forwardedString)
  462. }
  463. }
  464. return attributedString
  465. }
  466. func isMessageForwarded(at indexPath: IndexPath) -> Bool {
  467. let m = messageList[indexPath.section]
  468. return m.isForwarded
  469. }
  470. func isTimeLabelVisible(at indexPath: IndexPath) -> Bool {
  471. guard indexPath.section + 1 < messageList.count else { return false }
  472. let messageA = messageList[indexPath.section]
  473. let messageB = messageList[indexPath.section + 1]
  474. if messageA.fromContactId == messageB.fromContactId {
  475. return false
  476. }
  477. let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
  478. let dateA = messageA.sentDate
  479. let dateB = messageB.sentDate
  480. let dayA = (calendar?.component(.day, from: dateA))
  481. let dayB = (calendar?.component(.day, from: dateB))
  482. return dayA != dayB
  483. }
  484. func isPreviousMessageSameSender(at indexPath: IndexPath) -> Bool {
  485. guard indexPath.section - 1 >= 0 else { return false }
  486. let messageA = messageList[indexPath.section - 1]
  487. let messageB = messageList[indexPath.section]
  488. if messageA.isInfo {
  489. return false
  490. }
  491. return messageA.fromContactId == messageB.fromContactId
  492. }
  493. func isInfoMessage(at indexPath: IndexPath) -> Bool {
  494. return messageList[indexPath.section].isInfo
  495. }
  496. func isImmediateNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  497. guard indexPath.section + 1 < messageList.count else { return false }
  498. let messageA = messageList[indexPath.section]
  499. let messageB = messageList[indexPath.section + 1]
  500. if messageA.isInfo {
  501. return false
  502. }
  503. let dateA = messageA.sentDate
  504. let dateB = messageB.sentDate
  505. let timeinterval = dateB.timeIntervalSince(dateA)
  506. let minute = 60.0
  507. return messageA.fromContactId == messageB.fromContactId && timeinterval.isLessThanOrEqualTo(minute)
  508. }
  509. func isAvatarHidden(at indexPath: IndexPath) -> Bool {
  510. let message = messageList[indexPath.section]
  511. return isNextMessageSameSender(at: indexPath) || message.isInfo
  512. }
  513. func isNextMessageSameSender(at indexPath: IndexPath) -> Bool {
  514. guard indexPath.section + 1 < messageList.count else { return false }
  515. let messageA = messageList[indexPath.section]
  516. let messageB = messageList[indexPath.section + 1]
  517. if messageA.isInfo {
  518. return false
  519. }
  520. return messageA.fromContactId == messageB.fromContactId
  521. }
  522. func messageBottomLabelAttributedText(for message: MessageType, at indexPath: IndexPath) -> NSAttributedString? {
  523. guard indexPath.section < messageList.count else { return nil }
  524. let m = messageList[indexPath.section]
  525. if m.isInfo || isImmediateNextMessageSameSender(at: indexPath) {
  526. return nil
  527. }
  528. let timestampAttributes: [NSAttributedString.Key: Any] = [
  529. .font: UIFont.systemFont(ofSize: 12),
  530. .foregroundColor: UIColor.lightGray,
  531. ]
  532. if isFromCurrentSender(message: message) {
  533. let text = NSMutableAttributedString()
  534. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  535. // TODO: this should be replaced by the respective icons,
  536. // for accessibility, the a11y strings should be added
  537. var stateDescription: String
  538. switch Int32(m.state) {
  539. case DC_STATE_OUT_PENDING:
  540. stateDescription = "Pending"
  541. case DC_STATE_OUT_DELIVERED:
  542. stateDescription = "Sent"
  543. case DC_STATE_OUT_MDN_RCVD:
  544. stateDescription = "Read"
  545. case DC_STATE_OUT_FAILED:
  546. stateDescription = "Failed"
  547. default:
  548. stateDescription = "Unknown"
  549. }
  550. text.append(NSAttributedString(
  551. string: " - " + stateDescription,
  552. attributes: [
  553. .font: UIFont.systemFont(ofSize: 12),
  554. .foregroundColor: DcColors.defaultTextColor,
  555. ]
  556. ))
  557. return text
  558. }
  559. if !isAvatarHidden(at: indexPath) {
  560. let text = NSMutableAttributedString()
  561. text.append(NSAttributedString(string: " "))
  562. text.append(NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes))
  563. return text
  564. }
  565. return NSAttributedString(string: m.formattedSentDate(), attributes: timestampAttributes)
  566. }
  567. func updateMessage(_ messageId: Int) {
  568. if let index = messageList.firstIndex(where: { $0.id == messageId }) {
  569. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(messageId)]), 1)
  570. messageList[index] = DcMsg(id: messageId)
  571. // Reload section to update header/footer labels
  572. messagesCollectionView.performBatchUpdates({
  573. messagesCollectionView.reloadSections([index])
  574. if index > 0 {
  575. messagesCollectionView.reloadSections([index - 1])
  576. }
  577. if index < messageList.count - 1 {
  578. messagesCollectionView.reloadSections([index + 1])
  579. }
  580. }, completion: { [weak self] _ in
  581. if self?.isLastSectionVisible() == true {
  582. self?.messagesCollectionView.scrollToBottom(animated: true)
  583. }
  584. })
  585. } else {
  586. let msg = DcMsg(id: messageId)
  587. if msg.chatId == chatId {
  588. insertMessage(msg)
  589. }
  590. }
  591. }
  592. func insertMessage(_ message: DcMsg) {
  593. dc_markseen_msgs(mailboxPointer, UnsafePointer([UInt32(message.id)]), 1)
  594. messageList.append(message)
  595. // Reload last section to update header/footer labels and insert a new one
  596. messagesCollectionView.performBatchUpdates({
  597. messagesCollectionView.insertSections([messageList.count - 1])
  598. if messageList.count >= 2 {
  599. messagesCollectionView.reloadSections([messageList.count - 2])
  600. }
  601. }, completion: { [weak self] _ in
  602. if self?.isLastSectionVisible() == true {
  603. self?.messagesCollectionView.scrollToBottom(animated: true)
  604. }
  605. })
  606. }
  607. func isLastSectionVisible() -> Bool {
  608. guard !messageList.isEmpty else { return false }
  609. let lastIndexPath = IndexPath(item: 0, section: messageList.count - 1)
  610. return messagesCollectionView.indexPathsForVisibleItems.contains(lastIndexPath)
  611. }
  612. }
  613. // MARK: - MessagesDisplayDelegate
  614. extension ChatViewController: MessagesDisplayDelegate {
  615. // MARK: - Text Messages
  616. func textColor(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  617. return DcColors.defaultTextColor
  618. }
  619. // MARK: - All Messages
  620. func backgroundColor(for message: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> UIColor {
  621. return isFromCurrentSender(message: message) ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  622. }
  623. func messageStyle(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> MessageStyle {
  624. if isInfoMessage(at: indexPath) {
  625. return .custom { view in
  626. view.style = .none
  627. view.backgroundColor = UIColor(alpha: 10, red: 0, green: 0, blue: 0)
  628. let radius: CGFloat = 16
  629. let path = UIBezierPath(roundedRect: view.bounds,
  630. byRoundingCorners: UIRectCorner.allCorners,
  631. cornerRadii: CGSize(width: radius, height: radius))
  632. let mask = CAShapeLayer()
  633. mask.path = path.cgPath
  634. view.layer.mask = mask
  635. view.center.x = self.view.center.x
  636. }
  637. }
  638. var corners: UIRectCorner = []
  639. if isFromCurrentSender(message: message) {
  640. corners.formUnion(.topLeft)
  641. corners.formUnion(.bottomLeft)
  642. if !isPreviousMessageSameSender(at: indexPath) {
  643. corners.formUnion(.topRight)
  644. }
  645. if !isNextMessageSameSender(at: indexPath) {
  646. corners.formUnion(.bottomRight)
  647. }
  648. } else {
  649. corners.formUnion(.topRight)
  650. corners.formUnion(.bottomRight)
  651. if !isPreviousMessageSameSender(at: indexPath) {
  652. corners.formUnion(.topLeft)
  653. }
  654. if !isNextMessageSameSender(at: indexPath) {
  655. corners.formUnion(.bottomLeft)
  656. }
  657. }
  658. return .custom { view in
  659. let radius: CGFloat = 16
  660. let path = UIBezierPath(roundedRect: view.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
  661. let mask = CAShapeLayer()
  662. mask.path = path.cgPath
  663. view.layer.mask = mask
  664. }
  665. }
  666. func configureAvatarView(_ avatarView: AvatarView, for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) {
  667. let message = messageList[indexPath.section]
  668. let contact = message.fromContact
  669. let avatar = Avatar(image: contact.profileImage, initials: Utils.getInitials(inputName: contact.displayName))
  670. avatarView.set(avatar: avatar)
  671. avatarView.isHidden = isAvatarHidden(at: indexPath)
  672. avatarView.backgroundColor = contact.color
  673. }
  674. func enabledDetectors(for _: MessageType, at _: IndexPath, in _: MessagesCollectionView) -> [DetectorType] {
  675. return [.url, .date, .phoneNumber, .address]
  676. }
  677. }
  678. // MARK: - MessagesLayoutDelegate
  679. extension ChatViewController: MessagesLayoutDelegate {
  680. func cellTopLabelHeight(for _: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  681. if isTimeLabelVisible(at: indexPath) {
  682. return 18
  683. }
  684. return 0
  685. }
  686. func messageTopLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  687. if isInfoMessage(at: indexPath) {
  688. return 0
  689. }
  690. if !isPreviousMessageSameSender(at: indexPath) {
  691. return 40
  692. } else if isMessageForwarded(at: indexPath) {
  693. return 20
  694. }
  695. return 0
  696. }
  697. func messageBottomLabelHeight(for message: MessageType, at indexPath: IndexPath, in _: MessagesCollectionView) -> CGFloat {
  698. if isInfoMessage(at: indexPath) {
  699. return 0
  700. }
  701. if !isImmediateNextMessageSameSender(at: indexPath) {
  702. return 16
  703. }
  704. return 0
  705. }
  706. func heightForLocation(message _: MessageType, at _: IndexPath, with _: CGFloat, in _: MessagesCollectionView) -> CGFloat {
  707. return 40
  708. }
  709. func footerViewSize(for _: MessageType, at _: IndexPath, in messagesCollectionView: MessagesCollectionView) -> CGSize {
  710. return CGSize(width: messagesCollectionView.bounds.width, height: 20)
  711. }
  712. @objc private func clipperButtonPressed() {
  713. showClipperOptions()
  714. }
  715. private func showClipperOptions() {
  716. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
  717. let photoAction = PhotoPickerAlertAction(title: String.localized("photo"), style: .default, handler: photoButtonPressed(_:))
  718. let videoAction = PhotoPickerAlertAction(title: String.localized("video"), style: .default, handler: videoButtonPressed(_:))
  719. alert.addAction(photoAction)
  720. alert.addAction(videoAction)
  721. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  722. self.present(alert, animated: true, completion: nil)
  723. }
  724. private func photoButtonPressed(_ action: UIAlertAction) {
  725. coordinator?.showCameraViewController()
  726. }
  727. private func videoButtonPressed(_ action: UIAlertAction) {
  728. coordinator?.showVideoLibrary()
  729. }
  730. }
  731. // MARK: - MessageCellDelegate
  732. extension ChatViewController: MessageCellDelegate {
  733. @objc func didTapMessage(in cell: MessageCollectionViewCell) {
  734. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  735. let message = messageList[indexPath.section]
  736. if message.isSetupMessage {
  737. didTapAsm(msg: message, orgText: "")
  738. } else if let url = message.fileURL {
  739. // find all other messages with same message type
  740. var previousUrls: [URL] = []
  741. var nextUrls: [URL] = []
  742. var prev: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), -1, Int32(message.type), 0, 0))
  743. while prev != 0 {
  744. let prevMessage = DcMsg(id: prev)
  745. if let url = prevMessage.fileURL {
  746. previousUrls.insert(url, at: 0)
  747. }
  748. prev = Int(dc_get_next_media(mailboxPointer, UInt32(prevMessage.id), -1, Int32(prevMessage.type), 0, 0))
  749. }
  750. var next: Int = Int(dc_get_next_media(mailboxPointer, UInt32(message.id), 1, Int32(message.type), 0, 0))
  751. while next != 0 {
  752. let nextMessage = DcMsg(id: next)
  753. if let url = nextMessage.fileURL {
  754. nextUrls.insert(url, at: 0)
  755. }
  756. next = Int(dc_get_next_media(mailboxPointer, UInt32(nextMessage.id), 1, Int32(nextMessage.type), 0, 0))
  757. }
  758. // these are the files user will be able to swipe trough
  759. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  760. previewController = PreviewController(currentIndex: previousUrls.count, urls: mediaUrls)
  761. present(previewController!.qlController, animated: true)
  762. }
  763. }
  764. }
  765. private func didTapAsm(msg: DcMsg, orgText: String) {
  766. let inputDlg = UIAlertController(
  767. title: String.localized("autocrypt_continue_transfer_title"),
  768. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  769. preferredStyle: .alert)
  770. inputDlg.addTextField(configurationHandler: { (textField) in
  771. textField.placeholder = msg.setupCodeBegin + ".."
  772. textField.text = orgText
  773. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  774. })
  775. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  776. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  777. let textField = inputDlg.textFields![0]
  778. let modText = textField.text ?? ""
  779. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  780. let alert = UIAlertController(
  781. title: String.localized("autocrypt_continue_transfer_title"),
  782. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  783. preferredStyle: .alert)
  784. if success {
  785. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  786. } else {
  787. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  788. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  789. self.didTapAsm(msg: msg, orgText: modText)
  790. })
  791. alert.addAction(retryAction)
  792. alert.preferredAction = retryAction
  793. }
  794. self.navigationController?.present(alert, animated: true, completion: nil)
  795. })
  796. inputDlg.addAction(okAction)
  797. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  798. navigationController?.present(inputDlg, animated: true, completion: nil)
  799. }
  800. @objc func didTapAvatar(in cell: MessageCollectionViewCell) {
  801. if let indexPath = messagesCollectionView.indexPath(for: cell) {
  802. let message = messageList[indexPath.section]
  803. let chat = DcChat(id: chatId)
  804. coordinator?.showContactDetail(of: message.fromContact.id, in: chat.chatType)
  805. }
  806. }
  807. @objc(didTapCellTopLabelIn:) func didTapCellTopLabel(in _: MessageCollectionViewCell) {
  808. logger.info("Top label tapped")
  809. }
  810. @objc(didTapCellBottomLabelIn:) func didTapCellBottomLabel(in _: MessageCollectionViewCell) {
  811. print("Bottom label tapped")
  812. }
  813. func didTapPlayButton(in cell: AudioMessageCell) {
  814. guard let indexPath = messagesCollectionView.indexPath(for: cell),
  815. let message = messagesCollectionView.messagesDataSource?.messageForItem(at: indexPath, in: messagesCollectionView) else {
  816. print("Failed to identify message when audio cell receive tap gesture")
  817. return
  818. }
  819. guard audioController.state != .stopped else {
  820. // There is no audio sound playing - prepare to start playing for given audio message
  821. audioController.playSound(for: message, in: cell)
  822. return
  823. }
  824. if audioController.playingMessage?.messageId == message.messageId {
  825. // tap occur in the current cell that is playing audio sound
  826. if audioController.state == .playing {
  827. audioController.pauseSound(for: message, in: cell)
  828. } else {
  829. audioController.resumeSound()
  830. }
  831. } else {
  832. // tap occur in a difference cell that the one is currently playing sound. First stop currently playing and start the sound for given message
  833. audioController.stopAnyOngoingPlaying()
  834. audioController.playSound(for: message, in: cell)
  835. }
  836. }
  837. func didStartAudio(in cell: AudioMessageCell) {
  838. print("audio started")
  839. }
  840. func didStopAudio(in cell: AudioMessageCell) {
  841. print("audio stopped")
  842. }
  843. func didPauseAudio(in cell: AudioMessageCell) {
  844. print("audio paused")
  845. }
  846. @objc func didTapBackground(in cell: MessageCollectionViewCell) {
  847. print("background of message tapped")
  848. }
  849. }
  850. // MARK: - MessageLabelDelegate
  851. extension ChatViewController: MessageLabelDelegate {
  852. func didSelectAddress(_ addressComponents: [String: String]) {
  853. let mapAddress = Utils.formatAddressForQuery(address: addressComponents)
  854. if let escapedMapAddress = mapAddress.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  855. // Use query, to handle malformed addresses
  856. if let url = URL(string: "http://maps.apple.com/?q=\(escapedMapAddress)") {
  857. UIApplication.shared.open(url as URL)
  858. }
  859. }
  860. }
  861. func didSelectDate(_ date: Date) {
  862. let interval = date.timeIntervalSinceReferenceDate
  863. if let url = NSURL(string: "calshow:\(interval)") {
  864. UIApplication.shared.open(url as URL)
  865. }
  866. }
  867. func didSelectPhoneNumber(_ phoneNumber: String) {
  868. logger.info("phone open", phoneNumber)
  869. if let escapedPhoneNumber = phoneNumber.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
  870. if let url = NSURL(string: "tel:\(escapedPhoneNumber)") {
  871. UIApplication.shared.open(url as URL)
  872. }
  873. }
  874. }
  875. func didSelectURL(_ url: URL) {
  876. UIApplication.shared.open(url)
  877. }
  878. }
  879. // MARK: - LocationMessageDisplayDelegate
  880. /*
  881. extension ChatViewController: LocationMessageDisplayDelegate {
  882. func annotationViewForLocation(message: MessageType, at indexPath: IndexPath, in messageCollectionView: MessagesCollectionView) -> MKAnnotationView? {
  883. let annotationView = MKAnnotationView(annotation: nil, reuseIdentifier: nil)
  884. let pinImage = #imageLiteral(resourceName: "ic_block_36pt").withRenderingMode(.alwaysTemplate)
  885. annotationView.image = pinImage
  886. annotationView.centerOffset = CGPoint(x: 0, y: -pinImage.size.height / 2)
  887. return annotationView
  888. }
  889. func animationBlockForLocation(message: MessageType, at indexPath: IndexPath, in messagesCollectionView: MessagesCollectionView) -> ((UIImageView) -> Void)? {
  890. return { view in
  891. view.layer.transform = CATransform3DMakeScale(0, 0, 0)
  892. view.alpha = 0.0
  893. UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0, options: [], animations: {
  894. view.layer.transform = CATransform3DIdentity
  895. view.alpha = 1.0
  896. }, completion: nil)
  897. }
  898. }
  899. }
  900. */
  901. // MARK: - MessageInputBarDelegate
  902. extension ChatViewController: InputBarAccessoryViewDelegate {
  903. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  904. DispatchQueue.global().async {
  905. dc_send_text_msg(mailboxPointer, UInt32(self.chatId), text)
  906. }
  907. inputBar.inputTextView.text = String()
  908. }
  909. }
  910. /*
  911. extension ChatViewController: MessageInputBarDelegate {
  912. }
  913. */
  914. // MARK: - MessageCollectionViewCell
  915. extension MessageCollectionViewCell {
  916. @objc func messageInfo(_ sender: Any?) {
  917. // Get the collectionView
  918. if let collectionView = self.superview as? UICollectionView {
  919. // Get indexPath
  920. if let indexPath = collectionView.indexPath(for: self) {
  921. // Trigger action
  922. collectionView.delegate?.collectionView?(collectionView,
  923. performAction: #selector(MessageCollectionViewCell.messageInfo(_:)),
  924. forItemAt: indexPath, withSender: sender)
  925. }
  926. }
  927. }
  928. @objc func messageBlock(_ sender: Any?) {
  929. // Get the collectionView
  930. if let collectionView = self.superview as? UICollectionView {
  931. // Get indexPath
  932. if let indexPath = collectionView.indexPath(for: self) {
  933. // Trigger action
  934. collectionView.delegate?.collectionView?(collectionView,
  935. performAction: #selector(MessageCollectionViewCell.messageBlock(_:)),
  936. forItemAt: indexPath, withSender: sender)
  937. }
  938. }
  939. }
  940. @objc func messageDismiss(_ sender: Any?) {
  941. // Get the collectionView
  942. if let collectionView = self.superview as? UICollectionView {
  943. // Get indexPath
  944. if let indexPath = collectionView.indexPath(for: self) {
  945. // Trigger action
  946. collectionView.delegate?.collectionView?(collectionView,
  947. performAction: #selector(MessageCollectionViewCell.messageDismiss(_:)),
  948. forItemAt: indexPath, withSender: sender)
  949. }
  950. }
  951. }
  952. @objc func messageStartChat(_ sender: Any?) {
  953. // Get the collectionView
  954. if let collectionView = self.superview as? UICollectionView {
  955. // Get indexPath
  956. if let indexPath = collectionView.indexPath(for: self) {
  957. // Trigger action
  958. collectionView.delegate?.collectionView?(collectionView,
  959. performAction: #selector(MessageCollectionViewCell.messageStartChat(_:)),
  960. forItemAt: indexPath, withSender: sender)
  961. }
  962. }
  963. }
  964. }