AccountSetupController.swift 35 KB

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