ChatListController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. import UIKit
  2. import DcCore
  3. class ChatListController: UITableViewController {
  4. let viewModel: ChatListViewModelProtocol
  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: ChatListViewModelProtocol) {
  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 = DcMsg(viewType: DC_MSG_TEXT)
  67. msg.text = "What's new in 1.16?\n"
  68. + "\n"
  69. + "✍️ Add text to images and files before sending\n"
  70. + "\n"
  71. + "🎨 Draw on images before sending (tap the image selected for sending, then the icon in the upper right corner)\n"
  72. + "\n"
  73. + "✅ ☑️ Multi-select messages and forward or delete them with one tap "
  74. + "(long tap on message, admire the new, much nicer context menu, then \"Select more\")\n"
  75. + "\n"
  76. + "As always, see https://delta.chat/blog for more news and updates."
  77. dcContext.addDeviceMessage(label: "update_1_16g_ios", msg: msg)
  78. // create view
  79. updateTitle()
  80. viewModel.refreshData()
  81. if RelayHelper.sharedInstance.isForwarding() {
  82. quitSearch(animated: false)
  83. tableView.scrollToTop()
  84. }
  85. }
  86. override func viewDidAppear(_ animated: Bool) {
  87. super.viewDidAppear(animated)
  88. startTimer()
  89. let nc = NotificationCenter.default
  90. msgChangedObserver = nc.addObserver(
  91. forName: dcNotificationChanged,
  92. object: nil,
  93. queue: nil) { [weak self] _ in
  94. self?.refreshInBg()
  95. }
  96. msgsNoticedObserver = nc.addObserver(
  97. forName: dcMsgsNoticed,
  98. object: nil,
  99. queue: nil) { [weak self] _ in
  100. self?.refreshInBg()
  101. }
  102. incomingMsgObserver = nc.addObserver(
  103. forName: dcNotificationIncoming,
  104. object: nil,
  105. queue: nil) { [weak self] _ in
  106. self?.refreshInBg()
  107. }
  108. nc.addObserver(
  109. self,
  110. selector: #selector(applicationDidBecomeActive(_:)),
  111. name: UIApplication.didBecomeActiveNotification,
  112. object: nil)
  113. nc.addObserver(
  114. self,
  115. selector: #selector(applicationWillResignActive(_:)),
  116. name: UIApplication.willResignActiveNotification,
  117. object: nil)
  118. }
  119. override func viewDidDisappear(_ animated: Bool) {
  120. super.viewDidDisappear(animated)
  121. stopTimer()
  122. let nc = NotificationCenter.default
  123. // remove observers with a block
  124. if let msgChangedObserver = self.msgChangedObserver {
  125. nc.removeObserver(msgChangedObserver)
  126. }
  127. if let incomingMsgObserver = self.incomingMsgObserver {
  128. nc.removeObserver(incomingMsgObserver)
  129. }
  130. if let msgsNoticedObserver = self.msgsNoticedObserver {
  131. nc.removeObserver(msgsNoticedObserver)
  132. }
  133. // remove non-block observers
  134. NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
  135. NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
  136. }
  137. // MARK: - setup
  138. private func setupSubviews() {
  139. emptySearchStateLabel.addCenteredTo(parentView: view)
  140. }
  141. // MARK: - configuration
  142. private func configureTableView() {
  143. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  144. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  145. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  146. tableView.rowHeight = ContactCell.cellHeight
  147. }
  148. @objc func applicationDidBecomeActive(_ notification: NSNotification) {
  149. if navigationController?.visibleViewController == self {
  150. startTimer()
  151. refreshInBg()
  152. }
  153. }
  154. private var inBgRefresh = false
  155. private var needsAnotherBgRefresh = false
  156. private func refreshInBg() {
  157. if inBgRefresh {
  158. needsAnotherBgRefresh = true
  159. } else {
  160. inBgRefresh = true
  161. DispatchQueue.global(qos: .userInteractive).async { [weak self] in
  162. // do at least one refresh, without inital delay
  163. // (refreshData() calls handleChatListUpdate() on main thread when done)
  164. self?.needsAnotherBgRefresh = false
  165. self?.viewModel.refreshData()
  166. // do subsequent refreshes with a delay of 500ms
  167. while self?.needsAnotherBgRefresh != false {
  168. usleep(500000)
  169. self?.needsAnotherBgRefresh = false
  170. self?.viewModel.refreshData()
  171. }
  172. self?.inBgRefresh = false
  173. }
  174. }
  175. }
  176. @objc func applicationWillResignActive(_ notification: NSNotification) {
  177. if navigationController?.visibleViewController == self {
  178. stopTimer()
  179. }
  180. }
  181. // MARK: - actions
  182. @objc func didPressNewChat() {
  183. showNewChatController()
  184. }
  185. @objc func cancelButtonPressed() {
  186. // cancel forwarding
  187. RelayHelper.sharedInstance.cancel()
  188. updateTitle()
  189. refreshInBg()
  190. }
  191. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  192. if previousTraitCollection?.preferredContentSizeCategory !=
  193. traitCollection.preferredContentSizeCategory {
  194. tableView.rowHeight = ContactCell.cellHeight
  195. }
  196. }
  197. private func quitSearch(animated: Bool) {
  198. searchController.searchBar.text = nil
  199. self.viewModel.endSearch()
  200. searchController.dismiss(animated: animated) {
  201. self.tableView.scrollToTop()
  202. }
  203. }
  204. // MARK: - UITableViewDelegate + UITableViewDatasource
  205. override func numberOfSections(in tableView: UITableView) -> Int {
  206. return viewModel.numberOfSections
  207. }
  208. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  209. return viewModel.numberOfRowsIn(section: section)
  210. }
  211. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  212. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  213. switch cellData.type {
  214. case .deaddrop:
  215. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  216. break
  217. }
  218. deaddropCell.updateCell(cellViewModel: cellData)
  219. return deaddropCell
  220. case .chat(let chatData):
  221. let chatId = chatData.chatId
  222. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  223. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  224. archiveCell.backgroundColor = DcColors.chatBackgroundColor
  225. return archiveCell
  226. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  227. // default chatCell
  228. chatCell.updateCell(cellViewModel: cellData)
  229. return chatCell
  230. }
  231. case .contact:
  232. safe_assert(viewModel.searchActive)
  233. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  234. contactCell.updateCell(cellViewModel: cellData)
  235. return contactCell
  236. }
  237. case .profile:
  238. safe_fatalError("CellData type profile not allowed")
  239. }
  240. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  241. return UITableViewCell()
  242. }
  243. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  244. return viewModel.titleForHeaderIn(section: section)
  245. }
  246. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  247. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  248. switch cellData.type {
  249. case .deaddrop(let deaddropData):
  250. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  251. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  252. case .chat(let chatData):
  253. let chatId = chatData.chatId
  254. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  255. showArchive()
  256. } else {
  257. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  258. }
  259. case .contact(let contactData):
  260. let contactId = contactData.contactId
  261. if let chatId = contactData.chatId {
  262. showChat(chatId: chatId)
  263. } else {
  264. self.askToChatWith(contactId: contactId)
  265. }
  266. case .profile:
  267. safe_fatalError("CellData type profile not allowed")
  268. }
  269. tableView.deselectRow(at: indexPath, animated: false)
  270. }
  271. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  272. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  273. return []
  274. }
  275. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  276. return []
  277. // returning nil may result in a default delete action,
  278. // see https://forums.developer.apple.com/thread/115030
  279. }
  280. let chat = dcContext.getChat(chatId: chatId)
  281. let archived = chat.isArchived
  282. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  283. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  284. self?.viewModel.archiveChatToggle(chatId: chatId)
  285. }
  286. archiveAction.backgroundColor = UIColor.lightGray
  287. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  288. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  289. self?.viewModel.pinChatToggle(chatId: chat.id)
  290. }
  291. pinAction.backgroundColor = UIColor.systemGreen
  292. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  293. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  294. }
  295. deleteAction.backgroundColor = UIColor.systemRed
  296. return [archiveAction, pinAction, deleteAction]
  297. }
  298. // MARK: updates
  299. private func updateTitle() {
  300. if RelayHelper.sharedInstance.isForwarding() {
  301. title = String.localized("forward_to")
  302. if !viewModel.isArchive {
  303. navigationItem.setLeftBarButton(cancelButton, animated: true)
  304. }
  305. } else {
  306. title = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  307. String.localized("pref_chats")
  308. navigationItem.setLeftBarButton(nil, animated: true)
  309. }
  310. }
  311. func handleChatListUpdate() {
  312. tableView.reloadData()
  313. if let emptySearchText = viewModel.emptySearchText {
  314. let text = String.localizedStringWithFormat(
  315. String.localized("search_no_result_for_x"),
  316. emptySearchText
  317. )
  318. emptySearchStateLabel.text = text
  319. emptySearchStateLabel.isHidden = false
  320. } else {
  321. emptySearchStateLabel.text = nil
  322. emptySearchStateLabel.isHidden = true
  323. }
  324. }
  325. private func startTimer() {
  326. // check if the timer is not yet started
  327. if !(timer?.isValid ?? false) {
  328. timer = Timer.scheduledTimer(withTimeInterval: 60, repeats: true) { [weak self] _ in
  329. self?.refreshInBg()
  330. }
  331. }
  332. }
  333. private func stopTimer() {
  334. // check if the timer is not already stopped
  335. if timer?.isValid ?? false {
  336. timer?.invalidate()
  337. }
  338. }
  339. // MARK: - alerts
  340. private func showDeleteChatConfirmationAlert(chatId: Int) {
  341. let alert = UIAlertController(
  342. title: nil,
  343. message: String.localized("ask_delete_chat_desktop"),
  344. preferredStyle: .safeActionSheet
  345. )
  346. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  347. self.deleteChat(chatId: chatId, animated: true)
  348. }))
  349. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  350. self.present(alert, animated: true, completion: nil)
  351. }
  352. private func showDeaddropRequestAlert(msgId: Int) {
  353. let dcMsg = DcMsg(id: msgId)
  354. let (title, startButton, blockButton) = MailboxViewController.deaddropQuestion(context: dcContext, msg: dcMsg)
  355. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  356. alert.addAction(UIAlertAction(title: startButton, style: .default, handler: { _ in
  357. let chat = self.dcContext.decideOnContactRequest(msgId, DC_DECISION_START_CHAT)
  358. self.showChat(chatId: chat.id)
  359. }))
  360. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  361. DispatchQueue.global(qos: .userInitiated).async {
  362. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_NOT_NOW)
  363. }
  364. }))
  365. alert.addAction(UIAlertAction(title: blockButton, style: .destructive, handler: { _ in
  366. DispatchQueue.global(qos: .userInitiated).async {
  367. self.dcContext.decideOnContactRequest(msgId, DC_DECISION_BLOCK)
  368. }
  369. }))
  370. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  371. present(alert, animated: true, completion: nil)
  372. }
  373. private func askToChatWith(contactId: Int) {
  374. let dcContact = DcContact(id: contactId)
  375. let alert = UIAlertController(
  376. title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr),
  377. message: nil,
  378. preferredStyle: .safeActionSheet)
  379. alert.addAction(UIAlertAction(
  380. title: String.localized("start_chat"),
  381. style: .default,
  382. handler: { _ in
  383. self.showNewChat(contactId: contactId)
  384. }))
  385. alert.addAction(UIAlertAction(
  386. title: String.localized("cancel"),
  387. style: .cancel,
  388. handler: { _ in
  389. }))
  390. self.present(alert, animated: true, completion: nil)
  391. }
  392. private func deleteChat(chatId: Int, animated: Bool) {
  393. if !animated {
  394. _ = viewModel.deleteChat(chatId: chatId)
  395. refreshInBg()
  396. return
  397. }
  398. if viewModel.searchActive {
  399. _ = viewModel.deleteChat(chatId: chatId)
  400. viewModel.refreshData()
  401. viewModel.updateSearchResults(for: searchController)
  402. return
  403. }
  404. if let row = viewModel.deleteChat(chatId: chatId) {
  405. tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .fade)
  406. }
  407. }
  408. // MARK: - coordinator
  409. private func showNewChatController() {
  410. let newChatVC = NewChatViewController(dcContext: dcContext)
  411. navigationController?.pushViewController(newChatVC, animated: true)
  412. }
  413. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  414. //let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId)
  415. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  416. navigationController?.pushViewController(chatVC, animated: animated)
  417. }
  418. private func showArchive() {
  419. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  420. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  421. navigationController?.pushViewController(controller, animated: true)
  422. }
  423. private func showNewChat(contactId: Int) {
  424. let chatId = dcContext.createChatByContactId(contactId: contactId)
  425. showChat(chatId: Int(chatId))
  426. }
  427. }
  428. // MARK: - uisearchbardelegate
  429. extension ChatListController: UISearchBarDelegate {
  430. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  431. viewModel.beginSearch()
  432. return true
  433. }
  434. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  435. // searchBar will be set to "" by system
  436. viewModel.endSearch()
  437. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  438. self.tableView.scrollToTop()
  439. }
  440. }
  441. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  442. tableView.scrollToTop()
  443. return true
  444. }
  445. }