ChatViewControllerNew.swift 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077
  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. cell = tableView.dequeueReusableCell(withIdentifier: "file", for: indexPath) as? NewFileTextCell ?? NewFileTextCell()
  304. } else if message.type == DC_MSG_AUDIO || message.type == DC_MSG_VOICE {
  305. let audioMessageCell: NewAudioMessageCell = tableView.dequeueReusableCell(withIdentifier: "audio",
  306. for: indexPath) as? NewAudioMessageCell ?? NewAudioMessageCell()
  307. audioController.update(audioMessageCell, with: message.id)
  308. cell = audioMessageCell
  309. } else {
  310. cell = tableView.dequeueReusableCell(withIdentifier: "text", for: indexPath) as? NewTextMessageCell ?? NewTextMessageCell()
  311. }
  312. cell.baseDelegate = self
  313. cell.update(msg: message,
  314. messageStyle: configureMessageStyle(for: message, at: indexPath),
  315. isAvatarVisible: configureAvatarVisibility(for: message, at: indexPath),
  316. isGroup: isGroupChat)
  317. return cell
  318. }
  319. public override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
  320. lastContentOffset = scrollView.contentOffset.y
  321. }
  322. public override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
  323. if !decelerate {
  324. markSeenMessagesInVisibleArea()
  325. }
  326. if scrollView.contentOffset.y < lastContentOffset {
  327. if isKeyboardShown {
  328. tableView.endEditing(true)
  329. tableView.becomeFirstResponder()
  330. }
  331. }
  332. lastContentOffset = -1
  333. }
  334. public override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
  335. markSeenMessagesInVisibleArea()
  336. }
  337. func markSeenMessagesInVisibleArea() {
  338. if let indexPaths = tableView.indexPathsForVisibleRows {
  339. let visibleMessagesIds = indexPaths.map { UInt32(messageIds[$0.row]) }
  340. if !visibleMessagesIds.isEmpty {
  341. dcContext.markSeenMessages(messageIds: visibleMessagesIds)
  342. }
  343. }
  344. }
  345. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  346. let messageId = messageIds[indexPath.row]
  347. let message = DcMsg(id: messageId)
  348. if message.type == DC_MSG_FILE ||
  349. message.type == DC_MSG_AUDIO ||
  350. message.type == DC_MSG_VOICE {
  351. showMediaGalleryFor(message: message)
  352. }
  353. UIMenuController.shared.setMenuVisible(false, animated: true)
  354. }
  355. func configureAvatarVisibility(for message: DcMsg, at indexPath: IndexPath) -> Bool {
  356. return isGroupChat && !message.isFromCurrentSender && !isNextMessageSameSender(currentMessage: message, at: indexPath)
  357. }
  358. func configureMessageStyle(for message: DcMsg, at indexPath: IndexPath) -> UIRectCorner {
  359. var corners: UIRectCorner = []
  360. if message.isFromCurrentSender { //isFromCurrentSender(message: message) {
  361. corners.formUnion(.topLeft)
  362. corners.formUnion(.bottomLeft)
  363. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  364. corners.formUnion(.topRight)
  365. }
  366. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  367. corners.formUnion(.bottomRight)
  368. }
  369. } else {
  370. corners.formUnion(.topRight)
  371. corners.formUnion(.bottomRight)
  372. if !isPreviousMessageSameSender(currentMessage: message, at: indexPath) {
  373. corners.formUnion(.topLeft)
  374. }
  375. if !isNextMessageSameSender(currentMessage: message, at: indexPath) {
  376. corners.formUnion(.bottomLeft)
  377. }
  378. }
  379. return corners
  380. }
  381. private func getBackgroundColor(for currentMessage: DcMsg) -> UIColor {
  382. return currentMessage.isFromCurrentSender ? DcColors.messagePrimaryColor : DcColors.messageSecondaryColor
  383. }
  384. private func isPreviousMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  385. let previousRow = indexPath.row - 1
  386. if previousRow < 0 {
  387. return false
  388. }
  389. let messageId = messageIds[previousRow]
  390. let previousMessage = DcMsg(id: messageId)
  391. return previousMessage.fromContact.id == currentMessage.fromContact.id
  392. }
  393. private func isNextMessageSameSender(currentMessage: DcMsg, at indexPath: IndexPath) -> Bool {
  394. let nextRow = indexPath.row + 1
  395. if nextRow >= messageIds.count {
  396. return false
  397. }
  398. let messageId = messageIds[nextRow]
  399. let nextMessage = DcMsg(id: messageId)
  400. return nextMessage.fromContact.id == currentMessage.fromContact.id
  401. }
  402. private func updateTitle(chat: DcChat) {
  403. let titleView = ChatTitleView()
  404. var subtitle = "ErrSubtitle"
  405. let chatContactIds = chat.contactIds
  406. if chat.isGroup {
  407. subtitle = String.localized(stringID: "n_members", count: chatContactIds.count)
  408. } else if chatContactIds.count >= 1 {
  409. if chat.isDeviceTalk {
  410. subtitle = String.localized("device_talk_subtitle")
  411. } else if chat.isSelfTalk {
  412. subtitle = String.localized("chat_self_talk_subtitle")
  413. } else {
  414. subtitle = DcContact(id: chatContactIds[0]).email
  415. }
  416. }
  417. titleView.updateTitleView(title: chat.name, subtitle: subtitle)
  418. navigationItem.titleView = titleView
  419. var rightBarButtonItems = [badgeItem]
  420. if chat.isSendingLocations {
  421. rightBarButtonItems.append(locationStreamingItem)
  422. }
  423. if chat.isMuted {
  424. rightBarButtonItems.append(muteItem)
  425. }
  426. if dcContext.getChatEphemeralTimer(chatId: chat.id) > 0 {
  427. rightBarButtonItems.append(ephemeralMessageItem)
  428. }
  429. navigationItem.rightBarButtonItems = rightBarButtonItems
  430. }
  431. // TODO: is the delay of one second needed?
  432. @objc
  433. private func refreshMessages() {
  434. DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + 1) {
  435. DispatchQueue.main.async { [weak self] in
  436. guard let self = self else { return }
  437. self.messageIds = self.getMessageIds()
  438. self.tableView.reloadData()
  439. if self.isLastRowVisible() {
  440. self.scrollToBottom(animated: true)
  441. }
  442. self.showEmptyStateView(self.messageIds.isEmpty)
  443. }
  444. }
  445. }
  446. private func loadMessages() {
  447. DispatchQueue.global(qos: .userInitiated).async {
  448. DispatchQueue.main.async { [weak self] in
  449. guard let self = self else { return }
  450. let wasLastRowVisible = self.isLastRowVisible()
  451. let wasMessageIdsEmpty = self.messageIds.isEmpty
  452. // update message ids
  453. self.messageIds = self.getMessageIds()
  454. self.tableView.reloadData()
  455. if wasMessageIdsEmpty ||
  456. wasLastRowVisible {
  457. self.scrollToBottom(animated: false)
  458. }
  459. self.showEmptyStateView(self.messageIds.isEmpty)
  460. }
  461. }
  462. }
  463. func isLastRowVisible() -> Bool {
  464. guard !messageIds.isEmpty else { return false }
  465. let lastIndexPath = IndexPath(item: messageIds.count - 1, section: 0)
  466. return tableView.indexPathsForVisibleRows?.contains(lastIndexPath) ?? false
  467. }
  468. func scrollToBottom(animated: Bool) {
  469. if !messageIds.isEmpty {
  470. self.tableView.scrollToRow(at: IndexPath(row: self.messageIds.count - 1, section: 0), at: .bottom, animated: animated)
  471. }
  472. }
  473. private func showEmptyStateView(_ show: Bool) {
  474. if show {
  475. let dcChat = dcContext.getChat(chatId: chatId)
  476. if chatId == DC_CHAT_ID_DEADDROP {
  477. if dcContext.showEmails != DC_SHOW_EMAILS_ALL {
  478. emptyStateView.text = String.localized("chat_no_contact_requests")
  479. } else {
  480. emptyStateView.text = String.localized("chat_no_messages")
  481. }
  482. } else if dcChat.isGroup {
  483. if dcChat.isUnpromoted {
  484. emptyStateView.text = String.localized("chat_new_group_hint")
  485. } else {
  486. emptyStateView.text = String.localized("chat_no_messages")
  487. }
  488. } else if dcChat.isSelfTalk {
  489. emptyStateView.text = String.localized("saved_messages_explain")
  490. } else if dcChat.isDeviceTalk {
  491. emptyStateView.text = String.localized("device_talk_explain")
  492. } else {
  493. emptyStateView.text = String.localizedStringWithFormat(String.localized("chat_no_messages_hint"), dcChat.name, dcChat.name)
  494. }
  495. emptyStateView.isHidden = false
  496. } else {
  497. emptyStateView.isHidden = true
  498. }
  499. }
  500. private var textDraft: String? {
  501. return dcContext.getDraft(chatId: chatId)
  502. }
  503. private func getMessageIds() -> [Int] {
  504. return dcContext.getMessageIds(chatId: chatId)
  505. }
  506. @objc private func setTextDraft() {
  507. if let text = self.messageInputBar.inputTextView.text {
  508. dcContext.setDraft(chatId: chatId, draftText: text)
  509. }
  510. }
  511. private func configureMessageInputBar() {
  512. messageInputBar.delegate = self
  513. messageInputBar.inputTextView.tintColor = DcColors.primary
  514. messageInputBar.inputTextView.placeholder = String.localized("chat_input_placeholder")
  515. messageInputBar.separatorLine.isHidden = true
  516. messageInputBar.inputTextView.tintColor = DcColors.primary
  517. messageInputBar.inputTextView.textColor = DcColors.defaultTextColor
  518. messageInputBar.backgroundView.backgroundColor = DcColors.chatBackgroundColor
  519. //scrollsToBottomOnKeyboardBeginsEditing = true
  520. messageInputBar.inputTextView.backgroundColor = DcColors.inputFieldColor
  521. messageInputBar.inputTextView.placeholderTextColor = DcColors.placeholderColor
  522. messageInputBar.inputTextView.textContainerInset = UIEdgeInsets(top: 8, left: 16, bottom: 8, right: 38)
  523. messageInputBar.inputTextView.placeholderLabelInsets = UIEdgeInsets(top: 8, left: 20, bottom: 8, right: 38)
  524. messageInputBar.inputTextView.layer.borderColor = UIColor.themeColor(light: UIColor(red: 200 / 255, green: 200 / 255, blue: 200 / 255, alpha: 1),
  525. dark: UIColor(red: 55 / 255, green: 55/255, blue: 55/255, alpha: 1)).cgColor
  526. messageInputBar.inputTextView.layer.borderWidth = 1.0
  527. messageInputBar.inputTextView.layer.cornerRadius = 13.0
  528. messageInputBar.inputTextView.layer.masksToBounds = true
  529. messageInputBar.inputTextView.scrollIndicatorInsets = UIEdgeInsets(top: 8, left: 0, bottom: 8, right: 0)
  530. configureInputBarItems()
  531. }
  532. private func configureInputBarItems() {
  533. messageInputBar.setLeftStackViewWidthConstant(to: 40, animated: false)
  534. messageInputBar.setRightStackViewWidthConstant(to: 40, animated: false)
  535. let sendButtonImage = UIImage(named: "paper_plane")?.withRenderingMode(.alwaysTemplate)
  536. messageInputBar.sendButton.image = sendButtonImage
  537. messageInputBar.sendButton.accessibilityLabel = String.localized("menu_send")
  538. messageInputBar.sendButton.accessibilityTraits = .button
  539. messageInputBar.sendButton.title = nil
  540. messageInputBar.sendButton.tintColor = UIColor(white: 1, alpha: 1)
  541. messageInputBar.sendButton.layer.cornerRadius = 20
  542. messageInputBar.middleContentViewPadding = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 10)
  543. // this adds a padding between textinputfield and send button
  544. messageInputBar.sendButton.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
  545. messageInputBar.sendButton.setSize(CGSize(width: 40, height: 40), animated: false)
  546. messageInputBar.padding = UIEdgeInsets(top: 6, left: 6, bottom: 6, right: 12)
  547. let leftItems = [
  548. InputBarButtonItem()
  549. .configure {
  550. $0.spacing = .fixed(0)
  551. let clipperIcon = #imageLiteral(resourceName: "ic_attach_file_36pt").withRenderingMode(.alwaysTemplate)
  552. $0.image = clipperIcon
  553. $0.tintColor = DcColors.primary
  554. $0.setSize(CGSize(width: 40, height: 40), animated: false)
  555. $0.accessibilityLabel = String.localized("menu_add_attachment")
  556. $0.accessibilityTraits = .button
  557. }.onSelected {
  558. $0.tintColor = UIColor.themeColor(light: .lightGray, dark: .darkGray)
  559. }.onDeselected {
  560. $0.tintColor = DcColors.primary
  561. }.onTouchUpInside { [weak self] _ in
  562. self?.clipperButtonPressed()
  563. }
  564. ]
  565. messageInputBar.setStackViewItems(leftItems, forStack: .left, animated: false)
  566. // This just adds some more flare
  567. messageInputBar.sendButton
  568. .onEnabled { item in
  569. UIView.animate(withDuration: 0.3, animations: {
  570. item.backgroundColor = DcColors.primary
  571. })
  572. }.onDisabled { item in
  573. UIView.animate(withDuration: 0.3, animations: {
  574. item.backgroundColor = DcColors.colorDisabled
  575. })
  576. }
  577. }
  578. @objc private func chatProfilePressed() {
  579. if chatId != DC_CHAT_ID_DEADDROP {
  580. showChatDetail(chatId: chatId)
  581. }
  582. }
  583. @objc private func clipperButtonPressed() {
  584. showClipperOptions()
  585. }
  586. private func showClipperOptions() {
  587. let alert = UIAlertController(title: nil, message: nil, preferredStyle: .safeActionSheet)
  588. let galleryAction = PhotoPickerAlertAction(title: String.localized("gallery"), style: .default, handler: galleryButtonPressed(_:))
  589. let cameraAction = PhotoPickerAlertAction(title: String.localized("camera"), style: .default, handler: cameraButtonPressed(_:))
  590. let documentAction = UIAlertAction(title: String.localized("files"), style: .default, handler: documentActionPressed(_:))
  591. let voiceMessageAction = UIAlertAction(title: String.localized("voice_message"), style: .default, handler: voiceMessageButtonPressed(_:))
  592. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  593. let locationStreamingAction = UIAlertAction(title: isLocationStreaming ? String.localized("stop_sharing_location") : String.localized("location"),
  594. style: isLocationStreaming ? .destructive : .default,
  595. handler: locationStreamingButtonPressed(_:))
  596. alert.addAction(cameraAction)
  597. alert.addAction(galleryAction)
  598. alert.addAction(documentAction)
  599. alert.addAction(voiceMessageAction)
  600. if UserDefaults.standard.bool(forKey: "location_streaming") {
  601. alert.addAction(locationStreamingAction)
  602. }
  603. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  604. self.present(alert, animated: true, completion: {
  605. // unfortunately, voiceMessageAction.accessibilityHint does not work,
  606. // but this hack does the trick
  607. if UIAccessibility.isVoiceOverRunning {
  608. if let view = voiceMessageAction.value(forKey: "__representer") as? UIView {
  609. view.accessibilityHint = String.localized("a11y_voice_message_hint_ios")
  610. }
  611. }
  612. })
  613. }
  614. private func confirmationAlert(title: String, actionTitle: String, actionStyle: UIAlertAction.Style = .default, actionHandler: @escaping ((UIAlertAction) -> Void), cancelHandler: ((UIAlertAction) -> Void)? = nil) {
  615. let alert = UIAlertController(title: title,
  616. message: nil,
  617. preferredStyle: .safeActionSheet)
  618. alert.addAction(UIAlertAction(title: actionTitle, style: actionStyle, handler: actionHandler))
  619. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: cancelHandler ?? { _ in
  620. self.dismiss(animated: true, completion: nil)
  621. }))
  622. present(alert, animated: true, completion: nil)
  623. }
  624. private func askToChatWith(email: String) {
  625. let contactId = self.dcContext.createContact(name: "", email: email)
  626. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  627. self.dismiss(animated: true, completion: nil)
  628. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  629. self.showChat(chatId: chatId)
  630. } else {
  631. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  632. actionTitle: String.localized("start_chat"),
  633. actionHandler: { _ in
  634. self.dismiss(animated: true, completion: nil)
  635. let chatId = self.dcContext.createChatByContactId(contactId: contactId)
  636. self.showChat(chatId: chatId)})
  637. }
  638. }
  639. private func askToDeleteMessage(id: Int) {
  640. let title = String.localized(stringID: "ask_delete_messages", count: 1)
  641. confirmationAlert(title: title, actionTitle: String.localized("delete"), actionStyle: .destructive,
  642. actionHandler: { _ in
  643. self.dcContext.deleteMessage(msgId: id)
  644. self.dismiss(animated: true, completion: nil)})
  645. }
  646. private func askToForwardMessage() {
  647. let chat = dcContext.getChat(chatId: self.chatId)
  648. if chat.isSelfTalk {
  649. RelayHelper.sharedInstance.forward(to: self.chatId)
  650. } else {
  651. confirmationAlert(title: String.localizedStringWithFormat(String.localized("ask_forward"), chat.name),
  652. actionTitle: String.localized("menu_forward"),
  653. actionHandler: { _ in
  654. RelayHelper.sharedInstance.forward(to: self.chatId)
  655. self.dismiss(animated: true, completion: nil)},
  656. cancelHandler: { _ in
  657. self.dismiss(animated: false, completion: nil)
  658. self.navigationController?.popViewController(animated: true)})
  659. }
  660. }
  661. // MARK: - coordinator
  662. private func showChatDetail(chatId: Int) {
  663. let chat = dcContext.getChat(chatId: chatId)
  664. switch chat.chatType {
  665. case .SINGLE:
  666. if let contactId = chat.contactIds.first {
  667. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  668. navigationController?.pushViewController(contactDetailController, animated: true)
  669. }
  670. case .GROUP, .VERIFIEDGROUP:
  671. let groupChatDetailViewController = GroupChatDetailViewController(chatId: chatId, dcContext: dcContext)
  672. navigationController?.pushViewController(groupChatDetailViewController, animated: true)
  673. }
  674. }
  675. private func showContactDetail(of contactId: Int, in chatOfType: ChatType, chatId: Int?) {
  676. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  677. navigationController?.pushViewController(contactDetailController, animated: true)
  678. }
  679. func showChat(chatId: Int) {
  680. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  681. navigationController?.popToRootViewController(animated: false)
  682. appDelegate.appCoordinator.showChat(chatId: chatId)
  683. }
  684. }
  685. private func showDocumentLibrary() {
  686. mediaPicker?.showDocumentLibrary()
  687. }
  688. private func showVoiceMessageRecorder() {
  689. mediaPicker?.showVoiceRecorder()
  690. }
  691. private func showCameraViewController() {
  692. mediaPicker?.showCamera()
  693. }
  694. private func showPhotoVideoLibrary(delegate: MediaPickerDelegate) {
  695. mediaPicker?.showPhotoVideoLibrary()
  696. }
  697. private func showMediaGallery(currentIndex: Int, mediaUrls urls: [URL]) {
  698. let betterPreviewController = PreviewController(currentIndex: currentIndex, urls: urls)
  699. let nav = UINavigationController(rootViewController: betterPreviewController)
  700. nav.modalPresentationStyle = .fullScreen
  701. navigationController?.present(nav, animated: true)
  702. }
  703. private func documentActionPressed(_ action: UIAlertAction) {
  704. showDocumentLibrary()
  705. }
  706. private func voiceMessageButtonPressed(_ action: UIAlertAction) {
  707. showVoiceMessageRecorder()
  708. }
  709. private func cameraButtonPressed(_ action: UIAlertAction) {
  710. showCameraViewController()
  711. }
  712. private func galleryButtonPressed(_ action: UIAlertAction) {
  713. showPhotoVideoLibrary(delegate: self)
  714. }
  715. private func locationStreamingButtonPressed(_ action: UIAlertAction) {
  716. let isLocationStreaming = dcContext.isSendingLocationsToChat(chatId: chatId)
  717. if isLocationStreaming {
  718. locationStreamingFor(seconds: 0)
  719. } else {
  720. let alert = UIAlertController(title: String.localized("title_share_location"), message: nil, preferredStyle: .safeActionSheet)
  721. addDurationSelectionAction(to: alert, key: "share_location_for_5_minutes", duration: Time.fiveMinutes)
  722. addDurationSelectionAction(to: alert, key: "share_location_for_30_minutes", duration: Time.thirtyMinutes)
  723. addDurationSelectionAction(to: alert, key: "share_location_for_one_hour", duration: Time.oneHour)
  724. addDurationSelectionAction(to: alert, key: "share_location_for_two_hours", duration: Time.twoHours)
  725. addDurationSelectionAction(to: alert, key: "share_location_for_six_hours", duration: Time.sixHours)
  726. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  727. self.present(alert, animated: true, completion: nil)
  728. }
  729. }
  730. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  731. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  732. self.locationStreamingFor(seconds: duration)
  733. })
  734. alert.addAction(action)
  735. }
  736. private func locationStreamingFor(seconds: Int) {
  737. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  738. return
  739. }
  740. self.dcContext.sendLocationsToChat(chatId: self.chatId, seconds: seconds)
  741. appDelegate.locationManager.shareLocation(chatId: self.chatId, duration: seconds)
  742. }
  743. func updateMessage(_ messageId: Int) {
  744. if messageIds.firstIndex(where: { $0 == messageId }) != nil {
  745. dcContext.markSeenMessages(messageIds: [UInt32(messageId)])
  746. let wasLastSectionVisible = self.isLastRowVisible()
  747. tableView.reloadData()
  748. if wasLastSectionVisible {
  749. self.scrollToBottom(animated: true)
  750. }
  751. } else {
  752. let msg = DcMsg(id: messageId)
  753. if msg.chatId == chatId {
  754. insertMessage(msg)
  755. }
  756. }
  757. }
  758. func insertMessage(_ message: DcMsg) {
  759. dcContext.markSeenMessages(messageIds: [UInt32(message.id)])
  760. messageIds.append(message.id)
  761. emptyStateView.isHidden = true
  762. let wasLastSectionVisible = isLastRowVisible()
  763. tableView.reloadData()
  764. if wasLastSectionVisible || message.isFromCurrentSender {
  765. scrollToBottom(animated: true)
  766. }
  767. }
  768. private func sendTextMessage(message: String) {
  769. DispatchQueue.global().async {
  770. self.dcContext.sendTextInChat(id: self.chatId, message: message)
  771. }
  772. }
  773. private func sendImage(_ image: UIImage, message: String? = nil) {
  774. DispatchQueue.global().async {
  775. if let path = DcUtils.saveImage(image: image) {
  776. self.sendImageMessage(viewType: DC_MSG_IMAGE, image: image, filePath: path)
  777. }
  778. }
  779. }
  780. private func sendAnimatedImage(url: NSURL) {
  781. if let path = url.path {
  782. let result = SDAnimatedImage(contentsOfFile: path)
  783. if let result = result,
  784. let animatedImageData = result.animatedImageData,
  785. let pathInDocDir = DcUtils.saveImage(data: animatedImageData, suffix: "gif") {
  786. self.sendImageMessage(viewType: DC_MSG_GIF, image: result, filePath: pathInDocDir)
  787. }
  788. }
  789. }
  790. private func sendImageMessage(viewType: Int32, image: UIImage, filePath: String, message: String? = nil) {
  791. let msg = DcMsg(viewType: viewType)
  792. msg.setFile(filepath: filePath)
  793. msg.text = (message ?? "").isEmpty ? nil : message
  794. msg.sendInChat(id: self.chatId)
  795. }
  796. private func sendDocumentMessage(url: NSURL) {
  797. DispatchQueue.global().async {
  798. let msg = DcMsg(viewType: DC_MSG_FILE)
  799. msg.setFile(filepath: url.relativePath, mimeType: nil)
  800. msg.sendInChat(id: self.chatId)
  801. }
  802. }
  803. private func sendVoiceMessage(url: NSURL) {
  804. DispatchQueue.global().async {
  805. let msg = DcMsg(viewType: DC_MSG_VOICE)
  806. msg.setFile(filepath: url.relativePath, mimeType: "audio/m4a")
  807. msg.sendInChat(id: self.chatId)
  808. }
  809. }
  810. private func sendVideo(url: NSURL) {
  811. DispatchQueue.global().async {
  812. let msg = DcMsg(viewType: DC_MSG_VIDEO)
  813. msg.setFile(filepath: url.relativePath, mimeType: "video/mp4")
  814. msg.sendInChat(id: self.chatId)
  815. }
  816. }
  817. private func sendImage(url: NSURL) {
  818. if url.pathExtension == "gif" {
  819. sendAnimatedImage(url: url)
  820. } else if let data = try? Data(contentsOf: url as URL),
  821. let image = UIImage(data: data) {
  822. sendImage(image)
  823. }
  824. }
  825. // MARK: - Context menu
  826. private func prepareContextMenu() {
  827. UIMenuController.shared.menuItems = [
  828. UIMenuItem(title: String.localized("info"), action: #selector(BaseMessageCell.messageInfo)),
  829. UIMenuItem(title: String.localized("delete"), action: #selector(BaseMessageCell.messageDelete)),
  830. UIMenuItem(title: String.localized("forward"), action: #selector(BaseMessageCell.messageForward))
  831. ]
  832. UIMenuController.shared.update()
  833. }
  834. override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
  835. return !DcMsg(id: messageIds[indexPath.row]).isInfo
  836. }
  837. override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
  838. return action == #selector(UIResponderStandardEditActions.copy(_:))
  839. || action == #selector(BaseMessageCell.messageInfo)
  840. || action == #selector(BaseMessageCell.messageDelete)
  841. || action == #selector(BaseMessageCell.messageForward)
  842. }
  843. override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
  844. // handle standard actions here, but custom actions never trigger this. it still needs to be present for the menu to display, though.
  845. switch action {
  846. case #selector(copy(_:)):
  847. let id = messageIds[indexPath.row]
  848. let msg = DcMsg(id: id)
  849. let pasteboard = UIPasteboard.general
  850. if msg.type == DC_MSG_TEXT {
  851. pasteboard.string = msg.text
  852. } else {
  853. pasteboard.string = msg.summary(chars: 10000000)
  854. }
  855. case #selector(BaseMessageCell.messageInfo(_:)):
  856. let msg = DcMsg(id: messageIds[indexPath.row])
  857. let msgViewController = MessageInfoViewController(dcContext: dcContext, message: msg)
  858. if let ctrl = navigationController {
  859. ctrl.pushViewController(msgViewController, animated: true)
  860. }
  861. case #selector(BaseMessageCell.messageDelete(_:)):
  862. let msg = DcMsg(id: messageIds[indexPath.row])
  863. askToDeleteMessage(id: msg.id)
  864. case #selector(BaseMessageCell.messageForward(_:)):
  865. let msg = DcMsg(id: messageIds[indexPath.row])
  866. RelayHelper.sharedInstance.setForwardMessage(messageId: msg.id)
  867. navigationController?.popViewController(animated: true)
  868. default:
  869. break
  870. }
  871. }
  872. func showMediaGalleryFor(indexPath: IndexPath) {
  873. let messageId = messageIds[indexPath.row]
  874. let message = DcMsg(id: messageId)
  875. showMediaGalleryFor(message: message)
  876. }
  877. func showMediaGalleryFor(message: DcMsg) {
  878. if let url = message.fileURL {
  879. // find all other messages with same message type
  880. let previousUrls: [URL] = message.previousMediaURLs()
  881. let nextUrls: [URL] = message.nextMediaURLs()
  882. // these are the files user will be able to swipe trough
  883. let mediaUrls: [URL] = previousUrls + [url] + nextUrls
  884. showMediaGallery(currentIndex: previousUrls.count, mediaUrls: mediaUrls)
  885. }
  886. }
  887. }
  888. // MARK: - BaseMessageCellDelegate
  889. extension ChatViewControllerNew: BaseMessageCellDelegate {
  890. func linkTapped(link: String) {
  891. }
  892. func imageTapped(indexPath: IndexPath) {
  893. showMediaGalleryFor(indexPath: indexPath)
  894. }
  895. func avatarTapped(indexPath: IndexPath) {
  896. let message = DcMsg(id: messageIds[indexPath.row])
  897. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: message.fromContactId)
  898. navigationController?.pushViewController(contactDetailController, animated: true)
  899. }
  900. }
  901. // MARK: - MediaPickerDelegate
  902. extension ChatViewControllerNew: MediaPickerDelegate {
  903. func onVideoSelected(url: NSURL) {
  904. sendVideo(url: url)
  905. }
  906. func onImageSelected(url: NSURL) {
  907. sendImage(url: url)
  908. }
  909. func onImageSelected(image: UIImage) {
  910. sendImage(image)
  911. }
  912. func onVoiceMessageRecorded(url: NSURL) {
  913. sendVoiceMessage(url: url)
  914. }
  915. func onDocumentSelected(url: NSURL) {
  916. sendDocumentMessage(url: url)
  917. }
  918. }
  919. // MARK: - MessageInputBarDelegate
  920. extension ChatViewControllerNew: InputBarAccessoryViewDelegate {
  921. func inputBar(_ inputBar: InputBarAccessoryView, didPressSendButtonWith text: String) {
  922. if inputBar.inputTextView.images.isEmpty {
  923. self.sendTextMessage(message: text.trimmingCharacters(in: .whitespacesAndNewlines))
  924. } else {
  925. let trimmedText = text.replacingOccurrences(of: "\u{FFFC}", with: "", options: .literal, range: nil)
  926. .trimmingCharacters(in: .whitespacesAndNewlines)
  927. // only 1 attachment allowed for now, thus it takes the first one
  928. self.sendImage(inputBar.inputTextView.images[0], message: trimmedText)
  929. }
  930. inputBar.inputTextView.text = String()
  931. inputBar.inputTextView.attributedText = nil
  932. }
  933. }