ChatViewController.swift 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  1. import MapKit
  2. import QuickLook
  3. import UIKit
  4. import InputBarAccessoryView
  5. import AVFoundation
  6. import DcCore
  7. import SDWebImage
  8. class ChatViewController: UITableViewController {
  9. var dcContext: DcContext
  10. private var draftMessage: DcMsg?
  11. let outgoingAvatarOverlap: CGFloat = 17.5
  12. let loadCount = 30
  13. let chatId: Int
  14. var messageIds: [Int] = []
  15. var msgChangedObserver: Any?
  16. var incomingMsgObserver: Any?
  17. var ephemeralTimerModifiedObserver: Any?
  18. var lastContentOffset: CGFloat = -1
  19. var isKeyboardShown: Bool = false
  20. lazy var isGroupChat: Bool = {
  21. return dcContext.getChat(chatId: chatId).isGroup
  22. }()
  23. lazy var draft: DraftModel = {
  24. let draft = DraftModel(chatId: chatId)
  25. return draft
  26. }()
  27. /// The `InputBarAccessoryView` used as the `inputAccessoryView` in the view controller.
  28. open var messageInputBar = InputBarAccessoryView()
  29. lazy var quotePreview: QuotePreview = {
  30. let view = QuotePreview()
  31. view.delegate = self
  32. view.translatesAutoresizingMaskIntoConstraints = false
  33. return view
  34. }()
  35. open override var shouldAutorotate: Bool {
  36. return false
  37. }
  38. private weak var timer: Timer?
  39. lazy var navBarTap: UITapGestureRecognizer = {
  40. UITapGestureRecognizer(target: self, action: #selector(chatProfilePressed))
  41. }()
  42. private var locationStreamingItem: UIBarButtonItem = {
  43. let indicator = LocationStreamingIndicator()
  44. return UIBarButtonItem(customView: indicator)
  45. }()
  46. private lazy var muteItem: UIBarButtonItem = {
  47. let imageView = UIImageView()
  48. imageView.tintColor = DcColors.defaultTextColor
  49. imageView.image = #imageLiteral(resourceName: "volume_off").withRenderingMode(.alwaysTemplate)
  50. imageView.translatesAutoresizingMaskIntoConstraints = false
  51. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  52. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  53. return UIBarButtonItem(customView: imageView)
  54. }()
  55. private lazy var ephemeralMessageItem: UIBarButtonItem = {
  56. let imageView = UIImageView()
  57. imageView.tintColor = DcColors.defaultTextColor
  58. imageView.image = #imageLiteral(resourceName: "ephemeral_timer").withRenderingMode(.alwaysTemplate)
  59. imageView.translatesAutoresizingMaskIntoConstraints = false
  60. imageView.heightAnchor.constraint(equalToConstant: 20).isActive = true
  61. imageView.widthAnchor.constraint(equalToConstant: 20).isActive = true
  62. return UIBarButtonItem(customView: imageView)
  63. }()
  64. private lazy var badgeItem: UIBarButtonItem = {
  65. let badge: InitialsBadge
  66. let chat = dcContext.getChat(chatId: chatId)
  67. if let image = chat.profileImage {
  68. badge = InitialsBadge(image: image, size: 28, accessibilityLabel: String.localized("menu_view_profile"))
  69. } else {
  70. badge = InitialsBadge(
  71. name: chat.name,
  72. color: chat.color,
  73. size: 28,
  74. accessibilityLabel: String.localized("menu_view_profile")
  75. )
  76. badge.setLabelFont(UIFont.systemFont(ofSize: 14))
  77. }
  78. badge.setVerified(chat.isProtected)
  79. badge.accessibilityTraits = .button
  80. return UIBarButtonItem(customView: badge)
  81. }()
  82. /// The `BasicAudioController` controll the AVAudioPlayer state (play, pause, stop) and update audio cell UI accordingly.
  83. private lazy var audioController = AudioController(dcContext: dcContext, chatId: chatId)
  84. private var disableWriting: Bool
  85. private var showNamesAboveMessage: Bool
  86. var showCustomNavBar = true
  87. var highlightedMsg: Int?
  88. private lazy var mediaPicker: MediaPicker? = {
  89. let mediaPicker = MediaPicker(navigationController: navigationController)
  90. mediaPicker.delegate = self
  91. return mediaPicker
  92. }()
  93. var emptyStateView: EmptyStateLabel = {
  94. let view = EmptyStateLabel()
  95. return view
  96. }()
  97. init(dcContext: DcContext, chatId: Int, highlightedMsg: Int? = nil) {
  98. let dcChat = dcContext.getChat(chatId: chatId)
  99. self.dcContext = dcContext
  100. self.chatId = chatId
  101. self.disableWriting = !dcChat.canSend
  102. self.showNamesAboveMessage = dcChat.isGroup
  103. self.highlightedMsg = highlightedMsg
  104. super.init(nibName: nil, bundle: nil)
  105. hidesBottomBarWhenPushed = true
  106. }
  107. required init?(coder _: NSCoder) {
  108. fatalError("init(coder:) has not been implemented")
  109. }
  110. override func loadView() {
  111. self.tableView = ChatTableView(messageInputBar: self.disableWriting ? nil : messageInputBar)
  112. self.tableView.delegate = self
  113. self.tableView.dataSource = self
  114. self.view = self.tableView
  115. }
  116. override func viewDidLoad() {
  117. tableView.register(TextMessageCell.self, forCellReuseIdentifier: "text")
  118. tableView.register(ImageTextCell.self, forCellReuseIdentifier: "image")
  119. tableView.register(FileTextCell.self, forCellReuseIdentifier: "file")
  120. tableView.register(InfoMessageCell.self, forCellReuseIdentifier: "info")
  121. tableView.register(AudioMessageCell.self, forCellReuseIdentifier: "audio")
  122. tableView.rowHeight = UITableView.automaticDimension
  123. tableView.separatorStyle = .none
  124. super.viewDidLoad()
  125. if !dcContext.isConfigured() {
  126. // TODO: display message about nothing being configured
  127. return
  128. }
  129. configureEmptyStateView()
  130. if !disableWriting {
  131. configureMessageInputBar()
  132. draft.parse(draftMsg: dcContext.getDraft(chatId: chatId))
  133. messageInputBar.inputTextView.text = draft.draftText
  134. configureDraftArea(draft: draft)
  135. }
  136. let notificationCenter = NotificationCenter.default
  137. notificationCenter.addObserver(self,
  138. selector: #selector(saveDraft),
  139. name: UIApplication.willResignActiveNotification,
  140. object: nil)
  141. notificationCenter.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
  142. notificationCenter.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
  143. notificationCenter.addObserver(self, selector: #selector(keyboardDidShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
  144. prepareContextMenu()
  145. }
  146. @objc func keyboardDidShow(_ notification: Notification) {
  147. isKeyboardShown = true
  148. }
  149. @objc func keyboardWillShow(_ notification: Notification) {
  150. if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
  151. if keyboardSize.height > tableView.inputAccessoryView?.frame.height ?? 0 {
  152. if self.isLastRowVisible() {
  153. DispatchQueue.main.async { [weak self] in
  154. self?.scrollToBottom(animated: true)
  155. }
  156. }
  157. }
  158. }
  159. }
  160. @objc func keyboardWillHide(_ notification: Notification) {
  161. isKeyboardShown = false
  162. }
  163. private func startTimer() {
  164. timer?.invalidate()
  165. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  166. //reload table
  167. DispatchQueue.main.async {
  168. guard let self = self else { return }
  169. self.messageIds = self.getMessageIds()
  170. self.tableView.reloadData()
  171. }
  172. }
  173. }
  174. private func stopTimer() {
  175. timer?.invalidate()
  176. }
  177. private func configureEmptyStateView() {
  178. view.addSubview(emptyStateView)
  179. emptyStateView.translatesAutoresizingMaskIntoConstraints = false
  180. emptyStateView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  181. emptyStateView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  182. emptyStateView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  183. emptyStateView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  184. }
  185. override func viewWillAppear(_ animated: Bool) {
  186. super.viewWillAppear(animated)
  187. self.tableView.becomeFirstResponder()
  188. // this will be removed in viewWillDisappear
  189. navigationController?.navigationBar.addGestureRecognizer(navBarTap)
  190. if showCustomNavBar {
  191. updateTitle(chat: dcContext.getChat(chatId: chatId))
  192. }
  193. let nc = NotificationCenter.default
  194. msgChangedObserver = nc.addObserver(
  195. forName: dcNotificationChanged,
  196. object: nil,
  197. queue: OperationQueue.main
  198. ) { [weak self] notification in
  199. guard let self = self else { return }
  200. if let ui = notification.userInfo {
  201. if self.disableWriting {
  202. // always refresh, as we can't check currently
  203. self.refreshMessages()
  204. } else if let id = ui["message_id"] as? Int {
  205. if id > 0 {
  206. self.updateMessage(id)
  207. } else {
  208. // change might be a deletion
  209. self.refreshMessages()
  210. }
  211. }
  212. if self.showCustomNavBar {
  213. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  214. }
  215. }
  216. }
  217. incomingMsgObserver = nc.addObserver(
  218. forName: dcNotificationIncoming,
  219. object: nil, queue: OperationQueue.main
  220. ) { [weak self] notification in
  221. guard let self = self else { return }
  222. if let ui = notification.userInfo {
  223. if self.chatId == ui["chat_id"] as? Int {
  224. if let id = ui["message_id"] as? Int {
  225. if id > 0 {
  226. self.insertMessage(DcMsg(id: id))
  227. }
  228. }
  229. }
  230. }
  231. }
  232. ephemeralTimerModifiedObserver = nc.addObserver(
  233. forName: dcEphemeralTimerModified,
  234. object: nil, queue: OperationQueue.main
  235. ) { [weak self] _ in
  236. guard let self = self else { return }
  237. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  238. }
  239. loadMessages()
  240. if RelayHelper.sharedInstance.isForwarding() {
  241. askToForwardMessage()
  242. }
  243. }
  244. override func viewDidAppear(_ animated: Bool) {
  245. super.viewDidAppear(animated)
  246. AppStateRestorer.shared.storeLastActiveChat(chatId: chatId)
  247. // things that do not affect the chatview
  248. // and are delayed after the view is displayed
  249. DispatchQueue.global(qos: .background).async { [weak self] in
  250. guard let self = self else { return }
  251. self.dcContext.marknoticedChat(chatId: self.chatId)
  252. }
  253. startTimer()
  254. }
  255. override func viewWillDisappear(_ animated: Bool) {
  256. super.viewWillDisappear(animated)
  257. // the navigationController will be used when chatDetail is pushed, so we have to remove that gestureRecognizer
  258. navigationController?.navigationBar.removeGestureRecognizer(navBarTap)
  259. }
  260. override func viewDidDisappear(_ animated: Bool) {
  261. super.viewDidDisappear(animated)
  262. AppStateRestorer.shared.resetLastActiveChat()
  263. saveDraft()
  264. let nc = NotificationCenter.default
  265. if let msgChangedObserver = self.msgChangedObserver {
  266. nc.removeObserver(msgChangedObserver)
  267. }
  268. if let incomingMsgObserver = self.incomingMsgObserver {
  269. nc.removeObserver(incomingMsgObserver)
  270. }
  271. if let ephemeralTimerModifiedObserver = self.ephemeralTimerModifiedObserver {
  272. nc.removeObserver(ephemeralTimerModifiedObserver)
  273. }
  274. audioController.stopAnyOngoingPlaying()
  275. stopTimer()
  276. }
  277. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  278. let lastSectionVisibleBeforeTransition = self.isLastRowVisible()
  279. coordinator.animate(
  280. alongsideTransition: { [weak self] _ in
  281. guard let self = self else { return }
  282. if self.showCustomNavBar {
  283. self.navigationItem.setRightBarButton(self.badgeItem, animated: true)
  284. }
  285. if lastSectionVisibleBeforeTransition {
  286. self.scrollToBottom(animated: false)
  287. }
  288. },
  289. completion: {[weak self] _ in
  290. guard let self = self else { return }
  291. self.updateTitle(chat: self.dcContext.getChat(chatId: self.chatId))
  292. if lastSectionVisibleBeforeTransition {
  293. DispatchQueue.main.async { [weak self] in
  294. self?.tableView.reloadData()
  295. self?.scrollToBottom(animated: false)
  296. }
  297. }
  298. }
  299. )
  300. super.viewWillTransition(to: size, with: coordinator)
  301. }
  302. /// UITableView methods
  303. override func numberOfSections(in tableView: UITableView) -> Int {
  304. return 1
  305. }
  306. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  307. return messageIds.count //viewModel.numberOfRowsIn(section: section)
  308. }
  309. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  310. _ = handleUIMenu()
  311. let id = messageIds[indexPath.row]
  312. let message = DcMsg(id: id)
  313. if message.isInfo {
  314. let cell = tableView.dequeueReusableCell(withIdentifier: "info", for: indexPath) as? InfoMessageCell ?? InfoMessageCell()
  315. cell.update(msg: message)
  316. return cell
  317. }
  318. let cell: BaseMessageCell
  319. if message.type == DC_MSG_IMAGE || message.type == DC_MSG_GIF || message.type == DC_MSG_VIDEO {
  320. cell = tableView.dequeueReusableCell(withIdentifier: "image", for: indexPath) as? ImageTextCell ?? ImageTextCell()
  321. } else if message.type == DC_MSG_FILE {
  322. if message.isSetupMessage {
  323. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  324. message.text = String.localized("autocrypt_asm_click_body")
  325. } else {
  326. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? FileTextCell ?? FileTextCell()
  327. }
  328. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  329. let audioMessageCell: AudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  330. for: indexPath) as? AudioMessageCell ?? AudioMessageCell()
  331. audioController.update(audioMessageCell, with: message.id)
  332. cell = audioMessageCell
  333. } else {
  334. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? TextMessageCell ?? TextMessageCell()
  335. }
  336. cell.baseDelegate = self
  337. cell.update(msg: message,
  338. messageStyle: configureMessageStyle(for: message, at: indexPath),
  339. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  340. isGroup: isGroupChat)
  341. return cell
  342. }
  343. public override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  344. lastContentOffset = scrollView.contentOffset.y
  345. }
  346. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  347. if !decelerate {
  348. markSeenMessagesInVisibleArea()
  349. }
  350. if scrollView.contentOffset.y < lastContentOffset {
  351. if isKeyboardShown {
  352. tableView.endEditing(true)
  353. tableView.becomeFirstResponder()
  354. }
  355. }
  356. lastContentOffset = -1
  357. }
  358. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  359. markSeenMessagesInVisibleArea()
  360. }
  361. private func configureDraftArea(draft: DraftModel) {
  362. quotePreview.configure(draft: draft)
  363. // setStackViewItems recalculates the proper messageInputBar height
  364. messageInputBar.setStackViewItems([quotePreview], forStack: .top, animated: true)
  365. }
  366. override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  367. let action = UIContextualAction(style: .normal, title: nil,
  368. handler: { (_, _, completionHandler) in
  369. let message = DcMsg(id: self.messageIds[indexPath.row])
  370. self.draft.setQuote(quotedMsg: message)
  371. self.configureDraftArea(draft: self.draft)
  372. self.messageInputBar.inputTextView.becomeFirstResponder()
  373. completionHandler(true)
  374. })
  375. if #available(iOS 12.0, *) {
  376. action.image = UIImage(named: traitCollection.userInterfaceStyle == .light ? "ic_reply_black" : "ic_reply")
  377. } else {
  378. action.image = UIImage(named: "ic_reply_black")
  379. }
  380. action.image?.accessibilityTraits = .button
  381. action.image?.accessibilityLabel = String.localized("menu_reply")
  382. action.backgroundColor = DcColors.chatBackgroundColor
  383. let configuration = UISwipeActionsConfiguration(actions: [action])
  384. return configuration
  385. }
  386. func markSeenMessagesInVisibleArea() {
  387. if let indexPaths = tableView.indexPathsForVisibleRows {
  388. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  389. if !visibleMessagesIds.isEmpty {
  390. DispatchQueue.global(qos: .background).async { [weak self] in
  391. self?.dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  392. }
  393. }
  394. }
  395. }
  396. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  397. let messageId = messageIds[indexPath.row]
  398. let message = DcMsg(id: messageId)
  399. if message.isSetupMessage {
  400. didTapAsm(msg: message, orgText: "")
  401. } else if message.type == DC_MSG_FILE ||
  402. message.type == DC_MSG_AUDIO ||
  403. message.type == DC_MSG_VOICE {
  404. showMediaGalleryFor(message: message)
  405. }
  406. _ = handleUIMenu()
  407. }
  408. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  409. return isGroupChat && !message.isFromCurrentSender && !isNextMessageSameSender(currentMessage: message, at: indexPath)
  410. }
  411. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  412. var corners: UIRectCorner = []
  413. if message.isFromCurrentSender { //isFromCurrentSender(message: message) {
  414. corners.formUnion(.topLeft)
  415. corners.formUnion(.bottomLeft)
  416. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  417. corners.formUnion(.topRight)
  418. }
  419. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  420. corners.formUnion(.bottomRight)
  421. }
  422. } else {
  423. corners.formUnion(.topRight)
  424. corners.formUnion(.bottomRight)
  425. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  426. corners.formUnion(.topLeft)
  427. }
  428. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  429. corners.formUnion(.bottomLeft)
  430. }
  431. }
  432. return corners
  433. }
  434. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  435. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  436. }
  437. private func isPreviousMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  438. let previousRow = indexPath.row - 1
  439. if previousRow < 0 {
  440. return false
  441. }
  442. let messageId = messageIds[previousRow]
  443. let previousMessage = DcMsg(id: messageId)
  444. return previousMessage.fromContact.id == currentMessage.fromContact.id
  445. }
  446. private func isNextMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  447. let nextRow = indexPath.row + 1
  448. if nextRow >= messageIds.count {
  449. return false
  450. }
  451. let messageId = messageIds[nextRow]
  452. let nextMessage = DcMsg(id: messageId)
  453. return nextMessage.fromContact.id == currentMessage.fromContact.id
  454. }
  455. private func updateTitle(chat: DcChat) {
  456. let titleView = ChatTitleView()
  457. var subtitle = "ErrSubtitle"
  458. let chatContactIds = chat.contactIds
  459. if chat.isGroup {
  460. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  461. } else if chatContactIds.count >= 1 {
  462. if chat.isDeviceTalk {
  463. subtitle = String.localized("device_talk_subtitle")
  464. } else if chat.isSelfTalk {
  465. subtitle = String.localized("chat_self_talk_subtitle")
  466. } else {
  467. subtitle = DcContact(id: chatContactIds[0]).email
  468. }
  469. }
  470. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  471. navigationItem.titleView = titleView
  472. var rightBarButtonItems = [badgeItem]
  473. if chat.isSendingLocations {
  474. rightBarButtonItems.append(locationStreamingItem)
  475. }
  476. if chat.isMuted {
  477. rightBarButtonItems.append(muteItem)
  478. }
  479. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  480. rightBarButtonItems.append(ephemeralMessageItem)
  481. }
  482. navigationItem.rightBarButtonItems = rightBarButtonItems
  483. }
  484. // TODO: is the delay of one second needed?
  485. @objc
  486. private func refreshMessages() {
  487. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  488. DispatchQueue.main.async { [weak self] in
  489. guard let self = self else { return }
  490. self.messageIds = self.getMessageIds()
  491. self.tableView.reloadData()
  492. if self.isLastRowVisible() {
  493. self.scrollToBottom(animated: true)
  494. }
  495. self.showEmptyStateView(self.messageIds.isEmpty)
  496. }
  497. }
  498. }
  499. private func loadMessages() {
  500. DispatchQueue.global(qos: .userInitiated).async {
  501. DispatchQueue.main.async { [weak self] in
  502. guard let self = self else { return }
  503. let wasLastRowVisible = self.isLastRowVisible()
  504. let wasMessageIdsEmpty = self.messageIds.isEmpty
  505. // update message ids
  506. self.messageIds = self.getMessageIds()
  507. self.tableView.reloadData()
  508. if let msgId = self.highlightedMsg, let msgPosition = self.messageIds.firstIndex(of: msgId) {
  509. self.tableView.scrollToRow(at: IndexPath(row: msgPosition, section: 0), at: .top, animated: false)
  510. self.highlightedMsg = nil
  511. } else if wasMessageIdsEmpty ||
  512. wasLastRowVisible {
  513. self.scrollToBottom(animated: false)
  514. }
  515. self.showEmptyStateView(self.messageIds.isEmpty)
  516. }
  517. }
  518. }
  519. func isLastRowVisible() -> Bool {
  520. guard !messageIds.isEmpty else { return false }
  521. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  522. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  523. }
  524. func scrollToBottom(animated: Bool) {
  525. if !messageIds.isEmpty {
  526. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  527. }
  528. }
  529. private func showEmptyStateView(_ show: Bool) {
  530. if show {
  531. let dcChat = dcContext.getChat(chatId: chatId)
  532. if chatId == DC_CHAT_ID_DEADDROP {
  533. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  534. emptyStateView.text = String.localized("chat_no_contact_requests")
  535. } else {
  536. emptyStateView.text = String.localized("chat_no_messages")
  537. }
  538. } else if dcChat.isGroup {
  539. if dcChat.isUnpromoted {
  540. emptyStateView.text = String.localized("chat_new_group_hint")
  541. } else {
  542. emptyStateView.text = String.localized("chat_no_messages")
  543. }
  544. } else if dcChat.isSelfTalk {
  545. emptyStateView.text = String.localized("saved_messages_explain")
  546. } else if dcChat.isDeviceTalk {
  547. emptyStateView.text = String.localized("device_talk_explain")
  548. } else {
  549. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  550. }
  551. emptyStateView.isHidden = false
  552. } else {
  553. emptyStateView.isHidden = true
  554. }
  555. }
  556. private func getMessageIds() -> [Int] {
  557. return dcContext.getMessageIds(chatId: chatId)
  558. }
  559. @objc private func saveDraft() {
  560. draft.save(context: dcContext)
  561. }
  562. private func configureMessageInputBar() {
  563. messageInputBar.delegate = self
  564. messageInputBar.inputTextView.tintColor = DcColors.primary
  565. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  566. messageInputBar.separatorLine.isHidden = true
  567. messageInputBar.inputTextView.tintColor = DcColors.primary
  568. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  569. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  570. //scrollsToBottomOnKeyboardBeginsEditing = true
  571. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  572. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  573. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  574. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  575. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  576. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  577. messageInputBar.inputTextView.layer.borderWidth = 1.0
  578. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  579. messageInputBar.inputTextView.layer.masksToBounds = true
  580. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  581. configureInputBarItems()
  582. }
  583. private func configureInputBarItems() {
  584. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  585. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  586. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  587. messageInputBar.sendButton.image = sendButtonImage
  588. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  589. messageInputBar.sendButton.accessibilityTraits = .button
  590. messageInputBar.sendButton.title = nil
  591. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  592. messageInputBar.sendButton.layer.cornerRadius = 20
  593. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  594. // this adds a padding between textinputfield and send button
  595. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  596. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  597. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  598. let leftItems = [
  599. InputBarButtonItem()
  600. .configure {
  601. $0.spacing = .fixed(0)
  602. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  603. $0.image = clipperIcon
  604. $0.tintColor = DcColors.primary
  605. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  606. $0.accessibilityLabel = String.localized("menu_add_attachment")
  607. $0.accessibilityTraits = .button
  608. }.onSelected {
  609. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  610. }.onDeselected {
  611. $0.tintColor = DcColors.primary
  612. }.onTouchUpInside { [weak self] _ in
  613. self?.clipperButtonPressed()
  614. }
  615. ]
  616. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  617. // This just adds some more flare
  618. messageInputBar.sendButton
  619. .onEnabled { item in
  620. UIView.animate(withDuration: 0.3, animations: {
  621. item.backgroundColor = DcColors.primary
  622. })
  623. }.onDisabled { item in
  624. UIView.animate(withDuration: 0.3, animations: {
  625. item.backgroundColor = DcColors.colorDisabled
  626. })
  627. }
  628. }
  629. @objc private func chatProfilePressed() {
  630. if chatId != DC_CHAT_ID_DEADDROP {
  631. showChatDetail(chatId: chatId)
  632. }
  633. }
  634. @objc private func clipperButtonPressed() {
  635. showClipperOptions()
  636. }
  637. private func showClipperOptions() {
  638. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  639. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  640. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  641. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  642. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  643. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  644. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  645. style: isLocationStreaming ? .destructive : .default,
  646. handler: locationStreamingButtonPressed(_:))
  647. alert.addAction(cameraAction)
  648. alert.addAction(galleryAction)
  649. alert.addAction(documentAction)
  650. alert.addAction(voiceMessageAction)
  651. if UserDefaults.standard.bool(forKey: "location_streaming") {
  652. alert.addAction(locationStreamingAction)
  653. }
  654. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  655. self.present(alert, animated: true, completion: {
  656. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  657. // but this hack does the trick
  658. if UIAccessibility.isVoiceOverRunning {
  659. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  660. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  661. }
  662. }
  663. })
  664. }
  665. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  666. let alert = UIAlertController(title: title,
  667. message: nil,
  668. preferredStyle: .safeActionSheet)
  669. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  670. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  671. self.dismiss(animated: true, completion: nil)
  672. }))
  673. present(alert, animated: true, completion: nil)
  674. }
  675. private func askToChatWith(email: String) {
  676. let contactId = self.dcContext.createContact(name: "", email: email)
  677. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  678. self.dismiss(animated: true, completion: nil)
  679. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  680. self.showChat(chatId: chatId)
  681. } else {
  682. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  683. actionTitle: String.localized("start_chat"),
  684. actionHandler: { _ in
  685. self.dismiss(animated: true, completion: nil)
  686. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  687. self.showChat(chatId: chatId)})
  688. }
  689. }
  690. private func askToDeleteMessage(id: Int) {
  691. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  692. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  693. actionHandler: { _ in
  694. self.dcContext.deleteMessage(msgId: id)
  695. self.dismiss(animated: true, completion: nil)})
  696. }
  697. private func askToForwardMessage() {
  698. let chat = dcContext.getChat(chatId: self.chatId)
  699. if chat.isSelfTalk {
  700. RelayHelper.sharedInstance.forward(to: self.chatId)
  701. } else {
  702. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  703. actionTitle: String.localized("menu_forward"),
  704. actionHandler: { _ in
  705. RelayHelper.sharedInstance.forward(to: self.chatId)
  706. self.dismiss(animated: true, completion: nil)},
  707. cancelHandler: { _ in
  708. self.dismiss(animated: false, completion: nil)
  709. self.navigationController?.popViewController(animated: true)})
  710. }
  711. }
  712. // MARK: - coordinator
  713. private func showChatDetail(chatId: Int) {
  714. let chat = dcContext.getChat(chatId: chatId)
  715. switch chat.chatType {
  716. case .SINGLE:
  717. if let contactId = chat.contactIds.first {
  718. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  719. navigationController?.pushViewController(contactDetailController, animated: true)
  720. }
  721. case .GROUP, .VERIFIEDGROUP:
  722. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  723. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  724. }
  725. }
  726. func showChat(chatId: Int) {
  727. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  728. navigationController?.popToRootViewController(animated: false)
  729. appDelegate.appCoordinator.showChat(chatId: chatId)
  730. }
  731. }
  732. private func showDocumentLibrary() {
  733. mediaPicker?.showDocumentLibrary()
  734. }
  735. private func showVoiceMessageRecorder() {
  736. mediaPicker?.showVoiceRecorder()
  737. }
  738. private func showCameraViewController() {
  739. mediaPicker?.showCamera()
  740. }
  741. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  742. mediaPicker?.showPhotoVideoLibrary()
  743. }
  744. private func showMediaGallery(currentIndex: Int, msgIds: [Int]) {
  745. let betterPreviewController = PreviewController(type: .multi(msgIds, currentIndex))
  746. let nav = UINavigationController(rootViewController: betterPreviewController)
  747. nav.modalPresentationStyle = .fullScreen
  748. navigationController?.present(nav, animated: true)
  749. }
  750. private func documentActionPressed(_ action: UIAlertAction) {
  751. showDocumentLibrary()
  752. }
  753. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  754. showVoiceMessageRecorder()
  755. }
  756. private func cameraButtonPressed(_ action: UIAlertAction) {
  757. showCameraViewController()
  758. }
  759. private func galleryButtonPressed(_ action: UIAlertAction) {
  760. showPhotoVideoLibrary(delegate: self)
  761. }
  762. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  763. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  764. if isLocationStreaming {
  765. locationStreamingFor(seconds: 0)
  766. } else {
  767. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  768. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  769. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  770. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  771. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  772. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  773. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  774. self.present(alert, animated: true, completion: nil)
  775. }
  776. }
  777. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  778. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  779. self.locationStreamingFor(seconds: duration)
  780. })
  781. alert.addAction(action)
  782. }
  783. private func locationStreamingFor(seconds: Int) {
  784. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  785. return
  786. }
  787. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  788. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  789. }
  790. func updateMessage(_ messageId: Int) {
  791. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  792. DispatchQueue.global(qos: .background).async { [weak self] in
  793. self?.dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  794. }
  795. let wasLastSectionVisible = self.isLastRowVisible()
  796. tableView.reloadData()
  797. if wasLastSectionVisible {
  798. self.scrollToBottom(animated: true)
  799. }
  800. } else {
  801. let msg = DcMsg(id: messageId)
  802. if msg.chatId == chatId {
  803. insertMessage(msg)
  804. }
  805. }
  806. }
  807. func insertMessage(_ message: DcMsg) {
  808. DispatchQueue.global(qos: .background).async { [weak self] in
  809. self?.dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  810. }
  811. let wasLastSectionVisible = isLastRowVisible()
  812. messageIds.append(message.id)
  813. emptyStateView.isHidden = true
  814. tableView.reloadData()
  815. if wasLastSectionVisible || message.isFromCurrentSender {
  816. scrollToBottom(animated: true)
  817. }
  818. }
  819. private func sendTextMessage() {
  820. DispatchQueue.global().async {
  821. if let draftText = self.draft.draftText {
  822. let message = DcMsg(viewType: DC_MSG_TEXT)
  823. message.text = draftText.trimmingCharacters(in: .whitespacesAndNewlines)
  824. if let quoteMessage = self.draft.quoteMessage {
  825. message.quoteMessage = quoteMessage
  826. }
  827. message.sendInChat(id: self.chatId)
  828. DispatchQueue.main.async {
  829. self.quotePreview.cancel()
  830. }
  831. }
  832. }
  833. }
  834. private func sendImage(_ image: UIImage, message: String? = nil) {
  835. DispatchQueue.global().async {
  836. if let path = DcUtils.saveImage(image: image) {
  837. self.sendImageMessage(viewType: DC_MSG_IMAGE, image: image, filePath: path)
  838. }
  839. }
  840. }
  841. private func sendAnimatedImage(url: NSURL) {
  842. if let path = url.path {
  843. let result = SDAnimatedImage(contentsOfFile: path)
  844. if let result = result,
  845. let animatedImageData = result.animatedImageData,
  846. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  847. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  848. }
  849. }
  850. }
  851. private func sendImageMessage(viewType: Int32, image: UIImage, filePath: String, message: String? = nil) {
  852. let msg = DcMsg(viewType: viewType)
  853. msg.setFile(filepath: filePath)
  854. msg.text = (message ?? "").isEmpty ? nil : message
  855. msg.sendInChat(id: self.chatId)
  856. }
  857. private func sendDocumentMessage(url: NSURL) {
  858. DispatchQueue.global().async {
  859. let msg = DcMsg(viewType: DC_MSG_FILE)
  860. msg.setFile(filepath: url.relativePath, mimeType: nil)
  861. msg.sendInChat(id: self.chatId)
  862. }
  863. }
  864. private func sendVoiceMessage(url: NSURL) {
  865. DispatchQueue.global().async {
  866. let msg = DcMsg(viewType: DC_MSG_VOICE)
  867. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  868. msg.sendInChat(id: self.chatId)
  869. }
  870. }
  871. private func sendVideo(url: NSURL) {
  872. DispatchQueue.global().async {
  873. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  874. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  875. msg.sendInChat(id: self.chatId)
  876. }
  877. }
  878. private func sendImage(url: NSURL) {
  879. if url.pathExtension == "gif" {
  880. sendAnimatedImage(url: url)
  881. } else if let data = try? Data(contentsOf: url as URL),
  882. let image = UIImage(data: data) {
  883. sendImage(image)
  884. }
  885. }
  886. // MARK: - Context menu
  887. private func prepareContextMenu() {
  888. UIMenuController.shared.menuItems = [
  889. UIMenuItem(title: String.localized("info"), action: #selector(BaseMessageCell.messageInfo)),
  890. UIMenuItem(title: String.localized("delete"), action: #selector(BaseMessageCell.messageDelete)),
  891. UIMenuItem(title: String.localized("forward"), action: #selector(BaseMessageCell.messageForward))
  892. ]
  893. UIMenuController.shared.update()
  894. }
  895. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  896. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  897. }
  898. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  899. return action == #selector(UIResponderStandardEditActions.copy(_:))
  900. || action == #selector(BaseMessageCell.messageInfo)
  901. || action == #selector(BaseMessageCell.messageDelete)
  902. || action == #selector(BaseMessageCell.messageForward)
  903. }
  904. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  905. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  906. switch action {
  907. case #selector(copy(_:)):
  908. let id = messageIds[indexPath.row]
  909. let msg = DcMsg(id: id)
  910. let pasteboard = UIPasteboard.general
  911. if msg.type == DC_MSG_TEXT {
  912. pasteboard.string = msg.text
  913. } else {
  914. pasteboard.string = msg.summary(chars: 10000000)
  915. }
  916. case #selector(BaseMessageCell.messageInfo(_:)):
  917. let msg = DcMsg(id: messageIds[indexPath.row])
  918. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  919. if let ctrl = navigationController {
  920. ctrl.pushViewController(msgViewController, animated: true)
  921. }
  922. case #selector(BaseMessageCell.messageDelete(_:)):
  923. let msg = DcMsg(id: messageIds[indexPath.row])
  924. askToDeleteMessage(id: msg.id)
  925. case #selector(BaseMessageCell.messageForward(_:)):
  926. let msg = DcMsg(id: messageIds[indexPath.row])
  927. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  928. navigationController?.popViewController(animated: true)
  929. default:
  930. break
  931. }
  932. }
  933. func showMediaGalleryFor(indexPath: IndexPath) {
  934. let messageId = messageIds[indexPath.row]
  935. let message = DcMsg(id: messageId)
  936. showMediaGalleryFor(message: message)
  937. }
  938. func showMediaGalleryFor(message: DcMsg) {
  939. let msgIds = dcContext.getChatMedia(chatId: chatId, messageType: Int32(message.type), messageType2: 0, messageType3: 0)
  940. let index = msgIds.firstIndex(of: message.id) ?? 0
  941. showMediaGallery(currentIndex: index, msgIds: msgIds)
  942. }
  943. private func didTapAsm(msg: DcMsg, orgText: String) {
  944. let inputDlg = UIAlertController(
  945. title: String.localized("autocrypt_continue_transfer_title"),
  946. message: String.localized("autocrypt_continue_transfer_please_enter_code"),
  947. preferredStyle: .alert)
  948. inputDlg.addTextField(configurationHandler: { (textField) in
  949. textField.placeholder = msg.setupCodeBegin + ".."
  950. textField.text = orgText
  951. textField.keyboardType = UIKeyboardType.numbersAndPunctuation // allows entering spaces; decimalPad would require a mask to keep things readable
  952. })
  953. inputDlg.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  954. let okAction = UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  955. let textField = inputDlg.textFields![0]
  956. let modText = textField.text ?? ""
  957. let success = self.dcContext.continueKeyTransfer(msgId: msg.id, setupCode: modText)
  958. let alert = UIAlertController(
  959. title: String.localized("autocrypt_continue_transfer_title"),
  960. message: String.localized(success ? "autocrypt_continue_transfer_succeeded" : "autocrypt_bad_setup_code"),
  961. preferredStyle: .alert)
  962. if success {
  963. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  964. } else {
  965. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  966. let retryAction = UIAlertAction(title: String.localized("autocrypt_continue_transfer_retry"), style: .default, handler: { _ in
  967. self.didTapAsm(msg: msg, orgText: modText)
  968. })
  969. alert.addAction(retryAction)
  970. alert.preferredAction = retryAction
  971. }
  972. self.navigationController?.present(alert, animated: true, completion: nil)
  973. })
  974. inputDlg.addAction(okAction)
  975. inputDlg.preferredAction = okAction // without setting preferredAction, cancel become shown *bold* as the preferred action
  976. navigationController?.present(inputDlg, animated: true, completion: nil)
  977. }
  978. func handleUIMenu() -> Bool {
  979. if UIMenuController.shared.isMenuVisible {
  980. UIMenuController.shared.setMenuVisible(false, animated: true)
  981. return true
  982. }
  983. return false
  984. }
  985. }
  986. // MARK: - BaseMessageCellDelegate
  987. extension ChatViewController: BaseMessageCellDelegate {
  988. @objc func quoteTapped(indexPath: IndexPath) {
  989. _ = handleUIMenu()
  990. let msg = DcMsg(id: messageIds[indexPath.row])
  991. if let quoteMsg = msg.quoteMessage,
  992. let index = messageIds.firstIndex(of: quoteMsg.id) {
  993. let indexPath = IndexPath(row: index, section: 0)
  994. tableView.scrollToRow(at: indexPath, at: .top, animated: true)
  995. }
  996. }
  997. @objc func textTapped(indexPath: IndexPath) {
  998. if handleUIMenu() { return }
  999. let message = DcMsg(id: messageIds[indexPath.row])
  1000. if message.isSetupMessage {
  1001. didTapAsm(msg: message, orgText: "")
  1002. }
  1003. }
  1004. @objc func phoneNumberTapped(number: String) {
  1005. if handleUIMenu() { return }
  1006. logger.debug("phone number tapped \(number)")
  1007. }
  1008. @objc func commandTapped(command: String) {
  1009. if handleUIMenu() { return }
  1010. logger.debug("command tapped \(command)")
  1011. }
  1012. @objc func urlTapped(url: URL) {
  1013. if handleUIMenu() { return }
  1014. if Utils.isEmail(url: url) {
  1015. logger.debug("tapped on contact")
  1016. let email = Utils.getEmailFrom(url)
  1017. self.askToChatWith(email: email)
  1018. ///TODO: implement handling
  1019. } else {
  1020. UIApplication.shared.open(url)
  1021. }
  1022. }
  1023. @objc func imageTapped(indexPath: IndexPath) {
  1024. if handleUIMenu() { return }
  1025. showMediaGalleryFor(indexPath: indexPath)
  1026. }
  1027. @objc func avatarTapped(indexPath: IndexPath) {
  1028. let message = DcMsg(id: messageIds[indexPath.row])
  1029. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  1030. navigationController?.pushViewController(contactDetailController, animated: true)
  1031. }
  1032. }
  1033. // MARK: - MediaPickerDelegate
  1034. extension ChatViewController: MediaPickerDelegate {
  1035. func onVideoSelected(url: NSURL) {
  1036. sendVideo(url: url)
  1037. }
  1038. func onImageSelected(url: NSURL) {
  1039. sendImage(url: url)
  1040. }
  1041. func onImageSelected(image: UIImage) {
  1042. sendImage(image)
  1043. }
  1044. func onVoiceMessageRecorded(url: NSURL) {
  1045. sendVoiceMessage(url: url)
  1046. }
  1047. func onDocumentSelected(url: NSURL) {
  1048. sendDocumentMessage(url: url)
  1049. }
  1050. }
  1051. // MARK: - MessageInputBarDelegate
  1052. extension ChatViewController: InputBarAccessoryViewDelegate {
  1053. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  1054. if inputBar.inputTextView.images.isEmpty {
  1055. self.sendTextMessage()
  1056. } else {
  1057. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  1058. .trimmingCharacters(in: .whitespacesAndNewlines)
  1059. // only 1 attachment allowed for now, thus it takes the first one
  1060. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  1061. }
  1062. inputBar.inputTextView.text = String()
  1063. inputBar.inputTextView.attributedText = nil
  1064. }
  1065. func inputBar(_ inputBar: InputBarAccessoryView, textViewTextDidChangeTo text: String) {
  1066. draft.draftText = text
  1067. }
  1068. }
  1069. extension ChatViewController: QuotePreviewDelegate {
  1070. func onCancel() {
  1071. draft.setQuote(quotedMsg: nil)
  1072. configureDraftArea(draft: draft)
  1073. }
  1074. }