ChatListController.swift 15 KB

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