ChatListController.swift 19 KB

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