ChatListController.swift 17 KB

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