ChatViewControllerNew.swift 47 KB

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