AccountSetupController.swift 27 KB

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