AccountSetupController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  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. return cell
  121. }()
  122. private lazy var restoreCell: UITableViewCell = {
  123. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  124. cell.textLabel?.text = String.localized("import_backup_title")
  125. cell.accessoryType = .disclosureIndicator
  126. cell.tag = tagRestoreCell
  127. return cell
  128. }()
  129. private lazy var emptyServerCell: ActionCell = {
  130. let cell = ActionCell(frame: .zero)
  131. cell.actionTitle = String.localized("pref_empty_server_title")
  132. cell.actionColor = UIColor.red
  133. cell.tag = tagEmptyServerCell
  134. return cell
  135. }()
  136. private lazy var deleteAccountCell: ActionCell = {
  137. let cell = ActionCell(frame: .zero)
  138. cell.actionTitle = String.localized("delete_account")
  139. cell.actionColor = UIColor.red
  140. cell.tag = tagDeleteAccountCell
  141. return cell
  142. }()
  143. lazy var advancedShowCell: UITableViewCell = {
  144. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  145. cell.textLabel?.text = String.localized("menu_advanced")
  146. cell.accessoryType = .disclosureIndicator
  147. cell.tag = tagAdvancedCell
  148. return cell
  149. }()
  150. lazy var imapServerCell: TextFieldCell = {
  151. let cell = TextFieldCell(
  152. descriptionID: "login_imap_server",
  153. placeholder: String.localized("automatic"),
  154. delegate: self)
  155. cell.tag = tagImapServerCell
  156. cell.setText(text: DcConfig.mailServer ?? nil)
  157. cell.textField.tag = tagTextFieldImapServer
  158. cell.textField.autocorrectionType = .no
  159. cell.textField.spellCheckingType = .no
  160. cell.textField.autocapitalizationType = .none
  161. return cell
  162. }()
  163. lazy var imapUserCell: TextFieldCell = {
  164. let cell = TextFieldCell(
  165. descriptionID: "login_imap_login",
  166. placeholder: String.localized("automatic"),
  167. delegate: self)
  168. cell.setText(text: DcConfig.mailUser ?? nil)
  169. cell.textField.tag = tagTextFieldImapLogin
  170. cell.tag = tagImapUserCell
  171. return cell
  172. }()
  173. func editablePort(port: String?) -> String {
  174. if let port = port {
  175. if Int(port) == 0 {
  176. return ""
  177. }
  178. return port
  179. } else {
  180. return ""
  181. }
  182. }
  183. lazy var imapPortCell: TextFieldCell = {
  184. let cell = TextFieldCell(
  185. descriptionID: "login_imap_port",
  186. placeholder: String.localized("automatic"),
  187. delegate: self)
  188. cell.tag = tagImapPortCell
  189. cell.setText(text: editablePort(port: DcConfig.mailPort))
  190. cell.textField.tag = tagImapPortCell
  191. cell.textField.keyboardType = .numberPad
  192. return cell
  193. }()
  194. lazy var imapSecurityCell: UITableViewCell = {
  195. let text = "\(DcConfig.getImapSecurity())"
  196. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  197. cell.textLabel?.text = String.localized("login_imap_security")
  198. cell.accessoryType = .disclosureIndicator
  199. cell.detailTextLabel?.text = "\(DcConfig.getImapSecurity())"
  200. cell.selectionStyle = .none
  201. cell.tag = tagImapSecurityCell
  202. return cell
  203. }()
  204. lazy var smtpServerCell: TextFieldCell = {
  205. let cell = TextFieldCell(
  206. descriptionID: "login_smtp_server",
  207. placeholder: String.localized("automatic"),
  208. delegate: self)
  209. cell.textField.tag = tagTextFieldSmtpServer
  210. cell.setText(text: DcConfig.sendServer ?? nil)
  211. cell.tag = tagSmtpServerCell
  212. cell.textField.autocorrectionType = .no
  213. cell.textField.spellCheckingType = .no
  214. cell.textField.autocapitalizationType = .none
  215. return cell
  216. }()
  217. lazy var smtpUserCell: TextFieldCell = {
  218. let cell = TextFieldCell(
  219. descriptionID: "login_smtp_login",
  220. placeholder: String.localized("automatic"),
  221. delegate: self)
  222. cell.textField.tag = tagTextFieldSmtpUser
  223. cell.setText(text: DcConfig.sendUser ?? nil)
  224. cell.tag = tagSmtpUserCell
  225. return cell
  226. }()
  227. lazy var smtpPortCell: TextFieldCell = {
  228. let cell = TextFieldCell(
  229. descriptionID: "login_smtp_port",
  230. placeholder: String.localized("automatic"),
  231. delegate: self)
  232. cell.tag = tagSmtpPortCell
  233. cell.setText(text: editablePort(port: DcConfig.sendPort))
  234. cell.textField.tag = tagSmtpPortCell
  235. cell.textField.keyboardType = .numberPad
  236. return cell
  237. }()
  238. lazy var smtpPasswordCell: TextFieldCell = {
  239. let cell = TextFieldCell(
  240. descriptionID: "login_smtp_password",
  241. placeholder: String.localized("automatic"),
  242. delegate: self)
  243. cell.textField.textContentType = UITextContentType.password
  244. cell.setText(text: DcConfig.sendPw ?? nil)
  245. cell.textField.isSecureTextEntry = true
  246. cell.textField.tag = tagTextFieldSmtpPassword
  247. cell.tag = tagSmtpPasswordCell
  248. return cell
  249. }()
  250. lazy var smtpSecurityCell: UITableViewCell = {
  251. let security = "\(DcConfig.getSmtpSecurity())"
  252. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  253. cell.textLabel?.text = String.localized("login_smtp_security")
  254. cell.detailTextLabel?.text = security
  255. cell.tag = tagSmtpSecurityCell
  256. cell.accessoryType = .disclosureIndicator
  257. cell.selectionStyle = .none
  258. return cell
  259. }()
  260. lazy var certCheckCell: UITableViewCell = {
  261. let certCheckType = CertificateCheckController.ValueConverter.convertHexToString(value: DcConfig.certificateChecks)
  262. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  263. cell.textLabel?.text = String.localized("login_certificate_checks")
  264. cell.detailTextLabel?.text = certCheckType
  265. cell.tag = tagCertCheckCell
  266. cell.accessoryType = .disclosureIndicator
  267. cell.selectionStyle = .none
  268. return cell
  269. }()
  270. lazy var inboxWatchCell: SwitchCell = {
  271. return SwitchCell(
  272. textLabel: String.localized("pref_watch_inbox_folder"),
  273. on: dcContext.getConfigBool("inbox_watch"),
  274. action: { cell in
  275. self.dcContext.setConfigBool("inbox_watch", cell.isOn)
  276. })
  277. }()
  278. lazy var sentboxWatchCell: SwitchCell = {
  279. return SwitchCell(
  280. textLabel: String.localized("pref_watch_sent_folder"),
  281. on: dcContext.getConfigBool("sentbox_watch"),
  282. action: { cell in
  283. self.dcContext.setConfigBool("sentbox_watch", cell.isOn)
  284. })
  285. }()
  286. lazy var mvboxWatchCell: SwitchCell = {
  287. return SwitchCell(
  288. textLabel: String.localized("pref_watch_mvbox_folder"),
  289. on: dcContext.getConfigBool("mvbox_watch"),
  290. action: { cell in
  291. self.dcContext.setConfigBool("mvbox_watch", cell.isOn)
  292. })
  293. }()
  294. lazy var sendCopyToSelfCell: SwitchCell = {
  295. return SwitchCell(
  296. textLabel: String.localized("pref_send_copy_to_self"),
  297. on: dcContext.getConfigBool("bcc_self"),
  298. action: { cell in
  299. self.dcContext.setConfigBool("bcc_self", cell.isOn)
  300. })
  301. }()
  302. lazy var mvboxMoveCell: SwitchCell = {
  303. return SwitchCell(
  304. textLabel: String.localized("pref_auto_folder_moves"),
  305. on: dcContext.getConfigBool("mvbox_move"),
  306. action: { cell in
  307. self.dcContext.setConfigBool("mvbox_move", cell.isOn)
  308. })
  309. }()
  310. private lazy var loginButton: UIBarButtonItem = {
  311. let button = UIBarButtonItem(
  312. title: String.localized("login_title"),
  313. style: .done,
  314. target: self,
  315. action: #selector(loginButtonPressed))
  316. button.isEnabled = dc_is_configured(mailboxPointer) == 0
  317. return button
  318. }()
  319. // MARK: - constructor
  320. init(dcContext: DcContext, editView: Bool) {
  321. self.editView = editView
  322. self.dcContext = dcContext
  323. self.sections.append(basicSection)
  324. self.sections.append(advancedSection)
  325. if editView {
  326. self.sections.append(folderSection)
  327. self.sections.append(dangerSection)
  328. } else {
  329. self.sections.append(restoreSection)
  330. }
  331. super.init(style: .grouped)
  332. hidesBottomBarWhenPushed = true
  333. }
  334. required init?(coder _: NSCoder) {
  335. fatalError("init(coder:) has not been implemented")
  336. }
  337. // MARK: -lifecycle
  338. override func viewDidLoad() {
  339. super.viewDidLoad()
  340. if editView {
  341. title = String.localized("pref_password_and_account_settings")
  342. } else {
  343. title = String.localized("login_header")
  344. }
  345. navigationItem.rightBarButtonItem = loginButton
  346. }
  347. override func viewWillAppear(_ animated: Bool) {
  348. super.viewWillAppear(animated)
  349. initSelectionCells()
  350. handleLoginButton()
  351. }
  352. override func viewDidAppear(_ animated: Bool) {
  353. super.viewDidAppear(animated)
  354. }
  355. override func viewWillDisappear(_ animated: Bool) {
  356. resignFirstResponderOnAllCells()
  357. }
  358. override func viewDidDisappear(_: Bool) {
  359. let nc = NotificationCenter.default
  360. if let backupProgressObserver = self.backupProgressObserver {
  361. nc.removeObserver(backupProgressObserver)
  362. }
  363. if let configureProgressObserver = self.configureProgressObserver {
  364. nc.removeObserver(configureProgressObserver)
  365. }
  366. if let oauth2Observer = self.oauth2Observer {
  367. nc.removeObserver(oauth2Observer)
  368. }
  369. }
  370. // MARK: - Table view data source
  371. override func numberOfSections(in _: UITableView) -> Int {
  372. return sections.count
  373. }
  374. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  375. if sections[section] == basicSection {
  376. return basicSectionCells.count
  377. } else if sections[section] == restoreSection {
  378. return restoreCells.count
  379. } else if sections[section] == folderSection {
  380. return folderCells.count
  381. } else if sections[section] == dangerSection {
  382. return dangerCells.count
  383. } else {
  384. return advancedSectionShowing ? advancedSectionCells.count : 1
  385. }
  386. }
  387. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  388. if sections[section] == basicSection && editView {
  389. return String.localized("login_header")
  390. } else if sections[section] == folderSection {
  391. return String.localized("pref_imap_folder_handling")
  392. } else if sections[section] == dangerSection {
  393. return String.localized("danger")
  394. } else {
  395. return nil
  396. }
  397. }
  398. override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
  399. if sections[section] == basicSection {
  400. if provider != nil && (provider?.status==DC_PROVIDER_STATUS_PREPARATION || provider?.status==DC_PROVIDER_STATUS_BROKEN) {
  401. return provider?.beforeLoginHint
  402. } else {
  403. return String.localized("login_no_servers_hint")
  404. }
  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, let status = provider?.status, !hint.isEmpty {
  507. showProviderInfo(with: hint, hintType: .preparation)
  508. } else {
  509. hideProviderInfo()
  510. }
  511. }
  512. func showProviderInfo(with hint: String, hintType: ProviderInfoStatus) {
  513. providerInfoCell.updateInfo(hint: hint, hintType: hintType)
  514. basicSectionCells = [emailCell, passwordCell, providerInfoCell]
  515. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  516. tableView.insertRows(at: [providerInfoCellIndexPath], with: .automatic)
  517. }
  518. func hideProviderInfo() {
  519. providerInfoCell.updateInfo(hint: nil, hintType: .none)
  520. basicSectionCells = [emailCell, passwordCell]
  521. let providerInfoCellIndexPath = IndexPath(row: 2, section: 0)
  522. tableView.deleteRows(at: [providerInfoCellIndexPath], with: .automatic)
  523. }
  524. private func login(emailAddress: String, password: String, skipAdvanceSetup: Bool = false) {
  525. addProgressHudLoginListener()
  526. resignFirstResponderOnAllCells() // this will resign focus from all textFieldCells so the keyboard wont pop up anymore
  527. DcConfig.addr = emailAddress
  528. DcConfig.mailPw = password
  529. if !skipAdvanceSetup {
  530. evaluateAdvancedSetup() // this will set MRConfig related to advanced fields
  531. }
  532. print("oAuth-Flag when loggin in: \(DcConfig.getAuthFlags())")
  533. dc_configure(mailboxPointer)
  534. showProgressHud(title: String.localized("login_header"))
  535. }
  536. @objc func closeButtonPressed() {
  537. dismiss(animated: true, completion: nil)
  538. }
  539. // returns true if needed
  540. private func showOAuthAlertIfNeeded(emailAddress: String, handleCancel: (() -> Void)?) -> Bool {
  541. return false
  542. // disable oauth2 for now as not yet supported by deltachat-rust.
  543. /*
  544. if skipOauth {
  545. // user has previously denied oAuth2-setup
  546. return false
  547. }
  548. guard let oAuth2UrlPointer = dc_get_oauth2_url(mailboxPointer, emailAddress, "chat.delta:/auth") else {
  549. //MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL)) -- do not reset, there may be different values
  550. return false
  551. }
  552. let oAuth2Url = String(cString: oAuth2UrlPointer)
  553. if let url = URL(string: oAuth2Url) {
  554. let title = "Continue with simplified setup"
  555. // swiftlint:disable all
  556. 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."
  557. let oAuthAlertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  558. let confirm = UIAlertAction(title: "Confirm", style: .default, handler: {
  559. [unowned self] _ in
  560. let nc = NotificationCenter.default
  561. self.oauth2Observer = nc.addObserver(self, selector: #selector(self.oauthLoginApproved), name: NSNotification.Name("oauthLoginApproved"), object: nil)
  562. self.launchOAuthBrowserWindow(url: url)
  563. })
  564. let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: {
  565. _ in
  566. MRConfig.setAuthFlags(flags: Int(DC_LP_AUTH_NORMAL))
  567. self.skipOauth = true
  568. handleCancel?()
  569. })
  570. oAuthAlertController.addAction(confirm)
  571. oAuthAlertController.addAction(cancel)
  572. present(oAuthAlertController, animated: true, completion: nil)
  573. return true
  574. } else {
  575. return false
  576. }
  577. */
  578. }
  579. @objc func oauthLoginApproved(notification: Notification) {
  580. guard let userInfo = notification.userInfo, let token = userInfo["token"] as? String, let emailAddress = emailCell.getText() else {
  581. return
  582. }
  583. passwordCell.setText(text: token)
  584. DcConfig.setAuthFlags(flags: Int(DC_LP_AUTH_OAUTH2))
  585. login(emailAddress: emailAddress, password: token, skipAdvanceSetup: true)
  586. }
  587. private func launchOAuthBrowserWindow(url: URL) {
  588. UIApplication.shared.open(url) // this opens safari as seperate app
  589. }
  590. private func addProgressHudLoginListener() {
  591. let nc = NotificationCenter.default
  592. configureProgressObserver = nc.addObserver(
  593. forName: dcNotificationConfigureProgress,
  594. object: nil,
  595. queue: nil
  596. ) {
  597. notification in
  598. if let ui = notification.userInfo {
  599. if ui["error"] as! Bool {
  600. self.updateProgressHud(error: ui["errorMessage"] as? String)
  601. } else if ui["done"] as! Bool {
  602. self.updateProgressHudSuccess()
  603. } else {
  604. self.updateProgressHudValue(value: ui["progress"] as? Int)
  605. }
  606. }
  607. }
  608. }
  609. private func addProgressHudBackupListener() {
  610. let nc = NotificationCenter.default
  611. backupProgressObserver = nc.addObserver(
  612. forName: dcNotificationImexProgress,
  613. object: nil,
  614. queue: nil
  615. ) {
  616. notification in
  617. if let ui = notification.userInfo {
  618. if ui["error"] as! Bool {
  619. self.updateProgressHud(error: ui["errorMessage"] as? String)
  620. } else if ui["done"] as! Bool {
  621. self.updateProgressHudSuccess()
  622. } else {
  623. self.updateProgressHudValue(value: ui["progress"] as? Int)
  624. }
  625. }
  626. }
  627. }
  628. private func evaluateAdvancedSetup() {
  629. for cell in advancedSectionCells {
  630. if let textFieldCell = cell as? TextFieldCell {
  631. switch textFieldCell.tag {
  632. case tagImapServerCell:
  633. DcConfig.mailServer = textFieldCell.getText() ?? nil
  634. case tagImapPortCell:
  635. DcConfig.mailPort = textFieldCell.getText() ?? nil
  636. case tagImapUserCell:
  637. DcConfig.mailUser = textFieldCell.getText() ?? nil
  638. case tagSmtpServerCell:
  639. DcConfig.sendServer = textFieldCell.getText() ?? nil
  640. case tagSmtpPortCell:
  641. DcConfig.sendPort = textFieldCell.getText() ?? nil
  642. case tagSmtpUserCell:
  643. DcConfig.sendUser = textFieldCell.getText() ?? nil
  644. case tagSmtpPasswordCell:
  645. DcConfig.sendPw = textFieldCell.getText() ?? nil
  646. default:
  647. logger.info("unknown identifier \(cell.tag)")
  648. }
  649. }
  650. }
  651. }
  652. private func restoreBackup() {
  653. logger.info("restoring backup")
  654. if DcConfig.configured {
  655. return
  656. }
  657. addProgressHudBackupListener()
  658. let documents = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
  659. if !documents.isEmpty {
  660. logger.info("looking for backup in: \(documents[0])")
  661. if let cString = dc_imex_has_backup(mailboxPointer, documents[0]) {
  662. let file = String(cString: cString)
  663. dc_str_unref(cString)
  664. logger.info("restoring backup: \(file)")
  665. showProgressHud(title: String.localized("import_backup_title"))
  666. dc_imex(mailboxPointer, DC_IMEX_IMPORT_BACKUP, file, nil)
  667. }
  668. else {
  669. let alert = UIAlertController(
  670. title: String.localized("import_backup_title"),
  671. message: String.localizedStringWithFormat(
  672. String.localized("import_backup_no_backup_found"),
  673. "iTunes / <Your Device> / File Sharing / Delta Chat"), // TOOD: maybe better use an iOS-specific string here
  674. preferredStyle: .alert)
  675. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .cancel))
  676. present(alert, animated: true)
  677. }
  678. }
  679. logger.error("no documents directory found")
  680. }
  681. private func emptyServer() {
  682. let alert = UIAlertController(title: String.localized("pref_empty_server_title"),
  683. message: String.localized("pref_empty_server_msg"), preferredStyle: .safeActionSheet)
  684. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_inbox"), style: .destructive, handler: { _ in
  685. self.emptyServer2ndConfirm(title: String.localized("pref_empty_server_inbox"), flags: Int(DC_EMPTY_INBOX))
  686. }))
  687. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_mvbox"), style: .destructive, handler: { _ in
  688. self.emptyServer2ndConfirm(title: String.localized("pref_empty_server_mvbox"), flags: Int(DC_EMPTY_MVBOX))
  689. }))
  690. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  691. present(alert, animated: true, completion: nil)
  692. }
  693. private func emptyServer2ndConfirm(title: String, flags: Int) {
  694. let alert = UIAlertController(
  695. title: title,
  696. message: String.localized("pref_empty_server_msg"), preferredStyle: .alert)
  697. alert.addAction(UIAlertAction(title: String.localized("pref_empty_server_do_button"), style: .destructive, handler: { _ in
  698. self.dcContext.emptyServer(flags: flags)
  699. }))
  700. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  701. present(alert, animated: true, completion: nil)
  702. }
  703. private func deleteAccount() {
  704. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
  705. return
  706. }
  707. let dbfile = appDelegate.dbfile()
  708. let dburl = URL(fileURLWithPath: dbfile, isDirectory: false)
  709. let alert = UIAlertController(
  710. title: String.localized("delete_account_ask"),
  711. message: nil,
  712. preferredStyle: .safeActionSheet)
  713. alert.addAction(UIAlertAction(title: String.localized("delete_account"), style: .destructive, handler: { _ in
  714. appDelegate.stop()
  715. appDelegate.close()
  716. do {
  717. try FileManager.default.removeItem(at: dburl)
  718. } catch {
  719. logger.error("failed to delete db: \(error)")
  720. }
  721. appDelegate.open()
  722. appDelegate.start()
  723. appDelegate.appCoordinator.presentLoginController()
  724. }))
  725. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  726. present(alert, animated: true, completion: nil)
  727. }
  728. private func handleLoginSuccess() {
  729. // used when login hud successfully went trough
  730. dismiss(animated: true, completion: nil)
  731. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  732. appDelegate.registerForPushNotifications()
  733. initSelectionCells();
  734. if let onLoginSuccess = self.coordinator?.onLoginSuccess {
  735. onLoginSuccess()
  736. } else {
  737. self.coordinator?.navigateBack()
  738. }
  739. }
  740. private func initSelectionCells() {
  741. smtpSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .SMTPSecurity, hex: DcConfig.getSmtpSecurity())
  742. imapSecurityCell.detailTextLabel?.text = SecurityConverter.convertHexToString(type: .IMAPSecurity, hex: DcConfig.getImapSecurity())
  743. certCheckCell.detailTextLabel?.text = CertificateCheckController.ValueConverter.convertHexToString(value: DcConfig.certificateChecks)
  744. }
  745. private func resignFirstResponderOnAllCells() {
  746. let _ = basicSectionCells.map({
  747. resignCell(cell: $0)
  748. })
  749. let _ = advancedSectionCells.map({
  750. resignCell(cell: $0)
  751. }
  752. )
  753. }
  754. private func handleLoginButton() {
  755. loginButton.isEnabled = !(emailCell.getText() ?? "").isEmpty && !(passwordCell.getText() ?? "").isEmpty
  756. }
  757. func resignCell(cell: UITableViewCell) {
  758. if let c = cell as? TextFieldCell {
  759. c.textField.resignFirstResponder()
  760. }
  761. }
  762. @objc private func textFieldDidChange() {
  763. handleLoginButton()
  764. }
  765. }
  766. extension AccountSetupController: UITextFieldDelegate {
  767. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  768. let currentTag = textField.tag
  769. if let nextField = tableView.viewWithTag(currentTag + 100) as? UITextField {
  770. if nextField.tag > tagTextFieldPassword, !advancedSectionShowing {
  771. // gets here when trying to activate a collapsed cell
  772. return false
  773. }
  774. nextField.becomeFirstResponder()
  775. return true
  776. } else {
  777. textField.resignFirstResponder()
  778. emailCell.textField.becomeFirstResponder()
  779. let indexPath = IndexPath(row: 0, section: 0)
  780. tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: true)
  781. return true
  782. }
  783. }
  784. func textFieldDidBeginEditing(_ textField: UITextField) {
  785. if textField.tag == tagTextFieldEmail {
  786. // this will re-enable possible oAuth2-login
  787. skipOauth = false
  788. }
  789. }
  790. func textFieldDidEndEditing(_ textField: UITextField) {
  791. if textField.tag == tagTextFieldEmail {
  792. let _ = showOAuthAlertIfNeeded(emailAddress: textField.text ?? "", handleCancel: {
  793. self.passwordCell.textField.becomeFirstResponder()
  794. })
  795. updateProviderInfo()
  796. }
  797. }
  798. }