ChatListController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 msgsNoticedObserver: Any?
  11. private var incomingMsgObserver: Any?
  12. private var viewChatObserver: Any?
  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 = "new Delta Chat 1.10 features at a glance:\n"
  68. // + "\n"
  69. // + "⚡ faster\n"
  70. // + "💕 share to Delta Chat\n"
  71. // + "🤫 mute chats\n"
  72. // + "🖼️ reworked gallery\n"
  73. // + "\n"
  74. // + "more details at https://delta.chat/en/2020-06-24-releases"
  75. //dcContext.addDeviceMessage(label: "update_1_10k_ios", msg: msg)
  76. // create view
  77. updateTitle()
  78. viewModel.refreshData()
  79. if RelayHelper.sharedInstance.isForwarding() {
  80. quitSearch(animated: false)
  81. tableView.scrollToTop()
  82. }
  83. let nc = NotificationCenter.default
  84. msgChangedObserver = nc.addObserver(
  85. forName: dcNotificationChanged,
  86. object: nil,
  87. queue: nil) { [weak self] _ in
  88. self?.viewModel.refreshData()
  89. }
  90. msgsNoticedObserver = nc.addObserver(
  91. forName: dcMsgsNoticed,
  92. object: nil,
  93. queue: nil) { [weak self] _ in
  94. self?.viewModel.refreshData()
  95. }
  96. incomingMsgObserver = nc.addObserver(
  97. forName: dcNotificationIncoming,
  98. object: nil,
  99. queue: nil) { [weak self] _ in
  100. self?.viewModel.refreshData()
  101. }
  102. viewChatObserver = nc.addObserver(
  103. forName: dcNotificationViewChat,
  104. object: nil,
  105. queue: nil) { [weak self] notification in
  106. if let chatId = notification.userInfo?["chat_id"] as? Int {
  107. self?.showChat(chatId: chatId)
  108. }
  109. }
  110. }
  111. override func viewDidDisappear(_ animated: Bool) {
  112. super.viewDidDisappear(animated)
  113. let nc = NotificationCenter.default
  114. if let msgChangedObserver = self.msgChangedObserver {
  115. nc.removeObserver(msgChangedObserver)
  116. }
  117. if let incomingMsgObserver = self.incomingMsgObserver {
  118. nc.removeObserver(incomingMsgObserver)
  119. }
  120. if let viewChatObserver = self.viewChatObserver {
  121. nc.removeObserver(viewChatObserver)
  122. }
  123. }
  124. // MARK: - setup
  125. private func setupSubviews() {
  126. view.addSubview(emptySearchStateLabel)
  127. emptySearchStateLabel.translatesAutoresizingMaskIntoConstraints = false
  128. emptySearchStateLabel.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  129. emptySearchStateLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  130. emptySearchStateLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  131. emptySearchStateLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  132. }
  133. // MARK: - configuration
  134. private func configureTableView() {
  135. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  136. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  137. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  138. tableView.rowHeight = ContactCell.cellHeight
  139. }
  140. // MARK: - actions
  141. @objc func didPressNewChat() {
  142. showNewChatController()
  143. }
  144. @objc func cancelButtonPressed() {
  145. // cancel forwarding
  146. RelayHelper.sharedInstance.cancel()
  147. viewModel.refreshData()
  148. updateTitle()
  149. }
  150. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  151. if previousTraitCollection?.preferredContentSizeCategory !=
  152. traitCollection.preferredContentSizeCategory {
  153. tableView.rowHeight = ContactCell.cellHeight
  154. }
  155. }
  156. private func quitSearch(animated: Bool) {
  157. searchController.searchBar.text = nil
  158. self.viewModel.endSearch()
  159. searchController.dismiss(animated: animated) {
  160. self.tableView.scrollToTop()
  161. }
  162. }
  163. // MARK: - UITableViewDelegate + UITableViewDatasource
  164. override func numberOfSections(in tableView: UITableView) -> Int {
  165. return viewModel.numberOfSections
  166. }
  167. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  168. return viewModel.numberOfRowsIn(section: section)
  169. }
  170. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  171. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  172. switch cellData.type {
  173. case .deaddrop:
  174. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  175. break
  176. }
  177. deaddropCell.updateCell(cellViewModel: cellData)
  178. return deaddropCell
  179. case .chat(let chatData):
  180. let chatId = chatData.chatId
  181. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  182. archiveCell.actionTitle = dcContext.getChat(chatId: chatId).name
  183. return archiveCell
  184. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  185. // default chatCell
  186. chatCell.updateCell(cellViewModel: cellData)
  187. return chatCell
  188. }
  189. case .contact:
  190. safe_assert(viewModel.searchActive)
  191. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  192. contactCell.updateCell(cellViewModel: cellData)
  193. return contactCell
  194. }
  195. case .profile:
  196. safe_fatalError("CellData type profile not allowed")
  197. }
  198. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  199. return UITableViewCell()
  200. }
  201. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  202. return viewModel.titleForHeaderIn(section: section)
  203. }
  204. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  205. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  206. switch cellData.type {
  207. case .deaddrop(let deaddropData):
  208. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  209. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  210. case .chat(let chatData):
  211. let chatId = chatData.chatId
  212. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  213. showArchive()
  214. } else {
  215. showChat(chatId: chatId, highlightedMsg: chatData.highlightMsgId)
  216. }
  217. case .contact(let contactData):
  218. let contactId = contactData.contactId
  219. if let chatId = contactData.chatId {
  220. showChat(chatId: chatId)
  221. } else {
  222. self.askToChatWith(contactId: contactId)
  223. }
  224. case .profile:
  225. safe_fatalError("CellData type profile not allowed")
  226. }
  227. tableView.deselectRow(at: indexPath, animated: false)
  228. }
  229. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  230. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  231. return []
  232. }
  233. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  234. return []
  235. // returning nil may result in a default delete action,
  236. // see https://forums.developer.apple.com/thread/115030
  237. }
  238. let chat = dcContext.getChat(chatId: chatId)
  239. let archived = chat.isArchived
  240. let archiveActionTitle: String = String.localized(archived ? "unarchive" : "archive")
  241. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  242. self?.viewModel.archiveChatToggle(chatId: chatId)
  243. }
  244. archiveAction.backgroundColor = UIColor.lightGray
  245. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  246. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  247. self?.viewModel.pinChatToggle(chatId: chat.id)
  248. }
  249. pinAction.backgroundColor = UIColor.systemGreen
  250. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  251. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  252. }
  253. deleteAction.backgroundColor = UIColor.systemRed
  254. return [archiveAction, pinAction, deleteAction]
  255. }
  256. // MARK: updates
  257. private func updateTitle() {
  258. if RelayHelper.sharedInstance.isForwarding() {
  259. title = String.localized("forward_to")
  260. if !viewModel.isArchive {
  261. navigationItem.setLeftBarButton(cancelButton, animated: true)
  262. }
  263. } else {
  264. title = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  265. String.localized("pref_chats")
  266. navigationItem.setLeftBarButton(nil, animated: true)
  267. }
  268. }
  269. func handleChatListUpdate() {
  270. tableView.reloadData()
  271. if let emptySearchText = viewModel.emptySearchText {
  272. let text = String.localizedStringWithFormat(
  273. String.localized("search_no_result_for_x"),
  274. emptySearchText
  275. )
  276. emptySearchStateLabel.text = text
  277. emptySearchStateLabel.isHidden = false
  278. } else {
  279. emptySearchStateLabel.text = nil
  280. emptySearchStateLabel.isHidden = true
  281. }
  282. }
  283. // MARK: - alerts
  284. private func showDeleteChatConfirmationAlert(chatId: Int) {
  285. let alert = UIAlertController(
  286. title: nil,
  287. message: String.localized("ask_delete_chat_desktop"),
  288. preferredStyle: .safeActionSheet
  289. )
  290. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  291. self.deleteChat(chatId: chatId, animated: true)
  292. }))
  293. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  294. self.present(alert, animated: true, completion: nil)
  295. }
  296. private func showDeaddropRequestAlert(msgId: Int) {
  297. let dcMsg = DcMsg(id: msgId)
  298. let dcContact = DcContact(id: dcMsg.fromContactId)
  299. let title = String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr)
  300. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  301. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { _ in
  302. let chat = self.dcContext.createChatByMessageId(msgId)
  303. self.showChat(chatId: chat.id)
  304. }))
  305. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  306. DispatchQueue.global(qos: .background).async {
  307. dcContact.marknoticed()
  308. }
  309. }))
  310. alert.addAction(UIAlertAction(title: String.localized("menu_block_contact"), style: .destructive, handler: { _ in
  311. DispatchQueue.global(qos: .background).async {
  312. dcContact.block()
  313. }
  314. }))
  315. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  316. present(alert, animated: true, completion: nil)
  317. }
  318. private func askToChatWith(contactId: Int) {
  319. let dcContact = DcContact(id: contactId)
  320. let alert = UIAlertController(
  321. title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr),
  322. message: nil,
  323. preferredStyle: .safeActionSheet)
  324. alert.addAction(UIAlertAction(
  325. title: String.localized("start_chat"),
  326. style: .default,
  327. handler: { _ in
  328. self.showNewChat(contactId: contactId)
  329. }))
  330. alert.addAction(UIAlertAction(
  331. title: String.localized("cancel"),
  332. style: .cancel,
  333. handler: { _ in
  334. }))
  335. self.present(alert, animated: true, completion: nil)
  336. }
  337. private func deleteChat(chatId: Int, animated: Bool) {
  338. if !animated {
  339. _ = viewModel.deleteChat(chatId: chatId)
  340. viewModel.refreshData()
  341. return
  342. }
  343. if viewModel.searchActive {
  344. _ = viewModel.deleteChat(chatId: chatId)
  345. viewModel.refreshData()
  346. viewModel.updateSearchResults(for: searchController)
  347. return
  348. }
  349. let row = viewModel.deleteChat(chatId: chatId)
  350. tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .fade)
  351. }
  352. // MARK: - coordinator
  353. private func showNewChatController() {
  354. let newChatVC = NewChatViewController(dcContext: dcContext)
  355. navigationController?.pushViewController(newChatVC, animated: true)
  356. }
  357. func showChat(chatId: Int, highlightedMsg: Int? = nil, animated: Bool = true) {
  358. //let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId)
  359. let chatVC = ChatViewController(dcContext: dcContext, chatId: chatId, highlightedMsg: highlightedMsg)
  360. navigationController?.pushViewController(chatVC, animated: animated)
  361. }
  362. private func showArchive() {
  363. let viewModel = ChatListViewModel(dcContext: dcContext, isArchive: true)
  364. let controller = ChatListController(dcContext: dcContext, viewModel: viewModel)
  365. navigationController?.pushViewController(controller, animated: true)
  366. }
  367. private func showNewChat(contactId: Int) {
  368. let chatId = dcContext.createChatByContactId(contactId: contactId)
  369. showChat(chatId: Int(chatId))
  370. }
  371. }
  372. // MARK: - uisearchbardelegate
  373. extension ChatListController: UISearchBarDelegate {
  374. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  375. viewModel.beginSearch()
  376. return true
  377. }
  378. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  379. // searchBar will be set to "" by system
  380. viewModel.endSearch()
  381. DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
  382. self.tableView.scrollToTop()
  383. }
  384. }
  385. func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  386. tableView.scrollToTop()
  387. return true
  388. }
  389. }