2020-07-30 01:50:30 +02:00
|
|
|
// Copyright © 2020 Metabolist. All rights reserved.
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
import Combine
|
|
|
|
|
|
|
|
class AddIdentityViewModel: ObservableObject {
|
|
|
|
@Published var urlFieldText = ""
|
|
|
|
@Published var alertItem: AlertItem?
|
|
|
|
@Published private(set) var loading = false
|
2020-08-14 03:24:53 +02:00
|
|
|
let addedIdentityID: AnyPublisher<UUID, Never>
|
2020-07-30 01:50:30 +02:00
|
|
|
|
2020-08-09 13:27:38 +02:00
|
|
|
private let identitiesService: IdentitiesService
|
2020-08-14 03:24:53 +02:00
|
|
|
private let addedIdentityIDInput = PassthroughSubject<UUID, Never>()
|
2020-08-03 17:20:51 +02:00
|
|
|
private var cancellables = Set<AnyCancellable>()
|
2020-07-30 01:50:30 +02:00
|
|
|
|
2020-08-09 13:27:38 +02:00
|
|
|
init(identitiesService: IdentitiesService) {
|
|
|
|
self.identitiesService = identitiesService
|
2020-08-14 03:24:53 +02:00
|
|
|
addedIdentityID = addedIdentityIDInput.eraseToAnyPublisher()
|
2020-07-30 01:50:30 +02:00
|
|
|
}
|
|
|
|
|
2020-08-09 13:27:38 +02:00
|
|
|
func logInTapped() {
|
|
|
|
let identityID = UUID()
|
|
|
|
let instanceURL: URL
|
|
|
|
|
|
|
|
do {
|
|
|
|
try instanceURL = urlFieldText.url()
|
|
|
|
} catch {
|
|
|
|
alertItem = AlertItem(error: error)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
identitiesService.authorizeIdentity(id: identityID, instanceURL: instanceURL)
|
|
|
|
.map { (identityID, instanceURL) }
|
|
|
|
.flatMap(identitiesService.createIdentity(id:instanceURL:))
|
2020-08-14 03:24:53 +02:00
|
|
|
.map { identityID }
|
2020-07-30 01:50:30 +02:00
|
|
|
.assignErrorsToAlertItem(to: \.alertItem, on: self)
|
2020-08-02 09:02:03 +02:00
|
|
|
.receive(on: RunLoop.main)
|
2020-07-30 01:50:30 +02:00
|
|
|
.handleEvents(
|
|
|
|
receiveSubscription: { [weak self] _ in self?.loading = true },
|
|
|
|
receiveCompletion: { [weak self] _ in self?.loading = false })
|
2020-08-14 03:24:53 +02:00
|
|
|
.sink(receiveValue: addedIdentityIDInput.send)
|
2020-08-03 17:20:51 +02:00
|
|
|
.store(in: &cancellables)
|
2020-07-30 01:50:30 +02:00
|
|
|
}
|
2020-08-09 13:27:38 +02:00
|
|
|
|
|
|
|
func browseAnonymouslyTapped() {
|
|
|
|
let identityID = UUID()
|
|
|
|
let instanceURL: URL
|
|
|
|
|
|
|
|
do {
|
|
|
|
try instanceURL = urlFieldText.url()
|
|
|
|
} catch {
|
|
|
|
alertItem = AlertItem(error: error)
|
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-08-09 22:40:14 +02:00
|
|
|
// TODO: Ensure instance has not disabled public preview
|
2020-08-09 13:27:38 +02:00
|
|
|
identitiesService.createIdentity(id: identityID, instanceURL: instanceURL)
|
2020-08-14 03:24:53 +02:00
|
|
|
.map { identityID }
|
2020-08-09 13:27:38 +02:00
|
|
|
.assignErrorsToAlertItem(to: \.alertItem, on: self)
|
2020-08-14 03:24:53 +02:00
|
|
|
.sink(receiveValue: addedIdentityIDInput.send)
|
2020-08-09 13:27:38 +02:00
|
|
|
.store(in: &cancellables)
|
|
|
|
}
|
2020-07-30 01:50:30 +02:00
|
|
|
}
|