AccountSetupController.swift 35 KB

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