ChatViewController.swift 56 KB

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