AccountSetupController.swift 27 KB

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