ChatListController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import UIKit
  2. class ChatListController: UITableViewController {
  3. weak var coordinator: ChatListCoordinator?
  4. let viewModel: ChatListViewModelProtocol
  5. private let chatCellReuseIdentifier = "chat_cell"
  6. private let deadDropCellReuseIdentifier = "deaddrop_cell"
  7. private let contactCellReuseIdentifier = "contact_cell"
  8. private var msgChangedObserver: Any?
  9. private var incomingMsgObserver: Any?
  10. private var viewChatObserver: Any?
  11. private var deleteChatObserver: 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. func getArchiveCell(title: String) -> UITableViewCell {
  30. let cell = UITableViewCell()
  31. cell.textLabel?.textColor = .systemBlue
  32. cell.textLabel?.text = title
  33. cell.textLabel?.textAlignment = .center
  34. return cell
  35. }
  36. init(viewModel: ChatListViewModelProtocol) {
  37. self.viewModel = viewModel
  38. if viewModel.isArchive {
  39. super.init(nibName: nil, bundle: nil)
  40. } else {
  41. super.init(style: .grouped)
  42. }
  43. viewModel.onChatListUpdate = handleChatListUpdate // register listener
  44. }
  45. required init?(coder _: NSCoder) {
  46. fatalError("init(coder:) has not been implemented")
  47. }
  48. // MARK: - lifecycle
  49. override func viewDidLoad() {
  50. super.viewDidLoad()
  51. navigationItem.rightBarButtonItem = newButton
  52. if !viewModel.isArchive {
  53. navigationItem.searchController = searchController
  54. }
  55. configureTableView()
  56. }
  57. override func viewWillAppear(_ animated: Bool) {
  58. super.viewWillAppear(animated)
  59. updateTitle()
  60. viewModel.refreshData()
  61. if RelayHelper.sharedInstance.isForwarding() {
  62. quitSearch(animated: false)
  63. tableView.scrollToTop()
  64. }
  65. let nc = NotificationCenter.default
  66. msgChangedObserver = nc.addObserver(
  67. forName: dcNotificationChanged,
  68. object: nil,
  69. queue: nil) { _ in
  70. self.viewModel.refreshData()
  71. }
  72. incomingMsgObserver = nc.addObserver(
  73. forName: dcNotificationIncoming,
  74. object: nil,
  75. queue: nil) { _ in
  76. self.viewModel.refreshData()
  77. }
  78. viewChatObserver = nc.addObserver(
  79. forName: dcNotificationViewChat,
  80. object: nil,
  81. queue: nil) { notification in
  82. if let chatId = notification.userInfo?["chat_id"] as? Int {
  83. self.coordinator?.showChat(chatId: chatId)
  84. }
  85. }
  86. deleteChatObserver = nc.addObserver(
  87. forName: dcNotificationChatDeletedInChatDetail,
  88. object: nil,
  89. queue: nil) { notification in
  90. if let chatId = notification.userInfo?["chat_id"] as? Int {
  91. self.deleteChat(chatId: chatId, animated: true)
  92. }
  93. }
  94. }
  95. override func viewDidDisappear(_ animated: Bool) {
  96. super.viewDidDisappear(animated)
  97. let nc = NotificationCenter.default
  98. if let msgChangedObserver = self.msgChangedObserver {
  99. nc.removeObserver(msgChangedObserver)
  100. }
  101. if let incomingMsgObserver = self.incomingMsgObserver {
  102. nc.removeObserver(incomingMsgObserver)
  103. }
  104. if let viewChatObserver = self.viewChatObserver {
  105. nc.removeObserver(viewChatObserver)
  106. }
  107. if let deleteChatObserver = self.deleteChatObserver {
  108. nc.removeObserver(deleteChatObserver)
  109. }
  110. }
  111. // MARK: - configuration
  112. private func configureTableView() {
  113. tableView.register(ContactCell.self, forCellReuseIdentifier: chatCellReuseIdentifier)
  114. tableView.register(ContactCell.self, forCellReuseIdentifier: deadDropCellReuseIdentifier)
  115. tableView.register(ContactCell.self, forCellReuseIdentifier: contactCellReuseIdentifier)
  116. tableView.rowHeight = 80
  117. }
  118. // MARK: - actions
  119. @objc func didPressNewChat() {
  120. coordinator?.showNewChatController()
  121. }
  122. @objc func cancelButtonPressed() {
  123. // cancel forwarding
  124. RelayHelper.sharedInstance.cancel()
  125. viewModel.refreshData()
  126. updateTitle()
  127. }
  128. private func quitSearch(animated: Bool) {
  129. searchController.searchBar.text = nil
  130. self.viewModel.endSearch()
  131. searchController.dismiss(animated: animated) {
  132. self.tableView.scrollToTop()
  133. }
  134. }
  135. // MARK: - UITableViewDelegate + UITableViewDatasource
  136. override func numberOfSections(in tableView: UITableView) -> Int {
  137. return viewModel.numberOfSections
  138. }
  139. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  140. return viewModel.numberOfRowsIn(section: section)
  141. }
  142. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  143. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  144. switch cellData.type {
  145. case .deaddrop:
  146. guard let deaddropCell = tableView.dequeueReusableCell(withIdentifier: deadDropCellReuseIdentifier, for: indexPath) as? ContactCell else {
  147. break
  148. }
  149. deaddropCell.updateCell(cellViewModel: cellData)
  150. return deaddropCell
  151. case .chat(let chatData):
  152. let chatId = chatData.chatId
  153. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  154. return getArchiveCell(title: DcChat(id: chatId).name)
  155. } else if let chatCell = tableView.dequeueReusableCell(withIdentifier: chatCellReuseIdentifier, for: indexPath) as? ContactCell {
  156. // default chatCell
  157. chatCell.updateCell(cellViewModel: cellData)
  158. return chatCell
  159. }
  160. case .contact:
  161. safe_assert(viewModel.searchActive)
  162. if let contactCell = tableView.dequeueReusableCell(withIdentifier: contactCellReuseIdentifier, for: indexPath) as? ContactCell {
  163. contactCell.updateCell(cellViewModel: cellData)
  164. return contactCell
  165. }
  166. }
  167. safe_fatalError("Could not find/dequeue or recycle UITableViewCell.")
  168. return UITableViewCell()
  169. }
  170. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  171. return viewModel.titleForHeaderIn(section: section)
  172. }
  173. override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
  174. let cellData = viewModel.cellDataFor(section: indexPath.section, row: indexPath.row)
  175. switch cellData.type {
  176. case .deaddrop(let deaddropData):
  177. safe_assert(deaddropData.chatId == DC_CHAT_ID_DEADDROP)
  178. showDeaddropRequestAlert(msgId: deaddropData.msgId)
  179. case .chat(let chatData):
  180. let chatId = chatData.chatId
  181. if chatId == DC_CHAT_ID_ARCHIVED_LINK {
  182. coordinator?.showArchive()
  183. } else {
  184. coordinator?.showChat(chatId: chatId)
  185. }
  186. case .contact(let contactData):
  187. let contactId = contactData.contactId
  188. if let chatId = contactData.chatId {
  189. coordinator?.showChat(chatId: chatId)
  190. } else {
  191. self.askToChatWith(contactId: contactId)
  192. }
  193. }
  194. }
  195. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  196. if viewModel.searchActive {
  197. // no swipe actions during search
  198. return []
  199. }
  200. guard let chatId = viewModel.chatIdFor(section: indexPath.section, row: indexPath.row) else {
  201. return []
  202. }
  203. if chatId==DC_CHAT_ID_ARCHIVED_LINK || chatId==DC_CHAT_ID_DEADDROP {
  204. return []
  205. // returning nil may result in a default delete action,
  206. // see https://forums.developer.apple.com/thread/115030
  207. }
  208. let archiveActionTitle: String = String.localized(viewModel.isArchive ? "unarchive" : "archive")
  209. let archiveAction = UITableViewRowAction(style: .destructive, title: archiveActionTitle) { [unowned self] _, _ in
  210. self.viewModel.archiveChatToggle(chatId: chatId)
  211. }
  212. archiveAction.backgroundColor = UIColor.lightGray
  213. let chat = DcChat(id: chatId)
  214. let pinned = chat.visibility==DC_CHAT_VISIBILITY_PINNED
  215. let pinAction = UITableViewRowAction(style: .destructive, title: String.localized(pinned ? "unpin" : "pin")) { [unowned self] _, _ in
  216. self.viewModel.pinChatToggle(chatId: chat.id)
  217. }
  218. pinAction.backgroundColor = UIColor.systemGreen
  219. let deleteAction = UITableViewRowAction(style: .normal, title: String.localized("delete")) { [unowned self] _, _ in
  220. self.showDeleteChatConfirmationAlert(chatId: chatId)
  221. }
  222. deleteAction.backgroundColor = UIColor.systemRed
  223. return [archiveAction, pinAction, deleteAction]
  224. }
  225. // MARK: updates
  226. private func updateTitle() {
  227. if RelayHelper.sharedInstance.isForwarding() {
  228. title = String.localized("forward_to")
  229. if !viewModel.isArchive {
  230. navigationItem.setLeftBarButton(cancelButton, animated: true)
  231. }
  232. } else {
  233. title = viewModel.isArchive ? String.localized("chat_archived_chats_title") :
  234. String.localized("pref_chats")
  235. navigationItem.setLeftBarButton(nil, animated: true)
  236. }
  237. }
  238. func handleChatListUpdate() {
  239. tableView.reloadData()
  240. }
  241. func getArchiveCell(_ tableView: UITableView, title: String) -> UITableViewCell {
  242. let archiveCell: UITableViewCell
  243. if let cell = tableView.dequeueReusableCell(withIdentifier: "ArchiveCell") {
  244. archiveCell = cell
  245. } else {
  246. archiveCell = UITableViewCell(style: .default, reuseIdentifier: "ArchiveCell")
  247. }
  248. archiveCell.textLabel?.textAlignment = .center
  249. archiveCell.textLabel?.text = title
  250. archiveCell.textLabel?.textColor = .systemBlue
  251. return archiveCell
  252. }
  253. // MARK: - alerts
  254. private func showDeleteChatConfirmationAlert(chatId: Int) {
  255. let alert = UIAlertController(
  256. title: nil,
  257. message: String.localized("ask_delete_chat_desktop"),
  258. preferredStyle: .safeActionSheet
  259. )
  260. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  261. self.deleteChat(chatId: chatId, animated: true)
  262. }))
  263. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  264. self.present(alert, animated: true, completion: nil)
  265. }
  266. private func showDeaddropRequestAlert(msgId: Int) {
  267. let dcMsg = DcMsg(id: msgId)
  268. let dcContact = DcContact(id: dcMsg.fromContactId)
  269. let title = String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr)
  270. let alert = UIAlertController(title: title, message: nil, preferredStyle: .safeActionSheet)
  271. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { _ in
  272. let chat = dcMsg.createChat()
  273. self.coordinator?.showChat(chatId: chat.id)
  274. }))
  275. alert.addAction(UIAlertAction(title: String.localized("not_now"), style: .default, handler: { _ in
  276. dcContact.marknoticed()
  277. }))
  278. alert.addAction(UIAlertAction(title: String.localized("menu_block_contact"), style: .destructive, handler: { _ in
  279. dcContact.block()
  280. }))
  281. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  282. present(alert, animated: true, completion: nil)
  283. }
  284. private func askToChatWith(contactId: Int) {
  285. let dcContact = DcContact(id: contactId)
  286. let alert = UIAlertController(
  287. title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr),
  288. message: nil,
  289. preferredStyle: .safeActionSheet)
  290. alert.addAction(UIAlertAction(
  291. title: String.localized("start_chat"),
  292. style: .default,
  293. handler: { _ in
  294. self.coordinator?.showNewChat(contactId: contactId)
  295. }))
  296. alert.addAction(UIAlertAction(
  297. title: String.localized("cancel"),
  298. style: .cancel,
  299. handler: { _ in
  300. }))
  301. self.present(alert, animated: true, completion: nil)
  302. }
  303. private func deleteChat(chatId: Int, animated: Bool) {
  304. if !animated {
  305. _ = viewModel.deleteChat(chatId: chatId)
  306. viewModel.refreshData()
  307. return
  308. }
  309. let row = viewModel.deleteChat(chatId: chatId)
  310. tableView.deleteRows(at: [IndexPath(row: row, section: 0)], with: .fade)
  311. }
  312. }
  313. // MARK: - uisearchbardelegate
  314. extension ChatListController: UISearchBarDelegate {
  315. func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
  316. viewModel.beginSearch()
  317. return true
  318. }
  319. func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
  320. // searchBar will be set to "" by system
  321. viewModel.endSearch()
  322. }
  323. }