mastodon-ios/Mastodon/Scene/Onboarding/PickServer/MastodonPickServerViewContr...

450 lines
20 KiB
Swift
Raw Normal View History

//
2021-02-26 11:27:47 +01:00
// MastodonPickServerViewController.swift
// Mastodon
//
// Created by BradGao on 2021/2/20.
//
import os.log
import UIKit
import Combine
import GameController
import AuthenticationServices
import MastodonAsset
2022-10-08 07:43:06 +02:00
import MastodonCore
import MastodonLocalization
import MastodonUI
2021-02-26 11:27:47 +01:00
final class MastodonPickServerViewController: UIViewController, NeedsDependency {
private var disposeBag = Set<AnyCancellable>()
2022-01-04 11:30:21 +01:00
private var observations = Set<NSKeyValueObservation>()
private var tableViewObservation: NSKeyValueObservation?
weak var context: AppContext! { willSet { precondition(!isViewLoaded) } }
weak var coordinator: SceneCoordinator! { willSet { precondition(!isViewLoaded) } }
2021-02-26 11:27:47 +01:00
var viewModel: MastodonPickServerViewModel!
private(set) lazy var authenticationViewModel = AuthenticationViewModel(
context: context,
coordinator: coordinator,
isAuthenticationExist: false
)
2021-02-25 09:38:24 +01:00
private var expandServerDomainSet = Set<String>()
private let emptyStateView = PickServerEmptyStateView()
private var emptyStateViewLeadingLayoutConstraint: NSLayoutConstraint!
private var emptyStateViewTrailingLayoutConstraint: NSLayoutConstraint!
let tableView: UITableView = {
let tableView = ControlContainableTableView()
tableView.rowHeight = UITableView.automaticDimension
tableView.separatorStyle = .none
tableView.backgroundColor = .clear
2021-02-25 07:09:19 +01:00
tableView.keyboardDismissMode = .onDrag
tableView.sectionHeaderTopPadding = .leastNonzeroMagnitude
return tableView
}()
2022-01-04 11:30:21 +01:00
let navigationActionView: NavigationActionView = {
let navigationActionView = NavigationActionView()
2022-02-15 11:15:58 +01:00
navigationActionView.backgroundColor = Asset.Scene.Onboarding.background.color
2022-01-04 11:30:21 +01:00
return navigationActionView
}()
var mastodonAuthenticationController: MastodonAuthenticationController?
deinit {
tableViewObservation = nil
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s", ((#file as NSString).lastPathComponent), #line, #function)
}
}
2022-01-04 11:30:21 +01:00
extension MastodonPickServerViewController {
2021-04-01 08:39:15 +02:00
override func viewDidLoad() {
super.viewDidLoad()
2022-01-04 11:30:21 +01:00
navigationItem.leftBarButtonItem = UIBarButtonItem()
setupOnboardingAppearance()
defer { setupNavigationBarBackgroundView() }
2021-04-09 05:05:10 +02:00
#if DEBUG
navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(systemName: "ellipsis.circle"), style: .plain, target: nil, action: nil)
let children: [UIMenuElement] = [
UIAction(title: "Dismiss", image: nil, identifier: nil, discoverabilityTitle: nil, attributes: [], state: .off, handler: { [weak self] _ in
guard let self = self else { return }
self.dismiss(animated: true, completion: nil)
})
]
navigationItem.rightBarButtonItem?.menu = UIMenu(title: "Debug Tool", image: nil, identifier: nil, options: [], children: children)
#endif
2022-01-04 11:30:21 +01:00
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
NSLayoutConstraint.activate([
2022-01-04 11:30:21 +01:00
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
tableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor),
])
2022-01-04 11:30:21 +01:00
navigationActionView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(navigationActionView)
defer {
view.bringSubviewToFront(navigationActionView)
}
NSLayoutConstraint.activate([
2022-01-04 11:30:21 +01:00
navigationActionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
navigationActionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
view.bottomAnchor.constraint(equalTo: navigationActionView.bottomAnchor),
])
2022-01-04 11:30:21 +01:00
navigationActionView
.observe(\.bounds, options: [.initial, .new]) { [weak self] _, _ in
2022-01-04 11:30:21 +01:00
guard let self = self else { return }
let inset = self.navigationActionView.frame.height
self.viewModel.additionalTableViewInsets.bottom = inset
2022-01-04 11:30:21 +01:00
}
.store(in: &observations)
// fix AutoLayout warning when observe before view appear
viewModel.viewWillAppear
.receive(on: DispatchQueue.main)
.sink { [weak self] in
guard let self = self else { return }
self.tableViewObservation = self.tableView.observe(\.contentSize, options: [.initial, .new]) { [weak self] tableView, _ in
guard let self = self else { return }
self.updateEmptyStateViewLayout()
}
}
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
emptyStateView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(emptyStateView)
emptyStateViewLeadingLayoutConstraint = emptyStateView.leadingAnchor.constraint(equalTo: tableView.leadingAnchor)
emptyStateViewTrailingLayoutConstraint = tableView.trailingAnchor.constraint(equalTo: emptyStateView.trailingAnchor)
NSLayoutConstraint.activate([
emptyStateView.topAnchor.constraint(equalTo: view.topAnchor),
emptyStateViewLeadingLayoutConstraint,
emptyStateViewTrailingLayoutConstraint,
2022-01-04 11:30:21 +01:00
navigationActionView.topAnchor.constraint(equalTo: emptyStateView.bottomAnchor, constant: 21),
])
view.sendSubviewToBack(emptyStateView)
2022-01-04 11:30:21 +01:00
2021-02-25 09:38:24 +01:00
tableView.delegate = self
viewModel.setupDiffableDataSource(
for: tableView,
dependency: self,
2022-11-09 16:13:05 +01:00
pickServerServerSectionTableHeaderViewDelegate: self
)
KeyboardResponderService
.configure(
scrollView: tableView,
layoutNeedsUpdate: viewModel.viewDidAppear.eraseToAnyPublisher(),
additionalSafeAreaInsets: viewModel.$additionalTableViewInsets.eraseToAnyPublisher()
)
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
2021-02-25 07:09:19 +01:00
viewModel
.selectedServer
.map { $0 != nil }
2022-01-04 11:30:21 +01:00
.assign(to: \.isEnabled, on: navigationActionView.nextButton)
2021-02-25 07:09:19 +01:00
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
Publishers.Merge(
viewModel.error,
authenticationViewModel.error
)
.compactMap { $0 }
.receive(on: DispatchQueue.main)
.sink { [weak self] error in
guard let self = self else { return }
let alertController = UIAlertController(for: error, title: "Error", preferredStyle: .alert)
let okAction = UIAlertAction(title: L10n.Common.Controls.Actions.ok, style: .default, handler: nil)
alertController.addAction(okAction)
_ = self.coordinator.present(
scene: .alertController(alertController: alertController),
from: nil,
transition: .alertController(animated: true, completion: nil)
)
}
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
authenticationViewModel
2021-02-25 07:09:19 +01:00
.authenticated
.asyncMap { domain, user -> Result<Bool, Error> in
do {
let result = try await self.context.authenticationService.activeMastodonUser(domain: domain, userID: user.id)
return .success(result)
} catch {
return .failure(error)
}
2021-02-25 07:09:19 +01:00
}
2021-02-26 11:27:47 +01:00
.receive(on: DispatchQueue.main)
2021-02-25 07:09:19 +01:00
.sink { [weak self] result in
guard let self = self else { return }
switch result {
case .failure(let error):
assertionFailure(error.localizedDescription)
case .success(let isActived):
assert(isActived)
// self.dismiss(animated: true, completion: nil)
self.coordinator.setup()
2021-02-25 07:09:19 +01:00
}
}
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
authenticationViewModel.isAuthenticating
2021-02-25 09:38:24 +01:00
.receive(on: DispatchQueue.main)
.sink { [weak self] isAuthenticating in
guard let self = self else { return }
2022-01-04 11:30:21 +01:00
isAuthenticating ? self.navigationActionView.nextButton.showLoading() : self.navigationActionView.nextButton.stopLoading()
2021-02-25 09:38:24 +01:00
}
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
viewModel.emptyStateViewState
2022-01-04 11:30:21 +01:00
.receive(on: DispatchQueue.main)
.sink { [weak self] state in
guard let self = self else { return }
switch state {
case .none:
UIView.animate(withDuration: 0.3) {
self.emptyStateView.alpha = 0
}
case .loading:
self.emptyStateView.alpha = 1
self.emptyStateView.networkIndicatorImageView.isHidden = true
self.emptyStateView.activityIndicatorView.startAnimating()
self.emptyStateView.infoLabel.isHidden = false
self.emptyStateView.infoLabel.text = L10n.Scene.ServerPicker.EmptyState.findingServers
self.emptyStateView.infoLabel.textAlignment = self.traitCollection.layoutDirection == .rightToLeft ? .right : .left
case .badNetwork:
self.emptyStateView.alpha = 1
self.emptyStateView.networkIndicatorImageView.isHidden = false
self.emptyStateView.activityIndicatorView.stopAnimating()
self.emptyStateView.infoLabel.isHidden = false
self.emptyStateView.infoLabel.text = L10n.Scene.ServerPicker.EmptyState.badNetwork
self.emptyStateView.infoLabel.textAlignment = .center
}
}
.store(in: &disposeBag)
2022-01-04 11:30:21 +01:00
navigationActionView.backButton.addTarget(self, action: #selector(MastodonPickServerViewController.backButtonDidPressed(_:)), for: .touchUpInside)
navigationActionView.nextButton.addTarget(self, action: #selector(MastodonPickServerViewController.nextButtonDidPressed(_:)), for: .touchUpInside)
}
2021-02-25 07:09:19 +01:00
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.viewWillAppear.send()
}
2022-01-05 08:11:35 +01:00
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.flashScrollIndicators()
viewModel.viewDidAppear.send()
2022-01-05 08:11:35 +01:00
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
setupNavigationBarAppearance()
updateEmptyStateViewLayout()
}
}
extension MastodonPickServerViewController {
2022-01-04 11:30:21 +01:00
@objc private func backButtonDidPressed(_ sender: UIButton) {
navigationController?.popViewController(animated: true)
}
2022-01-04 11:30:21 +01:00
@objc private func nextButtonDidPressed(_ sender: UIButton) {
2021-02-25 07:09:19 +01:00
os_log(.info, log: .debug, "%{public}s[%{public}ld], %{public}s", ((#file as NSString).lastPathComponent), #line, #function)
guard let server = viewModel.selectedServer.value else { return }
authenticationViewModel.isAuthenticating.send(true)
2021-02-25 07:09:19 +01:00
context.apiService.instance(domain: server.domain)
2021-02-26 11:27:47 +01:00
.compactMap { [weak self] response -> AnyPublisher<MastodonPickServerViewModel.SignUpResponseFirst, Error>? in
2021-02-25 07:09:19 +01:00
guard let self = self else { return nil }
guard response.value.registrations != false else {
return Fail(error: AuthenticationViewModel.AuthenticationError.registrationClosed).eraseToAnyPublisher()
}
return self.context.apiService.createApplication(domain: server.domain)
2021-02-26 11:27:47 +01:00
.map { MastodonPickServerViewModel.SignUpResponseFirst(instance: response, application: $0) }
2021-02-25 07:09:19 +01:00
.eraseToAnyPublisher()
}
.switchToLatest()
2021-02-26 11:27:47 +01:00
.tryMap { response -> MastodonPickServerViewModel.SignUpResponseSecond in
2021-02-25 07:09:19 +01:00
let application = response.application.value
guard let authenticateInfo = AuthenticationViewModel.AuthenticateInfo(
domain: server.domain,
application: application
) else {
2021-02-25 07:09:19 +01:00
throw APIService.APIError.explicit(.badResponse)
}
return MastodonPickServerViewModel.SignUpResponseSecond(
instance: response.instance,
authenticateInfo: authenticateInfo
)
2021-02-25 07:09:19 +01:00
}
2021-02-26 11:27:47 +01:00
.compactMap { [weak self] response -> AnyPublisher<MastodonPickServerViewModel.SignUpResponseThird, Error>? in
2021-02-25 07:09:19 +01:00
guard let self = self else { return nil }
let instance = response.instance
let authenticateInfo = response.authenticateInfo
return self.context.apiService.applicationAccessToken(
domain: server.domain,
clientID: authenticateInfo.clientID,
clientSecret: authenticateInfo.clientSecret,
redirectURI: authenticateInfo.redirectURI
2021-02-25 07:09:19 +01:00
)
.map {
MastodonPickServerViewModel.SignUpResponseThird(
instance: instance,
authenticateInfo: authenticateInfo,
applicationToken: $0
)
}
2021-02-25 07:09:19 +01:00
.eraseToAnyPublisher()
}
.switchToLatest()
.receive(on: DispatchQueue.main)
.sink { [weak self] completion in
guard let self = self else { return }
self.authenticationViewModel.isAuthenticating.send(false)
2021-02-25 07:09:19 +01:00
switch completion {
case .failure(let error):
self.viewModel.error.send(error)
case .finished:
break
}
} receiveValue: { [weak self] response in
guard let self = self else { return }
if let rules = response.instance.value.rules, !rules.isEmpty {
// show server rules before register
let mastodonServerRulesViewModel = MastodonServerRulesViewModel(
domain: server.domain,
authenticateInfo: response.authenticateInfo,
rules: rules,
instance: response.instance.value,
applicationToken: response.applicationToken.value
)
_ = self.coordinator.present(scene: .mastodonServerRules(viewModel: mastodonServerRulesViewModel), from: self, transition: .show)
} else {
let mastodonRegisterViewModel = MastodonRegisterViewModel(
2021-03-02 06:27:53 +01:00
context: self.context,
2022-01-07 11:49:37 +01:00
domain: server.domain,
authenticateInfo: response.authenticateInfo,
instance: response.instance.value,
applicationToken: response.applicationToken.value
)
_ = self.coordinator.present(scene: .mastodonRegister(viewModel: mastodonRegisterViewModel), from: nil, transition: .show)
}
2021-02-25 07:09:19 +01:00
}
.store(in: &disposeBag)
}
}
2021-02-25 09:38:24 +01:00
// MARK: - UITableViewDelegate
2021-02-26 11:27:47 +01:00
extension MastodonPickServerViewController: UITableViewDelegate {
2021-02-25 09:38:24 +01:00
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard let diffableDataSource = viewModel.diffableDataSource else { return nil }
guard let item = diffableDataSource.itemIdentifier(for: indexPath) else { return nil }
2021-03-10 12:12:53 +01:00
guard case .server = item else { return nil }
2021-02-25 09:38:24 +01:00
if tableView.indexPathForSelectedRow == indexPath {
tableView.deselectRow(at: indexPath, animated: false)
viewModel.selectedServer.send(nil)
return nil
}
2021-02-25 09:38:24 +01:00
return indexPath
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let diffableDataSource = viewModel.diffableDataSource else { return }
guard let item = diffableDataSource.itemIdentifier(for: indexPath) else { return }
guard case let .server(server, _) = item else { return }
2021-02-25 09:38:24 +01:00
tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none)
viewModel.selectedServer.send(server)
2021-02-25 09:38:24 +01:00
}
2021-02-25 09:38:24 +01:00
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
viewModel.selectedServer.send(nil)
}
2022-01-04 11:30:21 +01:00
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let diffableDataSource = viewModel.diffableDataSource else { return nil }
let snapshot = diffableDataSource.snapshot()
guard section < snapshot.numberOfSections else { return nil }
let section = snapshot.sectionIdentifiers[section]
2022-01-04 11:30:21 +01:00
switch section {
case .servers:
return viewModel.serverSectionHeaderView
default:
2022-01-04 11:30:21 +01:00
return UIView()
}
}
2022-01-04 11:30:21 +01:00
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard let diffableDataSource = viewModel.diffableDataSource else { return .leastNonzeroMagnitude }
let snapshot = diffableDataSource.snapshot()
guard section < snapshot.numberOfSections else { return .leastNonzeroMagnitude }
let section = snapshot.sectionIdentifiers[section]
switch section {
case .servers:
return PickServerServerSectionTableHeaderView.height
default:
2022-01-04 11:30:21 +01:00
return .leastNonzeroMagnitude
}
}
2022-01-04 11:30:21 +01:00
}
2022-01-04 11:30:21 +01:00
extension MastodonPickServerViewController {
private func updateEmptyStateViewLayout() {
// guard let diffableDataSource = self.viewModel.diffableDataSource else { return }
// guard let indexPath = diffableDataSource.indexPath(for: .search) else { return }
// let rectInTableView = tableView.rectForRow(at: indexPath)
//
// emptyStateView.topPaddingViewTopLayoutConstraint.constant = rectInTableView.maxY
//
// switch traitCollection.horizontalSizeClass {
// case .regular:
// emptyStateViewLeadingLayoutConstraint.constant = MastodonPickServerViewController.viewEdgeMargin
// emptyStateViewTrailingLayoutConstraint.constant = MastodonPickServerViewController.viewEdgeMargin
// default:
// let margin = tableView.layoutMarginsGuide.layoutFrame.origin.x
// emptyStateViewLeadingLayoutConstraint.constant = margin
// emptyStateViewTrailingLayoutConstraint.constant = margin
// }
}
}
2022-01-04 11:30:21 +01:00
// MARK: - PickServerServerSectionTableHeaderViewDelegate
extension MastodonPickServerViewController: PickServerServerSectionTableHeaderViewDelegate {
func pickServerServerSectionTableHeaderView(_ headerView: PickServerServerSectionTableHeaderView, collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let diffableDataSource = headerView.diffableDataSource else { return }
let item = diffableDataSource.itemIdentifier(for: indexPath)
viewModel.selectCategoryItem.value = item ?? .all
}
func pickServerServerSectionTableHeaderView(_ headerView: PickServerServerSectionTableHeaderView, searchTextDidChange searchText: String?) {
viewModel.searchText.send(searchText ?? "")
2021-02-25 09:38:24 +01:00
}
}
// MARK: - OnboardingViewControllerAppearance
2021-02-26 11:27:47 +01:00
extension MastodonPickServerViewController: OnboardingViewControllerAppearance { }