// // OnboardingViewController.swift // Tusker // // Created by Shadowfacts on 8/18/18. // Copyright © 2018 Shadowfacts. All rights reserved. // import UIKit import AuthenticationServices protocol OnboardingViewControllerDelegate { func didFinishOnboarding() } class OnboardingViewController: UINavigationController { static var blocks: [NSRegularExpression] = { guard let path = Bundle.main.path(forResource: "DomainBlocks", ofType: "plist"), let array = NSArray(contentsOfFile: path) as? [String] else { return [] } return array.compactMap { try? NSRegularExpression(pattern: $0, options: .caseInsensitive) } }() var onboardingDelegate: OnboardingViewControllerDelegate? var instanceSelector = InstanceSelectorTableViewController() var authenticationSession: ASWebAuthenticationSession? init() { super.init(rootViewController: instanceSelector) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() instanceSelector.delegate = self } } extension OnboardingViewController: InstanceSelectorTableViewControllerDelegate { func didSelectInstance(url: URL) { LocalData.shared.instanceURL = url MastodonController.createClient() MastodonController.registerApp { let clientID = LocalData.shared.clientID! let callbackURL = "tusker://oauth" var components = URLComponents(url: url, resolvingAgainstBaseURL: false)! components.path = "/oauth/authorize" components.queryItems = [ URLQueryItem(name: "client_id", value: clientID), URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "scope", value: "read write follow"), URLQueryItem(name: "redirect_uri", value: callbackURL) ] let authorizeURL = components.url! self.authenticationSession = ASWebAuthenticationSession(url: authorizeURL, callbackURLScheme: callbackURL) { url, error in guard error == nil, let url = url, let components = URLComponents(url: url, resolvingAgainstBaseURL: true), let item = components.queryItems?.first(where: { $0.name == "code" }), let authCode = item.value else { return } MastodonController.authorize(authorizationCode: authCode) { DispatchQueue.main.async { self.onboardingDelegate?.didFinishOnboarding() } } } DispatchQueue.main.async { self.authenticationSession!.presentationContextProvider = self self.authenticationSession!.start() } } } } extension OnboardingViewController: ASWebAuthenticationPresentationContextProviding { func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { return view.window! } }