ChatListController.swift 18 KB

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