ChatViewControllerNew.swift 42 KB

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