NewChatViewController.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import Contacts
  2. import UIKit
  3. import DcCore
  4. class NewChatViewController: UITableViewController {
  5. private let dcContext: DcContext
  6. private let sectionNew = 0
  7. private let sectionNewRowNewContact = 0
  8. private let sectionNewRowNewGroup = 1
  9. private let sectionNewRowNewVerifiedGroup = 2
  10. private let sectionNewRowCount = 3
  11. private let sectionImportedContacts = 1
  12. private var sectionContacts: Int { return deviceContactAccessGranted ? 1 : 2 }
  13. private var sectionsCount: Int { return deviceContactAccessGranted ? 2 : 3 }
  14. private lazy var searchController: UISearchController = {
  15. let searchController = UISearchController(searchResultsController: nil)
  16. searchController.searchResultsUpdater = self
  17. searchController.obscuresBackgroundDuringPresentation = false
  18. searchController.searchBar.placeholder = String.localized("search")
  19. return searchController
  20. }()
  21. private lazy var emptySearchStateLabel: EmptyStateLabel = {
  22. let label = EmptyStateLabel()
  23. label.isHidden = true
  24. return label
  25. }()
  26. private var contactIds: [Int]
  27. private var filteredContactIds: [Int] = []
  28. private var searchText: String? {
  29. return searchController.searchBar.text
  30. }
  31. // searchBar active?
  32. var isFiltering: Bool {
  33. return !searchBarIsEmpty
  34. }
  35. private var searchBarIsEmpty: Bool {
  36. return searchController.searchBar.text?.isEmpty ?? true
  37. }
  38. lazy var deviceContactHandler: DeviceContactsHandler = {
  39. let handler = DeviceContactsHandler(dcContext: DcContext.shared)
  40. handler.contactListDelegate = self
  41. return handler
  42. }()
  43. var deviceContactAccessGranted: Bool = false {
  44. didSet {
  45. tableView.reloadData()
  46. }
  47. }
  48. init(dcContext: DcContext) {
  49. self.dcContext = dcContext
  50. self.contactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF)
  51. super.init(style: .grouped)
  52. hidesBottomBarWhenPushed = true
  53. }
  54. required init?(coder _: NSCoder) {
  55. fatalError("init(coder:) has not been implemented")
  56. }
  57. // MARK: - lifecycle
  58. override func viewDidLoad() {
  59. super.viewDidLoad()
  60. title = String.localized("menu_new_chat")
  61. deviceContactHandler.importDeviceContacts()
  62. navigationItem.searchController = searchController
  63. definesPresentationContext = true // to make sure searchbar will only be shown in this viewController
  64. if #available(iOS 11.0, *) {
  65. navigationItem.hidesSearchBarWhenScrolling = false
  66. }
  67. tableView.register(ActionCell.self, forCellReuseIdentifier: "actionCell")
  68. tableView.register(ContactCell.self, forCellReuseIdentifier: "contactCell")
  69. }
  70. override func viewWillAppear(_ animated: Bool) {
  71. super.viewWillAppear(animated)
  72. deviceContactAccessGranted = CNContactStore.authorizationStatus(for: .contacts) == .authorized
  73. }
  74. // MARK: - actions
  75. @objc func cancelButtonPressed() {
  76. dismiss(animated: true, completion: nil)
  77. }
  78. // MARK: - Table view data source
  79. override func numberOfSections(in _: UITableView) -> Int {
  80. return sectionsCount
  81. }
  82. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  83. if section == sectionNew {
  84. return sectionNewRowCount
  85. } else if section == sectionImportedContacts {
  86. if deviceContactAccessGranted {
  87. return isFiltering ? filteredContactIds.count : contactIds.count
  88. } else {
  89. return 1
  90. }
  91. } else {
  92. return isFiltering ? filteredContactIds.count : contactIds.count
  93. }
  94. }
  95. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  96. let section = indexPath.section
  97. if section == sectionNew {
  98. return UITableView.automaticDimension
  99. } else if section == sectionImportedContacts {
  100. if deviceContactAccessGranted {
  101. return ContactCell.cellHeight
  102. } else {
  103. return UITableView.automaticDimension
  104. }
  105. } else {
  106. return ContactCell.cellHeight
  107. }
  108. }
  109. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  110. let section = indexPath.section
  111. let row = indexPath.row
  112. if section == sectionNew {
  113. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  114. if let actionCell = cell as? ActionCell {
  115. switch row {
  116. case sectionNewRowNewGroup:
  117. actionCell.actionTitle = String.localized("menu_new_group")
  118. case sectionNewRowNewVerifiedGroup:
  119. actionCell.actionTitle = String.localized("menu_new_verified_group")
  120. default:
  121. actionCell.actionTitle = String.localized("menu_new_contact")
  122. }
  123. }
  124. return cell
  125. } else if section == sectionImportedContacts {
  126. // import device contacts section
  127. if deviceContactAccessGranted {
  128. let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
  129. if let contactCell = cell as? ContactCell {
  130. let contactCellViewModel = self.contactViewModelBy(row: indexPath.row)
  131. contactCell.updateCell(cellViewModel: contactCellViewModel)
  132. }
  133. return cell
  134. } else {
  135. let cell = tableView.dequeueReusableCell(withIdentifier: "actionCell", for: indexPath)
  136. if let actionCell = cell as? ActionCell {
  137. actionCell.actionTitle = String.localized("import_contacts")
  138. }
  139. return cell
  140. }
  141. } else {
  142. // section contact list if device contacts are not imported
  143. let cell = tableView.dequeueReusableCell(withIdentifier: "contactCell", for: indexPath)
  144. if let contactCell = cell as? ContactCell {
  145. let contactCellViewModel = self.contactViewModelBy(row: indexPath.row)
  146. contactCell.updateCell(cellViewModel: contactCellViewModel)
  147. }
  148. return cell
  149. }
  150. }
  151. override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
  152. let row = indexPath.row
  153. let section = indexPath.section
  154. if section == sectionNew {
  155. if row == sectionNewRowNewGroup {
  156. showNewGroupController(isVerified: false)
  157. } else if row == sectionNewRowNewVerifiedGroup {
  158. showNewGroupController(isVerified: true)
  159. } else if row == sectionNewRowNewContact {
  160. showNewContactController()
  161. }
  162. } else if section == sectionImportedContacts {
  163. if deviceContactAccessGranted {
  164. showChatAt(row: row)
  165. } else {
  166. showSettingsAlert()
  167. }
  168. } else {
  169. showChatAt(row: row)
  170. }
  171. tableView.deselectRow(at: indexPath, animated: false)
  172. }
  173. override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
  174. if indexPath.section == sectionContacts {
  175. let contactId = contactIdByRow(indexPath.row)
  176. let edit = UITableViewRowAction(style: .normal, title: String.localized("info")) { [weak self] _, _ in
  177. guard let self = self else { return }
  178. if self.searchController.isActive {
  179. self.searchController.dismiss(animated: false) {
  180. self.showContactDetail(contactId: contactId)
  181. }
  182. } else {
  183. self.showContactDetail(contactId: contactId)
  184. }
  185. }
  186. let delete = UITableViewRowAction(style: .destructive, title: String.localized("delete")) { [weak self] _, _ in
  187. guard let self = self else { return }
  188. let contactId = self.contactIdByRow(indexPath.row)
  189. self.askToDeleteContact(contactId: contactId, indexPath: indexPath)
  190. }
  191. edit.backgroundColor = DcColors.primary
  192. return [edit, delete]
  193. } else {
  194. return []
  195. }
  196. }
  197. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  198. return true
  199. }
  200. private func contactIdByRow(_ row: Int) -> Int {
  201. return isFiltering ? filteredContactIds[row] : contactIds[row]
  202. }
  203. private func contactViewModelBy(row: Int) -> ContactCellViewModel {
  204. let id = contactIdByRow(row)
  205. return ContactCellViewModel.make(contactId: id, searchText: searchText, dcContext: dcContext)
  206. }
  207. // MARK: - updates
  208. private func deleteContact(contactId: Int, indexPath: IndexPath) {
  209. if dcContext.deleteContact(contactId: contactId) {
  210. contactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF)
  211. if isFiltering {
  212. filteredContactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: searchText)
  213. }
  214. tableView.deleteRows(at: [indexPath], with: .automatic)
  215. }
  216. }
  217. // MARK: - search
  218. private func reactivateSearchBarIfNeeded() {
  219. if !searchBarIsEmpty {
  220. searchController.isActive = true
  221. }
  222. }
  223. private func showChatAt(row: Int) {
  224. if searchController.isActive {
  225. // edge case: when searchController is active but searchBar is empty -> filteredContacts is empty, so we fallback to contactIds
  226. let contactId = contactIdByRow(row)
  227. searchController.dismiss(animated: false, completion: {
  228. self.askToChatWith(contactId: contactId)
  229. })
  230. } else {
  231. let contactId = contactIds[row]
  232. self.askToChatWith(contactId: contactId)
  233. }
  234. }
  235. private func filterContentForSearchText(_ searchText: String, scope _: String = String.localized("pref_show_emails_all")) {
  236. filteredContactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF, queryString: searchText)
  237. tableView.reloadData()
  238. tableView.scrollToTop()
  239. // handle empty searchstate
  240. if searchController.isActive && filteredContactIds.isEmpty {
  241. let text = String.localizedStringWithFormat(
  242. String.localized("search_no_result_for_x"),
  243. searchText
  244. )
  245. emptySearchStateLabel.text = text
  246. emptySearchStateLabel.isHidden = false
  247. emptySearchStateLabel.frame = CGRect(x: 0, y: 0, width: 0, height: emptySearchStateLabel.intrinsicContentSize.height)
  248. tableView.tableHeaderView = emptySearchStateLabel
  249. } else {
  250. emptySearchStateLabel.text = nil
  251. emptySearchStateLabel.isHidden = true
  252. tableView.tableHeaderView = nil
  253. }
  254. }
  255. // MARK: - coordinator
  256. private func showNewGroupController(isVerified: Bool) {
  257. let newGroupController = NewGroupController(dcContext: dcContext, isVerified: isVerified)
  258. navigationController?.pushViewController(newGroupController, animated: true)
  259. }
  260. private func showNewContactController() {
  261. let newContactController = NewContactController(dcContext: dcContext)
  262. navigationController?.pushViewController(newContactController, animated: true)
  263. }
  264. private func showNewChat(contactId: Int) {
  265. let chatId = dcContext.createChatByContactId(contactId: contactId)
  266. showChat(chatId: Int(chatId))
  267. }
  268. private func showChat(chatId: Int) {
  269. let chatViewController = ChatViewController(dcContext: dcContext, chatId: chatId)
  270. navigationController?.pushViewController(chatViewController, animated: true)
  271. navigationController?.viewControllers.remove(at: 1)
  272. }
  273. private func showContactDetail(contactId: Int) {
  274. let contactDetailController = ContactDetailViewController(dcContext: dcContext, contactId: contactId)
  275. navigationController?.pushViewController(contactDetailController, animated: true)
  276. }
  277. }
  278. extension NewChatViewController: ContactListDelegate {
  279. func deviceContactsImported() {
  280. contactIds = dcContext.getContacts(flags: DC_GCL_ADD_SELF)
  281. tableView.reloadData()
  282. }
  283. func accessGranted() {
  284. deviceContactAccessGranted = true
  285. }
  286. func accessDenied() {
  287. deviceContactAccessGranted = false
  288. }
  289. private func showSettingsAlert() {
  290. let alert = UIAlertController(
  291. title: String.localized("import_contacts"),
  292. message: String.localized("import_contacts_message"),
  293. preferredStyle: .alert
  294. )
  295. alert.addAction(UIAlertAction(title: String.localized("menu_settings"), style: .default) { _ in
  296. UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
  297. })
  298. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel) { _ in
  299. })
  300. present(alert, animated: true)
  301. }
  302. }
  303. // MARK: - alerts
  304. extension NewChatViewController {
  305. private func askToDeleteContact(contactId: Int, indexPath: IndexPath) {
  306. let contact = DcContact(id: contactId)
  307. let alert = UIAlertController(
  308. title: String.localizedStringWithFormat(String.localized("ask_delete_contact"), contact.nameNAddr),
  309. message: nil,
  310. preferredStyle: .safeActionSheet
  311. )
  312. alert.addAction(UIAlertAction(title: String.localized("delete"), style: .destructive, handler: { [weak self] _ in
  313. self?.dismiss(animated: true, completion: nil)
  314. self?.deleteContact(contactId: contactId, indexPath: indexPath)
  315. }))
  316. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  317. self.dismiss(animated: true, completion: nil)
  318. }))
  319. present(alert, animated: true, completion: nil)
  320. }
  321. private func askToChatWith(contactId: Int) {
  322. if dcContext.getChatIdByContactId(contactId: contactId) != 0 {
  323. self.dismiss(animated: true, completion: nil)
  324. self.showNewChat(contactId: contactId)
  325. } else {
  326. let dcContact = DcContact(id: contactId)
  327. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), dcContact.nameNAddr),
  328. message: nil,
  329. preferredStyle: .safeActionSheet)
  330. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { _ in
  331. self.dismiss(animated: true, completion: nil)
  332. self.showNewChat(contactId: contactId)
  333. }))
  334. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  335. self.reactivateSearchBarIfNeeded()
  336. }))
  337. present(alert, animated: true, completion: nil)
  338. }
  339. }
  340. }
  341. // MARK: - UISearchResultsUpdating
  342. extension NewChatViewController: UISearchResultsUpdating {
  343. func updateSearchResults(for searchController: UISearchController) {
  344. if let searchText = searchController.searchBar.text {
  345. filterContentForSearchText(searchText)
  346. }
  347. }
  348. }
  349. struct ContactHighlights {
  350. let contactDetail: ContactDetail
  351. let indexes: [Int]
  352. }
  353. enum ContactDetail {
  354. case NAME
  355. case EMAIL
  356. }
  357. struct ContactWithSearchResults {
  358. let contact: DcContact
  359. let indexesToHighlight: [ContactHighlights]
  360. }