ChatViewControllerNew.swift 44 KB

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