WelcomeViewController.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import UIKit
  2. import DcCore
  3. class WelcomeViewController: UIViewController, ProgressAlertHandler {
  4. private var dcContext: DcContext
  5. private let dcAccounts: DcAccounts
  6. private let accountCode: String?
  7. private var backupProgressObserver: NSObjectProtocol?
  8. var progressObserver: NSObjectProtocol?
  9. var onProgressSuccess: VoidFunction?
  10. private var securityScopedResource: NSURL?
  11. private lazy var scrollView: UIScrollView = {
  12. let scrollView = UIScrollView()
  13. scrollView.showsVerticalScrollIndicator = false
  14. return scrollView
  15. }()
  16. private lazy var welcomeView: WelcomeContentView = {
  17. let view = WelcomeContentView()
  18. view.onLogin = { [weak self] in
  19. guard let self = self else { return }
  20. self.showAccountSetupController()
  21. }
  22. view.onScanQRCode = { [weak self] in
  23. guard let self = self else { return }
  24. let qrReader = QrCodeReaderController()
  25. qrReader.delegate = self
  26. self.qrCodeReader = qrReader
  27. self.navigationController?.pushViewController(qrReader, animated: true)
  28. }
  29. view.onImportBackup = { [weak self] in
  30. guard let self = self else { return }
  31. self.restoreBackup()
  32. }
  33. view.translatesAutoresizingMaskIntoConstraints = false
  34. return view
  35. }()
  36. private lazy var canCancel: Bool = {
  37. // "cancel" removes selected unconfigured account, so there needs to be at least one other account
  38. return dcAccounts.getAll().count >= 2
  39. }()
  40. private lazy var cancelButton: UIBarButtonItem = {
  41. return UIBarButtonItem(title: String.localized("cancel"), style: .plain, target: self, action: #selector(cancelAccountCreation))
  42. }()
  43. private lazy var moreButton: UIBarButtonItem = {
  44. let image: UIImage?
  45. if #available(iOS 13.0, *) {
  46. image = UIImage(systemName: "ellipsis.circle")
  47. } else {
  48. image = UIImage(named: "ic_more")
  49. }
  50. return UIBarButtonItem(image: image,
  51. style: .plain,
  52. target: self,
  53. action: #selector(moreButtonPressed))
  54. }()
  55. private lazy var mediaPicker: MediaPicker? = {
  56. let mediaPicker = MediaPicker(navigationController: navigationController)
  57. mediaPicker.delegate = self
  58. return mediaPicker
  59. }()
  60. private var qrCodeReader: QrCodeReaderController?
  61. weak var progressAlert: UIAlertController?
  62. init(dcAccounts: DcAccounts, accountCode: String? = nil) {
  63. self.dcAccounts = dcAccounts
  64. self.dcContext = dcAccounts.getSelected()
  65. self.accountCode = accountCode
  66. super.init(nibName: nil, bundle: nil)
  67. self.navigationItem.title = String.localized(canCancel ? "add_account" : "welcome_desktop")
  68. onProgressSuccess = { [weak self] in
  69. guard let self = self else { return }
  70. let profileInfoController = ProfileInfoViewController(context: self.dcContext)
  71. profileInfoController.onClose = {
  72. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  73. appDelegate.reloadDcContext()
  74. }
  75. }
  76. self.navigationController?.setViewControllers([profileInfoController], animated: true)
  77. }
  78. }
  79. required init?(coder: NSCoder) {
  80. fatalError("init(coder:) has not been implemented")
  81. }
  82. // MARK: - lifecycle
  83. override func viewDidLoad() {
  84. super.viewDidLoad()
  85. setupSubviews()
  86. if canCancel {
  87. navigationItem.leftBarButtonItem = cancelButton
  88. }
  89. navigationItem.rightBarButtonItem = moreButton
  90. if let accountCode = accountCode {
  91. handleQrCode(accountCode)
  92. }
  93. }
  94. override func viewDidLayoutSubviews() {
  95. super.viewDidLayoutSubviews()
  96. welcomeView.minContainerHeight = view.frame.height - view.safeAreaInsets.top
  97. }
  98. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  99. super.viewWillTransition(to: size, with: coordinator)
  100. welcomeView.minContainerHeight = size.height - view.safeAreaInsets.top
  101. }
  102. override func viewDidDisappear(_ animated: Bool) {
  103. let nc = NotificationCenter.default
  104. if let observer = self.progressObserver {
  105. nc.removeObserver(observer)
  106. self.progressObserver = nil
  107. }
  108. if let backupProgressObserver = self.backupProgressObserver {
  109. nc.removeObserver(backupProgressObserver)
  110. }
  111. }
  112. // MARK: - setup
  113. private func setupSubviews() {
  114. view.addSubview(scrollView)
  115. scrollView.translatesAutoresizingMaskIntoConstraints = false
  116. scrollView.addSubview(welcomeView)
  117. let frameGuide = scrollView.frameLayoutGuide
  118. let contentGuide = scrollView.contentLayoutGuide
  119. frameGuide.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0).isActive = true
  120. frameGuide.topAnchor.constraint(equalTo: view.topAnchor, constant: 0).isActive = true
  121. frameGuide.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0).isActive = true
  122. frameGuide.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0).isActive = true
  123. contentGuide.leadingAnchor.constraint(equalTo: welcomeView.leadingAnchor).isActive = true
  124. contentGuide.topAnchor.constraint(equalTo: welcomeView.topAnchor).isActive = true
  125. contentGuide.trailingAnchor.constraint(equalTo: welcomeView.trailingAnchor).isActive = true
  126. contentGuide.bottomAnchor.constraint(equalTo: welcomeView.bottomAnchor).isActive = true
  127. // this enables vertical scrolling
  128. frameGuide.widthAnchor.constraint(equalTo: contentGuide.widthAnchor).isActive = true
  129. }
  130. // MARK: - actions
  131. private func createAccountFromQRCode(qrCode: String) {
  132. if dcAccounts.getSelected().isConfigured() {
  133. UserDefaults.standard.setValue(dcAccounts.getSelected().id, forKey: Constants.Keys.lastSelectedAccountKey)
  134. // FIXME: what do we want to do with QR-Code created accounts? For now: adding an unencrypted account
  135. // ensure we're configuring on an empty new account
  136. _ = dcAccounts.add()
  137. }
  138. let accountId = dcAccounts.getSelected().id
  139. if accountId != 0 {
  140. dcContext = dcAccounts.get(id: accountId)
  141. addProgressAlertListener(dcAccounts: self.dcAccounts,
  142. progressName: dcNotificationConfigureProgress,
  143. onSuccess: self.handleLoginSuccess)
  144. showProgressAlert(title: String.localized("login_header"), dcContext: self.dcContext)
  145. DispatchQueue.global().async { [weak self] in
  146. guard let self = self else { return }
  147. let success = self.dcContext.setConfigFromQR(qrCode: qrCode)
  148. DispatchQueue.main.async {
  149. if success {
  150. self.dcAccounts.stopIo()
  151. self.dcContext.configure()
  152. } else {
  153. self.updateProgressAlert(error: self.dcContext.lastErrorString,
  154. completion: self.accountCode != nil ? self.cancelAccountCreation : nil)
  155. }
  156. }
  157. }
  158. }
  159. }
  160. private func handleLoginSuccess() {
  161. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  162. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  163. appDelegate.registerForNotifications()
  164. }
  165. onProgressSuccess?()
  166. }
  167. private func handleBackupRestoreSuccess() {
  168. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  169. if !UserDefaults.standard.bool(forKey: "notifications_disabled") {
  170. appDelegate.registerForNotifications()
  171. }
  172. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  173. appDelegate.reloadDcContext()
  174. }
  175. }
  176. @objc private func moreButtonPressed() {
  177. let alert = UIAlertController(title: "Encrypted Account (experimental)",
  178. message: "Do you want to encrypt your account database? This cannot be undone.",
  179. preferredStyle: .safeActionSheet)
  180. let encryptedAccountAction = UIAlertAction(title: "Create encrypted account", style: .default, handler: switchToEncrypted(_:))
  181. let cancelAction = UIAlertAction(title: String.localized("cancel"), style: .destructive, handler: nil)
  182. alert.addAction(encryptedAccountAction)
  183. alert.addAction(cancelAction)
  184. self.present(alert, animated: true, completion: nil)
  185. }
  186. private func switchToEncrypted(_ action: UIAlertAction) {
  187. let lastContextId = dcAccounts.getSelected().id
  188. let newContextId = dcAccounts.addClosedAccount()
  189. _ = dcAccounts.remove(id: lastContextId)
  190. KeychainManager.deleteAccountSecret(id: lastContextId)
  191. _ = dcAccounts.select(id: newContextId)
  192. dcContext = dcAccounts.getSelected()
  193. do {
  194. let secret = try KeychainManager.getAccountSecret(accountID: dcContext.id)
  195. guard dcContext.open(passphrase: secret) else {
  196. logger.error("Failed to open account database for account \(dcContext.id)")
  197. return
  198. }
  199. self.navigationItem.title = "Add encrypted account"
  200. } catch KeychainError.unhandledError(let message, let status) {
  201. logger.error("Keychain error. Failed to create encrypted account. \(message). Error status: \(status)")
  202. } catch {
  203. logger.error("Keychain error. Failed to create encrypted account.")
  204. }
  205. }
  206. private func showAccountSetupController() {
  207. let accountSetupController = AccountSetupController(dcAccounts: self.dcAccounts, editView: false)
  208. accountSetupController.onLoginSuccess = {
  209. if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
  210. appDelegate.reloadDcContext()
  211. }
  212. }
  213. self.navigationController?.pushViewController(accountSetupController, animated: true)
  214. }
  215. @objc private func cancelAccountCreation() {
  216. guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
  217. // take a bit care on account removal:
  218. // remove only openend and unconfigured and make sure, there is another account
  219. // (normally, both checks are not needed, however, some resilience wrt future program-flow-changes seems to be reasonable here)
  220. let selectedAccount = dcAccounts.getSelected()
  221. if selectedAccount.isOpen() && !selectedAccount.isConfigured() {
  222. _ = dcAccounts.remove(id: selectedAccount.id)
  223. KeychainManager.deleteAccountSecret(id: selectedAccount.id)
  224. if self.dcAccounts.getAll().isEmpty {
  225. _ = self.dcAccounts.add()
  226. }
  227. }
  228. let lastSelectedAccountId = UserDefaults.standard.integer(forKey: Constants.Keys.lastSelectedAccountKey)
  229. if lastSelectedAccountId != 0 {
  230. _ = dcAccounts.select(id: lastSelectedAccountId)
  231. }
  232. appDelegate.reloadDcContext()
  233. }
  234. private func restoreBackup() {
  235. logger.info("restoring backup")
  236. if dcContext.isConfigured() {
  237. return
  238. }
  239. addProgressHudBackupListener()
  240. if let documentsDirectory = ensureDcDocFolderExists(),
  241. let filePath = dcContext.imexHasBackup(filePath: documentsDirectory.relativePath) {
  242. importBackup(at: filePath)
  243. } else {
  244. mediaPicker?.showDocumentLibrary(selectFolder: true)
  245. }
  246. }
  247. private func importBackup(at filepath: String) {
  248. logger.info("restoring backup: \(filepath)")
  249. showProgressAlert(title: String.localized("import_backup_title"), dcContext: dcContext)
  250. dcAccounts.stopIo()
  251. dcContext.imex(what: DC_IMEX_IMPORT_BACKUP, directory: filepath)
  252. }
  253. private func ensureDcDocFolderExists() -> URL? {
  254. let fileManager = FileManager.default
  255. guard let documentsDirectory = try? fileManager.url(for: .documentDirectory,
  256. in: .userDomainMask,
  257. appropriateFor: nil,
  258. create: true) else { return nil }
  259. let emptyHiddenFileURL = documentsDirectory.appendingPathComponent(".Move your backup here")
  260. if !fileManager.fileExists(atPath: emptyHiddenFileURL.relativePath) {
  261. fileManager.createFile(atPath: emptyHiddenFileURL.relativePath, contents: nil)
  262. }
  263. return documentsDirectory
  264. }
  265. private func addProgressHudBackupListener() {
  266. let nc = NotificationCenter.default
  267. backupProgressObserver = nc.addObserver(
  268. forName: dcNotificationImexProgress,
  269. object: nil,
  270. queue: nil
  271. ) { notification in
  272. if let ui = notification.userInfo {
  273. if let error = ui["error"] as? Bool, error {
  274. self.dcAccounts.startIo()
  275. self.updateProgressAlert(error: ui["errorMessage"] as? String)
  276. self.securityScopedResource?.stopAccessingSecurityScopedResource()
  277. self.securityScopedResource = nil
  278. } else if let done = ui["done"] as? Bool, done {
  279. self.dcAccounts.startIo()
  280. self.updateProgressAlertSuccess(completion: self.handleBackupRestoreSuccess)
  281. self.securityScopedResource?.stopAccessingSecurityScopedResource()
  282. self.securityScopedResource = nil
  283. } else {
  284. self.updateProgressAlertValue(value: ui["progress"] as? Int)
  285. }
  286. }
  287. }
  288. }
  289. }
  290. extension WelcomeViewController: QrCodeReaderDelegate {
  291. func handleQrCode(_ code: String) {
  292. let lot = dcContext.checkQR(qrCode: code)
  293. if let domain = lot.text1, lot.state == DC_QR_ACCOUNT {
  294. confirmAccountCreationAlert(accountDomain: domain, qrCode: code)
  295. } else {
  296. qrErrorAlert()
  297. }
  298. }
  299. private func confirmAccountCreationAlert(accountDomain domain: String, qrCode: String) {
  300. let title = String.localizedStringWithFormat(
  301. String.localized(dcAccounts.getAll().count > 1 ? "qraccount_ask_create_and_login_another" : "qraccount_ask_create_and_login"),
  302. domain)
  303. let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
  304. let okAction = UIAlertAction(
  305. title: String.localized("ok"),
  306. style: .default,
  307. handler: { [weak self] _ in
  308. guard let self = self else { return }
  309. self.dismissQRReader()
  310. self.createAccountFromQRCode(qrCode: qrCode)
  311. }
  312. )
  313. let qrCancelAction = UIAlertAction(
  314. title: String.localized("cancel"),
  315. style: .cancel,
  316. handler: { [weak self] _ in
  317. guard let self = self else { return }
  318. self.dismissQRReader()
  319. // if an injected accountCode exists, the WelcomeViewController was only opened to handle that
  320. // cancelling the action should also dismiss the whole controller
  321. if self.accountCode != nil {
  322. self.cancelAccountCreation()
  323. }
  324. }
  325. )
  326. alert.addAction(okAction)
  327. alert.addAction(qrCancelAction)
  328. if qrCodeReader != nil {
  329. qrCodeReader?.present(alert, animated: true)
  330. } else {
  331. self.present(alert, animated: true)
  332. }
  333. }
  334. private func qrErrorAlert() {
  335. let title = String.localized("qraccount_qr_code_cannot_be_used")
  336. let alert = UIAlertController(title: title, message: nil, preferredStyle: .alert)
  337. let okAction = UIAlertAction(
  338. title: String.localized("ok"),
  339. style: .default,
  340. handler: { [weak self] _ in
  341. guard let self = self else { return }
  342. if self.accountCode != nil {
  343. // if an injected accountCode exists, the WelcomeViewController was only opened to handle that
  344. // if the action failed the whole controller should be dismissed
  345. self.cancelAccountCreation()
  346. } else {
  347. self.qrCodeReader?.startSession()
  348. }
  349. }
  350. )
  351. alert.addAction(okAction)
  352. qrCodeReader?.present(alert, animated: true, completion: nil)
  353. }
  354. private func dismissQRReader() {
  355. self.navigationController?.popViewController(animated: true)
  356. self.qrCodeReader = nil
  357. }
  358. }
  359. // MARK: - WelcomeContentView
  360. class WelcomeContentView: UIView {
  361. var onLogin: VoidFunction?
  362. var onScanQRCode: VoidFunction?
  363. var onImportBackup: VoidFunction?
  364. var minContainerHeight: CGFloat = 0 {
  365. didSet {
  366. containerMinHeightConstraint.constant = minContainerHeight
  367. logoHeightConstraint.constant = calculateLogoHeight()
  368. }
  369. }
  370. private lazy var containerMinHeightConstraint: NSLayoutConstraint = {
  371. return container.heightAnchor.constraint(greaterThanOrEqualToConstant: 0)
  372. }()
  373. private lazy var logoHeightConstraint: NSLayoutConstraint = {
  374. return logoView.heightAnchor.constraint(equalToConstant: 0)
  375. }()
  376. private var container = UIView()
  377. private var logoView: UIImageView = {
  378. let image = #imageLiteral(resourceName: "background_intro")
  379. let view = UIImageView(image: image)
  380. return view
  381. }()
  382. private lazy var titleLabel: UILabel = {
  383. let label = UILabel()
  384. label.text = String.localized("welcome_chat_over_email")
  385. label.textColor = DcColors.grayTextColor
  386. label.textAlignment = .center
  387. label.numberOfLines = 0
  388. label.font = UIFont.systemFont(ofSize: 24, weight: .bold)
  389. return label
  390. }()
  391. private lazy var buttonStack: UIStackView = {
  392. let stack = UIStackView(arrangedSubviews: [loginButton, qrCodeButton, importBackupButton])
  393. stack.axis = .vertical
  394. stack.spacing = 15
  395. return stack
  396. }()
  397. private lazy var loginButton: UIButton = {
  398. let button = UIButton(type: .roundedRect)
  399. let title = String.localized("login_header").uppercased()
  400. button.setTitle(title, for: .normal)
  401. button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: .regular)
  402. button.setTitleColor(.white, for: .normal)
  403. button.backgroundColor = DcColors.primary
  404. let insets = button.contentEdgeInsets
  405. button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 15, bottom: 8, right: 15)
  406. button.layer.cornerRadius = 5
  407. button.clipsToBounds = true
  408. button.addTarget(self, action: #selector(loginButtonPressed(_:)), for: .touchUpInside)
  409. return button
  410. }()
  411. private lazy var qrCodeButton: UIButton = {
  412. let button = UIButton()
  413. let title = String.localized("scan_invitation_code")
  414. button.setTitleColor(UIColor.systemBlue, for: .normal)
  415. button.setTitle(title, for: .normal)
  416. button.addTarget(self, action: #selector(qrCodeButtonPressed(_:)), for: .touchUpInside)
  417. return button
  418. }()
  419. private lazy var importBackupButton: UIButton = {
  420. let button = UIButton()
  421. let title = String.localized("import_backup_title")
  422. button.setTitleColor(UIColor.systemBlue, for: .normal)
  423. button.setTitle(title, for: .normal)
  424. button.addTarget(self, action: #selector(importBackupButtonPressed(_:)), for: .touchUpInside)
  425. return button
  426. }()
  427. private let defaultSpacing: CGFloat = 20
  428. init() {
  429. super.init(frame: .zero)
  430. setupSubviews()
  431. backgroundColor = DcColors.defaultBackgroundColor
  432. }
  433. required init?(coder: NSCoder) {
  434. fatalError("init(coder:) has not been implemented")
  435. }
  436. // MARK: - setup
  437. private func setupSubviews() {
  438. addSubview(container)
  439. container.translatesAutoresizingMaskIntoConstraints = false
  440. container.topAnchor.constraint(equalTo: topAnchor).isActive = true
  441. container.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
  442. container.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.75).isActive = true
  443. container.centerXAnchor.constraint(equalTo: centerXAnchor, constant: 0).isActive = true
  444. containerMinHeightConstraint.isActive = true
  445. _ = [logoView, titleLabel].map {
  446. addSubview($0)
  447. $0.translatesAutoresizingMaskIntoConstraints = false
  448. }
  449. let bottomLayoutGuide = UILayoutGuide()
  450. container.addLayoutGuide(bottomLayoutGuide)
  451. bottomLayoutGuide.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  452. bottomLayoutGuide.heightAnchor.constraint(equalTo: container.heightAnchor, multiplier: 0.45).isActive = true
  453. titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
  454. titleLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor).isActive = true
  455. titleLabel.topAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true
  456. titleLabel.setContentHuggingPriority(.defaultHigh, for: .vertical)
  457. logoView.bottomAnchor.constraint(equalTo: titleLabel.topAnchor, constant: -defaultSpacing).isActive = true
  458. logoView.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
  459. logoHeightConstraint.constant = calculateLogoHeight()
  460. logoHeightConstraint.isActive = true
  461. logoView.widthAnchor.constraint(equalTo: logoView.heightAnchor).isActive = true
  462. let logoTopAnchor = logoView.topAnchor.constraint(equalTo: container.topAnchor, constant: 20) // this will allow the container to grow in height
  463. logoTopAnchor.priority = .defaultLow
  464. logoTopAnchor.isActive = true
  465. let buttonContainerGuide = UILayoutGuide()
  466. container.addLayoutGuide(buttonContainerGuide)
  467. buttonContainerGuide.topAnchor.constraint(equalTo: titleLabel.bottomAnchor).isActive = true
  468. buttonContainerGuide.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
  469. loginButton.setContentHuggingPriority(.defaultHigh, for: .vertical)
  470. container.addSubview(buttonStack)
  471. buttonStack.translatesAutoresizingMaskIntoConstraints = false
  472. buttonStack.centerXAnchor.constraint(equalTo: container.centerXAnchor).isActive = true
  473. buttonStack.centerYAnchor.constraint(equalTo: buttonContainerGuide.centerYAnchor).isActive = true
  474. let buttonStackTopAnchor = buttonStack.topAnchor.constraint(equalTo: buttonContainerGuide.topAnchor, constant: defaultSpacing)
  475. // this will allow the container to grow in height
  476. let buttonStackBottomAnchor = buttonStack.bottomAnchor.constraint(equalTo: buttonContainerGuide.bottomAnchor, constant: -50)
  477. _ = [buttonStackTopAnchor, buttonStackBottomAnchor].map {
  478. $0.priority = .defaultLow
  479. $0.isActive = true
  480. }
  481. }
  482. private func calculateLogoHeight() -> CGFloat {
  483. if UIDevice.current.userInterfaceIdiom == .phone {
  484. return UIApplication.shared.statusBarOrientation.isLandscape ? UIScreen.main.bounds.height * 0.5 : UIScreen.main.bounds.width * 0.75
  485. } else {
  486. return 275
  487. }
  488. }
  489. // MARK: - actions
  490. @objc private func loginButtonPressed(_ sender: UIButton) {
  491. onLogin?()
  492. }
  493. @objc private func qrCodeButtonPressed(_ sender: UIButton) {
  494. onScanQRCode?()
  495. }
  496. @objc private func importBackupButtonPressed(_ sender: UIButton) {
  497. onImportBackup?()
  498. }
  499. }
  500. extension WelcomeViewController: MediaPickerDelegate {
  501. func onDocumentSelected(url: NSURL) {
  502. logger.debug("onDocumentsSelected: \(String(describing: url.relativePath))")
  503. // ensure we can access folders outside of the app's sandbox
  504. let shouldStopAccessing = url.startAccessingSecurityScopedResource()
  505. if shouldStopAccessing {
  506. securityScopedResource = url
  507. }
  508. if let path = url.relativePath, let filePath = dcContext.imexHasBackup(filePath: path) {
  509. importBackup(at: filePath)
  510. } else {
  511. onSelectionCancelled()
  512. securityScopedResource = nil
  513. }
  514. }
  515. func onSelectionCancelled() {
  516. let alert = UIAlertController(
  517. title: String.localized("import_backup_title"),
  518. message: String.localizedStringWithFormat(
  519. String.localized("import_backup_no_backup_found"),
  520. "➔ Mac-Finder or iTunes ➔ iPhone ➔ " + String.localized("files") + " ➔ Delta Chat"), // iTunes was used up to Maverick 10.4
  521. preferredStyle: .alert)
  522. alert.addAction(UIAlertAction(title: String.localized("ok"), style: .cancel))
  523. present(alert, animated: true)
  524. }
  525. }