ChatListController.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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: Any?
  10. private var incomingMsgObserver: Any?
  11. private var viewChatObserver: Any?
  12. private lazy var searchController: UISearchController = {
  13. let searchController = UISearchController(searchResultsController: nil)
  14. searchController.searchResultsUpdater = viewModel
  15. searchController.obscuresBackgroundDuringPresentation = false
  16. searchController.searchBar.placeholder = String.localized("search")
  17. searchController.searchBar.delegate = self
  18. return searchController
  19. }()
  20. private lazy var newButton: UIBarButtonItem = {
  21. let button = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.compose, target: self, action: #selector(didPressNewChat))
  22. button.tintColor = DcColors.primary
  23. return button
  24. }()
  25. private lazy var cancelButton: UIBarButtonItem = {
  26. let button = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelButtonPressed))
  27. return button
  28. }()
  29. private lazy var emptySearchStateLabel: EmptyStateLabel = {
  30. let label = EmptyStateLabel()
  31. label.isHidden = false
  32. return label
  33. }()
  34. func getArchiveCell(title: String) -> UITableViewCell {
  35. let cell = UITableViewCell()
  36. cell.textLabel?.textColor = .systemBlue
  37. cell.textLabel?.text = title
  38. cell.textLabel?.textAlignment = .center
  39. return cell
  40. }
  41. init(dcContext: DcContext, viewModel: ChatListViewModelProtocol) {
  42. self.viewModel = viewModel
  43. self.dcContext = dcContext
  44. if viewModel.isArchive {
  45. super.init(nibName: nil, bundle: nil)
  46. } else {
  47. super.init(style: .grouped)
  48. }
  49. viewModel.onChatListUpdate = handleChatListUpdate // register listener
  50. }
  51. required init?(coder _: NSCoder) {
  52. fatalError("init(coder:) has not been implemented")
  53. }
  54. // MARK: - lifecycle
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. navigationItem.rightBarButtonItem = newButton
  58. if !viewModel.isArchive {
  59. navigationItem.searchController = searchController
  60. }
  61. configureTableView()
  62. setupSubviews()
  63. }
  64. override func viewWillAppear(_ animated: Bool) {
  65. super.viewWillAppear(animated)
  66. dcContext.updateDeviceChats()
  67. updateTitle()
  68. viewModel.refreshData()
  69. if RelayHelper.sharedInstance.isForwarding() {
  70. quitSearch(animated: false)
  71. tableView.scrollToTop()
  72. }
  73. let nc = NotificationCenter.default
  74. msgChangedObserver = nc.addObserver(
  75. forName: dcNotificationChanged,
  76. object: nil,
  77. queue: nil) { [weak self] _ in
  78. self?.viewModel.refreshData()
  79. }
  80. incomingMsgObserver = nc.addObserver(
  81. forName: dcNotificationIncoming,
  82. object: nil,
  83. queue: nil) { [weak self] _ in
  84. self?.viewModel.refreshData()
  85. }
  86. viewChatObserver = nc.addObserver(
  87. forName: dcNotificationViewChat,
  88. object: nil,
  89. queue: nil) { [weak self] notification in
  90. if let chatId = notification.userInfo?["chat_id"] as? Int {
  91. self?.showChat(chatId: chatId)
  92. }
  93. }
  94. }
  95. override func viewDidDisappear(_ animated: Bool) {
  96. super.viewDidDisappear(animated)
  97. let nc = NotificationCenter.default
  98. if let msgChangedObserver = self.msgChangedObserver {
  99. nc.removeObserver(msgChangedObserver)
  100. }
  101. if let incomingMsgObserver = self.incomingMsgObserver {
  102. nc.removeObserver(incomingMsgObserver)
  103. }
  104. if let viewChatObserver = self.viewChatObserver {
  105. nc.removeObserver(viewChatObserver)
  106. }
  107. }
  108. // MARK: - setup
  109. private func setupSubviews() {
  110. view.addSubview(emptySearchStateLabel)
  111. emptySearchStateLabel.translatesAutoresizingMaskIntoConstraints = false
  112. emptySearchStateLabel.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  113. emptySearchStateLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  114. emptySearchStateLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  115. emptySearchStateLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  116. }
  117. // MARK: - configuration
  118. private func configureTableView() {
  119. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  120. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  121. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  122. tableView.rowHeight = 80
  123. }
  124. // MARK: - actions
  125. @objc func didPressNewChat() {
  126. showNewChatController()
  127. }
  128. @objc func cancelButtonPressed() {
  129. // cancel forwarding
  130. RelayHelper.sharedInstance.cancel()
  131. viewModel.refreshData()
  132. updateTitle()
  133. }
  134. private func quitSearch(animated: Bool) {
  135. searchController.searchBar.text = nil
  136. self.viewModel.endSearch()
  137. searchController.dismiss(animated: animated) {
  138. self.tableView.scrollToTop()
  139. }
  140. }
  141. // MARK: - UITableViewDelegate + UITableViewDatasource
  142. override func numberOfSections(in tableView: UITableView) -> Int {
  143. return viewModel.numberOfSections
  144. }
  145. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  146. return viewModel.numberOfRowsIn(section: section)
  147. }
  148. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  149. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  150. switch cellData.type {
  151. case .deaddrop:
  152. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  153. break
  154. }
  155. deaddropCell.updateCell(cellViewModel: cellData)
  156. return deaddropCell
  157. case .chat(let chatData):
  158. let chatId = chatData.chatId
  159. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  160. return getArchiveCell(title: dcContext.getChat(chatId: chatId).name)
  161. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  162. // default chatCell
  163. chatCell.updateCell(cellViewModel: cellData)
  164. return chatCell
  165. }
  166. case .contact:
  167. safe_assert(viewModel.searchActive)
  168. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  169. contactCell.updateCell(cellViewModel: cellData)
  170. return contactCell
  171. }
  172. }
  173. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  174. return UITableViewCell()
  175. }
  176. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  177. return viewModel.titleForHeaderIn(section: section)
  178. }
  179. override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
  180. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  181. switch cellData.type {
  182. case .deaddrop(let deaddropData):
  183. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  184. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  185. case .chat(let chatData):
  186. let chatId = chatData.chatId
  187. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  188. showArchive()
  189. } else {
  190. showChat(chatId: chatId)
  191. }
  192. case .contact(let contactData):
  193. let contactId = contactData.contactId
  194. if let chatId = contactData.chatId {
  195. showChat(chatId: chatId)
  196. } else {
  197. self.askToChatWith(contactId: contactId)
  198. }
  199. }
  200. }
  201. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  202. if viewModel.searchActive {
  203. // no swipe actions during search
  204. return []
  205. }
  206. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  207. return []
  208. }
  209. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  210. return []
  211. // returning nil may result in a default delete action,
  212. // see https://forums.developer.apple.com/thread/115030
  213. }
  214. let archiveActionTitle: String = String.localized(viewModel.isArchive ? "unarchive" : "archive")
  215. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  216. self?.viewModel.archiveChatToggle(chatId: chatId)
  217. }
  218. archiveAction.backgroundColor = UIColor.lightGray
  219. let chat = dcContext.getChat(chatId: chatId)
  220. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  221. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  222. self?.viewModel.pinChatToggle(chatId: chat.id)
  223. }
  224. pinAction.backgroundColor = UIColor.systemGreen
  225. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  226. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  227. }
  228. deleteAction.backgroundColor = UIColor.systemRed
  229. return [archiveAction, pinAction, deleteAction]
  230. }
  231. // MARK: updates
  232. private func updateTitle() {
  233. if RelayHelper.sharedInstance.isForwarding() {
  234. title = String.localized("forward_to")
  235. if !viewModel.isArchive {
  236. navigationItem.setLeftBarButton(cancelButton, animated: true)
  237. }
  238. } else {
  239. title = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  240. String.localized("pref_chats")
  241. navigationItem.setLeftBarButton(nil, animated: true)
  242. }
  243. }
  244. func handleChatListUpdate() {
  245. tableView.reloadData()
  246. if let emptySearchText = viewModel.emptySearchText {
  247. let text = String.localizedStringWithFormat(
  248. String.localized("search_no_result_for_x"),
  249. emptySearchText
  250. )
  251. emptySearchStateLabel.text = text
  252. emptySearchStateLabel.isHidden = false
  253. } else {
  254. emptySearchStateLabel.text = nil
  255. emptySearchStateLabel.isHidden = true
  256. }
  257. }
  258. func getArchiveCell(_ tableView: UITableView, title: String) -> UITableViewCell {
  259. let archiveCell: UITableViewCell
  260. if let cell = tableView.dequeueReusableCell(withIdentifier: "ArchiveCell") {
  261. archiveCell = cell
  262. } else {
  263. archiveCell = UITableViewCell(style: .default, reuseIdentifier: "ArchiveCell")
  264. }
  265. archiveCell.textLabel?.textAlignment = .center
  266. archiveCell.textLabel?.text = title
  267. archiveCell.textLabel?.textColor = UIColor.systemBlue
  268. return archiveCell
  269. }
  270. // MARK: - alerts
  271. private func showDeleteChatConfirmationAlert(chatId: Int) {
  272. let alert = UIAlertController(
  273. title: nil,
  274. message: String.localized("ask_delete_chat_desktop"),
  275. preferredStyle: .safeActionSheet
  276. )
  277. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  278. self.deleteChat(chatId: chatId, animated: true)
  279. }))
  280. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  281. self.present(alert, animated: true, completion: nil)
  282. }
  283. private func showDeaddropRequestAlert(msgId: Int) {
  284. let dcMsg = DcMsg(id: msgId)
  285. let dcContact = DcContact(id: dcMsg.fromContactId)
  286. let title = String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr)
  287. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  288. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { _ in
  289. let chat = self.dcContext.createChatByMessageId(msgId)
  290. self.showChat(chatId: chat.id)
  291. }))
  292. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  293. dcContact.marknoticed()
  294. }))
  295. alert.addAction(UIAlertAction(title: String.localized("menu_block_contact"), style: .destructive, handler: { _ in
  296. dcContact.block()
  297. }))
  298. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  299. present(alert, animated: true, completion: nil)
  300. }
  301. private func askToChatWith(contactId: Int) {
  302. let dcContact = DcContact(id: contactId)
  303. let alert = UIAlertController(
  304. title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr),
  305. message: nil,
  306. preferredStyle: .safeActionSheet)
  307. alert.addAction(UIAlertAction(
  308. title: String.localized("start_chat"),
  309. style: .default,
  310. handler: { _ in
  311. self.showNewChat(contactId: contactId)
  312. }))
  313. alert.addAction(UIAlertAction(
  314. title: String.localized("cancel"),
  315. style: .cancel,
  316. handler: { _ in
  317. }))
  318. self.present(alert, animated: true, completion: nil)
  319. }
  320. private func deleteChat(chatId: Int, animated: Bool) {
  321. if !animated {
  322. _ = viewModel.deleteChat(chatId: chatId)
  323. viewModel.refreshData()
  324. return
  325. }
  326. let row = viewModel.deleteChat(chatId: chatId)
  327. tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .fade)
  328. }
  329. // MARK: - coordinator
  330. private func showNewChatController() {
  331. let newChatVC = NewChatViewController(dcContext: dcContext)
  332. navigationController?.pushViewController(newChatVC, animated: true)
  333. }
  334. func showChat(chatId: Int, animated: Bool = true) {
  335. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId)
  336. navigationController?.pushViewController(chatVC, animated: animated)
  337. }
  338. private func showArchive() {
  339. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  340. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  341. navigationController?.pushViewController(controller, animated: true)
  342. }
  343. private func showNewChat(contactId: Int) {
  344. let chatId = dcContext.createChatByContactId(contactId: contactId)
  345. showChat(chatId: Int(chatId))
  346. }
  347. }
  348. // MARK: - uisearchbardelegate
  349. extension ChatListController: UISearchBarDelegate {
  350. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  351. viewModel.beginSearch()
  352. return true
  353. }
  354. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  355. // searchBar will be set to "" by system
  356. viewModel.endSearch()
  357. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  358. self.tableView.scrollToTop()
  359. }
  360. }
  361. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  362. tableView.scrollToTop()
  363. return true
  364. }
  365. }