SettingsController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. import UIKit
  2. import DcCore
  3. import DBDebugToolkit
  4. internal final class SettingsViewController: UITableViewController, ProgressAlertHandler {
  5. private struct SectionConfigs {
  6. let headerTitle: String?
  7. let footerTitle: String?
  8. let cells: [UITableViewCell]
  9. }
  10. private enum CellTags: Int {
  11. case profile = 0
  12. case contactRequest = 1
  13. case showEmails = 2
  14. case blockedContacts = 3
  15. case notifications = 4
  16. case receiptConfirmation = 5
  17. case autocryptPreferences = 6
  18. case sendAutocryptMessage = 7
  19. case exportBackup = 8
  20. case advanced = 9
  21. case help = 10
  22. case autodel = 11
  23. case mediaQuality = 12
  24. }
  25. private var dcContext: DcContext
  26. private let externalPathDescr = "File Sharing/Delta Chat"
  27. let documentInteractionController = UIDocumentInteractionController()
  28. weak var progressAlert: UIAlertController?
  29. var progressObserver: Any?
  30. // MARK: - cells
  31. private let profileHeader = ContactDetailHeader()
  32. private lazy var profileCell: ProfileCell = {
  33. let displayName = dcContext.displayname ?? String.localized("pref_your_name")
  34. let email = dcContext.addr ?? ""
  35. let selfContact = DcContact(id: Int(DC_CONTACT_ID_SELF))
  36. let cell = ProfileCell(contact: selfContact, displayName: displayName, address: email)
  37. cell.tag = CellTags.profile.rawValue
  38. return cell
  39. }()
  40. private var contactRequestCell: UITableViewCell = {
  41. let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
  42. cell.tag = CellTags.contactRequest.rawValue
  43. cell.textLabel?.text = String.localized("menu_deaddrop")
  44. cell.accessoryType = .disclosureIndicator
  45. return cell
  46. }()
  47. private lazy var showEmailsCell: UITableViewCell = {
  48. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  49. cell.tag = CellTags.showEmails.rawValue
  50. cell.textLabel?.text = String.localized("pref_show_emails")
  51. cell.accessoryType = .disclosureIndicator
  52. cell.detailTextLabel?.text = SettingsClassicViewController.getValString(val: dcContext.showEmails)
  53. return cell
  54. }()
  55. private var blockedContactsCell: UITableViewCell = {
  56. let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
  57. cell.tag = CellTags.blockedContacts.rawValue
  58. cell.textLabel?.text = String.localized("pref_blocked_contacts")
  59. cell.accessoryType = .disclosureIndicator
  60. return cell
  61. }()
  62. func autodelSummary() -> String {
  63. let delDeviceAfter = dcContext.getConfigInt("delete_device_after")
  64. let delServerAfter = dcContext.getConfigInt("delete_server_after")
  65. if delDeviceAfter==0 && delServerAfter==0 {
  66. return String.localized("off")
  67. } else {
  68. return String.localized("on")
  69. }
  70. }
  71. private lazy var autodelCell: UITableViewCell = {
  72. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  73. cell.tag = CellTags.autodel.rawValue
  74. cell.textLabel?.text = String.localized("autodel_title")
  75. cell.accessoryType = .disclosureIndicator
  76. cell.detailTextLabel?.text = autodelSummary()
  77. return cell
  78. }()
  79. private lazy var mediaQualityCell: UITableViewCell = {
  80. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  81. cell.tag = CellTags.mediaQuality.rawValue
  82. cell.textLabel?.text = String.localized("pref_outgoing_media_quality")
  83. cell.accessoryType = .disclosureIndicator
  84. cell.detailTextLabel?.text = MediaQualityController.getValString(val: dcContext.getConfigInt("media_quality"))
  85. return cell
  86. }()
  87. private var notificationSwitch: UISwitch = {
  88. let switchControl = UISwitch()
  89. switchControl.isOn = !UserDefaults.standard.bool(forKey: "notifications_disabled")
  90. switchControl.addTarget(self, action: #selector(handleNotificationToggle(_:)), for: .valueChanged)
  91. return switchControl
  92. }()
  93. private lazy var notificationCell: UITableViewCell = {
  94. let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
  95. cell.tag = CellTags.notifications.rawValue
  96. cell.textLabel?.text = String.localized("pref_notifications")
  97. cell.accessoryView = notificationSwitch
  98. cell.selectionStyle = .none
  99. return cell
  100. }()
  101. private lazy var receiptConfirmationSwitch: UISwitch = {
  102. let switchControl = UISwitch()
  103. switchControl.isOn = dcContext.mdnsEnabled
  104. switchControl.addTarget(self, action: #selector(handleReceiptConfirmationToggle(_:)), for: .valueChanged)
  105. return switchControl
  106. }()
  107. private lazy var receiptConfirmationCell: UITableViewCell = {
  108. let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
  109. cell.tag = CellTags.receiptConfirmation.rawValue
  110. cell.textLabel?.text = String.localized("pref_read_receipts")
  111. cell.accessoryView = receiptConfirmationSwitch
  112. cell.selectionStyle = .none
  113. return cell
  114. }()
  115. private lazy var autocryptSwitch: UISwitch = {
  116. let switchControl = UISwitch()
  117. switchControl.isOn = dcContext.e2eeEnabled
  118. switchControl.addTarget(self, action: #selector(handleAutocryptPreferencesToggle(_:)), for: .valueChanged)
  119. return switchControl
  120. }()
  121. private lazy var autocryptPreferencesCell: UITableViewCell = {
  122. let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
  123. cell.tag = CellTags.autocryptPreferences.rawValue
  124. cell.textLabel?.text = String.localized("autocrypt_prefer_e2ee")
  125. cell.accessoryView = autocryptSwitch
  126. cell.selectionStyle = .none
  127. return cell
  128. }()
  129. private var sendAutocryptMessageCell: ActionCell = {
  130. let cell = ActionCell()
  131. cell.tag = CellTags.sendAutocryptMessage.rawValue
  132. cell.actionTitle = String.localized("autocrypt_send_asm_title")
  133. cell.selectionStyle = .default
  134. return cell
  135. }()
  136. private var exportBackupCell: ActionCell = {
  137. let cell = ActionCell()
  138. cell.tag = CellTags.exportBackup.rawValue
  139. cell.actionTitle = String.localized("export_backup_desktop")
  140. cell.selectionStyle = .default
  141. return cell
  142. }()
  143. private var advancedCell: ActionCell = {
  144. let cell = ActionCell()
  145. cell.tag = CellTags.advanced.rawValue
  146. cell.actionTitle = String.localized("menu_advanced")
  147. cell.selectionStyle = .default
  148. return cell
  149. }()
  150. private var helpCell: ActionCell = {
  151. let cell = ActionCell()
  152. cell.tag = CellTags.help.rawValue
  153. cell.actionTitle = String.localized("menu_help")
  154. cell.selectionStyle = .default
  155. return cell
  156. }()
  157. private lazy var sections: [SectionConfigs] = {
  158. var appNameAndVersion = "Delta Chat"
  159. if let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
  160. appNameAndVersion += " v" + appVersion
  161. }
  162. let profileSection = SectionConfigs(
  163. headerTitle: String.localized("pref_profile_info_headline"),
  164. footerTitle: nil,
  165. cells: [profileCell]
  166. )
  167. let preferencesSection = SectionConfigs(
  168. headerTitle: String.localized("pref_chats_and_media"),
  169. footerTitle: String.localized("pref_read_receipts_explain"),
  170. cells: [contactRequestCell, showEmailsCell, blockedContactsCell, autodelCell, mediaQualityCell, notificationCell, receiptConfirmationCell]
  171. )
  172. let autocryptSection = SectionConfigs(
  173. headerTitle: String.localized("autocrypt"),
  174. footerTitle: String.localized("autocrypt_explain"),
  175. cells: [autocryptPreferencesCell, sendAutocryptMessageCell]
  176. )
  177. let backupSection = SectionConfigs(
  178. headerTitle: nil,
  179. footerTitle: String.localized("pref_backup_explain"),
  180. cells: [advancedCell, exportBackupCell])
  181. let helpSection = SectionConfigs(
  182. headerTitle: nil,
  183. footerTitle: appNameAndVersion,
  184. cells: [helpCell]
  185. )
  186. return [profileSection, preferencesSection, autocryptSection, backupSection, helpSection]
  187. }()
  188. init(dcContext: DcContext) {
  189. self.dcContext = dcContext
  190. super.init(style: .grouped)
  191. }
  192. required init?(coder _: NSCoder) {
  193. fatalError("init(coder:) has not been implemented")
  194. }
  195. // MARK: - lifecycle
  196. override func viewDidLoad() {
  197. super.viewDidLoad()
  198. title = String.localized("menu_settings")
  199. let backButton = UIBarButtonItem(title: String.localized("menu_settings"), style: .plain, target: nil, action: nil)
  200. navigationItem.backBarButtonItem = backButton
  201. documentInteractionController.delegate = self as? UIDocumentInteractionControllerDelegate
  202. }
  203. override func viewWillAppear(_ animated: Bool) {
  204. super.viewWillAppear(animated)
  205. updateCells()
  206. }
  207. override func viewDidAppear(_ animated: Bool) {
  208. super.viewDidAppear(animated)
  209. addProgressAlertListener(progressName: dcNotificationImexProgress) { [weak self] in
  210. guard let self = self else { return }
  211. self.progressAlert?.dismiss(animated: true, completion: nil)
  212. }
  213. }
  214. override func viewDidDisappear(_ animated: Bool) {
  215. super.viewDidDisappear(animated)
  216. let nc = NotificationCenter.default
  217. if let backupProgressObserver = self.progressObserver {
  218. nc.removeObserver(backupProgressObserver)
  219. }
  220. }
  221. // MARK: - UITableViewDelegate + UITableViewDatasource
  222. override func numberOfSections(in tableView: UITableView) -> Int {
  223. return sections.count
  224. }
  225. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  226. return sections[section].cells.count
  227. }
  228. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  229. return sections[indexPath.section].cells[indexPath.row]
  230. }
  231. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  232. guard let cell = tableView.cellForRow(at: indexPath), let cellTag = CellTags(rawValue: cell.tag) else {
  233. safe_fatalError()
  234. return
  235. }
  236. tableView.deselectRow(at: indexPath, animated: false) // to achieve highlight effect
  237. switch cellTag {
  238. case .profile: showEditSettingsController()
  239. case .contactRequest: showContactRequests()
  240. case .showEmails: showClassicMail()
  241. case .blockedContacts: showBlockedContacts()
  242. case .autodel: showAutodelOptions()
  243. case .mediaQuality: showMediaQuality()
  244. case .notifications: break
  245. case .receiptConfirmation: break
  246. case .autocryptPreferences: break
  247. case .sendAutocryptMessage: sendAutocryptSetupMessage()
  248. case .exportBackup: createBackup()
  249. case .advanced: showAdvancedDialog()
  250. case .help: showHelp()
  251. }
  252. }
  253. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  254. return sections[section].headerTitle
  255. }
  256. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  257. return sections[section].footerTitle
  258. }
  259. // MARK: - actions
  260. private func createBackup() {
  261. let alert = UIAlertController(title: String.localized("pref_backup_export_explain"), message: nil, preferredStyle: .safeActionSheet)
  262. alert.addAction(UIAlertAction(title: String.localized("pref_backup_export_start_button"), style: .default, handler: { _ in
  263. self.dismiss(animated: true, completion: nil)
  264. self.startImex(what: DC_IMEX_EXPORT_BACKUP)
  265. }))
  266. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  267. present(alert, animated: true, completion: nil)
  268. }
  269. @objc private func handleNotificationToggle(_ sender: UISwitch) {
  270. UserDefaults.standard.set(!sender.isOn, forKey: "notifications_disabled")
  271. UserDefaults.standard.synchronize()
  272. }
  273. @objc private func handleReceiptConfirmationToggle(_ sender: UISwitch) {
  274. dcContext.mdnsEnabled = sender.isOn
  275. }
  276. @objc private func handleAutocryptPreferencesToggle(_ sender: UISwitch) {
  277. dcContext.e2eeEnabled = sender.isOn
  278. }
  279. private func sendAutocryptSetupMessage() {
  280. let askAlert = UIAlertController(title: String.localized("autocrypt_send_asm_explain_before"), message: nil, preferredStyle: .safeActionSheet)
  281. askAlert.addAction(UIAlertAction(title: String.localized("autocrypt_send_asm_title"), style: .default, handler: { _ in
  282. let waitAlert = UIAlertController(title: String.localized("one_moment"), message: nil, preferredStyle: .alert)
  283. waitAlert.addAction(UIAlertAction(title: String.localized("cancel"), style: .default, handler: { _ in self.dcContext.stopOngoingProcess() }))
  284. self.present(waitAlert, animated: true, completion: nil)
  285. DispatchQueue.global(qos: .background).async {
  286. let sc = self.dcContext.initiateKeyTransfer()
  287. DispatchQueue.main.async {
  288. waitAlert.dismiss(animated: true, completion: nil)
  289. guard var sc = sc else {
  290. return
  291. }
  292. if sc.count == 44 {
  293. // format setup code to the typical 3 x 3 numbers
  294. sc = sc.substring(0, 4) + " - " + sc.substring(5, 9) + " - " + sc.substring(10, 14) + " -\n\n" +
  295. sc.substring(15, 19) + " - " + sc.substring(20, 24) + " - " + sc.substring(25, 29) + " -\n\n" +
  296. sc.substring(30, 34) + " - " + sc.substring(35, 39) + " - " + sc.substring(40, 44)
  297. }
  298. let text = String.localizedStringWithFormat(String.localized("autocrypt_send_asm_explain_after"), sc)
  299. let showAlert = UIAlertController(title: text, message: nil, preferredStyle: .alert)
  300. showAlert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  301. self.present(showAlert, animated: true, completion: nil)
  302. }
  303. }
  304. }))
  305. askAlert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  306. present(askAlert, animated: true, completion: nil)
  307. }
  308. private func showAdvancedDialog() {
  309. let alert = UIAlertController(title: String.localized("menu_advanced"), message: nil, preferredStyle: .safeActionSheet)
  310. alert.addAction(UIAlertAction(title: String.localized("pref_managekeys_export_secret_keys"), style: .default, handler: { _ in
  311. let msg = String.localizedStringWithFormat(String.localized("pref_managekeys_export_explain"), self.externalPathDescr)
  312. let alert = UIAlertController(title: nil, message: msg, preferredStyle: .alert)
  313. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  314. self.startImex(what: DC_IMEX_EXPORT_SELF_KEYS)
  315. }))
  316. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  317. self.present(alert, animated: true, completion: nil)
  318. }))
  319. alert.addAction(UIAlertAction(title: String.localized("pref_managekeys_import_secret_keys"), style: .default, handler: { _ in
  320. let msg = String.localizedStringWithFormat(String.localized("pref_managekeys_import_explain"), self.externalPathDescr)
  321. let alert = UIAlertController(title: nil, message: msg, preferredStyle: .alert)
  322. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: { _ in
  323. self.startImex(what: DC_IMEX_IMPORT_SELF_KEYS)
  324. }))
  325. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  326. self.present(alert, animated: true, completion: nil)
  327. }))
  328. let locationStreaming = UserDefaults.standard.bool(forKey: "location_streaming")
  329. let title = locationStreaming ?
  330. "Disable on-demand location streaming" : String.localized("pref_on_demand_location_streaming")
  331. alert.addAction(UIAlertAction(title: title, style: .default, handler: { _ in
  332. UserDefaults.standard.set(!locationStreaming, forKey: "location_streaming")
  333. }))
  334. let logAction = UIAlertAction(title: String.localized("pref_view_log"), style: .default, handler: { [weak self] _ in
  335. self?.showDebugToolkit()
  336. })
  337. alert.addAction(logAction)
  338. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  339. present(alert, animated: true, completion: nil)
  340. }
  341. private func startImex(what: Int32) {
  342. let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  343. if !documents.isEmpty {
  344. showProgressAlert(title: String.localized("imex_progress_title_desktop"), dcContext: dcContext)
  345. DispatchQueue.main.async {
  346. self.dcContext.imex(what: what, directory: documents[0])
  347. }
  348. } else {
  349. logger.error("document directory not found")
  350. }
  351. }
  352. // MARK: - updates
  353. private func updateCells() {
  354. let displayName = dcContext.displayname ?? String.localized("pref_your_name")
  355. let email = dcContext.addr ?? ""
  356. let selfContact = DcContact(id: Int(DC_CONTACT_ID_SELF))
  357. profileCell.update(contact: selfContact, displayName: displayName, address: email)
  358. showEmailsCell.detailTextLabel?.text = SettingsClassicViewController.getValString(val: dcContext.showEmails)
  359. mediaQualityCell.detailTextLabel?.text = MediaQualityController.getValString(val: dcContext.getConfigInt("media_quality"))
  360. autodelCell.detailTextLabel?.text = autodelSummary()
  361. }
  362. // MARK: - coordinator
  363. private func showEditSettingsController() {
  364. let editController = EditSettingsController(dcContext: dcContext)
  365. navigationController?.pushViewController(editController, animated: true)
  366. }
  367. private func showClassicMail() {
  368. let settingsClassicViewController = SettingsClassicViewController(dcContext: dcContext)
  369. navigationController?.pushViewController(settingsClassicViewController, animated: true)
  370. }
  371. private func showMediaQuality() {
  372. let mediaQualityController = MediaQualityController(dcContext: dcContext)
  373. navigationController?.pushViewController(mediaQualityController, animated: true)
  374. }
  375. private func showBlockedContacts() {
  376. let blockedContactsController = BlockedContactsViewController()
  377. navigationController?.pushViewController(blockedContactsController, animated: true)
  378. }
  379. private func showAutodelOptions() {
  380. let settingsAutodelOverviewController = SettingsAutodelOverviewController(dcContext: dcContext)
  381. navigationController?.pushViewController(settingsAutodelOverviewController, animated: true)
  382. }
  383. private func showContactRequests() {
  384. let deaddropViewController = MailboxViewController(dcContext: dcContext, chatId: Int(DC_CHAT_ID_DEADDROP))
  385. navigationController?.pushViewController(deaddropViewController, animated: true)
  386. }
  387. private func showHelp() {
  388. navigationController?.pushViewController(HelpViewController(), animated: true)
  389. }
  390. private func showDebugToolkit() {
  391. let info: [DBCustomVariable] = dcContext.getInfo().map { kv in
  392. let value = kv.count > 1 ? kv[1] : ""
  393. return DBCustomVariable(name: kv[0], value: value)
  394. }
  395. DBDebugToolkit.add(info)
  396. DBDebugToolkit.showMenu()
  397. }
  398. }