Reader and CloudKit Account Views

This commit is contained in:
Stuart Breckenridge
2022-12-16 16:38:06 +08:00
parent b3208bf269
commit 4ff0bc8f98
20 changed files with 554 additions and 149 deletions

View File

@@ -0,0 +1,20 @@
/*
Account.strings
NetNewsWire
Created by Stuart Breckenridge on 16/12/2022.
Copyright © 2022 Ranchero Software. All rights reserved.
*/
/* Account Names */
"CLOUDKIT" = "iCloud";
/* Explainers */
"BAZQUX_FOOTER_EXPLAINER" = "Sign in to your BazQux account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDont have a BazQux account? [Sign Up Here](https://bazqux.com)";
"INOREADER_FOOTER_EXPLAINER" = "Sign in to your InoReader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDont have an InoReader account? [Sign Up Here](https://www.inoreader.com)";
"OLDREADER_FOOTER_EXPLAINER" = "Sign in to your The Old Reader account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDont have a The Old Reader account? [Sign Up Here](https://theoldreader.com)";
"FRESHRSS_FOOTER_EXPLAINER" = "Sign in to your FreshRSS instance and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDont have an FreshRSS instance? [Sign Up Here](https://freshrss.org)";
"CLOUDKIT_FOOTER_EXPLAINER" = "NetNewsWire will use your iCloud account to sync your subscriptions across your Mac and iOS devices.";

View File

