ChatListController.swift 17 KB

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