ChatViewControllerNew.swift 47 KB

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