@@ -20,7 +20,7 @@ enum CloudKitAccountViewControllerError: LocalizedError {
class CloudKitAccountViewController: UITableViewController {
weak var delegate: AddAccountDismissDelegate?
//weak var delegate: AddAccountDismissDelegate?
@IBOutlet weak var footerLabel: UILabel!
override func viewDidLoad() {
@@ -36,7 +36,7 @@ class CloudKitAccountViewController: UITableViewController {
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
delegate?.dismiss()
//delegate?.dismiss()
}
@IBAction func add(_ sender: Any) {
@@ -47,7 +47,7 @@ class CloudKitAccountViewController: UITableViewController {
let _ = AccountManager.shared.createAccount(type: .cloudKit)
dismiss(animated: true, completion: nil)
delegate?.dismiss()
//delegate?.dismiss()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {

View File

@@ -24,7 +24,7 @@ class FeedbinAccountViewController: UITableViewController, Logging {
@IBOutlet weak var footerLabel: UILabel!
weak var account: Account?
weak var delegate: AddAccountDismissDelegate?
//weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
@@ -132,7 +132,7 @@ class FeedbinAccountViewController: UITableViewController, Logging {
}
self.dismiss(animated: true, completion: nil)
self.delegate?.dismiss()
//self.delegate?.dismiss()
} catch {
self.showError(NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error"))
self.logger.error("Keychain error while storing credentials: \(error.localizedDescription, privacy: .public).")

View File

@@ -1,65 +0,0 @@
//
// LocalAccountViewController.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 5/19/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import UIKit
import Account
class LocalAccountViewController: UITableViewController {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var footerLabel: UILabel!
weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
setupFooter()
navigationItem.title = Account.defaultLocalAccountName
nameTextField.delegate = self
tableView.register(ImageHeaderView.self, forHeaderFooterViewReuseIdentifier: "SectionHeader")
}
private func setupFooter() {
footerLabel.text = NSLocalizedString("Local accounts do not sync your feeds across devices.", comment: "Local")
}
@IBAction func cancel(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func add(_ sender: Any) {
let account = AccountManager.shared.createAccount(type: .onMyMac)
account.name = nameTextField.text
dismiss(animated: true, completion: nil)
delegate?.dismiss()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? ImageHeaderView.rowHeight : super.tableView(tableView, heightForHeaderInSection: section)
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 0 {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SectionHeader") as! ImageHeaderView
headerView.imageView.image = AppAssets.image(for: .onMyMac)
return headerView
} else {
return super.tableView(tableView, viewForHeaderInSection: section)
}
}
}
extension LocalAccountViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}

View File

@@ -24,7 +24,7 @@ class NewsBlurAccountViewController: UITableViewController, Logging {
@IBOutlet weak var footerLabel: UILabel!
weak var account: Account?
weak var delegate: AddAccountDismissDelegate?
//weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
@@ -135,7 +135,7 @@ class NewsBlurAccountViewController: UITableViewController, Logging {
}
self.dismiss(animated: true, completion: nil)
self.delegate?.dismiss()
//self.delegate?.dismiss()
} catch {
self.showError(NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error"))
self.logger.error("Keychain error while storing credentials: \(error.localizedDescription, privacy: .public).")

View File

@@ -27,7 +27,7 @@ class ReaderAPIAccountViewController: UITableViewController, Logging {
weak var account: Account?
var accountType: AccountType?
weak var delegate: AddAccountDismissDelegate?
//weak var delegate: AddAccountDismissDelegate?
override func viewDidLoad() {
super.viewDidLoad()
@@ -185,7 +185,7 @@ class ReaderAPIAccountViewController: UITableViewController, Logging {
}
}
self.delegate?.dismiss()
//self.delegate?.dismiss()
} catch {
self.showError(NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error"))
self.logger.error("Keychain error while storing credentials: \(error.localizedDescription, privacy: .public).")

View File

@@ -0,0 +1,254 @@
//
// ReaderAPIAccountView.swift
// NetNewsWire
//
// Created by Stuart Breckenridge on 16/12/2022.
// Copyright © 2022 Ranchero Software. All rights reserved.
//
import SwiftUI
import Account
import Secrets
import RSWeb
import SafariServices
import RSCore
struct ReaderAPIAccountView: View {
@Environment(\.dismiss) var dismiss
var accountType: AccountType?
@State var account: Account?
@State private var accountCredentials: Credentials?
@State private var accountUserName: String = ""
@State private var accountSecret: String = ""
@State private var accountAPIUrl: String = ""
@State private var showProgressIndicator: Bool = false
@State private var accountSetupError: (Error?, Bool) = (nil, false)
var body: some View {
NavigationView {
Form {
Section(header: readerAccountImage) {}
accountDetailsSection
Section(footer: readerAccountExplainer) {}
}
.navigationTitle(Text(accountType?.localizedAccountName() ?? ""))
.navigationBarTitleDisplayMode(.inline)
.task {
try? retrieveAccountCredentials()
}
.toolbar {
ToolbarItem(placement: .navigationBarLeading) {
Button(action: { dismiss() }, label: { Text("CANCEL_BUTTON_TITLE", tableName: "Buttons") })
}
ToolbarItem(placement: .navigationBarTrailing) {
if showProgressIndicator { ProgressView() }
}
}
.alert(Text("ERROR_TITLE", tableName: "Errors"), isPresented: $accountSetupError.1) {
Button(role: .cancel) {
//
} label: {
Text("DISMISS_BUTTON_TITLE", tableName: "Buttons")
}
} message: {
Text(accountSetupError.0?.localizedDescription ?? "")
}
.onReceive(NotificationCenter.default.publisher(for: .UserDidAddAccount)) { _ in
dismiss()
}
.edgesIgnoringSafeArea(.bottom) // Fix to make sure view is not offset from the top when presented
}
}
var readerAccountExplainer: some View {
if accountType == nil { return Text("").multilineTextAlignment(.center) }
switch accountType! {
case .bazQux:
return Text("BAZQUX_FOOTER_EXPLAINER", tableName: "Account").multilineTextAlignment(.center)
case .inoreader:
return Text("INOREADER_FOOTER_EXPLAINER", tableName: "Account").multilineTextAlignment(.center)
case .theOldReader:
return Text("OLDREADER_FOOTER_EXPLAINER", tableName: "Account").multilineTextAlignment(.center)
case .freshRSS:
return Text("FRESHRSS_FOOTER_EXPLAINER", tableName: "Account").multilineTextAlignment(.center)
default:
return Text("").multilineTextAlignment(.center)
}
}
var readerAccountImage: some View {
HStack {
Spacer()
if accountType == nil { Text("") }
switch accountType! {
case .bazQux:
Image(uiImage: AppAssets.accountBazQuxImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 48, height: 48)
case .inoreader:
Image(uiImage: AppAssets.accountInoreaderImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 48, height: 48)
case .theOldReader:
Image(uiImage: AppAssets.accountTheOldReaderImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 48, height: 48)
case .freshRSS:
Image(uiImage: AppAssets.accountFreshRSSImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 48, height: 48)
default:
Text("")
}
Spacer()
}
}
var accountDetailsSection: some View {
Group {
Section {
TextField("Username", text: $accountUserName)
.autocorrectionDisabled()
SecureField("Password", text: $accountSecret)
if accountType == .freshRSS && accountCredentials == nil {
TextField("FreshRSS URL", text: $accountAPIUrl, prompt: Text("fresh.rss.net/api/greader.php"))
.autocorrectionDisabled()
}
}
Section {
Button {
Task {
do {
try await executeAccountCredentials()
} catch {
accountSetupError = (error, true)
}
}
} label: {
HStack {
Spacer()
if accountCredentials == nil {
Text("ADD_ACCOUNT_BUTTON_TITLE", tableName: "Buttons")
} else {
Text("UPDATE_CREDENTIALS_BUTTON_TITLE", tableName: "Buttons")
}
Spacer()
}
}
.disabled(!validateCredentials())
}
}
}
// MARK: - API
private func retrieveAccountCredentials() throws {
if let account = account {
do {
if let creds = try account.retrieveCredentials(type: .readerBasic) {
self.accountCredentials = creds
accountUserName = creds.username
accountSecret = creds.secret
}
} catch {
accountSetupError = (error, true)
}
}
}
private func validateCredentials() -> Bool {
if accountType == nil { return false }
switch accountType! {
case .freshRSS:
if (accountUserName.trimmingWhitespace.count == 0) || (accountSecret.trimmingWhitespace.count == 0) || (accountAPIUrl.trimmingWhitespace.count == 0) {
return false
}
default:
if (accountUserName.trimmingWhitespace.count == 0) || (accountSecret.trimmingWhitespace.count == 0) {
return false
}
}
return true
}
@MainActor
private func executeAccountCredentials() async throws {
let trimmedAccountUserName = accountUserName.trimmingWhitespace
guard (account != nil || !AccountManager.shared.duplicateServiceAccount(type: accountType!, username: trimmedAccountUserName)) else {
throw LocalizedNetNewsWireError.duplicateAccount
}
showProgressIndicator = true
let credentials = Credentials(type: .readerBasic, username: trimmedAccountUserName, secret: accountSecret)
return try await withCheckedThrowingContinuation { continuation in
Account.validateCredentials(type: accountType!, credentials: credentials, endpoint: apiURL()) { result in
switch result {
case .success(let validatedCredentials):
if let validatedCredentials = validatedCredentials {
if self.account == nil {
self.account = AccountManager.shared.createAccount(type: accountType!)
}
do {
self.account?.endpointURL = apiURL()
try? self.account?.removeCredentials(type: .readerBasic)
try? self.account?.removeCredentials(type: .readerAPIKey)
try self.account?.storeCredentials(credentials)
try self.account?.storeCredentials(validatedCredentials)
self.account?.refreshAll(completion: { result in
switch result {
case .success:
showProgressIndicator = false
continuation.resume()
case .failure(let error):
showProgressIndicator = false
continuation.resume(throwing: error)
}
})
} catch {
showProgressIndicator = false
continuation.resume(throwing: error)
}
}
case .failure(let failure):
showProgressIndicator = false
continuation.resume(throwing: failure)
}
}
}
}
private func apiURL() -> URL? {
switch accountType! {
case .freshRSS:
return URL(string: accountAPIUrl)!
case .inoreader:
return URL(string: ReaderAPIVariant.inoreader.host)!
case .bazQux:
return URL(string: ReaderAPIVariant.bazQux.host)!
case .theOldReader:
return URL(string: ReaderAPIVariant.theOldReader.host)!
default:
return nil
}
}
}
struct ReaderAPIAccountView_Previews: PreviewProvider {
static var previews: some View {
ReaderAPIAccountView()
}
}

View File

@@ -0,0 +1,83 @@
//
// iCloudAccountView.swift
// NetNewsWire-iOS
//
// Created by Stuart Breckenridge on 16/12/2022.
// Copyright © 2022 Ranchero Software. All rights reserved.
//
import SwiftUI
import Account
struct iCloudAccountView: View {
@Environment(\.dismiss) private var dismiss
@State private var addAccountError: (LocalizedError?, Bool) = (nil, false)
var body: some View {
NavigationView {
Form {
Section(header: cloudKitHeader) {}
Section {
createCloudKitAccount
}
Section(footer: cloudKitExplainer) {}
}
.navigationTitle(Text("CLOUDKIT", tableName: "Account"))
.navigationBarTitleDisplayMode(.inline)
.alert(Text("ERROR_TITLE", tableName: "Errors"), isPresented: $addAccountError.1) {
Button(action: {}, label: { Text("DISMISS_BUTTON_TITLE", tableName: "Buttons") })
} message: {
Text(addAccountError.0?.localizedDescription ?? "Unknown Error")
}
.onReceive(NotificationCenter.default.publisher(for: .UserDidAddAccount)) { _ in
dismiss()
}
}
}
var cloudKitHeader: some View {
HStack {
Spacer()
Image(uiImage: AppAssets.accountCloudKitImage)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 48, height: 48)
Spacer()
}
}
var createCloudKitAccount: some View {
Button {
guard FileManager.default.ubiquityIdentityToken != nil else {
addAccountError = (LocalizedNetNewsWireError.iCloudDriveMissing, true)
return
}
let _ = AccountManager.shared.createAccount(type: .cloudKit)
} label: {
HStack {
Spacer()
Text("USE_CLOUDKIT_BUTTON_TITLE", tableName: "Buttons")
Spacer()
}
}
}
var cloudKitExplainer: some View {
VStack(spacing: 4) {
if !AccountManager.shared.accounts.contains(where: { $0.type == .cloudKit }) {
// The explainer is only shown when a CloudKit account doesn't exist.
Text("CLOUDKIT_FOOTER_EXPLAINER", tableName: "Account")
}
Text("CLOUDKIT_LIMITATIONS_TITLE", tableName: "Inspector")
}.multilineTextAlignment(.center)
}
}
struct iCloudAccountView_Previews: PreviewProvider {
static var previews: some View {
iCloudAccountView()
}
}