ContactDetailViewController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import UIKit
  2. import DcCore
  3. import Intents
  4. // this is also used as ChatDetail for SingleChats
  5. class ContactDetailViewController: UITableViewController {
  6. private let viewModel: ContactDetailViewModel
  7. private lazy var headerCell: ContactDetailHeader = {
  8. return ContactDetailHeader()
  9. }()
  10. private lazy var startChatCell: ActionCell = {
  11. let cell = ActionCell()
  12. cell.actionColor = SystemColor.blue.uiColor
  13. cell.actionTitle = String.localized("send_message")
  14. return cell
  15. }()
  16. private lazy var ephemeralMessagesCell: UITableViewCell = {
  17. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  18. cell.textLabel?.text = String.localized("ephemeral_messages")
  19. cell.accessoryType = .disclosureIndicator
  20. return cell
  21. }()
  22. private lazy var showEncrInfoCell: ActionCell = {
  23. let cell = ActionCell()
  24. cell.actionTitle = String.localized("encryption_info_title_desktop")
  25. cell.actionColor = SystemColor.blue.uiColor
  26. return cell
  27. }()
  28. private lazy var copyToClipboardCell: ActionCell = {
  29. let cell = ActionCell()
  30. cell.actionTitle = String.localized("menu_copy_to_clipboard")
  31. cell.actionColor = SystemColor.blue.uiColor
  32. return cell
  33. }()
  34. private lazy var blockContactCell: ActionCell = {
  35. let cell = ActionCell()
  36. cell.actionTitle = viewModel.contact.isBlocked ? String.localized("menu_unblock_contact") : String.localized("menu_block_contact")
  37. cell.actionColor = viewModel.contact.isBlocked ? SystemColor.blue.uiColor : UIColor.red
  38. return cell
  39. }()
  40. private lazy var muteChatCell: ActionCell = {
  41. let cell = ActionCell()
  42. cell.actionTitle = viewModel.chatIsMuted ? String.localized("menu_unmute") : String.localized("menu_mute")
  43. cell.actionColor = SystemColor.blue.uiColor
  44. return cell
  45. }()
  46. private lazy var archiveChatCell: ActionCell = {
  47. let cell = ActionCell()
  48. cell.actionTitle = viewModel.chatIsArchived ? String.localized("menu_unarchive_chat") : String.localized("menu_archive_chat")
  49. cell.actionColor = SystemColor.blue.uiColor
  50. return cell
  51. }()
  52. private lazy var deleteChatCell: ActionCell = {
  53. let cell = ActionCell()
  54. cell.actionTitle = String.localized("menu_delete_chat")
  55. cell.actionColor = UIColor.red
  56. return cell
  57. }()
  58. private lazy var galleryCell: UITableViewCell = {
  59. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  60. cell.textLabel?.text = String.localized("images_and_videos")
  61. cell.accessoryType = .disclosureIndicator
  62. if viewModel.chatId == 0 {
  63. cell.isUserInteractionEnabled = false
  64. cell.textLabel?.isEnabled = false
  65. }
  66. return cell
  67. }()
  68. private lazy var documentsCell: UITableViewCell = {
  69. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  70. cell.textLabel?.text = String.localized("files")
  71. cell.accessoryType = .disclosureIndicator
  72. if viewModel.chatId == 0 {
  73. cell.isUserInteractionEnabled = false
  74. cell.textLabel?.isEnabled = false
  75. }
  76. return cell
  77. }()
  78. private lazy var searchCell: UITableViewCell = {
  79. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  80. cell.textLabel?.text = String.localized("search")
  81. cell.accessoryType = .disclosureIndicator
  82. if viewModel.chatId == 0 {
  83. cell.isUserInteractionEnabled = false
  84. cell.textLabel?.isEnabled = false
  85. }
  86. return cell
  87. }()
  88. private lazy var statusCell: MultilineLabelCell = {
  89. let cell = MultilineLabelCell()
  90. cell.multilineDelegate = self
  91. return cell
  92. }()
  93. private var incomingMsgsObserver: NSObjectProtocol?
  94. private var contactChangedObserver: NSObjectProtocol?
  95. init(dcContext: DcContext, contactId: Int) {
  96. self.viewModel = ContactDetailViewModel(dcContext: dcContext, contactId: contactId)
  97. super.init(style: .grouped)
  98. }
  99. required init?(coder _: NSCoder) {
  100. fatalError("init(coder:) has not been implemented")
  101. }
  102. // MARK: - lifecycle
  103. override func viewDidLoad() {
  104. super.viewDidLoad()
  105. configureTableView()
  106. if !self.viewModel.isSavedMessages && !self.viewModel.isDeviceTalk {
  107. navigationItem.rightBarButtonItem = UIBarButtonItem(
  108. title: String.localized("global_menu_edit_desktop"),
  109. style: .plain, target: self, action: #selector(editButtonPressed))
  110. self.title = String.localized("tab_contact")
  111. } else {
  112. self.title = String.localized("profile")
  113. }
  114. }
  115. override func viewWillAppear(_ animated: Bool) {
  116. super.viewWillAppear(animated)
  117. setupObservers()
  118. updateHeader() // maybe contact name has been edited
  119. updateCellValues()
  120. tableView.reloadData()
  121. }
  122. override func viewWillDisappear(_ animated: Bool) {
  123. super.viewWillDisappear(animated)
  124. removeObservers()
  125. }
  126. // MARK: - setup and configuration
  127. private func configureTableView() {
  128. tableView.register(ActionCell.self, forCellReuseIdentifier: ActionCell.reuseIdentifier)
  129. tableView.register(ContactCell.self, forCellReuseIdentifier: ContactCell.reuseIdentifier)
  130. headerCell.frame = CGRect(0, 0, tableView.frame.width, ContactCell.cellHeight)
  131. tableView.tableHeaderView = headerCell
  132. tableView.sectionHeaderHeight = UITableView.automaticDimension
  133. tableView.rowHeight = UITableView.automaticDimension
  134. }
  135. // MARK: - UITableViewDatasource, UITableViewDelegate
  136. override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
  137. if previousTraitCollection?.preferredContentSizeCategory !=
  138. traitCollection.preferredContentSizeCategory {
  139. headerCell.frame = CGRect(0, 0, tableView.frame.width, ContactCell.cellHeight)
  140. }
  141. }
  142. override func numberOfSections(in tableView: UITableView) -> Int {
  143. return viewModel.numberOfSections
  144. }
  145. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  146. return viewModel.numberOfRowsInSection(section)
  147. }
  148. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  149. let row = indexPath.row
  150. let cellType = viewModel.typeFor(section: indexPath.section)
  151. switch cellType {
  152. case .chatOptions:
  153. switch viewModel.chatOptionFor(row: row) {
  154. case .documents:
  155. return documentsCell
  156. case .gallery:
  157. return galleryCell
  158. case .search:
  159. return searchCell
  160. case .ephemeralMessages:
  161. return ephemeralMessagesCell
  162. case .muteChat:
  163. return muteChatCell
  164. case .startChat:
  165. return startChatCell
  166. }
  167. case .statusArea:
  168. return statusCell
  169. case .chatActions:
  170. switch viewModel.chatActionFor(row: row) {
  171. case .archiveChat:
  172. return archiveChatCell
  173. case .showEncrInfo:
  174. return showEncrInfoCell
  175. case .copyToClipboard:
  176. return copyToClipboardCell
  177. case .blockContact:
  178. return blockContactCell
  179. case .deleteChat:
  180. return deleteChatCell
  181. }
  182. case .sharedChats:
  183. if let cell = tableView.dequeueReusableCell(withIdentifier: ContactCell.reuseIdentifier, for: indexPath) as? ContactCell {
  184. viewModel.update(sharedChatCell: cell, row: row)
  185. cell.backgroundColor = DcColors.sharedChatCellBackgroundColor
  186. return cell
  187. }
  188. }
  189. return UITableViewCell() // should never get here
  190. }
  191. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  192. let type = viewModel.typeFor(section: indexPath.section)
  193. switch type {
  194. case .chatOptions:
  195. handleChatOption(indexPath: indexPath)
  196. case .statusArea:
  197. break
  198. case .chatActions:
  199. handleChatAction(indexPath: indexPath)
  200. case .sharedChats:
  201. let chatId = viewModel.getSharedChatIdAt(indexPath: indexPath)
  202. showChat(chatId: chatId)
  203. }
  204. }
  205. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  206. let type = viewModel.typeFor(section: indexPath.section)
  207. switch type {
  208. case .sharedChats:
  209. return ContactCell.cellHeight
  210. default:
  211. return UITableView.automaticDimension
  212. }
  213. }
  214. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  215. return viewModel.titleFor(section: section)
  216. }
  217. // MARK: - observers
  218. private func setupObservers() {
  219. let nc = NotificationCenter.default
  220. contactChangedObserver = nc.addObserver(
  221. forName: dcNotificationContactChanged,
  222. object: nil,
  223. queue: OperationQueue.main) { [weak self] notification in
  224. guard let self = self else { return }
  225. if let ui = notification.userInfo,
  226. self.viewModel.contactId == ui["contact_id"] as? Int {
  227. self.updateHeader()
  228. }
  229. }
  230. incomingMsgsObserver = nc.addObserver(
  231. forName: dcNotificationIncoming,
  232. object: nil,
  233. queue: OperationQueue.main) { [weak self] notification in
  234. guard let self = self else { return }
  235. if let ui = notification.userInfo,
  236. let chatId = ui["chat_id"] as? Int {
  237. if self.viewModel.getSharedChatIds().contains(chatId) {
  238. self.viewModel.updateSharedChats()
  239. if self.viewModel.chatId == chatId {
  240. self.updateCellValues()
  241. }
  242. self.tableView.reloadData()
  243. }
  244. }
  245. }
  246. }
  247. private func removeObservers() {
  248. let nc = NotificationCenter.default
  249. if let contactChangedObserver = self.contactChangedObserver {
  250. nc.removeObserver(contactChangedObserver)
  251. }
  252. if let incomingMsgsObserver = self.incomingMsgsObserver {
  253. nc.removeObserver(incomingMsgsObserver)
  254. }
  255. }
  256. // MARK: - updates
  257. private func updateHeader() {
  258. if viewModel.isSavedMessages {
  259. let chat = viewModel.context.getChat(chatId: viewModel.chatId)
  260. headerCell.updateDetails(title: chat.name, subtitle: String.localized("chat_self_talk_subtitle"))
  261. if let img = chat.profileImage {
  262. headerCell.setImage(img)
  263. } else {
  264. headerCell.setBackupImage(name: chat.name, color: chat.color)
  265. }
  266. headerCell.setVerified(isVerified: false)
  267. } else {
  268. headerCell.updateDetails(title: viewModel.contact.displayName,
  269. subtitle: viewModel.isDeviceTalk ? String.localized("device_talk_subtitle") : viewModel.contact.email)
  270. if let img = viewModel.contact.profileImage {
  271. headerCell.setImage(img)
  272. } else {
  273. headerCell.setBackupImage(name: viewModel.contact.displayName, color: viewModel.contact.color)
  274. }
  275. headerCell.setVerified(isVerified: viewModel.contact.isVerified)
  276. }
  277. headerCell.onAvatarTap = showContactAvatarIfNeeded
  278. }
  279. private func updateCellValues() {
  280. ephemeralMessagesCell.detailTextLabel?.text = String.localized(viewModel.chatIsEphemeral ? "on" : "off")
  281. galleryCell.detailTextLabel?.text = String.numberOrNone(viewModel.galleryItemMessageIds.count)
  282. documentsCell.detailTextLabel?.text = String.numberOrNone(viewModel.documentItemMessageIds.count)
  283. statusCell.setText(text: viewModel.contact.status)
  284. }
  285. // MARK: - actions
  286. private func handleChatAction(indexPath: IndexPath) {
  287. let action = viewModel.chatActionFor(row: indexPath.row)
  288. switch action {
  289. case .archiveChat:
  290. tableView.deselectRow(at: indexPath, animated: true) // animated as no other elements pop up
  291. toggleArchiveChat()
  292. case .showEncrInfo:
  293. tableView.deselectRow(at: indexPath, animated: false)
  294. showEncrInfoAlert()
  295. case .copyToClipboard:
  296. tableView.deselectRow(at: indexPath, animated: true)
  297. let pasteboard = UIPasteboard.general
  298. pasteboard.string = viewModel.contact.email
  299. case .blockContact:
  300. tableView.deselectRow(at: indexPath, animated: false)
  301. toggleBlockContact()
  302. case .deleteChat:
  303. tableView.deselectRow(at: indexPath, animated: false)
  304. showDeleteChatConfirmationAlert()
  305. }
  306. }
  307. private func handleChatOption(indexPath: IndexPath) {
  308. let action = viewModel.chatOptionFor(row: indexPath.row)
  309. switch action {
  310. case .documents:
  311. showDocuments()
  312. case .gallery:
  313. showGallery()
  314. case .search:
  315. showSearch()
  316. case .ephemeralMessages:
  317. showEphemeralMessagesController()
  318. case .muteChat:
  319. tableView.deselectRow(at: indexPath, animated: false)
  320. if viewModel.chatIsMuted {
  321. self.viewModel.context.setChatMuteDuration(chatId: self.viewModel.chatId, duration: 0)
  322. muteChatCell.actionTitle = String.localized("menu_mute")
  323. self.navigationController?.popViewController(animated: true)
  324. } else {
  325. showMuteAlert()
  326. }
  327. case .startChat:
  328. tableView.deselectRow(at: indexPath, animated: false)
  329. let contactId = viewModel.contactId
  330. chatWith(contactId: contactId)
  331. }
  332. }
  333. private func toggleArchiveChat() {
  334. let archived = viewModel.toggleArchiveChat()
  335. if archived {
  336. self.navigationController?.popToRootViewController(animated: false)
  337. } else {
  338. archiveChatCell.actionTitle = String.localized("menu_archive_chat")
  339. }
  340. }
  341. private func updateBlockContactCell() {
  342. blockContactCell.actionTitle = viewModel.contact.isBlocked ? String.localized("menu_unblock_contact") : String.localized("menu_block_contact")
  343. blockContactCell.actionColor = viewModel.contact.isBlocked ? SystemColor.blue.uiColor : UIColor.red
  344. }
  345. @objc private func editButtonPressed() {
  346. showEditContact(contactId: viewModel.contactId)
  347. }
  348. // MARK: alerts
  349. private func showDeleteChatConfirmationAlert() {
  350. let alert = UIAlertController(
  351. title: nil,
  352. message: String.localized("ask_delete_chat_desktop"),
  353. preferredStyle: .safeActionSheet
  354. )
  355. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  356. self.deleteChat()
  357. }))
  358. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  359. self.present(alert, animated: true, completion: nil)
  360. }
  361. private func showEncrInfoAlert() {
  362. let alert = UIAlertController(
  363. title: nil,
  364. message: self.viewModel.context.getContactEncrInfo(contactId: self.viewModel.contactId),
  365. preferredStyle: .alert
  366. )
  367. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  368. self.present(alert, animated: true, completion: nil)
  369. }
  370. private func showEphemeralMessagesController() {
  371. let ephemeralMessagesController = SettingsEphemeralMessageController(dcContext: viewModel.context, chatId: viewModel.chatId)
  372. navigationController?.pushViewController(ephemeralMessagesController, animated: true)
  373. }
  374. private func showMuteAlert() {
  375. let alert = UIAlertController(title: String.localized("mute"), message: nil, preferredStyle: .safeActionSheet)
  376. let forever = -1
  377. addDurationSelectionAction(to: alert, key: "mute_for_one_hour", duration: Time.oneHour)
  378. addDurationSelectionAction(to: alert, key: "mute_for_two_hours", duration: Time.twoHours)
  379. addDurationSelectionAction(to: alert, key: "mute_for_one_day", duration: Time.oneDay)
  380. addDurationSelectionAction(to: alert, key: "mute_for_seven_days", duration: Time.oneWeek)
  381. addDurationSelectionAction(to: alert, key: "mute_forever", duration: forever)
  382. let cancelAction = UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil)
  383. alert.addAction(cancelAction)
  384. present(alert, animated: true, completion: nil)
  385. }
  386. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  387. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  388. self.viewModel.context.setChatMuteDuration(chatId: self.viewModel.chatId, duration: duration)
  389. self.muteChatCell.actionTitle = String.localized("menu_unmute")
  390. self.navigationController?.popViewController(animated: true)
  391. })
  392. alert.addAction(action)
  393. }
  394. private func toggleBlockContact() {
  395. if viewModel.contact.isBlocked {
  396. let alert = UIAlertController(title: String.localized("ask_unblock_contact"), message: nil, preferredStyle: .safeActionSheet)
  397. alert.addAction(UIAlertAction(title: String.localized("menu_unblock_contact"), style: .default, handler: { _ in
  398. self.viewModel.unblockContact()
  399. self.updateBlockContactCell()
  400. }))
  401. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  402. present(alert, animated: true, completion: nil)
  403. } else {
  404. let alert = UIAlertController(title: String.localized("ask_block_contact"), message: nil, preferredStyle: .safeActionSheet)
  405. alert.addAction(UIAlertAction(title: String.localized("menu_block_contact"), style: .destructive, handler: { _ in
  406. self.viewModel.blockContact()
  407. self.updateBlockContactCell()
  408. }))
  409. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  410. present(alert, animated: true, completion: nil)
  411. }
  412. }
  413. private func chatWith(contactId: Int) {
  414. let chatId = self.viewModel.context.createChatByContactId(contactId: contactId)
  415. self.showChat(chatId: chatId)
  416. }
  417. // MARK: - coordinator
  418. private func showChat(chatId: Int) {
  419. if let chatlistViewController = navigationController?.viewControllers[0] {
  420. let chatViewController = ChatViewController(dcContext: viewModel.context, chatId: chatId)
  421. navigationController?.setViewControllers([chatlistViewController, chatViewController], animated: true)
  422. }
  423. }
  424. private func showEditContact(contactId: Int) {
  425. let editContactController = EditContactController(dcContext: viewModel.context, contactIdForUpdate: contactId)
  426. navigationController?.pushViewController(editContactController, animated: true)
  427. }
  428. private func showDocuments() {
  429. let messageIds: [Int] = viewModel.documentItemMessageIds.reversed()
  430. let fileGalleryController = DocumentGalleryController(context: viewModel.context, chatId: viewModel.chatId, fileMessageIds: messageIds)
  431. navigationController?.pushViewController(fileGalleryController, animated: true)
  432. }
  433. private func showGallery() {
  434. let messageIds: [Int] = viewModel.galleryItemMessageIds.reversed()
  435. let galleryController = GalleryViewController(context: viewModel.context, chatId: viewModel.chatId, mediaMessageIds: messageIds)
  436. navigationController?.pushViewController(galleryController, animated: true)
  437. }
  438. private func showSearch() {
  439. if let chatViewController = navigationController?.viewControllers.last(where: {
  440. $0 is ChatViewController
  441. }) as? ChatViewController {
  442. chatViewController.activateSearchOnAppear()
  443. navigationController?.popViewController(animated: true)
  444. }
  445. }
  446. private func showContactAvatarIfNeeded() {
  447. if viewModel.isSavedMessages {
  448. let chat = viewModel.context.getChat(chatId: viewModel.chatId)
  449. if let url = chat.profileImageURL {
  450. let previewController = PreviewController(dcContext: viewModel.context, type: .single(url))
  451. previewController.customTitle = chat.name
  452. present(previewController, animated: true, completion: nil)
  453. }
  454. } else if let url = viewModel.contact.profileImageURL {
  455. let previewController = PreviewController(dcContext: viewModel.context, type: .single(url))
  456. previewController.customTitle = viewModel.contact.displayName
  457. present(previewController, animated: true, completion: nil)
  458. }
  459. }
  460. private func deleteChat() {
  461. if viewModel.chatId == 0 {
  462. return
  463. }
  464. viewModel.context.deleteChat(chatId: viewModel.chatId)
  465. NotificationManager.removeNotificationsForChat(dcContext: viewModel.context, chatId: viewModel.chatId)
  466. INInteraction.delete(with: ["\(viewModel.context.id).\(viewModel.chatId)"])
  467. navigationController?.popViewControllers(viewsToPop: 2, animated: true)
  468. }
  469. }
  470. extension ContactDetailViewController: MultilineLabelCellDelegate {
  471. func phoneNumberTapped(number: String) {
  472. let sanitizedNumber = number.filter("0123456789".contains)
  473. if let phoneURL = URL(string: "tel://\(sanitizedNumber)") {
  474. UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil)
  475. }
  476. }
  477. func urlTapped(url: URL) {
  478. if Utils.isEmail(url: url) {
  479. let email = Utils.getEmailFrom(url)
  480. let contactId = viewModel.context.createContact(name: "", email: email)
  481. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  482. message: nil, preferredStyle: .safeActionSheet)
  483. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  484. guard let self = self else { return }
  485. let chatId = self.viewModel.context.createChatByContactId(contactId: contactId)
  486. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  487. appDelegate.appCoordinator.showChat(chatId: chatId, clearViewControllerStack: true)
  488. }
  489. }))
  490. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  491. present(alert, animated: true, completion: nil)
  492. } else {
  493. UIApplication.shared.open(url)
  494. }
  495. }
  496. }