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 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. // add welcome message
  67. dcContext.updateDeviceChats()
  68. // update messages - for new messages, do not reuse or modify strings but create new ones.
  69. // it is not needed to keep all past update messages, however, when deleted, also the strings should be deleted.
  70. let msg = DcMsg(viewType: DC_MSG_TEXT)
  71. msg.text = "new Delta Chat 1.10 features at a glance:\n"
  72. + "\n"
  73. + "⚡ faster\n"
  74. + "💕 share to Delta Chat\n"
  75. + "🤫 mute chats\n"
  76. + "🖼️ reworked gallery\n"
  77. + "\n"
  78. + "more details at https://delta.chat/en/2020-06-24-releases"
  79. dcContext.addDeviceMessage(label: "update_1_10k_ios", msg: msg)
  80. // create view
  81. updateTitle()
  82. viewModel.refreshData()
  83. if RelayHelper.sharedInstance.isForwarding() {
  84. quitSearch(animated: false)
  85. tableView.scrollToTop()
  86. }
  87. let nc = NotificationCenter.default
  88. msgChangedObserver = nc.addObserver(
  89. forName: dcNotificationChanged,
  90. object: nil,
  91. queue: nil) { [weak self] _ in
  92. self?.viewModel.refreshData()
  93. }
  94. incomingMsgObserver = nc.addObserver(
  95. forName: dcNotificationIncoming,
  96. object: nil,
  97. queue: nil) { [weak self] _ in
  98. self?.viewModel.refreshData()
  99. }
  100. viewChatObserver = nc.addObserver(
  101. forName: dcNotificationViewChat,
  102. object: nil,
  103. queue: nil) { [weak self] notification in
  104. if let chatId = notification.userInfo?["chat_id"] as? Int {
  105. self?.showChat(chatId: chatId)
  106. }
  107. }
  108. }
  109. override func viewDidDisappear(_ animated: Bool) {
  110. super.viewDidDisappear(animated)
  111. let nc = NotificationCenter.default
  112. if let msgChangedObserver = self.msgChangedObserver {
  113. nc.removeObserver(msgChangedObserver)
  114. }
  115. if let incomingMsgObserver = self.incomingMsgObserver {
  116. nc.removeObserver(incomingMsgObserver)
  117. }
  118. if let viewChatObserver = self.viewChatObserver {
  119. nc.removeObserver(viewChatObserver)
  120. }
  121. }
  122. // MARK: - setup
  123. private func setupSubviews() {
  124. view.addSubview(emptySearchStateLabel)
  125. emptySearchStateLabel.translatesAutoresizingMaskIntoConstraints = false
  126. emptySearchStateLabel.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor).isActive = true
  127. emptySearchStateLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 40).isActive = true
  128. emptySearchStateLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40).isActive = true
  129. emptySearchStateLabel.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor).isActive = true
  130. }
  131. // MARK: - configuration
  132. private func configureTableView() {
  133. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  134. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  135. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  136. tableView.rowHeight = 80
  137. }
  138. // MARK: - actions
  139. @objc func didPressNewChat() {
  140. showNewChatController()
  141. }
  142. @objc func cancelButtonPressed() {
  143. // cancel forwarding
  144. RelayHelper.sharedInstance.cancel()
  145. viewModel.refreshData()
  146. updateTitle()
  147. }
  148. private func quitSearch(animated: Bool) {
  149. searchController.searchBar.text = nil
  150. self.viewModel.endSearch()
  151. searchController.dismiss(animated: animated) {
  152. self.tableView.scrollToTop()
  153. }
  154. }
  155. // MARK: - UITableViewDelegate + UITableViewDatasource
  156. override func numberOfSections(in tableView: UITableView) -> Int {
  157. return viewModel.numberOfSections
  158. }
  159. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  160. return viewModel.numberOfRowsIn(section: section)
  161. }
  162. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  163. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  164. switch cellData.type {
  165. case .deaddrop:
  166. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  167. break
  168. }
  169. deaddropCell.updateCell(cellViewModel: cellData)
  170. return deaddropCell
  171. case .chat(let chatData):
  172. let chatId = chatData.chatId
  173. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  174. return getArchiveCell(title: dcContext.getChat(chatId: chatId).name)
  175. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  176. // default chatCell
  177. chatCell.updateCell(cellViewModel: cellData)
  178. return chatCell
  179. }
  180. case .contact:
  181. safe_assert(viewModel.searchActive)
  182. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  183. contactCell.updateCell(cellViewModel: cellData)
  184. return contactCell
  185. }
  186. }
  187. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  188. return UITableViewCell()
  189. }
  190. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  191. return viewModel.titleForHeaderIn(section: section)
  192. }
  193. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  194. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  195. switch cellData.type {
  196. case .deaddrop(let deaddropData):
  197. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  198. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  199. case .chat(let chatData):
  200. let chatId = chatData.chatId
  201. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  202. showArchive()
  203. } else {
  204. showChat(chatId: chatId)
  205. }
  206. case .contact(let contactData):
  207. let contactId = contactData.contactId
  208. if let chatId = contactData.chatId {
  209. showChat(chatId: chatId)
  210. } else {
  211. self.askToChatWith(contactId: contactId)
  212. }
  213. }
  214. tableView.deselectRow(at: indexPath, animated: false)
  215. }
  216. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  217. if viewModel.searchActive {
  218. // no swipe actions during search
  219. return []
  220. }
  221. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  222. return []
  223. }
  224. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  225. return []
  226. // returning nil may result in a default delete action,
  227. // see https://forums.developer.apple.com/thread/115030
  228. }
  229. let archiveActionTitle: String = String.localized(viewModel.isArchive ? "unarchive" : "archive")
  230. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [weak self] _, _ in
  231. self?.viewModel.archiveChatToggle(chatId: chatId)
  232. }
  233. archiveAction.backgroundColor = UIColor.lightGray
  234. let chat = dcContext.getChat(chatId: chatId)
  235. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  236. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [weak self] _, _ in
  237. self?.viewModel.pinChatToggle(chatId: chat.id)
  238. }
  239. pinAction.backgroundColor = UIColor.systemGreen
  240. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [weak self] _, _ in
  241. self?.showDeleteChatConfirmationAlert(chatId: chatId)
  242. }
  243. deleteAction.backgroundColor = UIColor.systemRed
  244. return [archiveAction, pinAction, deleteAction]
  245. }
  246. // MARK: updates
  247. private func updateTitle() {
  248. if RelayHelper.sharedInstance.isForwarding() {
  249. title = String.localized("forward_to")
  250. if !viewModel.isArchive {
  251. navigationItem.setLeftBarButton(cancelButton, animated: true)
  252. }
  253. } else {
  254. title = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  255. String.localized("pref_chats")
  256. navigationItem.setLeftBarButton(nil, animated: true)
  257. }
  258. }
  259. func handleChatListUpdate() {
  260. tableView.reloadData()
  261. if let emptySearchText = viewModel.emptySearchText {
  262. let text = String.localizedStringWithFormat(
  263. String.localized("search_no_result_for_x"),
  264. emptySearchText
  265. )
  266. emptySearchStateLabel.text = text
  267. emptySearchStateLabel.isHidden = false
  268. } else {
  269. emptySearchStateLabel.text = nil
  270. emptySearchStateLabel.isHidden = true
  271. }
  272. }
  273. func getArchiveCell(_ tableView: UITableView, title: String) -> UITableViewCell {
  274. let archiveCell: UITableViewCell
  275. if let cell = tableView.dequeueReusableCell(withIdentifier: "ArchiveCell") {
  276. archiveCell = cell
  277. } else {
  278. archiveCell = UITableViewCell(style: .default, reuseIdentifier: "ArchiveCell")
  279. }
  280. archiveCell.textLabel?.textAlignment = .center
  281. archiveCell.textLabel?.text = title
  282. archiveCell.textLabel?.textColor = UIColor.systemBlue
  283. return archiveCell
  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. let row = viewModel.deleteChat(chatId: chatId)
  342. tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .fade)
  343. }
  344. // MARK: - coordinator
  345. private func showNewChatController() {
  346. let newChatVC = NewChatViewController(dcContext: dcContext)
  347. navigationController?.pushViewController(newChatVC, animated: true)
  348. }
  349. func showChat(chatId: Int, animated: Bool = true) {
  350. let chatVC = ChatViewController(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. }