ChatListController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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: 17, 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. navigationItem.backButtonTitle = String.localized("pref_chats")
  150. }
  151. @objc
  152. public func onNavigationTitleTapped() {
  153. logger.debug("on navigation title tapped")
  154. let connectivityViewController = ConnectivityViewController(dcContext: dcContext)
  155. navigationController?.pushViewController(connectivityViewController, animated: true)
  156. }
  157. // MARK: - configuration
  158. private func configureTableView() {
  159. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  160. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  161. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  162. tableView.rowHeight = ContactCell.cellHeight
  163. }
  164. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  165. if navigationController?.visibleViewController == self {
  166. startTimer()
  167. refreshInBg()
  168. }
  169. }
  170. private var inBgRefresh = false
  171. private var needsAnotherBgRefresh = false
  172. private func refreshInBg() {
  173. if inBgRefresh {
  174. needsAnotherBgRefresh = true
  175. } else {
  176. inBgRefresh = true
  177. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  178. // do at least one refresh, without inital delay
  179. // (refreshData() calls handleChatListUpdate() on main thread when done)
  180. self?.needsAnotherBgRefresh = false
  181. self?.viewModel.refreshData()
  182. // do subsequent refreshes with a delay of 500ms
  183. while self?.needsAnotherBgRefresh != false {
  184. usleep(500000)
  185. self?.needsAnotherBgRefresh = false
  186. self?.viewModel.refreshData()
  187. }
  188. self?.inBgRefresh = false
  189. }
  190. }
  191. }
  192. @objc func applicationWillResignActive(_ notification: NSNotification) {
  193. if navigationController?.visibleViewController == self {
  194. stopTimer()
  195. }
  196. }
  197. // MARK: - actions
  198. @objc func didPressNewChat() {
  199. showNewChatController()
  200. }
  201. @objc func cancelButtonPressed() {
  202. // cancel forwarding
  203. RelayHelper.sharedInstance.cancel()
  204. updateTitle()
  205. refreshInBg()
  206. }
  207. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  208. if previousTraitCollection?.preferredContentSizeCategory !=
  209. traitCollection.preferredContentSizeCategory {
  210. tableView.rowHeight = ContactCell.cellHeight
  211. }
  212. }
  213. private func quitSearch(animated: Bool) {
  214. searchController.searchBar.text = nil
  215. self.viewModel.endSearch()
  216. searchController.dismiss(animated: animated) {
  217. self.tableView.scrollToTop()
  218. }
  219. }
  220. // MARK: - UITableViewDelegate + UITableViewDatasource
  221. override func numberOfSections(in tableView: UITableView) -> Int {
  222. return viewModel.numberOfSections
  223. }
  224. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  225. return viewModel.numberOfRowsIn(section: section)
  226. }
  227. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  228. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  229. switch cellData.type {
  230. case .chat(let chatData):
  231. let chatId = chatData.chatId
  232. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  233. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  234. archiveCell.backgroundColor = DcColors.chatBackgroundColor
  235. return archiveCell
  236. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  237. // default chatCell
  238. chatCell.updateCell(cellViewModel: cellData)
  239. return chatCell
  240. }
  241. case .contact:
  242. safe_assert(viewModel.searchActive)
  243. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  244. contactCell.updateCell(cellViewModel: cellData)
  245. return contactCell
  246. }
  247. case .profile:
  248. safe_fatalError("CellData type profile not allowed")
  249. }
  250. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  251. return UITableViewCell()
  252. }
  253. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  254. return viewModel.titleForHeaderIn(section: section)
  255. }
  256. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  257. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  258. switch cellData.type {
  259. case .chat(let chatData):
  260. let chatId = chatData.chatId
  261. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  262. showArchive(animated: true)
  263. } else {
  264. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  265. }
  266. case .contact(let contactData):
  267. let contactId = contactData.contactId
  268. if let chatId = contactData.chatId {
  269. showChat(chatId: chatId)
  270. } else {
  271. self.askToChatWith(contactId: contactId)
  272. }
  273. case .profile:
  274. safe_fatalError("CellData type profile not allowed")
  275. }
  276. tableView.deselectRow(at: indexPath, animated: false)
  277. }
  278. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  279. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  280. return []
  281. }
  282. if chatId==DC_CHAT_ID_ARCHIVED_LINK {
  283. return []
  284. // returning nil may result in a default delete action,
  285. // see https://forums.developer.apple.com/thread/115030
  286. }
  287. let chat = dcContext.getChat(chatId: chatId)
  288. let archived = chat.isArchived
  289. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  290. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  291. self?.viewModel.archiveChatToggle(chatId: chatId)
  292. }
  293. archiveAction.backgroundColor = UIColor.lightGray
  294. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  295. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  296. self?.viewModel.pinChatToggle(chatId: chat.id)
  297. }
  298. pinAction.backgroundColor = UIColor.systemGreen
  299. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  300. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  301. }
  302. deleteAction.backgroundColor = UIColor.systemRed
  303. return [archiveAction, pinAction, deleteAction]
  304. }
  305. // MARK: updates
  306. private func updateTitle() {
  307. if RelayHelper.sharedInstance.isForwarding() {
  308. titleView.text = String.localized("forward_to")
  309. if !viewModel.isArchive {
  310. navigationItem.setLeftBarButton(cancelButton, animated: true)
  311. }
  312. } else if viewModel.isArchive {
  313. titleView.text = String.localized("chat_archived_chats_title")
  314. navigationItem.setLeftBarButton(nil, animated: true)
  315. } else {
  316. titleView.text = DcUtils.getConnectivityString(dcContext: dcContext, connectedString: String.localized("pref_chats"))
  317. navigationItem.setLeftBarButton(nil, animated: true)
  318. }
  319. titleView.sizeToFit()
  320. }
  321. func handleChatListUpdate() {
  322. tableView.reloadData()
  323. if let emptySearchText = viewModel.emptySearchText {
  324. let text = String.localizedStringWithFormat(
  325. String.localized("search_no_result_for_x"),
  326. emptySearchText
  327. )
  328. emptySearchStateLabel.text = text
  329. emptySearchStateLabel.isHidden = false
  330. } else {
  331. emptySearchStateLabel.text = nil
  332. emptySearchStateLabel.isHidden = true
  333. }
  334. }
  335. private func startTimer() {
  336. // check if the timer is not yet started
  337. stopTimer()
  338. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  339. guard let self = self,
  340. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  341. else { return }
  342. if appDelegate.appIsInForeground() {
  343. self.refreshInBg()
  344. } else {
  345. logger.warning("startTimer() must not be executed in background")
  346. }
  347. }
  348. }
  349. private func stopTimer() {
  350. // check if the timer is not already stopped
  351. if let timer = timer {
  352. timer.invalidate()
  353. }
  354. timer = nil
  355. }
  356. public func handleMailto() {
  357. if let mailtoAddress = RelayHelper.sharedInstance.mailtoAddress {
  358. // FIXME: the line below should work
  359. // var contactId = dcContext.lookupContactIdByAddress(mailtoAddress)
  360. // workaround:
  361. let contacts: [Int] = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: mailtoAddress)
  362. let index = contacts.firstIndex(where: { dcContext.getContact(id: $0).email == mailtoAddress }) ?? -1
  363. var contactId = 0
  364. if index >= 0 {
  365. contactId = contacts[index]
  366. }
  367. if contactId != 0 && dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  368. showChat(chatId: dcContext.getChatIdByContactId(contactId: contactId), animated: false)
  369. } else {
  370. askToChatWith(address: mailtoAddress)
  371. }
  372. }
  373. }
  374. // MARK: - alerts
  375. private func showDeleteChatConfirmationAlert(chatId: Int) {
  376. let alert = UIAlertController(
  377. title: nil,
  378. message: String.localized("ask_delete_chat_desktop"),
  379. preferredStyle: .safeActionSheet
  380. )
  381. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  382. self.deleteChat(chatId: chatId, animated: true)
  383. }))
  384. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  385. self.present(alert, animated: true, completion: nil)
  386. }
  387. private func askToChatWith(address: String, contactId: Int = 0) {
  388. var contactId = contactId
  389. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), address),
  390. message: nil,
  391. preferredStyle: .safeActionSheet)
  392. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  393. guard let self = self else { return }
  394. if contactId == 0 {
  395. contactId = self.dcContext.createContact(name: nil, email: address)
  396. }
  397. self.showNewChat(contactId: contactId)
  398. }))
  399. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  400. if RelayHelper.sharedInstance.isMailtoHandling() {
  401. RelayHelper.sharedInstance.finishMailto()
  402. }
  403. }))
  404. present(alert, animated: true, completion: nil)
  405. }
  406. private func askToChatWith(contactId: Int) {
  407. let dcContact = dcContext.getContact(id: contactId)
  408. askToChatWith(address: dcContact.nameNAddr, contactId: contactId)
  409. }
  410. private func deleteChat(chatId: Int, animated: Bool) {
  411. if !animated {
  412. viewModel.deleteChat(chatId: chatId)
  413. refreshInBg()
  414. return
  415. }
  416. if viewModel.searchActive {
  417. viewModel.deleteChat(chatId: chatId)
  418. viewModel.refreshData()
  419. viewModel.updateSearchResults(for: searchController)
  420. return
  421. }
  422. viewModel.deleteChat(chatId: chatId)
  423. }
  424. // MARK: - coordinator
  425. private func showNewChatController() {
  426. let newChatVC = NewChatViewController(dcContext: dcContext)
  427. navigationController?.pushViewController(newChatVC, animated: true)
  428. }
  429. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  430. if searchController.isActive {
  431. searchController.searchBar.resignFirstResponder()
  432. }
  433. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  434. navigationController?.pushViewController(chatVC, animated: animated)
  435. }
  436. public func showArchive(animated: Bool) {
  437. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  438. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  439. navigationController?.pushViewController(controller, animated: animated)
  440. }
  441. private func showNewChat(contactId: Int) {
  442. let chatId = dcContext.createChatByContactId(contactId: contactId)
  443. showChat(chatId: Int(chatId))
  444. }
  445. }
  446. // MARK: - uisearchbardelegate
  447. extension ChatListController: UISearchBarDelegate {
  448. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  449. viewModel.beginSearch()
  450. return true
  451. }
  452. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  453. // searchBar will be set to "" by system
  454. viewModel.endSearch()
  455. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  456. self.tableView.scrollToTop()
  457. }
  458. }
  459. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  460. tableView.scrollToTop()
  461. return true
  462. }
  463. }