ChatListController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. import UIKit
  2. import DcCore
  3. class ChatListController: UITableViewController {
  4. let viewModel: ChatListViewModel
  5. let dcContext: DcContext
  6. private let chatCellReuseIdentifier = "chat_cell"
  7. private let deadDropCellReuseIdentifier = "deaddrop_cell"
  8. private let contactCellReuseIdentifier = "contact_cell"
  9. private var msgChangedObserver: NSObjectProtocol?
  10. private var msgsNoticedObserver: NSObjectProtocol?
  11. private var incomingMsgObserver: NSObjectProtocol?
  12. private var connectivityChangedObserver: NSObjectProtocol?
  13. private weak var timer: Timer?
  14. private lazy var titleView: UILabel = {
  15. let view = UILabel()
  16. let navTapGesture = UITapGestureRecognizer(target: self, action: #selector(onNavigationTitleTapped))
  17. view.addGestureRecognizer(navTapGesture)
  18. view.isUserInteractionEnabled = true
  19. view.font = UIFont.systemFont(ofSize: 20, weight: .semibold)
  20. return view
  21. }()
  22. private lazy var searchController: UISearchController = {
  23. let searchController = UISearchController(searchResultsController: nil)
  24. searchController.searchResultsUpdater = viewModel
  25. searchController.obscuresBackgroundDuringPresentation = false
  26. searchController.searchBar.placeholder = String.localized("search")
  27. searchController.searchBar.delegate = self
  28. return searchController
  29. }()
  30. private lazy var archiveCell: ActionCell = {
  31. let actionCell = ActionCell()
  32. return actionCell
  33. }()
  34. private lazy var newButton: UIBarButtonItem = {
  35. let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.compose, target: self, action: #selector(didPressNewChat))
  36. button.tintColor = DcColors.primary
  37. return button
  38. }()
  39. private lazy var cancelButton: UIBarButtonItem = {
  40. let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed))
  41. return button
  42. }()
  43. private lazy var emptySearchStateLabel: EmptyStateLabel = {
  44. let label = EmptyStateLabel()
  45. label.isHidden = false
  46. return label
  47. }()
  48. init(dcContext: DcContext, viewModel: ChatListViewModel) {
  49. self.viewModel = viewModel
  50. self.dcContext = dcContext
  51. if viewModel.isArchive {
  52. super.init(nibName: nil, bundle: nil)
  53. } else {
  54. super.init(style: .grouped)
  55. }
  56. viewModel.onChatListUpdate = handleChatListUpdate // register listener
  57. }
  58. required init?(coder _: NSCoder) {
  59. fatalError("init(coder:) has not been implemented")
  60. }
  61. // MARK: - lifecycle
  62. override func viewDidLoad() {
  63. super.viewDidLoad()
  64. navigationItem.rightBarButtonItem = newButton
  65. if !viewModel.isArchive {
  66. navigationItem.searchController = searchController
  67. }
  68. configureTableView()
  69. setupSubviews()
  70. }
  71. override func viewWillAppear(_ animated: Bool) {
  72. super.viewWillAppear(animated)
  73. // update messages - for new messages, do not reuse or modify strings but create new ones.
  74. // it is not needed to keep all past update messages, however, when deleted, also the strings should be deleted.
  75. let msg = dcContext.newMessage(viewType: DC_MSG_TEXT)
  76. msg.text = String.localized("update_1_20") + " https://delta.chat/en/2021-05-05-email-compat"
  77. dcContext.addDeviceMessage(label: "update_1_20b_ios", msg: msg)
  78. // create view
  79. navigationItem.titleView = titleView
  80. updateTitle()
  81. viewModel.refreshData()
  82. if RelayHelper.sharedInstance.isForwarding() {
  83. quitSearch(animated: false)
  84. tableView.scrollToTop()
  85. }
  86. }
  87. override func viewDidAppear(_ animated: Bool) {
  88. super.viewDidAppear(animated)
  89. startTimer()
  90. let nc = NotificationCenter.default
  91. msgChangedObserver = nc.addObserver(
  92. forName: dcNotificationChanged,
  93. object: nil,
  94. queue: nil) { [weak self] _ in
  95. self?.refreshInBg()
  96. }
  97. msgsNoticedObserver = nc.addObserver(
  98. forName: dcMsgsNoticed,
  99. object: nil,
  100. queue: nil) { [weak self] _ in
  101. self?.refreshInBg()
  102. }
  103. incomingMsgObserver = nc.addObserver(
  104. forName: dcNotificationIncoming,
  105. object: nil,
  106. queue: nil) { [weak self] _ in
  107. self?.refreshInBg()
  108. }
  109. connectivityChangedObserver = nc.addObserver(forName: dcNotificationConnectivityChanged,
  110. object: nil,
  111. queue: nil) { [weak self] _ in
  112. self?.updateTitle()
  113. }
  114. nc.addObserver(
  115. self,
  116. selector: #selector(applicationDidBecomeActive(_:)),
  117. name: UIApplication.didBecomeActiveNotification,
  118. object: nil)
  119. nc.addObserver(
  120. self,
  121. selector: #selector(applicationWillResignActive(_:)),
  122. name: UIApplication.willResignActiveNotification,
  123. object: nil)
  124. }
  125. override func viewDidDisappear(_ animated: Bool) {
  126. super.viewDidDisappear(animated)
  127. stopTimer()
  128. let nc = NotificationCenter.default
  129. // remove observers with a block
  130. if let msgChangedObserver = self.msgChangedObserver {
  131. nc.removeObserver(msgChangedObserver)
  132. }
  133. if let incomingMsgObserver = self.incomingMsgObserver {
  134. nc.removeObserver(incomingMsgObserver)
  135. }
  136. if let msgsNoticedObserver = self.msgsNoticedObserver {
  137. nc.removeObserver(msgsNoticedObserver)
  138. }
  139. if let connectivityChangedObserver = self.connectivityChangedObserver {
  140. nc.removeObserver(connectivityChangedObserver)
  141. }
  142. // remove non-block observers
  143. NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
  144. NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
  145. }
  146. // MARK: - setup
  147. private func setupSubviews() {
  148. emptySearchStateLabel.addCenteredTo(parentView: view)
  149. }
  150. @objc
  151. public func onNavigationTitleTapped() {
  152. logger.debug("on navigation title tapped")
  153. let connectivityViewController = ConnectivityViewController(dcContext: dcContext)
  154. navigationController?.pushViewController(connectivityViewController, animated: true)
  155. }
  156. func getConnectivityString(conenctedString: String) -> String {
  157. let connectivity = dcContext.getConnectivity()
  158. if connectivity >= DC_CONNECTIVITY_CONNECTED {
  159. return conenctedString
  160. } else if connectivity >= DC_CONNECTIVITY_WORKING {
  161. return String.localized("connectivity_getting_new_msgs")
  162. } else if connectivity >= DC_CONNECTIVITY_CONNECTING {
  163. return String.localized("connectivity_connecting")
  164. } else {
  165. return String.localized("connectivity_not_connected")
  166. }
  167. }
  168. // MARK: - configuration
  169. private func configureTableView() {
  170. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  171. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  172. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  173. tableView.rowHeight = ContactCell.cellHeight
  174. }
  175. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  176. if navigationController?.visibleViewController == self {
  177. startTimer()
  178. refreshInBg()
  179. }
  180. }
  181. private var inBgRefresh = false
  182. private var needsAnotherBgRefresh = false
  183. private func refreshInBg() {
  184. if inBgRefresh {
  185. needsAnotherBgRefresh = true
  186. } else {
  187. inBgRefresh = true
  188. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  189. // do at least one refresh, without inital delay
  190. // (refreshData() calls handleChatListUpdate() on main thread when done)
  191. self?.needsAnotherBgRefresh = false
  192. self?.viewModel.refreshData()
  193. // do subsequent refreshes with a delay of 500ms
  194. while self?.needsAnotherBgRefresh != false {
  195. usleep(500000)
  196. self?.needsAnotherBgRefresh = false
  197. self?.viewModel.refreshData()
  198. }
  199. self?.inBgRefresh = false
  200. }
  201. }
  202. }
  203. @objc func applicationWillResignActive(_ notification: NSNotification) {
  204. if navigationController?.visibleViewController == self {
  205. stopTimer()
  206. }
  207. }
  208. // MARK: - actions
  209. @objc func didPressNewChat() {
  210. showNewChatController()
  211. }
  212. @objc func cancelButtonPressed() {
  213. // cancel forwarding
  214. RelayHelper.sharedInstance.cancel()
  215. updateTitle()
  216. refreshInBg()
  217. }
  218. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  219. if previousTraitCollection?.preferredContentSizeCategory !=
  220. traitCollection.preferredContentSizeCategory {
  221. tableView.rowHeight = ContactCell.cellHeight
  222. }
  223. }
  224. private func quitSearch(animated: Bool) {
  225. searchController.searchBar.text = nil
  226. self.viewModel.endSearch()
  227. searchController.dismiss(animated: animated) {
  228. self.tableView.scrollToTop()
  229. }
  230. }
  231. // MARK: - UITableViewDelegate + UITableViewDatasource
  232. override func numberOfSections(in tableView: UITableView) -> Int {
  233. return viewModel.numberOfSections
  234. }
  235. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  236. return viewModel.numberOfRowsIn(section: section)
  237. }
  238. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  239. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  240. switch cellData.type {
  241. case .deaddrop:
  242. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  243. break
  244. }
  245. deaddropCell.updateCell(cellViewModel: cellData)
  246. return deaddropCell
  247. case .chat(let chatData):
  248. let chatId = chatData.chatId
  249. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  250. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  251. archiveCell.backgroundColor = DcColors.chatBackgroundColor
  252. return archiveCell
  253. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  254. // default chatCell
  255. chatCell.updateCell(cellViewModel: cellData)
  256. return chatCell
  257. }
  258. case .contact:
  259. safe_assert(viewModel.searchActive)
  260. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  261. contactCell.updateCell(cellViewModel: cellData)
  262. return contactCell
  263. }
  264. case .profile:
  265. safe_fatalError("CellData type profile not allowed")
  266. }
  267. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  268. return UITableViewCell()
  269. }
  270. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  271. return viewModel.titleForHeaderIn(section: section)
  272. }
  273. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  274. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  275. switch cellData.type {
  276. case .deaddrop(let deaddropData):
  277. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  278. if dcContext.showEmails == DC_SHOW_EMAILS_ALL {
  279. let deaddropViewController = MailboxViewController(dcContext: dcContext, chatId: Int(DC_CHAT_ID_DEADDROP))
  280. navigationController?.pushViewController(deaddropViewController, animated: true)
  281. } else {
  282. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  283. }
  284. case .chat(let chatData):
  285. let chatId = chatData.chatId
  286. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  287. showArchive()
  288. } else {
  289. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  290. }
  291. case .contact(let contactData):
  292. let contactId = contactData.contactId
  293. if let chatId = contactData.chatId {
  294. showChat(chatId: chatId)
  295. } else {
  296. self.askToChatWith(contactId: contactId)
  297. }
  298. case .profile:
  299. safe_fatalError("CellData type profile not allowed")
  300. }
  301. tableView.deselectRow(at: indexPath, animated: false)
  302. }
  303. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  304. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  305. return []
  306. }
  307. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  308. return []
  309. // returning nil may result in a default delete action,
  310. // see https://forums.developer.apple.com/thread/115030
  311. }
  312. let chat = dcContext.getChat(chatId: chatId)
  313. let archived = chat.isArchived
  314. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  315. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  316. self?.viewModel.archiveChatToggle(chatId: chatId)
  317. }
  318. archiveAction.backgroundColor = UIColor.lightGray
  319. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  320. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  321. self?.viewModel.pinChatToggle(chatId: chat.id)
  322. }
  323. pinAction.backgroundColor = UIColor.systemGreen
  324. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  325. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  326. }
  327. deleteAction.backgroundColor = UIColor.systemRed
  328. return [archiveAction, pinAction, deleteAction]
  329. }
  330. // MARK: updates
  331. private func updateTitle() {
  332. if RelayHelper.sharedInstance.isForwarding() {
  333. titleView.text = String.localized("forward_to")
  334. if !viewModel.isArchive {
  335. navigationItem.setLeftBarButton(cancelButton, animated: true)
  336. }
  337. } else {
  338. let connectedText: String = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  339. String.localized("app_name")
  340. titleView.text = getConnectivityString(conenctedString: connectedText)
  341. navigationItem.setLeftBarButton(nil, animated: true)
  342. }
  343. titleView.sizeToFit()
  344. }
  345. func handleChatListUpdate() {
  346. tableView.reloadData()
  347. if let emptySearchText = viewModel.emptySearchText {
  348. let text = String.localizedStringWithFormat(
  349. String.localized("search_no_result_for_x"),
  350. emptySearchText
  351. )
  352. emptySearchStateLabel.text = text
  353. emptySearchStateLabel.isHidden = false
  354. } else {
  355. emptySearchStateLabel.text = nil
  356. emptySearchStateLabel.isHidden = true
  357. }
  358. }
  359. private func startTimer() {
  360. // check if the timer is not yet started
  361. stopTimer()
  362. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  363. guard let self = self,
  364. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  365. else { return }
  366. if appDelegate.appIsInForeground() {
  367. self.refreshInBg()
  368. } else {
  369. logger.warning("startTimer() must not be executed in background")
  370. }
  371. }
  372. }
  373. private func stopTimer() {
  374. // check if the timer is not already stopped
  375. if let timer = timer {
  376. timer.invalidate()
  377. }
  378. timer = nil
  379. }
  380. public func handleMailto() {
  381. if let mailtoAddress = RelayHelper.sharedInstance.mailtoAddress {
  382. // FIXME: the line below should work
  383. // var contactId = dcContext.lookupContactIdByAddress(mailtoAddress)
  384. // workaround:
  385. let contacts: [Int] = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: mailtoAddress)
  386. let index = contacts.firstIndex(where: { dcContext.getContact(id: $0).email == mailtoAddress }) ?? -1
  387. var contactId = 0
  388. if index >= 0 {
  389. contactId = contacts[index]
  390. }
  391. if contactId != 0 && dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  392. showChat(chatId: dcContext.getChatIdByContactId(contactId: contactId), animated: false)
  393. } else {
  394. askToChatWith(address: mailtoAddress)
  395. }
  396. }
  397. }
  398. // MARK: - alerts
  399. private func showDeleteChatConfirmationAlert(chatId: Int) {
  400. let alert = UIAlertController(
  401. title: nil,
  402. message: String.localized("ask_delete_chat_desktop"),
  403. preferredStyle: .safeActionSheet
  404. )
  405. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  406. self.deleteChat(chatId: chatId, animated: true)
  407. }))
  408. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  409. self.present(alert, animated: true, completion: nil)
  410. }
  411. private func showDeaddropRequestAlert(msgId: Int) {
  412. let dcMsg = dcContext.getMessage(id: msgId)
  413. let (title, startButton, blockButton) = MailboxViewController.deaddropQuestion(context: dcContext, msg: dcMsg)
  414. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  415. alert.addAction(UIAlertAction(title: startButton, style: .default, handler: { _ in
  416. let chat = self.dcContext.decideOnContactRequest(msgId, DC_DECISION_START_CHAT)
  417. self.showChat(chatId: chat.id)
  418. }))
  419. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  420. DispatchQueue.global(qos: .userInitiated).async {
  421. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_NOT_NOW)
  422. }
  423. }))
  424. alert.addAction(UIAlertAction(title: blockButton, style: .destructive, handler: { _ in
  425. DispatchQueue.global(qos: .userInitiated).async {
  426. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_BLOCK)
  427. }
  428. }))
  429. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  430. present(alert, animated: true, completion: nil)
  431. }
  432. private func askToChatWith(address: String, contactId: Int = 0) {
  433. var contactId = contactId
  434. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), address),
  435. message: nil,
  436. preferredStyle: .safeActionSheet)
  437. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  438. guard let self = self else { return }
  439. if contactId == 0 {
  440. contactId = self.dcContext.createContact(name: nil, email: address)
  441. }
  442. self.showNewChat(contactId: contactId)
  443. }))
  444. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  445. if RelayHelper.sharedInstance.isMailtoHandling() {
  446. RelayHelper.sharedInstance.finishMailto()
  447. }
  448. }))
  449. present(alert, animated: true, completion: nil)
  450. }
  451. private func askToChatWith(contactId: Int) {
  452. let dcContact = dcContext.getContact(id: contactId)
  453. askToChatWith(address: dcContact.nameNAddr, contactId: contactId)
  454. }
  455. private func deleteChat(chatId: Int, animated: Bool) {
  456. if !animated {
  457. viewModel.deleteChat(chatId: chatId)
  458. refreshInBg()
  459. return
  460. }
  461. if viewModel.searchActive {
  462. viewModel.deleteChat(chatId: chatId)
  463. viewModel.refreshData()
  464. viewModel.updateSearchResults(for: searchController)
  465. return
  466. }
  467. viewModel.deleteChat(chatId: chatId)
  468. }
  469. // MARK: - coordinator
  470. private func showNewChatController() {
  471. let newChatVC = NewChatViewController(dcContext: dcContext)
  472. navigationController?.pushViewController(newChatVC, animated: true)
  473. }
  474. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  475. if searchController.isActive {
  476. searchController.searchBar.resignFirstResponder()
  477. }
  478. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  479. navigationController?.pushViewController(chatVC, animated: animated)
  480. }
  481. private func showArchive() {
  482. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  483. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  484. navigationController?.pushViewController(controller, animated: true)
  485. }
  486. private func showNewChat(contactId: Int) {
  487. let chatId = dcContext.createChatByContactId(contactId: contactId)
  488. showChat(chatId: Int(chatId))
  489. }
  490. }
  491. // MARK: - uisearchbardelegate
  492. extension ChatListController: UISearchBarDelegate {
  493. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  494. viewModel.beginSearch()
  495. return true
  496. }
  497. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  498. // searchBar will be set to "" by system
  499. viewModel.endSearch()
  500. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  501. self.tableView.scrollToTop()
  502. }
  503. }
  504. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  505. tableView.scrollToTop()
  506. return true
  507. }
  508. }