ContactDetailViewController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  218. return viewModel.footerFor(section: section)
  219. }
  220. // MARK: - observers
  221. private func setupObservers() {
  222. let nc = NotificationCenter.default
  223. contactChangedObserver = nc.addObserver(
  224. forName: dcNotificationContactChanged,
  225. object: nil,
  226. queue: OperationQueue.main) { [weak self] notification in
  227. guard let self = self else { return }
  228. if let ui = notification.userInfo,
  229. self.viewModel.contactId == ui["contact_id"] as? Int {
  230. self.updateHeader()
  231. }
  232. }
  233. incomingMsgsObserver = nc.addObserver(
  234. forName: dcNotificationIncoming,
  235. object: nil,
  236. queue: OperationQueue.main) { [weak self] notification in
  237. guard let self = self else { return }
  238. if let ui = notification.userInfo,
  239. let chatId = ui["chat_id"] as? Int {
  240. if self.viewModel.getSharedChatIds().contains(chatId) {
  241. self.viewModel.updateSharedChats()
  242. if self.viewModel.chatId == chatId {
  243. self.updateCellValues()
  244. }
  245. self.tableView.reloadData()
  246. }
  247. }
  248. }
  249. }
  250. private func removeObservers() {
  251. let nc = NotificationCenter.default
  252. if let contactChangedObserver = self.contactChangedObserver {
  253. nc.removeObserver(contactChangedObserver)
  254. }
  255. if let incomingMsgsObserver = self.incomingMsgsObserver {
  256. nc.removeObserver(incomingMsgsObserver)
  257. }
  258. }
  259. // MARK: - updates
  260. private func updateHeader() {
  261. if viewModel.isSavedMessages {
  262. let chat = viewModel.context.getChat(chatId: viewModel.chatId)
  263. headerCell.updateDetails(title: chat.name, subtitle: String.localized("chat_self_talk_subtitle"))
  264. if let img = chat.profileImage {
  265. headerCell.setImage(img)
  266. } else {
  267. headerCell.setBackupImage(name: chat.name, color: chat.color)
  268. }
  269. headerCell.setVerified(isVerified: false)
  270. } else {
  271. headerCell.updateDetails(title: viewModel.contact.displayName,
  272. subtitle: viewModel.isDeviceTalk ? String.localized("device_talk_subtitle") : viewModel.contact.email)
  273. if let img = viewModel.contact.profileImage {
  274. headerCell.setImage(img)
  275. } else {
  276. headerCell.setBackupImage(name: viewModel.contact.displayName, color: viewModel.contact.color)
  277. }
  278. headerCell.setVerified(isVerified: viewModel.contact.isVerified)
  279. }
  280. headerCell.onAvatarTap = showContactAvatarIfNeeded
  281. }
  282. private func updateCellValues() {
  283. ephemeralMessagesCell.detailTextLabel?.text = String.localized(viewModel.chatIsEphemeral ? "on" : "off")
  284. galleryCell.detailTextLabel?.text = String.numberOrNone(viewModel.galleryItemMessageIds.count)
  285. documentsCell.detailTextLabel?.text = String.numberOrNone(viewModel.documentItemMessageIds.count)
  286. statusCell.setText(text: viewModel.contact.status)
  287. }
  288. // MARK: - actions
  289. private func handleChatAction(indexPath: IndexPath) {
  290. let action = viewModel.chatActionFor(row: indexPath.row)
  291. switch action {
  292. case .archiveChat:
  293. tableView.deselectRow(at: indexPath, animated: true) // animated as no other elements pop up
  294. toggleArchiveChat()
  295. case .showEncrInfo:
  296. tableView.deselectRow(at: indexPath, animated: false)
  297. showEncrInfoAlert()
  298. case .copyToClipboard:
  299. tableView.deselectRow(at: indexPath, animated: true)
  300. let pasteboard = UIPasteboard.general
  301. pasteboard.string = viewModel.contact.email
  302. case .blockContact:
  303. tableView.deselectRow(at: indexPath, animated: false)
  304. toggleBlockContact()
  305. case .deleteChat:
  306. tableView.deselectRow(at: indexPath, animated: false)
  307. showDeleteChatConfirmationAlert()
  308. }
  309. }
  310. private func handleChatOption(indexPath: IndexPath) {
  311. let action = viewModel.chatOptionFor(row: indexPath.row)
  312. switch action {
  313. case .documents:
  314. showDocuments()
  315. case .gallery:
  316. showGallery()
  317. case .search:
  318. showSearch()
  319. case .ephemeralMessages:
  320. showEphemeralMessagesController()
  321. case .muteChat:
  322. tableView.deselectRow(at: indexPath, animated: false)
  323. if viewModel.chatIsMuted {
  324. self.viewModel.context.setChatMuteDuration(chatId: self.viewModel.chatId, duration: 0)
  325. muteChatCell.actionTitle = String.localized("menu_mute")
  326. self.navigationController?.popViewController(animated: true)
  327. } else {
  328. showMuteAlert()
  329. }
  330. case .startChat:
  331. tableView.deselectRow(at: indexPath, animated: false)
  332. let contactId = viewModel.contactId
  333. chatWith(contactId: contactId)
  334. }
  335. }
  336. private func toggleArchiveChat() {
  337. let archived = viewModel.toggleArchiveChat()
  338. if archived {
  339. self.navigationController?.popToRootViewController(animated: false)
  340. } else {
  341. archiveChatCell.actionTitle = String.localized("menu_archive_chat")
  342. }
  343. }
  344. private func updateBlockContactCell() {
  345. blockContactCell.actionTitle = viewModel.contact.isBlocked ? String.localized("menu_unblock_contact") : String.localized("menu_block_contact")
  346. blockContactCell.actionColor = viewModel.contact.isBlocked ? SystemColor.blue.uiColor : UIColor.red
  347. }
  348. @objc private func editButtonPressed() {
  349. showEditContact(contactId: viewModel.contactId)
  350. }
  351. // MARK: alerts
  352. private func showDeleteChatConfirmationAlert() {
  353. let alert = UIAlertController(
  354. title: nil,
  355. message: String.localizedStringWithFormat(String.localized("ask_delete_named_chat"), viewModel.context.getChat(chatId: viewModel.chatId).name),
  356. preferredStyle: .safeActionSheet
  357. )
  358. alert.addAction(UIAlertAction(title: String.localized("menu_delete_chat"), style: .destructive, handler: { _ in
  359. self.deleteChat()
  360. }))
  361. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  362. self.present(alert, animated: true, completion: nil)
  363. }
  364. private func showEncrInfoAlert() {
  365. let alert = UIAlertController(
  366. title: nil,
  367. message: self.viewModel.context.getContactEncrInfo(contactId: self.viewModel.contactId),
  368. preferredStyle: .alert
  369. )
  370. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  371. self.present(alert, animated: true, completion: nil)
  372. }
  373. private func showEphemeralMessagesController() {
  374. let ephemeralMessagesController = SettingsEphemeralMessageController(dcContext: viewModel.context, chatId: viewModel.chatId)
  375. navigationController?.pushViewController(ephemeralMessagesController, animated: true)
  376. }
  377. private func showMuteAlert() {
  378. let alert = UIAlertController(title: String.localized("mute"), message: nil, preferredStyle: .safeActionSheet)
  379. let forever = -1
  380. addDurationSelectionAction(to: alert, key: "mute_for_one_hour", duration: Time.oneHour)
  381. addDurationSelectionAction(to: alert, key: "mute_for_two_hours", duration: Time.twoHours)
  382. addDurationSelectionAction(to: alert, key: "mute_for_one_day", duration: Time.oneDay)
  383. addDurationSelectionAction(to: alert, key: "mute_for_seven_days", duration: Time.oneWeek)
  384. addDurationSelectionAction(to: alert, key: "mute_forever", duration: forever)
  385. let cancelAction = UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil)
  386. alert.addAction(cancelAction)
  387. present(alert, animated: true, completion: nil)
  388. }
  389. private func addDurationSelectionAction(to alert: UIAlertController, key: String, duration: Int) {
  390. let action = UIAlertAction(title: String.localized(key), style: .default, handler: { _ in
  391. self.viewModel.context.setChatMuteDuration(chatId: self.viewModel.chatId, duration: duration)
  392. self.muteChatCell.actionTitle = String.localized("menu_unmute")
  393. self.navigationController?.popViewController(animated: true)
  394. })
  395. alert.addAction(action)
  396. }
  397. private func toggleBlockContact() {
  398. if viewModel.contact.isBlocked {
  399. let alert = UIAlertController(title: String.localized("ask_unblock_contact"), message: nil, preferredStyle: .safeActionSheet)
  400. alert.addAction(UIAlertAction(title: String.localized("menu_unblock_contact"), style: .default, handler: { _ in
  401. self.viewModel.unblockContact()
  402. self.updateBlockContactCell()
  403. }))
  404. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  405. present(alert, animated: true, completion: nil)
  406. } else {
  407. let alert = UIAlertController(title: String.localized("ask_block_contact"), message: nil, preferredStyle: .safeActionSheet)
  408. alert.addAction(UIAlertAction(title: String.localized("menu_block_contact"), style: .destructive, handler: { _ in
  409. self.viewModel.blockContact()
  410. self.updateBlockContactCell()
  411. }))
  412. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  413. present(alert, animated: true, completion: nil)
  414. }
  415. }
  416. private func chatWith(contactId: Int) {
  417. let chatId = self.viewModel.context.createChatByContactId(contactId: contactId)
  418. self.showChat(chatId: chatId)
  419. }
  420. // MARK: - coordinator
  421. private func showChat(chatId: Int) {
  422. if let chatlistViewController = navigationController?.viewControllers[0] {
  423. let chatViewController = ChatViewController(dcContext: viewModel.context, chatId: chatId)
  424. navigationController?.setViewControllers([chatlistViewController, chatViewController], animated: true)
  425. }
  426. }
  427. private func showEditContact(contactId: Int) {
  428. let editContactController = EditContactController(dcContext: viewModel.context, contactIdForUpdate: contactId)
  429. navigationController?.pushViewController(editContactController, animated: true)
  430. }
  431. private func showDocuments() {
  432. let messageIds: [Int] = viewModel.documentItemMessageIds.reversed()
  433. let fileGalleryController = DocumentGalleryController(context: viewModel.context, chatId: viewModel.chatId, fileMessageIds: messageIds)
  434. navigationController?.pushViewController(fileGalleryController, animated: true)
  435. }
  436. private func showGallery() {
  437. let messageIds: [Int] = viewModel.galleryItemMessageIds.reversed()
  438. let galleryController = GalleryViewController(context: viewModel.context, chatId: viewModel.chatId, mediaMessageIds: messageIds)
  439. navigationController?.pushViewController(galleryController, animated: true)
  440. }
  441. private func showSearch() {
  442. if let chatViewController = navigationController?.viewControllers.last(where: {
  443. $0 is ChatViewController
  444. }) as? ChatViewController {
  445. chatViewController.activateSearchOnAppear()
  446. navigationController?.popViewController(animated: true)
  447. }
  448. }
  449. private func showContactAvatarIfNeeded() {
  450. if viewModel.isSavedMessages {
  451. let chat = viewModel.context.getChat(chatId: viewModel.chatId)
  452. if let url = chat.profileImageURL {
  453. let previewController = PreviewController(dcContext: viewModel.context, type: .single(url))
  454. previewController.customTitle = chat.name
  455. present(previewController, animated: true, completion: nil)
  456. }
  457. } else if let url = viewModel.contact.profileImageURL {
  458. let previewController = PreviewController(dcContext: viewModel.context, type: .single(url))
  459. previewController.customTitle = viewModel.contact.displayName
  460. present(previewController, animated: true, completion: nil)
  461. }
  462. }
  463. private func deleteChat() {
  464. if viewModel.chatId == 0 {
  465. return
  466. }
  467. viewModel.context.deleteChat(chatId: viewModel.chatId)
  468. NotificationManager.removeNotificationsForChat(dcContext: viewModel.context, chatId: viewModel.chatId)
  469. INInteraction.delete(with: ["\(viewModel.context.id).\(viewModel.chatId)"])
  470. navigationController?.popViewControllers(viewsToPop: 2, animated: true)
  471. }
  472. }
  473. extension ContactDetailViewController: MultilineLabelCellDelegate {
  474. func phoneNumberTapped(number: String) {
  475. let sanitizedNumber = number.filter("0123456789".contains)
  476. if let phoneURL = URL(string: "tel://\(sanitizedNumber)") {
  477. UIApplication.shared.open(phoneURL, options: [:], completionHandler: nil)
  478. }
  479. }
  480. func urlTapped(url: URL) {
  481. if Utils.isEmail(url: url) {
  482. let email = Utils.getEmailFrom(url)
  483. let contactId = viewModel.context.createContact(name: "", email: email)
  484. let alert = UIAlertController(title: String.localizedStringWithFormat(String.localized("ask_start_chat_with"), email),
  485. message: nil, preferredStyle: .safeActionSheet)
  486. alert.addAction(UIAlertAction(title: String.localized("start_chat"), style: .default, handler: { [weak self] _ in
  487. guard let self = self else { return }
  488. let chatId = self.viewModel.context.createChatByContactId(contactId: contactId)
  489. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  490. appDelegate.appCoordinator.showChat(chatId: chatId, clearViewControllerStack: true)
  491. }
  492. }))
  493. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  494. present(alert, animated: true, completion: nil)
  495. } else {
  496. UIApplication.shared.open(url)
  497. }
  498. }
  499. }