AccountSetupController.swift 34 KB

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