ChatListController.swift 15 KB

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