AccountSetupController.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. import SafariServices
  2. import UIKit
  3. import DcCore
  4. class AccountSetupController: UITableViewController, ProgressAlertHandler {
  5. private let dcContext: DcContext
  6. private var skipOauth = false
  7. private var backupProgressObserver: NSObjectProtocol?
  8. var progressObserver: NSObjectProtocol?
  9. var onProgressSuccess: VoidFunction? // not needed here
  10. var onLoginSuccess: (() -> Void)?
  11. private var oauth2Observer: NSObjectProtocol?
  12. private let tagEmailCell = 0
  13. private let tagPasswordCell = 1
  14. private let tagAdvancedCell = 2
  15. private let tagImapServerCell = 3
  16. private let tagImapUserCell = 4
  17. private let tagImapPortCell = 5
  18. private let tagImapSecurityCell = 6
  19. private let tagSmtpServerCell = 7
  20. private let tagSmtpUserCell = 8
  21. private let tagSmtpPortCell = 9
  22. private let tagSmtpPasswordCell = 10
  23. private let tagSmtpSecurityCell = 11
  24. private let tagCertCheckCell = 12
  25. private let tagDeleteAccountCell = 13
  26. private let tagRestoreCell = 14
  27. private let tagViewLogCell = 15
  28. private let tagTextFieldEmail = 100
  29. private let tagTextFieldPassword = 200
  30. private let tagTextFieldImapLogin = 300
  31. private let tagTextFieldImapServer = 400
  32. private let tagTextFieldImapPort = 500
  33. private let tagTextFieldSmtpLogin = 600
  34. private let tagTextFieldSmtpPassword = 700
  35. private let tagTextFieldSmtpServer = 800
  36. private let tagTextFieldSmtpPort = 900
  37. // add cells to sections
  38. let basicSection = 100
  39. let advancedSection = 200
  40. let restoreSection = 300
  41. let folderSection = 400
  42. let dangerSection = 500
  43. private var sections = [Int]()
  44. private lazy var basicSectionCells: [UITableViewCell] = [emailCell, passwordCell]
  45. private lazy var restoreCells: [UITableViewCell] = [restoreCell]
  46. private lazy var advancedSectionCells: [UITableViewCell] = [
  47. advancedShowCell,
  48. imapSecurityCell,
  49. imapUserCell,
  50. imapServerCell,
  51. imapPortCell,
  52. smtpSecurityCell,
  53. smtpUserCell,
  54. smtpPasswordCell,
  55. smtpServerCell,
  56. smtpPortCell,
  57. certCheckCell,
  58. viewLogCell
  59. ]
  60. private lazy var folderCells: [UITableViewCell] = [inboxWatchCell, sentboxWatchCell, mvboxWatchCell, sendCopyToSelfCell, mvboxMoveCell]
  61. private lazy var dangerCells: [UITableViewCell] = [deleteAccountCell]
  62. private let editView: Bool
  63. private var advancedSectionShowing: Bool = false
  64. private var providerInfoShowing: Bool = false
  65. private var provider: DcProvider?
  66. // MARK: - the progress dialog
  67. weak var progressAlert: UIAlertController?
  68. // MARK: - cells
  69. private lazy var emailCell: TextFieldCell = {
  70. let cell = TextFieldCell.makeEmailCell(delegate: self)
  71. cell.tag = tagEmailCell
  72. cell.textField.addTarget(self, action: #selector(emailCellEdited), for: .editingChanged)
  73. cell.textField.tag = tagTextFieldEmail // will be used to eventually show oAuth-Dialogue when pressing return key
  74. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  75. cell.textField.returnKeyType = .next
  76. return cell
  77. }()
  78. private lazy var passwordCell: TextFieldCell = {
  79. let cell = TextFieldCell.makePasswordCell(delegate: self)
  80. cell.tag = tagPasswordCell
  81. cell.textField.tag = tagTextFieldPassword // will be used to eventually show oAuth-Dialogue when selecting
  82. cell.textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
  83. cell.textField.returnKeyType = advancedSectionShowing ? .next : .default
  84. return cell
  85. }()
  86. private lazy var providerInfoCell: ProviderInfoCell = {
  87. let cell = ProviderInfoCell()
  88. cell.onInfoButtonPressed = {
  89. [weak self] in
  90. self?.handleProviderInfoButton()
  91. }
  92. return cell
  93. }()
  94. private lazy var restoreCell: UITableViewCell = {
  95. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  96. cell.textLabel?.text = String.localized("import_backup_title")
  97. cell.accessoryType = .disclosureIndicator
  98. cell.tag = tagRestoreCell
  99. return cell
  100. }()
  101. private lazy var deleteAccountCell: ActionCell = {
  102. let cell = ActionCell(frame: .zero)
  103. cell.actionTitle = String.localized("delete_account")
  104. cell.actionColor = UIColor.red
  105. cell.tag = tagDeleteAccountCell
  106. return cell
  107. }()
  108. lazy var advancedShowCell: UITableViewCell = {
  109. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  110. cell.textLabel?.text = String.localized("menu_advanced")
  111. cell.accessoryType = .disclosureIndicator
  112. cell.tag = tagAdvancedCell
  113. return cell
  114. }()
  115. lazy var imapServerCell: TextFieldCell = {
  116. let cell = TextFieldCell(
  117. descriptionID: "login_imap_server",
  118. placeholder: String.localized("automatic"),
  119. delegate: self)
  120. cell.tag = tagImapServerCell
  121. cell.setText(text: dcContext.mailServer ?? nil)
  122. cell.textField.tag = tagTextFieldImapServer
  123. cell.textField.autocorrectionType = .no
  124. cell.textField.spellCheckingType = .no
  125. cell.textField.autocapitalizationType = .none
  126. cell.textField.returnKeyType = .next
  127. return cell
  128. }()
  129. lazy var imapUserCell: TextFieldCell = {
  130. let cell = TextFieldCell(
  131. descriptionID: "login_imap_login",
  132. placeholder: String.localized("automatic"),
  133. delegate: self)
  134. cell.setText(text: dcContext.mailUser ?? nil)
  135. cell.textField.tag = tagTextFieldImapLogin
  136. cell.tag = tagImapUserCell
  137. cell.textField.autocorrectionType = .no
  138. cell.textField.spellCheckingType = .no
  139. cell.textField.autocapitalizationType = .none
  140. cell.textField.returnKeyType = .next
  141. return cell
  142. }()
  143. func editablePort(port: String?) -> String {
  144. if let port = port {
  145. if Int(port) == 0 {
  146. return ""
  147. }
  148. return port
  149. } else {
  150. return ""
  151. }
  152. }
  153. lazy var imapPortCell: TextFieldCell = {
  154. let cell = TextFieldCell(
  155. descriptionID: "login_imap_port",
  156. placeholder: String.localized("automatic"),
  157. delegate: self)
  158. cell.tag = tagImapPortCell
  159. cell.setText(text: editablePort(port: dcContext.mailPort))
  160. cell.textField.tag = tagTextFieldImapPort
  161. cell.textField.keyboardType = .numberPad
  162. return cell
  163. }()
  164. lazy var imapSecurityCell: UITableViewCell = {
  165. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  166. cell.textLabel?.text = String.localized("login_imap_security")
  167. cell.accessoryType = .disclosureIndicator
  168. cell.selectionStyle = .none
  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. cell.selectionStyle = .none
  230. return cell
  231. }()
  232. lazy var certCheckCell: UITableViewCell = {
  233. let certCheckType = CertificateCheckController.ValueConverter.convertHexToString(value: dcContext.certificateChecks)
  234. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  235. cell.textLabel?.text = String.localized("login_certificate_checks")
  236. cell.detailTextLabel?.text = certCheckType
  237. cell.tag = tagCertCheckCell
  238. cell.accessoryType = .disclosureIndicator
  239. cell.selectionStyle = .none
  240. return cell
  241. }()
  242. lazy var viewLogCell: UITableViewCell = {
  243. let cell = UITableViewCell(style: .value1, reuseIdentifier: nil)
  244. cell.textLabel?.text = String.localized("pref_view_log")
  245. cell.tag = tagViewLogCell
  246. cell.accessoryType = .disclosureIndicator
  247. return cell
  248. }()
  249. lazy var inboxWatchCell: SwitchCell = {
  250. return SwitchCell(
  251. textLabel: String.localized("pref_watch_inbox_folder"),
  252. on: dcContext.getConfigBool("inbox_watch"),
  253. action: { cell in
  254. self.dcContext.stopIo()
  255. self.dcContext.setConfigBool("inbox_watch", cell.isOn)
  256. self.dcContext.maybeStartIo()
  257. })
  258. }()
  259. lazy var sentboxWatchCell: SwitchCell = {
  260. return SwitchCell(
  261. textLabel: String.localized("pref_watch_sent_folder"),
  262. on: dcContext.getConfigBool("sentbox_watch"),
  263. action: { cell in
  264. self.dcContext.stopIo()
  265. self.dcContext.setConfigBool("sentbox_watch", cell.isOn)
  266. self.dcContext.maybeStartIo()
  267. })
  268. }()
  269. lazy var mvboxWatchCell: SwitchCell = {
  270. return SwitchCell(
  271. textLabel: String.localized("pref_watch_mvbox_folder"),
  272. on: dcContext.getConfigBool("mvbox_watch"),
  273. action: { cell in
  274. self.dcContext.stopIo()
  275. self.dcContext.setConfigBool("mvbox_watch", cell.isOn)
  276. self.dcContext.maybeStartIo()
  277. })
  278. }()
  279. lazy var sendCopyToSelfCell: SwitchCell = {
  280. return SwitchCell(
  281. textLabel: String.localized("pref_send_copy_to_self"),
  282. on: dcContext.getConfigBool("bcc_self"),
  283. action: { cell in
  284. self.dcContext.setConfigBool("bcc_self", cell.isOn)
  285. })
  286. }()
  287. lazy var mvboxMoveCell: SwitchCell = {
  288. return SwitchCell(
  289. textLabel: String.localized("pref_auto_folder_moves"),
  290. on: dcContext.getConfigBool("mvbox_move"),
  291. action: { cell in
  292. self.dcContext.setConfigBool("mvbox_move", cell.isOn)
  293. })
  294. }()
  295. private lazy var loginButton: UIBarButtonItem = {
  296. let button = UIBarButtonItem(
  297. title: String.localized("login_title"),
  298. style: .done,
  299. target: self,
  300. action: #selector(loginButtonPressed))
  301. button.isEnabled = !dcContext.isConfigured()
  302. return button
  303. }()
  304. // MARK: - constructor
  305. init(dcContext: DcContext, editView: Bool) {
  306. self.editView = editView
  307. self.dcContext = dcContext
  308. self.sections.append(basicSection)
  309. self.sections.append(advancedSection)
  310. if editView {
  311. self.sections.append(folderSection)
  312. self.sections.append(dangerSection)
  313. } else {
  314. self.sections.append(restoreSection)
  315. }
  316. super.init(style: .grouped)
  317. hidesBottomBarWhenPushed = true
  318. }
  319. required init?(coder _: NSCoder) {
  320. fatalError("init(coder:) has not been implemented")
  321. }
  322. // MARK: - lifecycle
  323. override func viewDidLoad() {
  324. super.viewDidLoad()
  325. if editView {
  326. title = String.localized("pref_password_and_account_settings")
  327. } else {
  328. title = String.localized("login_header")
  329. }
  330. navigationItem.rightBarButtonItem = loginButton
  331. emailCell.setText(text: dcContext.addr ?? nil)
  332. passwordCell.setText(text: dcContext.mailPw ?? nil)
  333. }
  334. override func viewWillAppear(_ animated: Bool) {
  335. super.viewWillAppear(animated)
  336. initSelectionCells()
  337. handleLoginButton()
  338. }
  339. override func viewDidAppear(_ animated: Bool) {
  340. super.viewDidAppear(animated)
  341. }
  342. override func viewWillDisappear(_ animated: Bool) {
  343. resignFirstResponderOnAllCells()
  344. progressObserver = nil
  345. }
  346. override func viewDidDisappear(_: Bool) {
  347. let nc = NotificationCenter.default
  348. if let backupProgressObserver = self.backupProgressObserver {
  349. nc.removeObserver(backupProgressObserver)
  350. }
  351. if let configureProgressObserver = self.progressObserver {
  352. nc.removeObserver(configureProgressObserver)
  353. }
  354. if let oauth2Observer = self.oauth2Observer {
  355. nc.removeObserver(oauth2Observer)
  356. }
  357. }
  358. // MARK: - Table view data source
  359. override func numberOfSections(in _: UITableView) -> Int {
  360. return sections.count
  361. }
  362. override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
  363. if sections[section] == basicSection {
  364. return basicSectionCells.count
  365. } else if sections[section] == restoreSection {
  366. return restoreCells.count
  367. } else if sections[section] == folderSection {
  368. return folderCells.count
  369. } else if sections[section] == dangerSection {
  370. return dangerCells.count
  371. } else {
  372. return advancedSectionShowing ? advancedSectionCells.count : 1
  373. }
  374. }
  375. override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
  376. if sections[section] == basicSection && editView {
  377. return String.localized("login_header")
  378. } else if sections[section] == folderSection {
  379. return String.localized("pref_imap_folder_handling")
  380. } else if sections[section] == dangerSection {
  381. return String.localized("danger")
  382. } else {
  383. return nil
  384. }
  385. }
  386. override func tableView(_: UITableView, titleForFooterInSection section: Int) -> String? {
  387. if sections[section] == basicSection {
  388. return String.localized("login_no_servers_hint")
  389. } else if sections[section] == advancedSection {
  390. if advancedSectionShowing && dcContext.isConfigured() {
  391. var info = String.localized("used_settings") + "\n"
  392. info += "IMAP "
  393. info += SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("mail_security"))) + " "
  394. info += (dcContext.getConfig("configured_mail_user") ?? "unset") + ":***@"
  395. info += (dcContext.getConfig("configured_mail_server") ?? "unset") + ":"
  396. info += (dcContext.getConfig("configured_mail_port") ?? "unset") + "\n"
  397. info += "SMTP "
  398. info += SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("send_security"))) + " "
  399. info += (dcContext.getConfig("configured_send_user") ?? "unset") + ":***@"
  400. info += (dcContext.getConfig("configured_send_server") ?? "unset") + ":"
  401. info += (dcContext.getConfig("configured_send_port") ?? "unset") + "\n\n"
  402. info += String.localized("login_subheader")
  403. return info
  404. } else {
  405. return String.localized("login_subheader")
  406. }
  407. } else if sections[section] == folderSection {
  408. return String.localized("pref_auto_folder_moves_explain")
  409. } else {
  410. return nil
  411. }
  412. }
  413. override func tableView(_: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  414. let section = indexPath.section
  415. let row = indexPath.row
  416. if sections[section] == basicSection {
  417. return basicSectionCells[row]
  418. } else if sections[section] == restoreSection {
  419. return restoreCells[row]
  420. } else if sections[section] == folderSection {
  421. return folderCells[row]
  422. } else if sections[section] == dangerSection {
  423. return dangerCells[row]
  424. } else {
  425. return advancedSectionCells[row]
  426. }
  427. }
  428. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  429. guard let tappedCell = tableView.cellForRow(at: indexPath) else { return }
  430. // handle tap on password -> show oAuthDialogue
  431. switch tappedCell.tag {
  432. case tagPasswordCell:
  433. if let textFieldCell = tappedCell as? TextFieldCell {
  434. if let emailAdress = textFieldCell.getText() {
  435. _ = showOAuthAlertIfNeeded(emailAddress: emailAdress, handleCancel: nil)
  436. }
  437. }
  438. case tagRestoreCell:
  439. tableView.reloadData() // otherwise the disclosureIndicator may stay selected
  440. restoreBackup()
  441. case tagDeleteAccountCell:
  442. deleteAccount()
  443. case tagAdvancedCell:
  444. toggleAdvancedSection()
  445. case tagImapSecurityCell:
  446. showImapSecurityOptions()
  447. case tagSmtpSecurityCell:
  448. showSmptpSecurityOptions()
  449. case tagCertCheckCell:
  450. showCertCheckOptions()
  451. case tagViewLogCell:
  452. tableView.deselectRow(at: indexPath, animated: true)
  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. dcContext.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.dcContext.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=\(DcContext.shared.lastWarningString) (progress=\(DcContext.shared.maxConfigureProgress))"
  599. }
  600. self.updateProgressAlert(error: errorMessage)
  601. } else if ui["done"] as! Bool {
  602. self.dcContext.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: { _ in
  689. self.dcContext.stopIo()
  690. appDelegate.closeDatabase()
  691. DatabaseHelper().clearAccountData()
  692. appDelegate.openDatabase()
  693. appDelegate.installEventHandler()
  694. self.dcContext.maybeStartIo()
  695. appDelegate.appCoordinator.presentWelcomeController()
  696. }))
  697. alert.addAction(UIAlertAction(title: String.localized("cancel"), style: .cancel))
  698. present(alert, animated: true, completion: nil)
  699. }
  700. private func handleLoginSuccess() {
  701. // used when login hud successfully went through
  702. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  703. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  704. appDelegate.registerForNotifications()
  705. }
  706. initSelectionCells();
  707. if let onLoginSuccess = self.onLoginSuccess {
  708. onLoginSuccess()
  709. } else {
  710. navigationController?.popViewController(animated: true)
  711. }
  712. }
  713. private func initSelectionCells() {
  714. imapSecurityCell.detailTextLabel?.text = SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("mail_security")))
  715. smtpSecurityCell.detailTextLabel?.text = SecurityConverter.getSocketName(value: Int32(dcContext.getConfigInt("send_security")))
  716. certCheckCell.detailTextLabel?.text = CertificateCheckController.ValueConverter.convertHexToString(value: dcContext.certificateChecks)
  717. }
  718. private func resignFirstResponderOnAllCells() {
  719. let _ = basicSectionCells.map({
  720. resignCell(cell: $0)
  721. })
  722. let _ = advancedSectionCells.map({
  723. resignCell(cell: $0)
  724. })
  725. }
  726. private func handleLoginButton() {
  727. loginButton.isEnabled = !(emailCell.getText() ?? "").isEmpty && !(passwordCell.getText() ?? "").isEmpty
  728. }
  729. private func handleProviderInfoButton() {
  730. guard let provider = provider else {
  731. return
  732. }
  733. openProviderInfo(provider: provider)
  734. }
  735. func resignCell(cell: UITableViewCell) {
  736. if let c = cell as? TextFieldCell {
  737. c.textField.resignFirstResponder()
  738. }
  739. }
  740. @objc private func textFieldDidChange() {
  741. handleLoginButton()
  742. }
  743. @objc private func emailCellEdited() {
  744. if providerInfoShowing {
  745. updateProviderInfo()
  746. }
  747. }
  748. // MARK: - coordinator
  749. private func showCertCheckOptions() {
  750. let certificateCheckController = CertificateCheckController(dcContext: dcContext, sectionTitle: String.localized("login_certificate_checks"))
  751. navigationController?.pushViewController(certificateCheckController, animated: true)
  752. }
  753. private func showImapSecurityOptions() {
  754. let securitySettingsController = SecuritySettingsController(dcContext: dcContext, title: String.localized("login_imap_security"),
  755. type: SecurityType.IMAPSecurity)
  756. navigationController?.pushViewController(securitySettingsController, animated: true)
  757. }
  758. private func showSmptpSecurityOptions() {
  759. let securitySettingsController = SecuritySettingsController(dcContext: dcContext,
  760. title: String.localized("login_imap_security"),
  761. type: SecurityType.SMTPSecurity)
  762. navigationController?.pushViewController(securitySettingsController, animated: true)
  763. }
  764. private func openProviderInfo(provider: DcProvider) {
  765. guard let url = URL(string: provider.getOverviewPage) else { return }
  766. UIApplication.shared.open(url)
  767. }
  768. }
  769. // MARK: - UITextFieldDelegate
  770. extension AccountSetupController: UITextFieldDelegate {
  771. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  772. let currentTag = textField.tag
  773. if let nextField = tableView.viewWithTag(currentTag + 100) as? UITextField {
  774. nextField.becomeFirstResponder()
  775. return true
  776. } else {
  777. textField.resignFirstResponder()
  778. let indexPath = IndexPath(row: 0, section: 0)
  779. tableView.scrollToRow(at: indexPath, at: UITableView.ScrollPosition.top, animated: true)
  780. return true
  781. }
  782. }
  783. func textFieldDidBeginEditing(_ textField: UITextField) {
  784. if textField.tag == tagTextFieldEmail {
  785. // this will re-enable possible oAuth2-login
  786. skipOauth = false
  787. }
  788. }
  789. func textFieldDidEndEditing(_ textField: UITextField) {
  790. if textField.tag == tagTextFieldEmail {
  791. let _ = showOAuthAlertIfNeeded(emailAddress: textField.text ?? "", handleCancel: {
  792. self.passwordCell.textField.becomeFirstResponder()
  793. })
  794. updateProviderInfo()
  795. }
  796. }
  797. }