AccountSetupController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. import SafariServices
  2. import UIKit
  3. class AccountSetupController: UITableViewController {
  4. weak var coordinator: AccountSetupCoordinator?
  5. private let dcContext: DcContext
  6. private var skipOauth = false
  7. private var backupProgressObserver: Any?
  8. private var configureProgressObserver: Any?
  9. private var oauth2Observer: Any?
  10. private let tagEmailCell = 0
  11. private let tagPasswordCell = 1
  12. private let tagAdvancedCell = 2
  13. private let tagImapServerCell = 3
  14. private let tagImapUserCell = 4
  15. private let tagImapPortCell = 5
  16. private let tagImapSecurityCell = 6
  17. private let tagSmtpServerCell = 7
  18. private let tagSmtpUserCell = 8
  19. private let tagSmtpPortCell = 9
  20. private let tagSmtpPasswordCell = 10
  21. private let tagSmtpSecurityCell = 11
  22. private let tagCertCheckCell = 12
  23. private let tagEmptyServerCell = 13
  24. private let tagDeleteAccountCell = 14
  25. private let tagRestoreCell = 15
  26. private let tagTextFieldEmail = 100
  27. private let tagTextFieldPassword = 200
  28. private let tagTextFieldImapServer = 300
  29. private let tagTextFieldImapLogin = 400
  30. private let tagTextFieldSmtpServer = 500
  31. private let tagTextFieldSmtpUser = 600
  32. private let tagTextFieldSmtpPassword = 700
  33. // add cells to sections
  34. let basicSection = 100
  35. let advancedSection = 200
  36. let restoreSection = 300
  37. let folderSection = 400
  38. let dangerSection = 500
  39. private var sections = [Int]()
  40. private lazy var basicSectionCells: [UITableViewCell] = [emailCell, passwordCell]
  41. private lazy var restoreCells: [UITableViewCell] = [restoreCell]
  42. private lazy var advancedSectionCells: [UITableViewCell] = [
  43. advancedShowCell,
  44. imapSecurityCell,
  45. imapUserCell,
  46. imapServerCell,
  47. imapPortCell,
  48. smtpSecurityCell,
  49. smtpUserCell,
  50. smtpPasswordCell,
  51. smtpServerCell,
  52. smtpPortCell,
  53. certCheckCell
  54. ]
  55. private lazy var folderCells: [UITableViewCell] = [inboxWatchCell, sentboxWatchCell, mvboxWatchCell, sendCopyToSelfCell, mvboxMoveCell]
  56. private lazy var dangerCells: [UITableViewCell] = [emptyServerCell, deleteAccountCell]
  57. private let editView: Bool
  58. private var advancedSectionShowing: Bool = false
  59. private var providerInfoShowing: Bool = false
  60. private var provider: DcProvider?
  61. //MARK: -the progress dialog
  62. private lazy var configProgressAlert: UIAlertController = {
  63. let alert = UIAlertController(title: "", message: "", preferredStyle: .alert)
  64. alert.addAction(UIAlertAction(
  65. title: String.localized("cancel"),
  66. style: .cancel,
  67. handler: { _ in
  68. self.dcContext.stopOngoingProcess()
  69. }))
  70. return alert
  71. }()
  72. private func showProgressHud(title: String) {
  73. configProgressAlert.actions[0].isEnabled = true
  74. configProgressAlert.title = title
  75. configProgressAlert.message = String.localized("one_moment")
  76. present(configProgressAlert, animated: true, completion: nil)
  77. }
  78. private func updateProgressHud(error message: String?) {
  79. DispatchQueue.main.async(execute: {
  80. self.configProgressAlert.dismiss(animated: false)
  81. let errorAlert = UIAlertController(title: String.localized("error"), message: message, preferredStyle: .alert)
  82. errorAlert.addAction(UIAlertAction(title: String.localized("ok"), style: .default, handler: nil))
  83. self.present(errorAlert, animated: true, completion: nil)
  84. })
  85. }
  86. private func updateProgressHudSuccess() {
  87. updateProgressHudValue(value: 1000)
  88. DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
  89. self.configProgressAlert.dismiss(animated: true) {
  90. self.handleLoginSuccess()
  91. }
  92. })
  93. }
  94. private func updateProgressHudValue(value: Int?) {
  95. if let value = value {
  96. configProgressAlert.message = String.localized("one_moment") + " " + String(value/10) + "%"
  97. }
  98. }
  99. // MARK: -cells
  100. private lazy var emailCell: TextFieldCell = {
  101. let cell = TextFieldCell.makeEmailCell(delegate: self)
  102. cell.tag = tagEmailCell
  103. cell.textField.tag = tagTextFieldEmail // will be used to eventually show oAuth-Dialogue when pressing return key
  104. cell.setText(text: DcConfig.addr ?? nil)
  105. cell.textField.delegate = self
  106. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  107. return cell
  108. }()
  109. private lazy var passwordCell: TextFieldCell = {
  110. let cell = TextFieldCell.makePasswordCell(delegate: self)
  111. cell.tag = tagPasswordCell
  112. cell.textField.tag = tagTextFieldPassword // will be used to eventually show oAuth-Dialogue when selecting
  113. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  114. cell.setText(text: DcConfig.mailPw ?? nil)
  115. cell.textField.delegate = self
  116. return cell
  117. }()
  118. private lazy var providerInfoCell: ProviderInfoCell = {
  119. let cell = ProviderInfoCell()
  120. cell.onInfoButtonPressed = {
  121. [unowned self] in
  122. self.handleProviderInfoButton()
  123. }
  124. return cell
  125. }()
  126. private lazy var restoreCell: UITableViewCell = {
  127. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  128. cell.textLabel?.text = String.localized("import_backup_title")
  129. cell.accessoryType = .disclosureIndicator
  130. cell.tag = tagRestoreCell
  131. return cell
  132. }()
  133. private lazy var emptyServerCell: ActionCell = {
  134. let cell = ActionCell(frame: .zero)
  135. cell.actionTitle = String.localized("pref_empty_server_title")
  136. cell.actionColor = UIColor.red
  137. cell.tag = tagEmptyServerCell
  138. return cell
  139. }()
  140. private lazy var deleteAccountCell: ActionCell = {
  141. let cell = ActionCell(frame: .zero)
  142. cell.actionTitle = String.localized("delete_account")
  143. cell.actionColor = UIColor.red
  144. cell.tag = tagDeleteAccountCell
  145. return cell
  146. }()
  147. lazy var advancedShowCell: UITableViewCell = {
  148. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  149. cell.textLabel?.text = String.localized("menu_advanced")
  150. cell.accessoryType = .disclosureIndicator
  151. cell.tag = tagAdvancedCell
  152. return cell
  153. }()
  154. lazy var imapServerCell: TextFieldCell = {
  155. let cell = TextFieldCell(
  156. descriptionID: "login_imap_server",
  157. placeholder: String.localized("automatic"),
  158. delegate: self)
  159. cell.tag = tagImapServerCell
  160. cell.setText(text: DcConfig.mailServer ?? nil)
  161. cell.textField.tag = tagTextFieldImapServer
  162. cell.textField.autocorrectionType = .no
  163. cell.textField.spellCheckingType = .no
  164. cell.textField.autocapitalizationType = .none
  165. return cell
  166. }()
  167. lazy var imapUserCell: TextFieldCell = {
  168. let cell = TextFieldCell(
  169. descriptionID: "login_imap_login",
  170. placeholder: String.localized("automatic"),
  171. delegate: self)
  172. cell.setText(text: DcConfig.mailUser ?? nil)
  173. cell.textField.tag = tagTextFieldImapLogin
  174. cell.tag = tagImapUserCell
  175. return cell
  176. }()
  177. func editablePort(port: String?) -> String {
  178. if let port = port {
  179. if Int(port) == 0 {
  180. return ""
  181. }
  182. return port
  183. } else {
  184. return ""
  185. }
  186. }
  187. lazy var imapPortCell: TextFieldCell = {
  188. let cell = TextFieldCell(
  189. descriptionID: "login_imap_port",
  190. placeholder: String.localized("automatic"),
  191. delegate: self)
  192. cell.tag = tagImapPortCell
  193. cell.setText(text: editablePort(port: DcConfig.mailPort))
  194. cell.textField.tag = tagImapPortCell
  195. cell.textField.keyboardType = .numberPad
  196. return cell
  197. }()
  198. lazy var imapSecurityCell: UITableViewCell = {
  199. let text = "\(DcConfig.getImapSecurity())"
  200. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  201. cell.textLabel?.text = String.localized("login_imap_security")
  202. cell.accessoryType = .disclosureIndicator
  203. cell.detailTextLabel?.text = "\(DcConfig.getImapSecurity())"
  204. cell.selectionStyle = .none
  205. cell.tag = tagImapSecurityCell
  206. return cell
  207. }()
  208. lazy var smtpServerCell: TextFieldCell = {
  209. let cell = TextFieldCell(
  210. descriptionID: "login_smtp_server",
  211. placeholder: String.localized("automatic"),
  212. delegate: self)
  213. cell.textField.tag = tagTextFieldSmtpServer
  214. cell.setText(text: DcConfig.sendServer ?? nil)
  215. cell.tag = tagSmtpServerCell
  216. cell.textField.autocorrectionType = .no
  217. cell.textField.spellCheckingType = .no
  218. cell.textField.autocapitalizationType = .none
  219. return cell
  220. }()
  221. lazy var smtpUserCell: TextFieldCell = {
  222. let cell = TextFieldCell(
  223. descriptionID: "login_smtp_login",
  224. placeholder: String.localized("automatic"),
  225. delegate: self)
  226. cell.textField.tag = tagTextFieldSmtpUser
  227. cell.setText(text: DcConfig.sendUser ?? nil)
  228. cell.tag = tagSmtpUserCell
  229. return cell
  230. }()
  231. lazy var smtpPortCell: TextFieldCell = {
  232. let cell = TextFieldCell(
  233. descriptionID: "login_smtp_port",
  234. placeholder: String.localized("automatic"),
  235. delegate: self)
  236. cell.tag = tagSmtpPortCell
  237. cell.setText(text: editablePort(port: DcConfig.sendPort))
  238. cell.textField.tag = tagSmtpPortCell
  239. cell.textField.keyboardType = .numberPad
  240. return cell
  241. }()
  242. lazy var smtpPasswordCell: TextFieldCell = {
  243. let cell = TextFieldCell(
  244. descriptionID: "login_smtp_password",
  245. placeholder: String.localized("automatic"),
  246. delegate: self)
  247. cell.textField.textContentType = UITextContentType.password
  248. cell.setText(text: DcConfig.sendPw ?? nil)
  249. cell.textField.isSecureTextEntry = true
  250. cell.textField.tag = tagTextFieldSmtpPassword
  251. cell.tag = tagSmtpPasswordCell
  252. return cell
  253. }()
  254. lazy var smtpSecurityCell: UITableViewCell = {
  255. let security = "\(DcConfig.getSmtpSecurity())"
  256. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  257. cell.textLabel?.text = String.localized("login_smtp_security")
  258. cell.detailTextLabel?.text = security
  259. cell.tag = tagSmtpSecurityCell
  260. cell.accessoryType = .disclosureIndicator
  261. cell.selectionStyle = .none
  262. return cell
  263. }()
  264. lazy var certCheckCell: UITableViewCell = {
  265. let certCheckType = CertificateCheckController.ValueConverter.convertHexToString(value: DcConfig.certificateChecks)
  266. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  267. cell.textLabel?.text = String.localized("login_certificate_checks")
  268. cell.detailTextLabel?.text = certCheckType
  269. cell.tag = tagCertCheckCell
  270. cell.accessoryType = .disclosureIndicator
  271. cell.selectionStyle = .none
  272. return cell
  273. }()
  274. lazy var inboxWatchCell: SwitchCell = {
  275. return SwitchCell(
  276. textLabel: String.localized("pref_watch_inbox_folder"),
  277. on: dcContext.getConfigBool("inbox_watch"),
  278. action: { cell in
  279. self.dcContext.setConfigBool("inbox_watch", cell.isOn)
  280. })
  281. }()
  282. lazy var sentboxWatchCell: SwitchCell = {
  283. return SwitchCell(
  284. textLabel: String.localized("pref_watch_sent_folder"),
  285. on: dcContext.getConfigBool("sentbox_watch"),
  286. action: { cell in
  287. self.dcContext.setConfigBool("sentbox_watch", cell.isOn)
  288. })
  289. }()
  290. lazy var mvboxWatchCell: SwitchCell = {
  291. return SwitchCell(
  292. textLabel: String.localized("pref_watch_mvbox_folder"),
  293. on: dcContext.getConfigBool("mvbox_watch"),
  294. action: { cell in
  295. self.dcContext.setConfigBool("mvbox_watch", cell.isOn)
  296. })
  297. }()
  298. lazy var sendCopyToSelfCell: SwitchCell = {
  299. return SwitchCell(
  300. textLabel: String.localized("pref_send_copy_to_self"),
  301. on: dcContext.getConfigBool("bcc_self"),
  302. action: { cell in
  303. self.dcContext.setConfigBool("bcc_self", cell.isOn)
  304. })
  305. }()
  306. lazy var mvboxMoveCell: SwitchCell = {
  307. return SwitchCell(
  308. textLabel: String.localized("pref_auto_folder_moves"),
  309. on: dcContext.getConfigBool("mvbox_move"),
  310. action: { cell in
  311. self.dcContext.setConfigBool("mvbox_move", cell.isOn)
  312. })
  313. }()
  314. private lazy var loginButton: UIBarButtonItem = {
  315. let button = UIBarButtonItem(
  316. title: String.localized("login_title"),
  317. style: .done,
  318. target: self,
  319. action: #selector(loginButtonPressed))
  320. button.isEnabled = dc_is_configured(mailboxPointer) == 0
  321. return button
  322. }()
  323. // MARK: - constructor
  324. init(dcContext: DcContext, editView: Bool) {
  325. self.editView = editView
  326. self.dcContext = dcContext
  327. self.sections.append(basicSection)
  328. self.sections.append(advancedSection)
  329. if editView {
  330. self.sections.append(folderSection)
  331. self.sections.append(dangerSection)
  332. } else {
  333. self.sections.append(restoreSection)
  334. }
  335. super.init(style: .grouped)
  336. hidesBottomBarWhenPushed = true
  337. }
  338. required init?(coder _: NSCoder) {
  339. fatalError("init(coder:) has not been implemented")
  340. }
  341. // MARK: -lifecycle
  342. override func viewDidLoad() {
  343. super.viewDidLoad()
  344. if editView {
  345. title = String.localized("pref_password_and_account_settings")
  346. } else {
  347. title = String.localized("login_header")
  348. }
  349. navigationItem.rightBarButtonItem = loginButton
  350. }
  351. override func viewWillAppear(_ animated: Bool) {
  352. super.viewWillAppear(animated)
  353. initSelectionCells()
  354. handleLoginButton()
  355. }
  356. override func viewDidAppear(_ animated: Bool) {
  357. super.viewDidAppear(animated)
  358. }
  359. override func viewWillDisappear(_ animated: Bool) {
  360. resignFirstResponderOnAllCells()
  361. }
  362. override func viewDidDisappear(_: Bool) {
  363. let nc = NotificationCenter.default
  364. if let backupProgressObserver = self.backupProgressObserver {
  365. nc.removeObserver(backupProgressObserver)
  366. }
  367. if let configureProgressObserver = self.configureProgressObserver {
  368. nc.removeObserver(configureProgressObserver)
  369. }
  370. if let oauth2Observer = self.oauth2Observer {
  371. nc.removeObserver(oauth2Observer)
  372. }
  373. }
  374. // MARK: - Table view data source
  375. override func numberOfSections(in _: UITableView) -> Int {
  376. return sections.count
  377. }
  378. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  379. if sections[section] == basicSection {
  380. return basicSectionCells.count
  381. } else if sections[section] == restoreSection {
  382. return restoreCells.count
  383. } else if sections[section] == folderSection {
  384. return folderCells.count
  385. } else if sections[section] == dangerSection {
  386. return dangerCells.count
  387. } else {
  388. return advancedSectionShowing ? advancedSectionCells.count : 1
  389. }
  390. }
  391. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  392. if sections[section] == basicSection && editView {
  393. return String.localized("login_header")
  394. } else if sections[section] == folderSection {
  395. return String.localized("pref_imap_folder_handling")
  396. } else if sections[section] == dangerSection {
  397. return String.localized("danger")
  398. } else {
  399. return nil
  400. }
  401. }
  402. override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
  403. if sections[section] == basicSection {
  404. return String.localized("login_no_servers_hint")
  405. } else if sections[section] == advancedSection {
  406. if advancedSectionShowing && dcContext.isConfigured() {
  407. var info = String.localized("used_settings") + "\n"
  408. let serverFlags = Int(dcContext.getConfig("configured_server_flags") ?? "") ?? 0
  409. info += "IMAP "
  410. info += SecurityConverter.convertHexToString(type: .IMAPSecurity, hex: serverFlags&0x700) + " "
  411. info += (dcContext.getConfig("configured_mail_user") ?? "unset") + ":***@"
  412. info += (dcContext.getConfig("configured_mail_server") ?? "unset") + ":"
  413. info += (dcContext.getConfig("configured_mail_port") ?? "unset") + "\n"
  414. info += "SMTP "
  415. info += SecurityConverter.convertHexToString(type: .SMTPSecurity, hex: serverFlags&0x70000) + " "
  416. info += (dcContext.getConfig("configured_send_user") ?? "unset") + ":***@"
  417. info += (dcContext.getConfig("configured_send_server") ?? "unset") + ":"
  418. info += (dcContext.getConfig("configured_send_port") ?? "unset") + "\n\n"
  419. info += String.localized("login_subheader")
  420. return info
  421. } else {
  422. return String.localized("login_subheader")
  423. }
  424. } else if sections[section] == folderSection {
  425. return String.localized("pref_auto_folder_moves_explain")
  426. } else {
  427. return nil
  428. }
  429. }
  430. override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  431. let section = indexPath.section
  432. let row = indexPath.row
  433. if sections[section] == basicSection {
  434. return basicSectionCells[row]
  435. } else if sections[section] == restoreSection {
  436. return restoreCells[row]
  437. } else if sections[section] == folderSection {
  438. return folderCells[row]
  439. } else if sections[section] == dangerSection {
  440. return dangerCells[row]
  441. } else {
  442. return advancedSectionCells[row]
  443. }
  444. }
  445. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  446. guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
  447. // handle tap on password -> show oAuthDialogue
  448. switch tappedCell.tag {
  449. case tagPasswordCell:
  450. if let textFieldCell = tappedCell as? TextFieldCell {
  451. if let emailAdress = textFieldCell.getText() {
  452. _ = showOAuthAlertIfNeeded(emailAddress: emailAdress, handleCancel: nil)
  453. }
  454. }
  455. case tagRestoreCell:
  456. tableView.reloadData() // otherwise the disclosureIndicator may stay selected
  457. restoreBackup()
  458. case tagEmptyServerCell:
  459. emptyServer()
  460. case tagDeleteAccountCell:
  461. deleteAccount()
  462. case tagAdvancedCell:
  463. toggleAdvancedSection()
  464. case tagImapSecurityCell:
  465. coordinator?.showImapSecurityOptions()
  466. case tagSmtpSecurityCell:
  467. coordinator?.showSmptpSecurityOptions()
  468. case tagCertCheckCell:
  469. coordinator?.showCertCheckOptions()
  470. default:
  471. break
  472. }
  473. }
  474. // MARK: -actions
  475. private func toggleAdvancedSection() {
  476. let willShow = !advancedSectionShowing
  477. guard let advancedSectionIndex = sections.firstIndex(of: advancedSection) else { return }
  478. var advancedIndexPaths: [IndexPath] = advancedSectionCells.indices.map { IndexPath(row: $0, section: advancedSectionIndex) }
  479. advancedIndexPaths.removeFirst() // do not touch the first item that is the switch itself
  480. // on expansion, replace the disclosureIndicator by an n-dash
  481. advancedShowCell.accessoryType = willShow ? .none : .disclosureIndicator
  482. advancedShowCell.detailTextLabel?.text = willShow ? "\u{2013}" : nil
  483. advancedSectionShowing = willShow // set flag before delete/insert, because cellForRowAt will be triggered and uses this flag
  484. if willShow {
  485. tableView.insertRows(at: advancedIndexPaths, with: .fade)
  486. } else {
  487. tableView.deleteRows(at: advancedIndexPaths, with: .fade)
  488. }
  489. tableView.reloadData() // needed to force a redraw
  490. }
  491. @objc private func loginButtonPressed() {
  492. guard let emailAddress = emailCell.getText() else {
  493. return // handle case when either email or pw fields are empty
  494. }
  495. let oAuthStarted = showOAuthAlertIfNeeded(emailAddress: emailAddress, handleCancel: loginButtonPressed)
  496. // if canceled we will run this method again but this time oAuthStarted will be false
  497. if oAuthStarted {
  498. // the loginFlow will be handled by oAuth2
  499. return
  500. }
  501. let password = passwordCell.getText() ?? "" // empty passwords are ok -> for oauth there is no password needed
  502. login(emailAddress: emailAddress, password: password)
  503. }
  504. func updateProviderInfo() {
  505. provider = dcContext.getProviderFromEmail(addr: emailCell.getText() ?? "")
  506. if let hint = provider?.beforeLoginHint,
  507. let status = provider?.status,
  508. let statusType = ProviderInfoStatus(rawValue: status),
  509. !hint.isEmpty {
  510. providerInfoCell.updateInfo(hint: hint, hintType: statusType)
  511. if !providerInfoShowing {
  512. showProviderInfo()
  513. }
  514. } else if providerInfoShowing {
  515. hideProviderInfo()
  516. }
  517. }
  518. func showProviderInfo() {
  519. basicSectionCells = [emailCell, passwordCell, providerInfoCell]
  520. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  521. tableView.insertRows(at: [providerInfoCellIndexPath], with: .fade)
  522. providerInfoShowing = true
  523. }
  524. func hideProviderInfo() {
  525. providerInfoCell.updateInfo(hint: nil, hintType: .none)
  526. basicSectionCells = [emailCell, passwordCell]
  527. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  528. tableView.deleteRows(at: [providerInfoCellIndexPath], with: .automatic)
  529. providerInfoShowing = false
  530. }
  531. private func login(emailAddress: String, password: String, skipAdvanceSetup: Bool = false) {
  532. addProgressHudLoginListener()
  533. resignFirstResponderOnAllCells() // this will resign focus from all textFieldCells so the keyboard wont pop up anymore
  534. DcConfig.addr = emailAddress
  535. DcConfig.mailPw = password
  536. if !skipAdvanceSetup {
  537. evaluateAdvancedSetup() // this will set MRConfig related to advanced fields
  538. }
  539. print("oAuth-Flag when loggin in: \(DcConfig.getAuthFlags())")
  540. dc_configure(mailboxPointer)
  541. showProgressHud(title: String.localized("login_header"))
  542. }
  543. @objc func closeButtonPressed() {
  544. dismiss(animated: true, completion: nil)
  545. }
  546. // returns true if needed
  547. private func showOAuthAlertIfNeeded(emailAddress: String, handleCancel: (() -> Void)?) -> Bool {
  548. return false
  549. // disable oauth2 for now as not yet supported by deltachat-rust.
  550. /*
  551. if skipOauth {
  552. // user has previously denied oAuth2-setup
  553. return false
  554. }
  555. guard let oAuth2UrlPointer = dc_get_oauth2_url(mailboxPointer, emailAddress, "chat.delta:/auth") else {
  556. //MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL)) -- do not reset, there may be different values
  557. return false
  558. }
  559. let oAuth2Url = String(cString: oAuth2UrlPointer)
  560. if let url = URL(string: oAuth2Url) {
  561. let title = "Continue with simplified setup"
  562. // swiftlint:disable all
  563. 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."
  564. let oAuthAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  565. let confirm = UIAlertAction(title: "Confirm", style: .default, handler: {
  566. [unowned self] _ in
  567. let nc = NotificationCenter.default
  568. self.oauth2Observer = nc.addObserver(self, selector: #selector(self.oauthLoginApproved), name: NSNotification.Name("oauthLoginApproved"), object: nil)
  569. self.launchOAuthBrowserWindow(url: url)
  570. })
  571. let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: {
  572. _ in
  573. MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL))
  574. self.skipOauth = true
  575. handleCancel?()
  576. })
  577. oAuthAlertController.addAction(confirm)
  578. oAuthAlertController.addAction(cancel)
  579. present(oAuthAlertController, animated: true, completion: nil)
  580. return true
  581. } else {
  582. return false
  583. }
  584. */
  585. }
  586. @objc func oauthLoginApproved(notification: Notification) {
  587. guard let userInfo = notification.userInfo, let token = userInfo["token"] as? String, let emailAddress = emailCell.getText() else {
  588. return
  589. }
  590. passwordCell.setText(text: token)
  591. DcConfig.setAuthFlags(flags: Int(DC_LP_AUTH_OAUTH2))
  592. login(emailAddress: emailAddress, password: token, skipAdvanceSetup: true)
  593. }
  594. private func launchOAuthBrowserWindow(url: URL) {
  595. UIApplication.shared.open(url) // this opens safari as seperate app
  596. }
  597. private func addProgressHudLoginListener() {
  598. let nc = NotificationCenter.default
  599. configureProgressObserver = nc.addObserver(
  600. forName: dcNotificationConfigureProgress,
  601. object: nil,
  602. queue: nil
  603. ) {
  604. notification in
  605. if let ui = notification.userInfo {
  606. if ui["error"] as! Bool {
  607. self.updateProgressHud(error: ui["errorMessage"] as? String)
  608. } else if ui["done"] as! Bool {
  609. self.updateProgressHudSuccess()
  610. } else {
  611. self.updateProgressHudValue(value: ui["progress"] as? Int)
  612. }
  613. }
  614. }
  615. }
  616. private func addProgressHudBackupListener() {
  617. let nc = NotificationCenter.default
  618. backupProgressObserver = nc.addObserver(
  619. forName: dcNotificationImexProgress,
  620. object: nil,
  621. queue: nil
  622. ) {
  623. notification in
  624. if let ui = notification.userInfo {
  625. if ui["error"] as! Bool {
  626. self.updateProgressHud(error: ui["errorMessage"] as? String)
  627. } else if ui["done"] as! Bool {
  628. self.updateProgressHudSuccess()
  629. } else {
  630. self.updateProgressHudValue(value: ui["progress"] as? Int)
  631. }
  632. }
  633. }
  634. }
  635. private func evaluateAdvancedSetup() {
  636. for cell in advancedSectionCells {
  637. if let textFieldCell = cell as? TextFieldCell {
  638. switch textFieldCell.tag {
  639. case tagImapServerCell:
  640. DcConfig.mailServer = textFieldCell.getText() ?? nil
  641. case tagImapPortCell:
  642. DcConfig.mailPort = textFieldCell.getText() ?? nil
  643. case tagImapUserCell:
  644. DcConfig.mailUser = textFieldCell.getText() ?? nil
  645. case tagSmtpServerCell:
  646. DcConfig.sendServer = textFieldCell.getText() ?? nil
  647. case tagSmtpPortCell:
  648. DcConfig.sendPort = textFieldCell.getText() ?? nil
  649. case tagSmtpUserCell:
  650. DcConfig.sendUser = textFieldCell.getText() ?? nil
  651. case tagSmtpPasswordCell:
  652. DcConfig.sendPw = textFieldCell.getText() ?? nil
  653. default:
  654. logger.info("unknown identifier \(cell.tag)")
  655. }
  656. }
  657. }
  658. }
  659. private func restoreBackup() {
  660. logger.info("restoring backup")
  661. if DcConfig.configured {
  662. return
  663. }
  664. addProgressHudBackupListener()
  665. let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  666. if !documents.isEmpty {
  667. logger.info("looking for backup in: \(documents[0])")
  668. if let cString = dc_imex_has_backup(mailboxPointer, documents[0]) {
  669. let file = String(cString: cString)
  670. dc_str_unref(cString)
  671. logger.info("restoring backup: \(file)")
  672. showProgressHud(title: String.localized("import_backup_title"))
  673. dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
  674. }
  675. else {
  676. let alert = UIAlertController(
  677. title: String.localized("import_backup_title"),
  678. message: String.localizedStringWithFormat(
  679. String.localized("import_backup_no_backup_found"),
  680. "iTunes / <Your Device> / File Sharing / Delta Chat"), // TOOD: maybe better use an iOS-specific string here
  681. preferredStyle: .alert)
  682. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .cancel))
  683. present(alert, animated: true)
  684. }
  685. }
  686. logger.error("no documents directory found")
  687. }
  688. private func emptyServer() {
  689. let alert = UIAlertController(title: String.localized("pref_empty_server_title"),
  690. message: String.localized("pref_empty_server_msg"), preferredStyle: .safeActionSheet)
  691. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_inbox"), style: .destructive, handler: { _ in
  692. self.emptyServer2ndConfirm(title: String.localized("pref_empty_server_inbox"), flags: Int(DC_EMPTY_INBOX))
  693. }))
  694. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_mvbox"), style: .destructive, handler: { _ in
  695. self.emptyServer2ndConfirm(title: String.localized("pref_empty_server_mvbox"), flags: Int(DC_EMPTY_MVBOX))
  696. }))
  697. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  698. present(alert, animated: true, completion: nil)
  699. }
  700. private func emptyServer2ndConfirm(title: String, flags: Int) {
  701. let alert = UIAlertController(
  702. title: title,
  703. message: String.localized("pref_empty_server_msg"), preferredStyle: .alert)
  704. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_do_button"), style: .destructive, handler: { _ in
  705. self.dcContext.emptyServer(flags: flags)
  706. }))
  707. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  708. present(alert, animated: true, completion: nil)
  709. }
  710. private func deleteAccount() {
  711. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  712. return
  713. }
  714. let dbfile = appDelegate.dbfile()
  715. let dburl = URL(fileURLWithPath: dbfile, isDirectory: false)
  716. let alert = UIAlertController(
  717. title: String.localized("delete_account_ask"),
  718. message: nil,
  719. preferredStyle: .safeActionSheet)
  720. alert.addAction(UIAlertAction(title: String.localized("delete_account"), style: .destructive, handler: { _ in
  721. appDelegate.stop()
  722. appDelegate.close()
  723. do {
  724. try FileManager.default.removeItem(at: dburl)
  725. } catch {
  726. logger.error("failed to delete db: \(error)")
  727. }
  728. appDelegate.open()
  729. appDelegate.start()
  730. appDelegate.appCoordinator.presentLoginController()
  731. }))
  732. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  733. present(alert, animated: true, completion: nil)
  734. }
  735. private func handleLoginSuccess() {
  736. // used when login hud successfully went trough
  737. dismiss(animated: true, completion: nil)
  738. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  739. appDelegate.registerForPushNotifications()
  740. initSelectionCells();
  741. if let onLoginSuccess = self.coordinator?.onLoginSuccess {
  742. onLoginSuccess()
  743. } else {
  744. self.coordinator?.navigateBack()
  745. }
  746. }
  747. private func initSelectionCells() {
  748. smtpSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .SMTPSecurity, hex: DcConfig.getSmtpSecurity())
  749. imapSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .IMAPSecurity, hex: DcConfig.getImapSecurity())
  750. certCheckCell.detailTextLabel?.text = CertificateCheckController.ValueConverter.convertHexToString(value: DcConfig.certificateChecks)
  751. }
  752. private func resignFirstResponderOnAllCells() {
  753. let _ = basicSectionCells.map({
  754. resignCell(cell: $0)
  755. })
  756. let _ = advancedSectionCells.map({
  757. resignCell(cell: $0)
  758. }
  759. )
  760. }
  761. private func handleLoginButton() {
  762. loginButton.isEnabled = !(emailCell.getText() ?? "").isEmpty && !(passwordCell.getText() ?? "").isEmpty
  763. }
  764. private func handleProviderInfoButton() {
  765. print("handle provider info button")
  766. }
  767. func resignCell(cell: UITableViewCell) {
  768. if let c = cell as? TextFieldCell {
  769. c.textField.resignFirstResponder()
  770. }
  771. }
  772. @objc private func textFieldDidChange() {
  773. handleLoginButton()
  774. }
  775. }
  776. extension AccountSetupController: UITextFieldDelegate {
  777. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  778. let currentTag = textField.tag
  779. if let nextField = tableView.viewWithTag(currentTag + 100) as? UITextField {
  780. if nextField.tag > tagTextFieldPassword, !advancedSectionShowing {
  781. // gets here when trying to activate a collapsed cell
  782. return false
  783. }
  784. nextField.becomeFirstResponder()
  785. return true
  786. } else {
  787. textField.resignFirstResponder()
  788. emailCell.textField.becomeFirstResponder()
  789. let indexPath = IndexPath(row: 0, section: 0)
  790. tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: true)
  791. return true
  792. }
  793. }
  794. func textFieldDidBeginEditing(_ textField: UITextField) {
  795. if textField.tag == tagTextFieldEmail {
  796. // this will re-enable possible oAuth2-login
  797. skipOauth = false
  798. }
  799. }
  800. func textFieldDidEndEditing(_ textField: UITextField) {
  801. if textField.tag == tagTextFieldEmail {
  802. let _ = showOAuthAlertIfNeeded(emailAddress: textField.text ?? "", handleCancel: {
  803. self.passwordCell.textField.becomeFirstResponder()
  804. })
  805. updateProviderInfo()
  806. }
  807. }
  808. }