SettingsController.swift 20 KB

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