AccountSetupController.swift 27 KB

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