ChatListController.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 .deaddrop:
  231. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  232. break
  233. }
  234. deaddropCell.updateCell(cellViewModel: cellData)
  235. return deaddropCell
  236. case .chat(let chatData):
  237. let chatId = chatData.chatId
  238. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  239. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  240. archiveCell.backgroundColor = DcColors.chatBackgroundColor
  241. return archiveCell
  242. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  243. // default chatCell
  244. chatCell.updateCell(cellViewModel: cellData)
  245. return chatCell
  246. }
  247. case .contact:
  248. safe_assert(viewModel.searchActive)
  249. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  250. contactCell.updateCell(cellViewModel: cellData)
  251. return contactCell
  252. }
  253. case .profile:
  254. safe_fatalError("CellData type profile not allowed")
  255. }
  256. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  257. return UITableViewCell()
  258. }
  259. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  260. return viewModel.titleForHeaderIn(section: section)
  261. }
  262. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  263. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  264. switch cellData.type {
  265. case .deaddrop(let deaddropData):
  266. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  267. if dcContext.showEmails == DC_SHOW_EMAILS_ALL {
  268. let deaddropViewController = MailboxViewController(dcContext: dcContext, chatId: Int(DC_CHAT_ID_DEADDROP))
  269. navigationController?.pushViewController(deaddropViewController, animated: true)
  270. } else {
  271. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  272. }
  273. case .chat(let chatData):
  274. let chatId = chatData.chatId
  275. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  276. showArchive()
  277. } else {
  278. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  279. }
  280. case .contact(let contactData):
  281. let contactId = contactData.contactId
  282. if let chatId = contactData.chatId {
  283. showChat(chatId: chatId)
  284. } else {
  285. self.askToChatWith(contactId: contactId)
  286. }
  287. case .profile:
  288. safe_fatalError("CellData type profile not allowed")
  289. }
  290. tableView.deselectRow(at: indexPath, animated: false)
  291. }
  292. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  293. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  294. return []
  295. }
  296. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  297. return []
  298. // returning nil may result in a default delete action,
  299. // see https://forums.developer.apple.com/thread/115030
  300. }
  301. let chat = dcContext.getChat(chatId: chatId)
  302. let archived = chat.isArchived
  303. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  304. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  305. self?.viewModel.archiveChatToggle(chatId: chatId)
  306. }
  307. archiveAction.backgroundColor = UIColor.lightGray
  308. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  309. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  310. self?.viewModel.pinChatToggle(chatId: chat.id)
  311. }
  312. pinAction.backgroundColor = UIColor.systemGreen
  313. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  314. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  315. }
  316. deleteAction.backgroundColor = UIColor.systemRed
  317. return [archiveAction, pinAction, deleteAction]
  318. }
  319. // MARK: updates
  320. private func updateTitle() {
  321. if RelayHelper.sharedInstance.isForwarding() {
  322. titleView.text = String.localized("forward_to")
  323. if !viewModel.isArchive {
  324. navigationItem.setLeftBarButton(cancelButton, animated: true)
  325. }
  326. } else if viewModel.isArchive {
  327. titleView.text = String.localized("chat_archived_chats_title")
  328. navigationItem.setLeftBarButton(nil, animated: true)
  329. } else {
  330. titleView.text = DcUtils.getConnectivityString(dcContext: dcContext, connectedString: String.localized("pref_chats"))
  331. navigationItem.setLeftBarButton(nil, animated: true)
  332. }
  333. titleView.sizeToFit()
  334. }
  335. func handleChatListUpdate() {
  336. tableView.reloadData()
  337. if let emptySearchText = viewModel.emptySearchText {
  338. let text = String.localizedStringWithFormat(
  339. String.localized("search_no_result_for_x"),
  340. emptySearchText
  341. )
  342. emptySearchStateLabel.text = text
  343. emptySearchStateLabel.isHidden = false
  344. } else {
  345. emptySearchStateLabel.text = nil
  346. emptySearchStateLabel.isHidden = true
  347. }
  348. }
  349. private func startTimer() {
  350. // check if the timer is not yet started
  351. stopTimer()
  352. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  353. guard let self = self,
  354. let appDelegate = UIApplication.shared.delegate as? AppDelegate
  355. else { return }
  356. if appDelegate.appIsInForeground() {
  357. self.refreshInBg()
  358. } else {
  359. logger.warning("startTimer() must not be executed in background")
  360. }
  361. }
  362. }
  363. private func stopTimer() {
  364. // check if the timer is not already stopped
  365. if let timer = timer {
  366. timer.invalidate()
  367. }
  368. timer = nil
  369. }
  370. public func handleMailto() {
  371. if let mailtoAddress = RelayHelper.sharedInstance.mailtoAddress {
  372. // FIXME: the line below should work
  373. // var contactId = dcContext.lookupContactIdByAddress(mailtoAddress)
  374. // workaround:
  375. let contacts: [Int] = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: mailtoAddress)
  376. let index = contacts.firstIndex(where: { dcContext.getContact(id: $0).email == mailtoAddress }) ?? -1
  377. var contactId = 0
  378. if index >= 0 {
  379. contactId = contacts[index]
  380. }
  381. if contactId != 0 && dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  382. showChat(chatId: dcContext.getChatIdByContactId(contactId: contactId), animated: false)
  383. } else {
  384. askToChatWith(address: mailtoAddress)
  385. }
  386. }
  387. }
  388. // MARK: - alerts
  389. private func showDeleteChatConfirmationAlert(chatId: Int) {
  390. let alert = UIAlertController(
  391. title: nil,
  392. message: String.localized("ask_delete_chat_desktop"),
  393. preferredStyle: .safeActionSheet
  394. )
  395. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  396. self.deleteChat(chatId: chatId, animated: true)
  397. }))
  398. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  399. self.present(alert, animated: true, completion: nil)
  400. }
  401. private func showDeaddropRequestAlert(msgId: Int) {
  402. let dcMsg = dcContext.getMessage(id: msgId)
  403. let (title, startButton, blockButton) = MailboxViewController.deaddropQuestion(context: dcContext, msg: dcMsg)
  404. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  405. alert.addAction(UIAlertAction(title: startButton, style: .default, handler: { _ in
  406. let chat = self.dcContext.decideOnContactRequest(msgId, DC_DECISION_START_CHAT)
  407. self.showChat(chatId: chat.id)
  408. }))
  409. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  410. DispatchQueue.global(qos: .userInitiated).async {
  411. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_NOT_NOW)
  412. }
  413. }))
  414. alert.addAction(UIAlertAction(title: blockButton, style: .destructive, handler: { _ in
  415. DispatchQueue.global(qos: .userInitiated).async {
  416. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_BLOCK)
  417. }
  418. }))
  419. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  420. present(alert, animated: true, completion: nil)
  421. }
  422. private func askToChatWith(address: String, contactId: Int = 0) {
  423. var contactId = contactId
  424. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), address),
  425. message: nil,
  426. preferredStyle: .safeActionSheet)
  427. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  428. guard let self = self else { return }
  429. if contactId == 0 {
  430. contactId = self.dcContext.createContact(name: nil, email: address)
  431. }
  432. self.showNewChat(contactId: contactId)
  433. }))
  434. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  435. if RelayHelper.sharedInstance.isMailtoHandling() {
  436. RelayHelper.sharedInstance.finishMailto()
  437. }
  438. }))
  439. present(alert, animated: true, completion: nil)
  440. }
  441. private func askToChatWith(contactId: Int) {
  442. let dcContact = dcContext.getContact(id: contactId)
  443. askToChatWith(address: dcContact.nameNAddr, contactId: contactId)
  444. }
  445. private func deleteChat(chatId: Int, animated: Bool) {
  446. if !animated {
  447. viewModel.deleteChat(chatId: chatId)
  448. refreshInBg()
  449. return
  450. }
  451. if viewModel.searchActive {
  452. viewModel.deleteChat(chatId: chatId)
  453. viewModel.refreshData()
  454. viewModel.updateSearchResults(for: searchController)
  455. return
  456. }
  457. viewModel.deleteChat(chatId: chatId)
  458. }
  459. // MARK: - coordinator
  460. private func showNewChatController() {
  461. let newChatVC = NewChatViewController(dcContext: dcContext)
  462. navigationController?.pushViewController(newChatVC, animated: true)
  463. }
  464. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  465. if searchController.isActive {
  466. searchController.searchBar.resignFirstResponder()
  467. }
  468. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  469. navigationController?.pushViewController(chatVC, animated: animated)
  470. }
  471. private func showArchive() {
  472. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  473. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  474. navigationController?.pushViewController(controller, animated: true)
  475. }
  476. private func showNewChat(contactId: Int) {
  477. let chatId = dcContext.createChatByContactId(contactId: contactId)
  478. showChat(chatId: Int(chatId))
  479. }
  480. }
  481. // MARK: - uisearchbardelegate
  482. extension ChatListController: UISearchBarDelegate {
  483. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  484. viewModel.beginSearch()
  485. return true
  486. }
  487. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  488. // searchBar will be set to "" by system
  489. viewModel.endSearch()
  490. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  491. self.tableView.scrollToTop()
  492. }
  493. }
  494. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  495. tableView.scrollToTop()
  496. return true
  497. }
  498. }