ChatViewController.swift 49 KB

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