Automatic retry during onboarding, better UI while waiting

This commit is contained in:
Shadowfacts 2023-01-27 18:59:22 -05:00
parent 0e1cbce10d
commit 16347b2ad0
1 changed files with 102 additions and 23 deletions

View File

@ -9,12 +9,15 @@
import UIKit import UIKit
import AuthenticationServices import AuthenticationServices
import Pachyderm import Pachyderm
import OSLog
protocol OnboardingViewControllerDelegate { protocol OnboardingViewControllerDelegate {
@MainActor @MainActor
func didFinishOnboarding(account: LocalData.UserAccountInfo) func didFinishOnboarding(account: LocalData.UserAccountInfo)
} }
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "OnboardingViewController")
class OnboardingViewController: UINavigationController { class OnboardingViewController: UINavigationController {
var onboardingDelegate: OnboardingViewControllerDelegate? var onboardingDelegate: OnboardingViewControllerDelegate?
@ -40,7 +43,78 @@ class OnboardingViewController: UINavigationController {
} }
@MainActor @MainActor
private func tryLoginTo(instanceURL: URL) async throws { private func login(to instanceURL: URL) async {
let dimmingView = UIView()
dimmingView.translatesAutoresizingMaskIntoConstraints = false
dimmingView.backgroundColor = .black.withAlphaComponent(0.1)
let blur = UIBlurEffect(style: .prominent)
let blurView = UIVisualEffectView(effect: blur)
blurView.translatesAutoresizingMaskIntoConstraints = false
blurView.layer.cornerRadius = 15
blurView.layer.masksToBounds = true
let spinner = UIActivityIndicatorView(style: .large)
spinner.translatesAutoresizingMaskIntoConstraints = false
spinner.startAnimating()
let statusLabel = UILabel()
statusLabel.translatesAutoresizingMaskIntoConstraints = false
statusLabel.font = .preferredFont(forTextStyle: .headline)
statusLabel.numberOfLines = 0
statusLabel.textAlignment = .center
blurView.contentView.addSubview(spinner)
blurView.contentView.addSubview(statusLabel)
dimmingView.addSubview(blurView)
view.addSubview(dimmingView)
NSLayoutConstraint.activate([
dimmingView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
dimmingView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
dimmingView.topAnchor.constraint(equalTo: view.topAnchor),
dimmingView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
blurView.widthAnchor.constraint(equalToConstant: 150),
blurView.heightAnchor.constraint(equalToConstant: 150),
blurView.centerXAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerXAnchor),
blurView.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor),
spinner.centerXAnchor.constraint(equalTo: blurView.contentView.centerXAnchor),
spinner.bottomAnchor.constraint(equalTo: blurView.contentView.centerYAnchor, constant: -2),
statusLabel.leadingAnchor.constraint(equalTo: blurView.contentView.leadingAnchor),
statusLabel.trailingAnchor.constraint(equalTo: blurView.contentView.trailingAnchor),
statusLabel.topAnchor.constraint(equalTo: blurView.contentView.centerYAnchor, constant: 2),
])
dimmingView.layer.opacity = 0
blurView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut) {
dimmingView.layer.opacity = 1
blurView.transform = .identity
}
do {
try await tryLogin(to: instanceURL) {
statusLabel.text = $0
}
} catch Error.cancelled {
// no-op, don't show an error message
} catch {
let message: String
if let error = error as? Error {
message = error.localizedDescription
} else {
message = error.localizedDescription
}
let alert = UIAlertController(title: "Error Logging In", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
dimmingView.removeFromSuperview()
}
private func tryLogin(to instanceURL: URL, updateStatus: (String) -> Void) async throws {
let mastodonController = MastodonController(instanceURL: instanceURL, transient: true) let mastodonController = MastodonController(instanceURL: instanceURL, transient: true)
let clientID: String let clientID: String
let clientSecret: String let clientSecret: String
@ -48,28 +122,24 @@ class OnboardingViewController: UINavigationController {
clientID = clientInfo.id clientID = clientInfo.id
clientSecret = clientInfo.secret clientSecret = clientInfo.secret
} else { } else {
updateStatus("Registering App")
do { do {
(clientID, clientSecret) = try await mastodonController.registerApp() (clientID, clientSecret) = try await mastodonController.registerApp()
self.clientInfo = (instanceURL, clientID, clientSecret) self.clientInfo = (instanceURL, clientID, clientSecret)
// m.s has problems with (I think) the read replicas not updating fast enough updateStatus("Reticulating Splines")
// so give it some more time to propagate, and prevent invalid_client/etc. errors try await Task.sleep(nanoseconds: 500 * NSEC_PER_MSEC)
if instanceURL.host == "mastodon.social" {
try await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC)
}
} catch { } catch {
throw Error.registeringApp(error) throw Error.registeringApp(error)
} }
} }
updateStatus("Logging in")
let authCode = try await getAuthorizationCode(instanceURL: instanceURL, clientID: clientID) let authCode = try await getAuthorizationCode(instanceURL: instanceURL, clientID: clientID)
if instanceURL.host == "mastodon.social" { updateStatus("Authorizing")
try await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC)
}
let accessToken: String let accessToken: String
do { do {
accessToken = try await mastodonController.authorize(authorizationCode: authCode) accessToken = try await retrying("Getting access token") {
if instanceURL.host == "mastodon.social" { try await mastodonController.authorize(authorizationCode: authCode)
try await Task.sleep(nanoseconds: 2 * NSEC_PER_SEC) }
}
} catch { } catch {
throw Error.gettingAccessToken(error) throw Error.gettingAccessToken(error)
} }
@ -78,9 +148,12 @@ class OnboardingViewController: UINavigationController {
let tempAccountInfo = LocalData.UserAccountInfo(tempInstanceURL: instanceURL, clientID: clientID, clientSecret: clientSecret, accessToken: accessToken) let tempAccountInfo = LocalData.UserAccountInfo(tempInstanceURL: instanceURL, clientID: clientID, clientSecret: clientSecret, accessToken: accessToken)
mastodonController.accountInfo = tempAccountInfo mastodonController.accountInfo = tempAccountInfo
updateStatus("Checking Credentials")
let ownAccount: Account let ownAccount: Account
do { do {
ownAccount = try await mastodonController.getOwnAccount() ownAccount = try await retrying("Getting own account") {
try await mastodonController.getOwnAccount()
}
} catch { } catch {
throw Error.gettingOwnAccount(error) throw Error.gettingOwnAccount(error)
} }
@ -91,6 +164,19 @@ class OnboardingViewController: UINavigationController {
self.onboardingDelegate?.didFinishOnboarding(account: accountInfo) self.onboardingDelegate?.didFinishOnboarding(account: accountInfo)
} }
private func retrying<T>(_ label: StaticString, action: () async throws -> T) async throws -> T {
for attempt in 0..<4 {
do {
return try await action()
} catch {
let seconds = (pow(2, attempt) as NSDecimalNumber).uint64Value
logger.error("\(label, privacy: .public) failed, waiting \(seconds, privacy: .public)s before retrying. Reason: \(String(describing: error))")
try! await Task.sleep(nanoseconds: seconds * NSEC_PER_SEC)
}
}
return try await action()
}
@MainActor @MainActor
private func getAuthorizationCode(instanceURL: URL, clientID: String) async throws -> String { private func getAuthorizationCode(instanceURL: URL, clientID: String) async throws -> String {
var components = URLComponents(url: instanceURL, resolvingAgainstBaseURL: false)! var components = URLComponents(url: instanceURL, resolvingAgainstBaseURL: false)!
@ -160,15 +246,8 @@ extension OnboardingViewController {
extension OnboardingViewController: InstanceSelectorTableViewControllerDelegate { extension OnboardingViewController: InstanceSelectorTableViewControllerDelegate {
func didSelectInstance(url instanceURL: URL) { func didSelectInstance(url instanceURL: URL) {
Task { Task {
do { await self.login(to: instanceURL)
try await self.tryLoginTo(instanceURL: instanceURL) instanceSelector.tableView.selectRow(at: nil, animated: true, scrollPosition: .none)
} catch Error.cancelled {
// no-op, don't show an error message
} catch let error as Error {
let alert = UIAlertController(title: "Error Logging In", message: error.localizedDescription, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alert, animated: true)
}
} }
} }
} }