NewChatViewController.swift 14 KB

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