AccountSetupController.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736
  1. import SafariServices
  2. import UIKit
  3. import DcCore
  4. class AccountSetupController: UITableViewController, ProgressAlertHandler {
  5. private var dcContext: DcContext
  6. private let dcAccounts: DcAccounts
  7. private var skipOauth = false
  8. var progressObserver: NSObjectProtocol?
  9. var onLoginSuccess: (() -> Void)?
  10. private var oauth2Observer: NSObjectProtocol?
  11. private let tagEmailCell = 0
  12. private let tagPasswordCell = 1
  13. private let tagAdvancedCell = 2
  14. private let tagImapServerCell = 3
  15. private let tagImapUserCell = 4
  16. private let tagImapPortCell = 5
  17. private let tagImapSecurityCell = 6
  18. private let tagSmtpServerCell = 7
  19. private let tagSmtpUserCell = 8
  20. private let tagSmtpPortCell = 9
  21. private let tagSmtpPasswordCell = 10
  22. private let tagSmtpSecurityCell = 11
  23. private let tagCertCheckCell = 12
  24. private let tagViewLogCell = 15
  25. private let tagTextFieldEmail = 100
  26. private let tagTextFieldPassword = 200
  27. private let tagTextFieldImapLogin = 300
  28. private let tagTextFieldImapServer = 400
  29. private let tagTextFieldImapPort = 500
  30. private let tagTextFieldSmtpLogin = 600
  31. private let tagTextFieldSmtpPassword = 700
  32. private let tagTextFieldSmtpServer = 800
  33. private let tagTextFieldSmtpPort = 900
  34. // add cells to sections
  35. let basicSection = 100
  36. let advancedSection = 200
  37. private var sections = [Int]()
  38. private lazy var basicSectionCells: [UITableViewCell] = [emailCell, passwordCell]
  39. private lazy var advancedSectionCells: [UITableViewCell] = [
  40. advancedShowCell,
  41. imapSecurityCell,
  42. imapUserCell,
  43. imapServerCell,
  44. imapPortCell,
  45. smtpSecurityCell,
  46. smtpUserCell,
  47. smtpPasswordCell,
  48. smtpServerCell,
  49. smtpPortCell,
  50. certCheckCell,
  51. viewLogCell
  52. ]
  53. private let editView: Bool
  54. private var advancedSectionShowing: Bool = false
  55. private var providerInfoShowing: Bool = false
  56. private var provider: DcProvider?
  57. // MARK: - the progress dialog
  58. weak var progressAlert: UIAlertController?
  59. // MARK: - cells
  60. private lazy var emailCell: TextFieldCell = {
  61. let cell = TextFieldCell.makeEmailCell(delegate: self)
  62. cell.tag = tagEmailCell
  63. cell.textField.addTarget(self, action: #selector(emailCellEdited), for: .editingChanged)
  64. cell.textField.tag = tagTextFieldEmail // will be used to eventually show oAuth-Dialogue when pressing return key
  65. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  66. cell.textField.returnKeyType = .next
  67. return cell
  68. }()
  69. private lazy var passwordCell: TextFieldCell = {
  70. let cell = TextFieldCell.makePasswordCell(delegate: self)
  71. cell.tag = tagPasswordCell
  72. cell.textField.tag = tagTextFieldPassword // will be used to eventually show oAuth-Dialogue when selecting
  73. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  74. cell.textField.returnKeyType = advancedSectionShowing ? .next : .default
  75. return cell
  76. }()
  77. private lazy var providerInfoCell: ProviderInfoCell = {
  78. let cell = ProviderInfoCell()
  79. cell.onInfoButtonPressed = { [weak self] in
  80. self?.handleProviderInfoButton()
  81. }
  82. return cell
  83. }()
  84. lazy var advancedShowCell: UITableViewCell = {
  85. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  86. cell.textLabel?.text = String.localized("menu_advanced")
  87. cell.accessoryType = .disclosureIndicator
  88. cell.tag = tagAdvancedCell
  89. return cell
  90. }()
  91. lazy var imapServerCell: TextFieldCell = {
  92. let cell = TextFieldCell(
  93. descriptionID: "login_imap_server",
  94. placeholder: String.localized("automatic"),
  95. delegate: self)
  96. cell.tag = tagImapServerCell
  97. cell.setText(text: dcContext.mailServer ?? nil)
  98. cell.textField.tag = tagTextFieldImapServer
  99. cell.textField.autocorrectionType = .no
  100. cell.textField.spellCheckingType = .no
  101. cell.textField.autocapitalizationType = .none
  102. cell.textField.returnKeyType = .next
  103. return cell
  104. }()
  105. lazy var imapUserCell: TextFieldCell = {
  106. let cell = TextFieldCell(
  107. descriptionID: "login_imap_login",
  108. placeholder: String.localized("automatic"),
  109. delegate: self)
  110. cell.setText(text: dcContext.mailUser ?? nil)
  111. cell.textField.tag = tagTextFieldImapLogin
  112. cell.tag = tagImapUserCell
  113. cell.textField.autocorrectionType = .no
  114. cell.textField.spellCheckingType = .no
  115. cell.textField.autocapitalizationType = .none
  116. cell.textField.returnKeyType = .next
  117. return cell
  118. }()
  119. func editablePort(port: String?) -> String {
  120. if let port = port {
  121. if Int(port) == 0 {
  122. return ""
  123. }
  124. return port
  125. } else {
  126. return ""
  127. }
  128. }
  129. lazy var imapPortCell: TextFieldCell = {
  130. let cell = TextFieldCell(
  131. descriptionID: "login_imap_port",
  132. placeholder: String.localized("automatic"),
  133. delegate: self)
  134. cell.tag = tagImapPortCell
  135. cell.setText(text: editablePort(port: dcContext.mailPort))
  136. cell.textField.tag = tagTextFieldImapPort
  137. cell.textField.keyboardType = .numberPad
  138. return cell
  139. }()
  140. lazy var imapSecurityCell: UITableViewCell = {
  141. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  142. cell.textLabel?.text = String.localized("login_imap_security")
  143. cell.accessoryType = .disclosureIndicator
  144. cell.tag = tagImapSecurityCell
  145. return cell
  146. }()
  147. lazy var smtpServerCell: TextFieldCell = {
  148. let cell = TextFieldCell(
  149. descriptionID: "login_smtp_server",
  150. placeholder: String.localized("automatic"),
  151. delegate: self)
  152. cell.textField.tag = tagTextFieldSmtpServer
  153. cell.setText(text: dcContext.sendServer ?? nil)
  154. cell.tag = tagSmtpServerCell
  155. cell.textField.autocorrectionType = .no
  156. cell.textField.spellCheckingType = .no
  157. cell.textField.autocapitalizationType = .none
  158. cell.textField.returnKeyType = .next
  159. return cell
  160. }()
  161. lazy var smtpUserCell: TextFieldCell = {
  162. let cell = TextFieldCell(
  163. descriptionID: "login_smtp_login",
  164. placeholder: String.localized("automatic"),
  165. delegate: self)
  166. cell.textField.tag = tagTextFieldSmtpLogin
  167. cell.setText(text: dcContext.sendUser ?? nil)
  168. cell.tag = tagSmtpUserCell
  169. cell.textField.autocorrectionType = .no
  170. cell.textField.spellCheckingType = .no
  171. cell.textField.autocapitalizationType = .none
  172. cell.textField.returnKeyType = .next
  173. return cell
  174. }()
  175. lazy var smtpPortCell: TextFieldCell = {
  176. let cell = TextFieldCell(
  177. descriptionID: "login_smtp_port",
  178. placeholder: String.localized("automatic"),
  179. delegate: self)
  180. cell.tag = tagSmtpPortCell
  181. cell.setText(text: editablePort(port: dcContext.sendPort))
  182. cell.textField.tag = tagTextFieldSmtpPort
  183. cell.textField.keyboardType = .numberPad
  184. return cell
  185. }()
  186. lazy var smtpPasswordCell: TextFieldCell = {
  187. let cell = TextFieldCell(
  188. descriptionID: "login_smtp_password",
  189. placeholder: String.localized("automatic"),
  190. delegate: self)
  191. cell.textField.textContentType = UITextContentType.password
  192. cell.setText(text: dcContext.sendPw ?? nil)
  193. cell.textField.isSecureTextEntry = true
  194. cell.textField.tag = tagTextFieldSmtpPassword
  195. cell.tag = tagSmtpPasswordCell
  196. cell.textField.returnKeyType = .next
  197. return cell
  198. }()
  199. lazy var smtpSecurityCell: UITableViewCell = {
  200. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  201. cell.textLabel?.text = String.localized("login_smtp_security")
  202. cell.tag = tagSmtpSecurityCell
  203. cell.accessoryType = .disclosureIndicator
  204. return cell
  205. }()
  206. lazy var certCheckCell: UITableViewCell = {
  207. let certCheckType = CertificateCheckController.ValueConverter.convertHexToString(value: dcContext.certificateChecks)
  208. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  209. cell.textLabel?.text = String.localized("login_certificate_checks")
  210. cell.detailTextLabel?.text = certCheckType
  211. cell.tag = tagCertCheckCell
  212. cell.accessoryType = .disclosureIndicator
  213. return cell
  214. }()
  215. lazy var viewLogCell: UITableViewCell = {
  216. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  217. cell.textLabel?.text = String.localized("pref_view_log")
  218. cell.tag = tagViewLogCell
  219. cell.accessoryType = .disclosureIndicator
  220. return cell
  221. }()
  222. private lazy var loginButton: UIBarButtonItem = {
  223. let button = UIBarButtonItem(
  224. title: String.localized("login_title"),
  225. style: .done,
  226. target: self,
  227. action: #selector(loginButtonPressed))
  228. button.isEnabled = !dcContext.isConfigured()
  229. return button
  230. }()
  231. // MARK: - constructor
  232. init(dcAccounts: DcAccounts, editView: Bool) {
  233. self.editView = editView
  234. self.dcAccounts = dcAccounts
  235. self.dcContext = dcAccounts.getSelected()
  236. self.sections.append(basicSection)
  237. self.sections.append(advancedSection)
  238. super.init(style: .grouped)
  239. hidesBottomBarWhenPushed = true
  240. }
  241. required init?(coder _: NSCoder) {
  242. fatalError("init(coder:) has not been implemented")
  243. }
  244. // MARK: - lifecycle
  245. override func viewDidLoad() {
  246. super.viewDidLoad()
  247. if editView {
  248. title = String.localized("pref_password_and_account_settings")
  249. } else {
  250. title = String.localized("login_header")
  251. }
  252. navigationItem.rightBarButtonItem = loginButton
  253. emailCell.setText(text: dcContext.addr ?? nil)
  254. passwordCell.setText(text: dcContext.mailPw ?? nil)
  255. }
  256. override func viewWillAppear(_ animated: Bool) {
  257. super.viewWillAppear(animated)
  258. initSelectionCells()
  259. handleLoginButton()
  260. }
  261. override func viewWillDisappear(_ animated: Bool) {
  262. resignFirstResponderOnAllCells()
  263. progressObserver = nil
  264. }
  265. override func viewDidDisappear(_: Bool) {
  266. let nc = NotificationCenter.default
  267. if let configureProgressObserver = self.progressObserver {
  268. nc.removeObserver(configureProgressObserver)
  269. }
  270. if let oauth2Observer = self.oauth2Observer {
  271. nc.removeObserver(oauth2Observer)
  272. }
  273. }
  274. // MARK: - Table view data source
  275. override func numberOfSections(in _: UITableView) -> Int {
  276. return sections.count
  277. }
  278. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  279. if sections[section] == basicSection {
  280. return basicSectionCells.count
  281. } else {
  282. return advancedSectionShowing ? advancedSectionCells.count : 1
  283. }
  284. }
  285. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  286. if sections[section] == basicSection && editView {
  287. return String.localized("login_header")
  288. } else {
  289. return nil
  290. }
  291. }
  292. override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
  293. if sections[section] == basicSection {
  294. return String.localized("login_no_servers_hint")
  295. } else if sections[section] == advancedSection {
  296. if advancedSectionShowing && dcContext.isConfigured() {
  297. var info = String.localized("used_settings") + "\n"
  298. info += "IMAP "
  299. info += SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("mail_security"))) + " "
  300. info += (dcContext.getConfig("configured_mail_user") ?? "unset") + ":***@"
  301. info += (dcContext.getConfig("configured_mail_server") ?? "unset") + ":"
  302. info += (dcContext.getConfig("configured_mail_port") ?? "unset") + "\n"
  303. info += "SMTP "
  304. info += SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("send_security"))) + " "
  305. info += (dcContext.getConfig("configured_send_user") ?? "unset") + ":***@"
  306. info += (dcContext.getConfig("configured_send_server") ?? "unset") + ":"
  307. info += (dcContext.getConfig("configured_send_port") ?? "unset") + "\n\n"
  308. info += String.localized("login_subheader")
  309. return info
  310. } else {
  311. return String.localized("login_subheader")
  312. }
  313. } else {
  314. return nil
  315. }
  316. }
  317. override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  318. let section = indexPath.section
  319. let row = indexPath.row
  320. if sections[section] == basicSection {
  321. return basicSectionCells[row]
  322. } else {
  323. return advancedSectionCells[row]
  324. }
  325. }
  326. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  327. guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
  328. // handle tap on password -> show oAuthDialogue
  329. switch tappedCell.tag {
  330. case tagPasswordCell:
  331. if let textFieldCell = tappedCell as? TextFieldCell {
  332. if let emailAdress = textFieldCell.getText() {
  333. _ = showOAuthAlertIfNeeded(emailAddress: emailAdress, handleCancel: nil)
  334. }
  335. }
  336. case tagAdvancedCell:
  337. toggleAdvancedSection()
  338. case tagImapSecurityCell:
  339. showImapSecurityOptions()
  340. case tagSmtpSecurityCell:
  341. showSmtpSecurityOptions()
  342. case tagCertCheckCell:
  343. showCertCheckOptions()
  344. case tagViewLogCell:
  345. tableView.deselectRow(at: indexPath, animated: false)
  346. showLogViewController()
  347. default:
  348. break
  349. }
  350. }
  351. // MARK: - actions
  352. private func toggleAdvancedSection() {
  353. let willShow = !advancedSectionShowing
  354. guard let advancedSectionIndex = sections.firstIndex(of: advancedSection) else { return }
  355. var advancedIndexPaths: [IndexPath] = advancedSectionCells.indices.map { IndexPath(row: $0, section: advancedSectionIndex) }
  356. advancedIndexPaths.removeFirst() // do not touch the first item that is the switch itself
  357. // on expansion, replace the disclosureIndicator by an n-dash
  358. advancedShowCell.accessoryType = willShow ? .none : .disclosureIndicator
  359. advancedShowCell.detailTextLabel?.text = willShow ? "\u{2013}" : nil
  360. advancedSectionShowing = willShow // set flag before delete/insert, because cellForRowAt will be triggered and uses this flag
  361. passwordCell.textField.returnKeyType = willShow ? .next : .default
  362. if willShow {
  363. tableView.insertRows(at: advancedIndexPaths, with: .fade)
  364. } else {
  365. tableView.deleteRows(at: advancedIndexPaths, with: .fade)
  366. }
  367. tableView.reloadData() // needed to force a redraw
  368. }
  369. @objc private func loginButtonPressed() {
  370. guard let emailAddress = emailCell.getText() else {
  371. return // handle case when either email or pw fields are empty
  372. }
  373. func loginButtonPressedContinue() {
  374. let oAuthStarted = showOAuthAlertIfNeeded(emailAddress: emailAddress, handleCancel: loginButtonPressed)
  375. // if canceled we will run this method again but this time oAuthStarted will be false
  376. if oAuthStarted {
  377. // the loginFlow will be handled by oAuth2
  378. return
  379. }
  380. let password = passwordCell.getText() ?? "" // empty passwords are ok -> for oauth there is no password needed
  381. login(emailAddress: emailAddress, password: password)
  382. }
  383. if dcContext.isConfigured(),
  384. let oldAddress = dcContext.getConfig("configured_addr"),
  385. oldAddress != emailAddress {
  386. let msg = String.localizedStringWithFormat(String.localized("aeap_explanation"), oldAddress, emailAddress)
  387. let alert = UIAlertController(title: msg, message: nil, preferredStyle: .safeActionSheet)
  388. alert.addAction(UIAlertAction(title: String.localized("perm_continue"), style: .default, handler: { _ in
  389. loginButtonPressedContinue()
  390. }))
  391. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel, handler: nil))
  392. self.present(alert, animated: true, completion: nil)
  393. } else {
  394. loginButtonPressedContinue()
  395. }
  396. }
  397. private func updateProviderInfo() {
  398. provider = dcContext.getProviderFromEmailWithDns(addr: emailCell.getText() ?? "")
  399. if let hint = provider?.beforeLoginHint,
  400. let status = provider?.status,
  401. let statusType = ProviderInfoStatus(rawValue: status),
  402. !hint.isEmpty {
  403. providerInfoCell.updateInfo(hint: hint, hintType: statusType)
  404. if !providerInfoShowing {
  405. showProviderInfo()
  406. }
  407. } else if providerInfoShowing {
  408. hideProviderInfo()
  409. }
  410. }
  411. private func showProviderInfo() {
  412. basicSectionCells = [emailCell, passwordCell, providerInfoCell]
  413. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  414. tableView.insertRows(at: [providerInfoCellIndexPath], with: .fade)
  415. providerInfoShowing = true
  416. }
  417. private func hideProviderInfo() {
  418. providerInfoCell.updateInfo(hint: nil, hintType: .none)
  419. basicSectionCells = [emailCell, passwordCell]
  420. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  421. tableView.deleteRows(at: [providerInfoCellIndexPath], with: .automatic)
  422. providerInfoShowing = false
  423. }
  424. private func login(emailAddress: String, password: String, skipAdvanceSetup: Bool = false) {
  425. addProgressHudLoginListener()
  426. resignFirstResponderOnAllCells() // this will resign focus from all textFieldCells so the keyboard wont pop up anymore
  427. dcContext.addr = emailAddress
  428. dcContext.mailPw = password
  429. if !skipAdvanceSetup {
  430. evaluateAdvancedSetup() // this will set MRConfig related to advanced fields
  431. }
  432. print("oAuth-Flag when loggin in: \(dcContext.getAuthFlags())")
  433. dcAccounts.stopIo()
  434. dcContext.configure()
  435. showProgressAlert(title: String.localized("login_header"), dcContext: dcContext)
  436. }
  437. @objc func closeButtonPressed() {
  438. dismiss(animated: true, completion: nil)
  439. }
  440. // returns true if needed
  441. private func showOAuthAlertIfNeeded(emailAddress: String, handleCancel: (() -> Void)?) -> Bool {
  442. return false
  443. // don't use oauth2 for now as not yet supported by deltachat-rust.
  444. //
  445. // if skipOauth {
  446. // // user has previously denied oAuth2-setup
  447. // return false
  448. // }
  449. //
  450. // guard let oAuth2UrlPointer = dc_get_oauth2_url(mailboxPointer, emailAddress, "chat.delta:/auth") else {
  451. // //MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL)) -- do not reset, there may be different values
  452. // return false
  453. // }
  454. //
  455. // let oAuth2Url = String(cString: oAuth2UrlPointer)
  456. //
  457. // if let url = URL(string: oAuth2Url) {
  458. // let title = "Continue with simplified setup"
  459. // 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."
  460. //
  461. // let oAuthAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  462. // let confirm = UIAlertAction(title: "Confirm", style: .default, handler: {
  463. // [weak self] _ in // TODO: refactor usages of `self` to `self?` when this code is used again
  464. // let nc = NotificationCenter.default
  465. // self.oauth2Observer = nc.addObserver(self, selector: #selector(self.oauthLoginApproved), name: NSNotification.Name("oauthLoginApproved"), object: nil)
  466. // self.launchOAuthBrowserWindow(url: url)
  467. // })
  468. // let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: {
  469. // _ in
  470. // MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL))
  471. // self.skipOauth = true
  472. // handleCancel?()
  473. //
  474. // })
  475. // oAuthAlertController.addAction(confirm)
  476. // oAuthAlertController.addAction(cancel)
  477. //
  478. // present(oAuthAlertController, animated: true, completion: nil)
  479. // return true
  480. // } else {
  481. // return false
  482. // }
  483. }
  484. @objc func oauthLoginApproved(notification: Notification) {
  485. guard let userInfo = notification.userInfo, let token = userInfo["token"] as? String, let emailAddress = emailCell.getText() else {
  486. return
  487. }
  488. passwordCell.setText(text: token)
  489. dcContext.setAuthFlags(flags: Int(DC_LP_AUTH_OAUTH2))
  490. login(emailAddress: emailAddress, password: token, skipAdvanceSetup: true)
  491. }
  492. private func launchOAuthBrowserWindow(url: URL) {
  493. UIApplication.shared.open(url) // this opens safari as seperate app
  494. }
  495. private func addProgressHudLoginListener() {
  496. let nc = NotificationCenter.default
  497. progressObserver = nc.addObserver(
  498. forName: dcNotificationConfigureProgress,
  499. object: nil,
  500. queue: nil
  501. ) { notification in
  502. if let ui = notification.userInfo {
  503. if let error = ui["error"] as? Bool, error {
  504. self.dcAccounts.startIo()
  505. var errorMessage = ui["errorMessage"] as? String
  506. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  507. if let reachability = appDelegate.reachability, reachability.connection == .unavailable {
  508. errorMessage = String.localized("login_error_no_internet_connection")
  509. }
  510. } else {
  511. errorMessage = "\(errorMessage ?? "no message")\n\n(warning=\(self.dcContext.lastWarningString) (progress=\(self.dcContext.maxConfigureProgress))"
  512. }
  513. self.updateProgressAlert(error: errorMessage)
  514. } else if let done = ui["done"] as? Bool, done {
  515. self.dcAccounts.startIo()
  516. self.updateProgressAlertSuccess(completion: self.handleLoginSuccess)
  517. } else {
  518. self.updateProgressAlertValue(value: ui["progress"] as? Int)
  519. }
  520. }
  521. }
  522. }
  523. private func evaluateAdvancedSetup() {
  524. for cell in advancedSectionCells {
  525. if let textFieldCell = cell as? TextFieldCell {
  526. switch textFieldCell.tag {
  527. case tagImapServerCell:
  528. dcContext.mailServer = textFieldCell.getText() ?? nil
  529. case tagImapPortCell:
  530. dcContext.mailPort = textFieldCell.getText() ?? nil
  531. case tagImapUserCell:
  532. dcContext.mailUser = textFieldCell.getText() ?? nil
  533. case tagSmtpServerCell:
  534. dcContext.sendServer = textFieldCell.getText() ?? nil
  535. case tagSmtpPortCell:
  536. dcContext.sendPort = textFieldCell.getText() ?? nil
  537. case tagSmtpUserCell:
  538. dcContext.sendUser = textFieldCell.getText() ?? nil
  539. case tagSmtpPasswordCell:
  540. dcContext.sendPw = textFieldCell.getText() ?? nil
  541. default:
  542. logger.info("unknown identifier \(cell.tag)")
  543. }
  544. }
  545. }
  546. }
  547. private func handleLoginSuccess() {
  548. // used when login hud successfully went through
  549. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  550. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  551. appDelegate.registerForNotifications()
  552. }
  553. initSelectionCells()
  554. if let onLoginSuccess = self.onLoginSuccess {
  555. onLoginSuccess()
  556. } else {
  557. navigationController?.popViewController(animated: true)
  558. }
  559. }
  560. private func initSelectionCells() {
  561. imapSecurityCell.detailTextLabel?.text = SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("mail_security")))
  562. smtpSecurityCell.detailTextLabel?.text = SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("send_security")))
  563. certCheckCell.detailTextLabel?.text = CertificateCheckController.ValueConverter.convertHexToString(value: dcContext.certificateChecks)
  564. }
  565. private func resignFirstResponderOnAllCells() {
  566. _ = basicSectionCells.map({
  567. resignCell(cell: $0)
  568. })
  569. _ = advancedSectionCells.map({
  570. resignCell(cell: $0)
  571. })
  572. }
  573. private func handleLoginButton() {
  574. loginButton.isEnabled = !(emailCell.getText() ?? "").isEmpty && !(passwordCell.getText() ?? "").isEmpty
  575. }
  576. private func handleProviderInfoButton() {
  577. guard let provider = provider else {
  578. return
  579. }
  580. openProviderInfo(provider: provider)
  581. }
  582. func resignCell(cell: UITableViewCell) {
  583. if let c = cell as? TextFieldCell {
  584. c.textField.resignFirstResponder()
  585. }
  586. }
  587. @objc private func textFieldDidChange() {
  588. handleLoginButton()
  589. }
  590. @objc private func emailCellEdited() {
  591. if providerInfoShowing {
  592. updateProviderInfo()
  593. }
  594. }
  595. // MARK: - coordinator
  596. private func showLogViewController() {
  597. let controller = LogViewController(dcContext: dcContext)
  598. navigationController?.pushViewController(controller, animated: true)
  599. }
  600. private func showCertCheckOptions() {
  601. let certificateCheckController = CertificateCheckController(dcContext: dcContext, sectionTitle: String.localized("login_certificate_checks"))
  602. navigationController?.pushViewController(certificateCheckController, animated: true)
  603. }
  604. private func showImapSecurityOptions() {
  605. let securitySettingsController = SecuritySettingsController(dcContext: dcContext, title: String.localized("login_imap_security"),
  606. type: SecurityType.IMAPSecurity)
  607. navigationController?.pushViewController(securitySettingsController, animated: true)
  608. }
  609. private func showSmtpSecurityOptions() {
  610. let securitySettingsController = SecuritySettingsController(dcContext: dcContext,
  611. title: String.localized("login_smtp_security"),
  612. type: SecurityType.SMTPSecurity)
  613. navigationController?.pushViewController(securitySettingsController, animated: true)
  614. }
  615. private func openProviderInfo(provider: DcProvider) {
  616. guard let url = URL(string: provider.getOverviewPage) else { return }
  617. UIApplication.shared.open(url)
  618. }
  619. }
  620. // MARK: - UITextFieldDelegate
  621. extension AccountSetupController: UITextFieldDelegate {
  622. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  623. let currentTag = textField.tag
  624. if let nextField = tableView.viewWithTag(currentTag + 100) as? UITextField {
  625. nextField.becomeFirstResponder()
  626. return true
  627. } else {
  628. textField.resignFirstResponder()
  629. let indexPath = IndexPath(row: 0, section: 0)
  630. tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: true)
  631. return true
  632. }
  633. }
  634. func textFieldDidBeginEditing(_ textField: UITextField) {
  635. if textField.tag == tagTextFieldEmail {
  636. // this will re-enable possible oAuth2-login
  637. skipOauth = false
  638. }
  639. }
  640. func textFieldDidEndEditing(_ textField: UITextField) {
  641. if textField.tag == tagTextFieldEmail {
  642. _ = showOAuthAlertIfNeeded(emailAddress: textField.text ?? "", handleCancel: {
  643. self.passwordCell.textField.becomeFirstResponder()
  644. })
  645. updateProviderInfo()
  646. }
  647. }
  648. }