AccountSetupController.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. import SafariServices
  2. import UIKit
  3. import UICircularProgressRing
  4. class AccountSetupController: UITableViewController {
  5. weak var coordinator: AccountSetupCoordinator?
  6. private let dcContext: DcContext
  7. private var skipOauth = false
  8. private var backupProgressObserver: Any?
  9. private var configureProgressObserver: Any?
  10. private var oauth2Observer: Any?
  11. // the progress dialog
  12. private lazy var configProgressIndicator: UICircularProgressRing = {
  13. let progress = UICircularProgressRing()
  14. progress.style = UICircularRingStyle.inside
  15. progress.outerRingColor = UIColor.clear
  16. progress.maxValue = 100
  17. progress.innerRingColor = DcColors.primary
  18. progress.innerRingWidth = 2
  19. progress.startAngle = 270
  20. progress.fontColor = UIColor.lightGray
  21. progress.font = UIFont.systemFont(ofSize: 12)
  22. return progress
  23. }()
  24. private lazy var configProgressAlert: UIAlertController = {
  25. let alert = UIAlertController(title: String.localized("one_moment"), message: "\n\n\n", preferredStyle: .alert)
  26. // workaround: add 3 newlines to let alertbox grow to fit progressview
  27. let progressView = configProgressIndicator
  28. progressView.translatesAutoresizingMaskIntoConstraints = false
  29. alert.view.addSubview(progressView)
  30. progressView.centerXAnchor.constraint(equalTo: alert.view.centerXAnchor).isActive = true
  31. progressView.centerYAnchor.constraint(equalTo: alert.view.centerYAnchor, constant: 0).isActive = true
  32. progressView.heightAnchor.constraint(equalToConstant: 65).isActive = true
  33. progressView.widthAnchor.constraint(equalToConstant: 65).isActive = true
  34. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: { _ in
  35. self.dcContext.stopOngoingProcess()
  36. }))
  37. return alert
  38. }()
  39. private func showProgressHud() {
  40. configProgressAlert.actions[0].isEnabled = true
  41. configProgressAlert.title = String.localized("one_moment")
  42. configProgressAlert.message = "\n\n\n" // workaround to create space for progress indicator
  43. configProgressIndicator.alpha = 1
  44. configProgressIndicator.value = 0
  45. present(configProgressAlert, animated: true, completion: nil)
  46. }
  47. private func updateProgressHud(error message: String?) {
  48. DispatchQueue.main.async(execute: {
  49. self.configProgressAlert.dismiss(animated: false)
  50. let errorAlert = UIAlertController(title: String.localized("error"), message: message, preferredStyle: .alert)
  51. errorAlert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  52. self.present(errorAlert, animated: true, completion: nil)
  53. })
  54. }
  55. private func updateProgressHudSuccess() {
  56. updateProgressHudValue(value: 1000)
  57. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  58. self.configProgressAlert.dismiss(animated: true) {
  59. self.handleLoginSuccess()
  60. }
  61. })
  62. }
  63. private func updateProgressHudValue(value: Int?) {
  64. if let value = value {
  65. print("progress hud: \(value)")
  66. configProgressIndicator.value = CGFloat(value / 10)
  67. }
  68. }
  69. // account setup
  70. private lazy var emailCell: TextFieldCell = {
  71. let cell = TextFieldCell.makeEmailCell(delegate: self)
  72. cell.textField.tag = 0
  73. cell.textField.accessibilityIdentifier = "emailTextField" // will be used to eventually show oAuth-Dialogue when pressing return key
  74. cell.setText(text: DcConfig.addr ?? nil)
  75. cell.textField.delegate = self
  76. return cell
  77. }()
  78. private lazy var passwordCell: TextFieldCell = {
  79. let cell = TextFieldCell.makePasswordCell(delegate: self)
  80. cell.textField.tag = 1
  81. cell.accessibilityIdentifier = "passwordCell" // will be used to eventually show oAuth-Dialogue when selecting
  82. cell.setText(text: DcConfig.mailPw ?? nil)
  83. return cell
  84. }()
  85. private lazy var restoreCell: UITableViewCell = {
  86. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  87. cell.textLabel?.text = String.localized("import_backup_title")
  88. cell.accessoryType = .disclosureIndicator
  89. cell.accessibilityIdentifier = "restoreCell"
  90. return cell
  91. }()
  92. private lazy var deleteAccountCell: ActionCell = {
  93. let cell = ActionCell(frame: .zero)
  94. cell.actionTitle = String.localized("delete_account")
  95. cell.actionColor = UIColor.red
  96. cell.accessibilityIdentifier = "deleteAccountCell"
  97. return cell
  98. }()
  99. lazy var advancedShowCell: UITableViewCell = {
  100. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  101. cell.textLabel?.text = String.localized("menu_advanced")
  102. cell.accessoryType = .disclosureIndicator
  103. cell.accessibilityIdentifier = "advancedShowCell"
  104. return cell
  105. }()
  106. lazy var imapServerCell: TextFieldCell = {
  107. let cell = TextFieldCell(descriptionID: "login_imap_server",
  108. placeholder: DcConfig.mailServer ?? DcConfig.configuredMailServer,
  109. delegate: self)
  110. cell.accessibilityIdentifier = "IMAPServerCell"
  111. cell.textField.tag = 2
  112. cell.textField.autocorrectionType = .no
  113. cell.textField.spellCheckingType = .no
  114. cell.textField.autocapitalizationType = .none
  115. return cell
  116. }()
  117. lazy var imapUserCell: TextFieldCell = {
  118. let cell = TextFieldCell(descriptionID: "login_imap_login", placeholder: DcConfig.mailUser ?? DcConfig.configuredMailUser, delegate: self)
  119. cell.accessibilityIdentifier = "IMAPUserCell"
  120. cell.textField.tag = 3
  121. return cell
  122. }()
  123. lazy var imapPortCell: UITableViewCell = {
  124. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  125. cell.textLabel?.text = String.localized("login_imap_port")
  126. cell.accessoryType = .disclosureIndicator
  127. cell.detailTextLabel?.text = DcConfig.mailPort ?? DcConfig.configuredMailPort
  128. cell.accessibilityIdentifier = "IMAPPortCell"
  129. cell.selectionStyle = .none
  130. return cell
  131. }()
  132. lazy var imapSecurityCell: UITableViewCell = {
  133. let text = "\(DcConfig.getImapSecurity())"
  134. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  135. cell.textLabel?.text = String.localized("login_imap_security")
  136. // let cell = TextFieldCell(description: "IMAP Security", placeholder: text, delegate: self)
  137. cell.accessibilityIdentifier = "IMAPSecurityCell"
  138. cell.accessoryType = .disclosureIndicator
  139. cell.detailTextLabel?.text = "\(DcConfig.getImapSecurity())"
  140. cell.selectionStyle = .none
  141. return cell
  142. }()
  143. lazy var smtpServerCell: TextFieldCell = {
  144. let cell = TextFieldCell(descriptionID: "login_smtp_server",
  145. placeholder: DcConfig.sendServer ?? DcConfig.configuredSendServer,
  146. delegate: self)
  147. cell.accessibilityIdentifier = "SMTPServerCell"
  148. cell.textField.tag = 4
  149. cell.textField.autocorrectionType = .no
  150. cell.textField.spellCheckingType = .no
  151. cell.textField.autocapitalizationType = .none
  152. return cell
  153. }()
  154. lazy var smtpUserCell: TextFieldCell = {
  155. let cell = TextFieldCell(descriptionID: "login_smtp_login", placeholder: DcConfig.sendUser ?? DcConfig.configuredSendUser, delegate: self)
  156. cell.accessibilityIdentifier = "SMTPUserCell"
  157. cell.textField.tag = 5
  158. return cell
  159. }()
  160. lazy var smtpPortCell: UITableViewCell = {
  161. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  162. cell.textLabel?.text = String.localized("login_smtp_port")
  163. cell.accessoryType = .disclosureIndicator
  164. cell.detailTextLabel?.text = DcConfig.sendPort ?? DcConfig.configuredSendPort
  165. cell.accessibilityIdentifier = "SMTPPortCell"
  166. cell.selectionStyle = .none
  167. return cell
  168. }()
  169. lazy var smtpPasswordCell: TextFieldCell = {
  170. let cell = TextFieldCell(descriptionID: "login_smtp_password", placeholder: "*************", delegate: self)
  171. cell.textField.textContentType = UITextContentType.password
  172. cell.textField.isSecureTextEntry = true
  173. cell.accessibilityIdentifier = "SMTPPasswordCell"
  174. cell.textField.tag = 6
  175. return cell
  176. }()
  177. lazy var smtpSecurityCell: UITableViewCell = {
  178. let security = "\(DcConfig.getSmtpSecurity())"
  179. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  180. cell.textLabel?.text = String.localized("login_smtp_security")
  181. cell.detailTextLabel?.text = security
  182. cell.accessibilityIdentifier = "SMTPSecurityCell"
  183. cell.accessoryType = .disclosureIndicator
  184. cell.selectionStyle = .none
  185. return cell
  186. }()
  187. // this loginButton can be enabled and disabled
  188. private lazy var loginButton: UIBarButtonItem = {
  189. let button = UIBarButtonItem(title: String.localized("login_title"), style: .done, target: self, action: #selector(loginButtonPressed))
  190. button.isEnabled = dc_is_configured(mailboxPointer) == 0
  191. return button
  192. }()
  193. let basicSection = 0
  194. let restoreSection = 1
  195. let advancedSection = 2
  196. let dangerSection = 3
  197. private var sections = [Int]()
  198. private lazy var basicSectionCells: [UITableViewCell] = [emailCell, passwordCell]
  199. private lazy var restoreCells: [UITableViewCell] = [restoreCell]
  200. private lazy var advancedSectionCells: [UITableViewCell] = [
  201. advancedShowCell,
  202. imapServerCell,
  203. imapUserCell,
  204. imapPortCell,
  205. imapSecurityCell,
  206. smtpServerCell,
  207. smtpUserCell,
  208. smtpPortCell,
  209. smtpPasswordCell,
  210. smtpSecurityCell
  211. ]
  212. private lazy var dangerCells: [UITableViewCell] = [deleteAccountCell]
  213. private let editView: Bool
  214. private var advancedSectionShowing: Bool = false
  215. init(dcContext: DcContext, editView: Bool) {
  216. self.editView = editView
  217. self.dcContext = dcContext
  218. self.sections.append(basicSection)
  219. self.sections.append(advancedSection)
  220. if editView {
  221. self.sections.append(dangerSection)
  222. } else {
  223. self.sections.append(restoreSection)
  224. }
  225. super.init(style: .grouped)
  226. hidesBottomBarWhenPushed = true
  227. }
  228. required init?(coder _: NSCoder) {
  229. fatalError("init(coder:) has not been implemented")
  230. }
  231. override func viewDidLoad() {
  232. super.viewDidLoad()
  233. if editView {
  234. title = String.localized("pref_password_and_account_settings")
  235. } else {
  236. title = String.localized("login_header")
  237. }
  238. navigationItem.rightBarButtonItem = loginButton
  239. }
  240. override func viewWillAppear(_ animated: Bool) {
  241. super.viewWillAppear(animated)
  242. // needs to be changed if returning from portSettingsController
  243. smtpPortCell.detailTextLabel?.text = DcConfig.sendPort ?? DcConfig.configuredSendPort
  244. imapPortCell.detailTextLabel?.text = DcConfig.mailPort ?? DcConfig.configuredMailPort
  245. smtpSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .SMTPSecurity, hex: DcConfig.getSmtpSecurity())
  246. imapSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .IMAPSecurity, hex: DcConfig.getImapSecurity())
  247. }
  248. override func viewDidAppear(_ animated: Bool) {
  249. super.viewDidAppear(animated)
  250. addProgressHudEventListener()
  251. }
  252. override func viewWillDisappear(_ animated: Bool) {
  253. resignFirstResponderOnAllCells()
  254. }
  255. override func viewDidDisappear(_: Bool) {
  256. let nc = NotificationCenter.default
  257. if let backupProgressObserver = self.backupProgressObserver {
  258. nc.removeObserver(backupProgressObserver)
  259. }
  260. if let configureProgressObserver = self.configureProgressObserver {
  261. nc.removeObserver(configureProgressObserver)
  262. }
  263. if let oauth2Observer = self.oauth2Observer {
  264. nc.removeObserver(oauth2Observer)
  265. }
  266. }
  267. // MARK: - Table view data source
  268. override func numberOfSections(in _: UITableView) -> Int {
  269. return sections.count
  270. }
  271. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  272. if sections[section] == basicSection {
  273. return basicSectionCells.count
  274. } else if sections[section] == restoreSection {
  275. return restoreCells.count
  276. } else if sections[section] == dangerSection {
  277. return dangerCells.count
  278. } else {
  279. return advancedSectionShowing ? advancedSectionCells.count : 1
  280. }
  281. }
  282. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  283. if sections[section] == basicSection && editView {
  284. return String.localized("login_header")
  285. } else if sections[section] == dangerSection {
  286. return String.localized("danger")
  287. } else {
  288. return nil
  289. }
  290. }
  291. override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
  292. if sections[section] == basicSection {
  293. return String.localized("login_no_servers_hint")
  294. } else if sections[section] == advancedSection {
  295. return String.localized("login_subheader")
  296. } else {
  297. return nil
  298. }
  299. }
  300. override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  301. let section = indexPath.section
  302. let row = indexPath.row
  303. if sections[section] == basicSection {
  304. return basicSectionCells[row]
  305. } else if sections[section] == restoreSection {
  306. return restoreCells[row]
  307. } else if sections[section] == dangerSection {
  308. return dangerCells[row]
  309. } else {
  310. return advancedSectionCells[row]
  311. }
  312. }
  313. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  314. guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
  315. // handle tap on password -> show oAuthDialogue
  316. if let textFieldCell = tappedCell as? TextFieldCell {
  317. if textFieldCell.accessibilityIdentifier == "passwordCell" {
  318. if let emailAdress = textFieldCell.getText() {
  319. _ = showOAuthAlertIfNeeded(emailAddress: emailAdress, handleCancel: nil)
  320. }
  321. }
  322. }
  323. if tappedCell.accessibilityIdentifier == "restoreCell" {
  324. tableView.reloadData() // otherwise the disclosureIndicator may stay selected
  325. restoreBackup()
  326. } else if tappedCell.accessibilityIdentifier == "deleteAccountCell" {
  327. deleteAccount()
  328. } else if tappedCell.accessibilityIdentifier == "advancedShowCell" {
  329. toggleAdvancedSection()
  330. } else if tappedCell.accessibilityIdentifier == "IMAPPortCell" {
  331. coordinator?.showImapPortOptions()
  332. } else if tappedCell.accessibilityIdentifier == "SMTPPortCell" {
  333. coordinator?.showSmtpPortsOptions()
  334. } else if tappedCell.accessibilityIdentifier == "IMAPSecurityCell" {
  335. coordinator?.showImapSecurityOptions()
  336. } else if tappedCell.accessibilityIdentifier == "SMTPSecurityCell" {
  337. coordinator?.showSmptpSecurityOptions()
  338. }
  339. }
  340. private func toggleAdvancedSection() {
  341. let willShow = !advancedSectionShowing
  342. guard let advancedSectionIndex = sections.firstIndex(of: advancedSection) else { return }
  343. var advancedIndexPaths: [IndexPath] = advancedSectionCells.indices.map { IndexPath(row: $0, section: advancedSectionIndex) }
  344. advancedIndexPaths.removeFirst() // do not touch the first item that is the switch itself
  345. advancedSectionShowing = willShow // set flag before delete/insert, because cellForRowAt will be triggered and uses this flag
  346. if willShow {
  347. tableView.insertRows(at: advancedIndexPaths, with: .fade)
  348. } else {
  349. tableView.deleteRows(at: advancedIndexPaths, with: .fade)
  350. }
  351. tableView.reloadData() // needed to force a redraw
  352. }
  353. @objc private func loginButtonPressed() {
  354. guard let emailAddress = emailCell.getText() else {
  355. return // handle case when either email or pw fields are empty
  356. }
  357. let oAuthStarted = showOAuthAlertIfNeeded(emailAddress: emailAddress, handleCancel: loginButtonPressed)
  358. // if canceled we will run this method again but this time oAuthStarted will be false
  359. if oAuthStarted {
  360. // the loginFlow will be handled by oAuth2
  361. return
  362. }
  363. let password = passwordCell.getText() ?? "" // empty passwords are ok -> for oauth there is no password needed
  364. login(emailAddress: emailAddress, password: password)
  365. }
  366. private func login(emailAddress: String, password: String, skipAdvanceSetup: Bool = false) {
  367. resignFirstResponderOnAllCells() // this will resign focus from all textFieldCells so the keyboard wont pop up anymore
  368. DcConfig.addr = emailAddress
  369. DcConfig.mailPw = password
  370. if !skipAdvanceSetup {
  371. evaluateAdvancedSetup() // this will set MRConfig related to advanced fields
  372. }
  373. print("oAuth-Flag when loggin in: \(DcConfig.getAuthFlags())")
  374. dc_configure(mailboxPointer)
  375. showProgressHud()
  376. }
  377. @objc func closeButtonPressed() {
  378. dismiss(animated: true, completion: nil)
  379. }
  380. // returns true if needed
  381. private func showOAuthAlertIfNeeded(emailAddress: String, handleCancel: (() -> Void)?) -> Bool {
  382. return false
  383. // disable oauth2 for now as not yet supported by deltachat-rust.
  384. /*
  385. if skipOauth {
  386. // user has previously denied oAuth2-setup
  387. return false
  388. }
  389. guard let oAuth2UrlPointer = dc_get_oauth2_url(mailboxPointer, emailAddress, "chat.delta:/auth") else {
  390. //MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL)) -- do not reset, there may be different values
  391. return false
  392. }
  393. let oAuth2Url = String(cString: oAuth2UrlPointer)
  394. if let url = URL(string: oAuth2Url) {
  395. let title = "Continue with simplified setup"
  396. // swiftlint:disable all
  397. let message = "The entered e-mail address supports a simplified setup (oAuth2).\n\nIn the next step, please allow Delta Chat to act as your Chat with E-Mail app.\n\nThere are no Delta Chat servers, your data stays on your device."
  398. let oAuthAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  399. let confirm = UIAlertAction(title: "Confirm", style: .default, handler: {
  400. [unowned self] _ in
  401. let nc = NotificationCenter.default
  402. self.oauth2Observer = nc.addObserver(self, selector: #selector(self.oauthLoginApproved), name: NSNotification.Name("oauthLoginApproved"), object: nil)
  403. self.launchOAuthBrowserWindow(url: url)
  404. })
  405. let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: {
  406. _ in
  407. MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL))
  408. self.skipOauth = true
  409. handleCancel?()
  410. })
  411. oAuthAlertController.addAction(confirm)
  412. oAuthAlertController.addAction(cancel)
  413. present(oAuthAlertController, animated: true, completion: nil)
  414. return true
  415. } else {
  416. return false
  417. }
  418. */
  419. }
  420. @objc func oauthLoginApproved(notification: Notification) {
  421. guard let userInfo = notification.userInfo, let token = userInfo["token"] as? String, let emailAddress = emailCell.getText() else {
  422. return
  423. }
  424. passwordCell.setText(text: token)
  425. DcConfig.setAuthFlags(flags: Int(DC_LP_AUTH_OAUTH2))
  426. login(emailAddress: emailAddress, password: token, skipAdvanceSetup: true)
  427. }
  428. private func launchOAuthBrowserWindow(url: URL) {
  429. UIApplication.shared.open(url) // this opens safari as seperate app
  430. }
  431. private func addProgressHudEventListener() {
  432. let nc = NotificationCenter.default
  433. backupProgressObserver = nc.addObserver(
  434. forName: dcNotificationImexProgress,
  435. object: nil,
  436. queue: nil
  437. ) {
  438. notification in
  439. if let ui = notification.userInfo {
  440. if ui["error"] as! Bool {
  441. self.updateProgressHud(error: ui["errorMessage"] as? String)
  442. } else if ui["done"] as! Bool {
  443. self.updateProgressHudSuccess()
  444. } else {
  445. self.updateProgressHudValue(value: ui["progress"] as? Int)
  446. }
  447. }
  448. }
  449. configureProgressObserver = nc.addObserver(
  450. forName: dcNotificationConfigureProgress,
  451. object: nil,
  452. queue: nil
  453. ) {
  454. notification in
  455. if let ui = notification.userInfo {
  456. if ui["error"] as! Bool {
  457. self.updateProgressHud(error: ui["errorMessage"] as? String)
  458. } else if ui["done"] as! Bool {
  459. self.updateProgressHudSuccess()
  460. } else {
  461. self.updateProgressHudValue(value: ui["progress"] as? Int)
  462. }
  463. }
  464. }
  465. }
  466. private func evaluateAdvancedSetup() {
  467. for cell in advancedSectionCells {
  468. if let textFieldCell = cell as? TextFieldCell {
  469. switch cell.accessibilityIdentifier {
  470. case "IMAPServerCell":
  471. DcConfig.mailServer = textFieldCell.getText() ?? nil
  472. case "IMAPUserCell":
  473. DcConfig.mailUser = textFieldCell.getText() ?? nil
  474. case "IMAPPortCell":
  475. DcConfig.mailPort = textFieldCell.getText() ?? nil
  476. case "IMAPSecurityCell":
  477. let flag = 0
  478. DcConfig.setImapSecurity(imapFlags: flag)
  479. case "SMTPServerCell":
  480. DcConfig.sendServer = textFieldCell.getText() ?? nil
  481. case "SMTPUserCell":
  482. DcConfig.sendUser = textFieldCell.getText() ?? nil
  483. case "SMTPPortCell":
  484. DcConfig.sendPort = textFieldCell.getText() ?? nil
  485. case "SMTPPasswordCell":
  486. DcConfig.sendPw = textFieldCell.getText() ?? nil
  487. case "SMTPSecurityCell":
  488. let flag = 0
  489. DcConfig.setSmtpSecurity(smptpFlags: flag)
  490. default:
  491. logger.info("unknown identifier", cell.accessibilityIdentifier ?? "")
  492. }
  493. }
  494. }
  495. }
  496. private func restoreBackup() {
  497. logger.info("restoring backup")
  498. if DcConfig.configured {
  499. return
  500. }
  501. let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  502. if !documents.isEmpty {
  503. logger.info("looking for backup in: \(documents[0])")
  504. if let cString = dc_imex_has_backup(mailboxPointer, documents[0]) {
  505. let file = String(cString: cString)
  506. free(cString)
  507. logger.info("restoring backup: \(file)")
  508. showProgressHud()
  509. dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
  510. }
  511. else {
  512. let alert = UIAlertController(title: String.localized("import_backup_title"),
  513. message: String.localizedStringWithFormat(String.localized("import_backup_no_backup_found"),
  514. "iTunes / <Your Device> / File Sharing / Delta Chat"), // TOOD: maybe better use an iOS-specific string here
  515. preferredStyle: .alert)
  516. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .cancel))
  517. present(alert, animated: true)
  518. }
  519. }
  520. logger.error("no documents directory found")
  521. }
  522. private func deleteAccount() {
  523. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  524. return
  525. }
  526. let dbfile = appDelegate.dbfile()
  527. let dburl = URL(fileURLWithPath: dbfile, isDirectory: false)
  528. let alert = UIAlertController(title: String.localized("delete_account_message"),
  529. message: nil,
  530. preferredStyle: .actionSheet)
  531. alert.addAction(UIAlertAction(title: String.localized("delete_account"), style: .destructive, handler: { _ in
  532. appDelegate.stop()
  533. appDelegate.close()
  534. do {
  535. try FileManager.default.removeItem(at: dburl)
  536. } catch {
  537. logger.error("failed to delete db: \(error)")
  538. }
  539. appDelegate.open()
  540. appDelegate.start()
  541. self.coordinator?.navigationController.popToRootViewController(animated: true)
  542. appDelegate.appCoordinator.presentLoginController()
  543. }))
  544. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  545. present(alert, animated: true, completion: nil)
  546. coordinator?.navigationController.popToRootViewController(animated: true)
  547. }
  548. private func handleLoginSuccess() {
  549. // used when login hud successfully went trough
  550. dismiss(animated: true, completion: nil)
  551. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  552. appDelegate.registerForPushNotifications()
  553. }
  554. private func resignFirstResponderOnAllCells() {
  555. let _ = basicSectionCells.map({
  556. resignCell(cell: $0)
  557. })
  558. let _ = advancedSectionCells.map({
  559. resignCell(cell: $0)
  560. }
  561. )
  562. }
  563. func resignCell(cell: UITableViewCell) {
  564. if let c = cell as? TextFieldCell {
  565. c.textField.resignFirstResponder()
  566. }
  567. }
  568. }
  569. extension AccountSetupController: UITextFieldDelegate {
  570. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  571. let currentTag = textField.tag
  572. if let nextField = tableView.viewWithTag(currentTag + 1) as? UITextField {
  573. if nextField.tag > 1, !advancedSectionShowing {
  574. // gets here when trying to activate a collapsed cell
  575. return false
  576. }
  577. nextField.becomeFirstResponder()
  578. }
  579. return false
  580. }
  581. func textFieldDidBeginEditing(_ textField: UITextField) {
  582. if textField.accessibilityIdentifier == "emailTextField" {
  583. loginButton.isEnabled = true
  584. // this will re-enable possible oAuth2-login
  585. skipOauth = false
  586. }
  587. }
  588. func textFieldDidEndEditing(_ textField: UITextField) {
  589. if textField.accessibilityIdentifier == "emailTextField" {
  590. let _ = showOAuthAlertIfNeeded(emailAddress: textField.text ?? "", handleCancel: {
  591. self.passwordCell.textField.becomeFirstResponder()
  592. })
  593. }
  594. }
  595. }