Files
NetNewsWire/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift
T
Dave MarquardandIngmar Stein ba63d58712 Add native Miniflux account type and sync support
Adds Miniflux as a first-class account type alongside Feedbin, Feedly,
NewsBlur, and Reader API accounts, on both macOS and iOS.

Refreshes are incremental: the changed_after parameter means read and
starred status ride along with the entries in a single pass instead of
needing separate status scans. Articles missing locally are backfilled by
ID via GET /v1/entries/{id}; a 404 means the entry is gone server-side, so
its statuses are deleted and it is not requested again on every refresh.
Starred changes go out as idempotent batch updates.

Requires Miniflux 2.0.49 or newer. The server version is detected at
runtime via GET /v1/version and persisted in AccountSettings. Servers
older than 2.3.2 have no /v1/entries/ids and no batch starred updates, so
those paths fall back transparently to paged /v1/entries and per-entry
bookmark toggles.

Both HTTP Basic and API-token authentication are supported, selectable in
the account sheet on either platform. Entered URLs are normalized (scheme
added, trailing slash and /v1 suffix stripped), and adding a second
account for a server that already has one is rejected.

Tests cover folder sync, model decoding, version parsing, the pre-2.3.2
fallback paths, and duplicate-endpoint detection, with JSON fixtures for
the API responses.

The runtime version detection and the duplicate-endpoint check were
informed by IngmarStein's independent Miniflux implementation in #5335.

Written with help from Claude Code.

Co-Authored-By: Ingmar Stein <490610+IngmarStein@users.noreply.github.com>
2026-11-22 07:06:11 -08:00

356 lines
12 KiB
Swift

//
// AccountsPreferencesViewController.swift
// NetNewsWire
//
// Created by Brent Simmons on 3/17/19.
// Copyright © 2019 Ranchero Software. All rights reserved.
//
import AppKit
import SwiftUI
import Account
import RSCore
// MARK: - AccountsPreferencesAddAccountDelegate
@MainActor protocol AccountsPreferencesAddAccountDelegate {
func presentSheetForAccount(_ accountType: AccountType)
}
// MARK: - AccountsPreferencesViewController
final class AccountsPreferencesViewController: NSViewController {
@IBOutlet var tableView: NSTableView!
@IBOutlet var detailView: NSView!
@IBOutlet var deleteButton: NSButton!
var addAccountDelegate: AccountsPreferencesAddAccountDelegate?
var addAccountWindowController: NSWindowController?
var addAccountsViewController: NSHostingController<AddAccountsView>?
private var sortedAccounts = [Account]()
private var isReloadingTable = false
private var selectedAccount: Account? {
account(at: tableView.selectedRow)
}
convenience init() {
self.init(nibName: "AccountsPreferencesView", bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
updateSortedAccounts()
tableView.delegate = self
tableView.dataSource = self
addAccountDelegate = self
NotificationCenter.default.addObserver(self, selector: #selector(displayNameDidChange(_:)), name: .DisplayNameDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidAddAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(accountsDidChange(_:)), name: .UserDidDeleteAccount, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleAccountRefreshStateChanged(_:)), name: .AccountRefreshDidBegin, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(handleAccountRefreshStateChanged(_:)), name: .AccountRefreshDidFinish, object: nil)
// Fix tableView frame — for some reason IB wants it 1pt wider than the clip view. This leads to unwanted horizontal scrolling.
var rTable = tableView.frame
rTable.size.width = tableView.superview!.frame.size.width
tableView.frame = rTable
hideController()
}
@IBAction func addAccount(_ sender: Any) {
let controller = NSHostingController(rootView: AddAccountsView(delegate: self))
controller.rootView.parent = controller
addAccountsViewController = controller
presentAsSheet(controller)
}
@IBAction func removeAccount(_ sender: Any) {
guard let account = selectedAccount else {
return
}
let accountName = account.nameForDisplay
let alert = NSAlert()
alert.alertStyle = .warning
let messageFormat = NSLocalizedString("Delete “%@”?", comment: "Delete account alert title")
alert.messageText = String(format: messageFormat, accountName)
let informativeFormat = NSLocalizedString("Are you sure you want to delete the account “%@”? This cannot be undone.", comment: "Delete account alert message")
alert.informativeText = String(format: informativeFormat, accountName)
alert.addButton(withTitle: NSLocalizedString("Delete", comment: "Delete button"))
alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel button"))
guard let window = view.window else {
return
}
alert.beginSheetModal(for: window) { [weak self] result in
if result == NSApplication.ModalResponse.alertFirstButtonReturn {
guard let self else {
return
}
AccountManager.shared.deleteAccount(account)
self.hideController()
}
}
}
@objc func displayNameDidChange(_ note: Notification) {
reloadTablePreservingSelection()
}
@objc func accountsDidChange(_ note: Notification) {
if note.name == .UserDidAddAccount, let addedAccount = note.userInfo?[Account.UserInfoKey.account] as? Account {
reloadTable(selecting: addedAccount)
} else {
reloadTablePreservingSelection()
}
}
@objc func handleAccountRefreshStateChanged(_ note: Notification) {
updateDeleteButtonState()
}
}
// MARK: - NSTableViewDataSource
extension AccountsPreferencesViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
sortedAccounts.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
account(at: row)
}
}
// MARK: - NSTableViewDelegate
extension AccountsPreferencesViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), owner: nil) as? AccountCell {
guard let account = account(at: row) else {
return nil
}
cell.textField?.stringValue = account.nameForDisplay
cell.imageView?.image = account.smallIcon?.image
if account.type == .feedbin {
cell.isImageTemplateCapable = false
}
return cell
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
updateDeleteButtonState()
// A reload can report its selection more than once, so reloadTable(selecting:) updates the detail view when it settles.
if isReloadingTable {
return
}
updateDetailView()
}
}
extension AccountsPreferencesViewController: AccountsPreferencesAddAccountDelegate {
func presentSheetForAccount(_ accountType: AccountType) {
guard let window = view.window else {
return
}
switch accountType {
case .onMyMac:
let accountsAddLocalWindowController = AccountsAddLocalWindowController()
addAccountWindowController = accountsAddLocalWindowController
accountsAddLocalWindowController.runSheetOnWindow(window)
case .cloudKit:
let accountsAddCloudKitWindowController = AccountsAddCloudKitWindowController()
addAccountWindowController = accountsAddCloudKitWindowController
Task { @MainActor in
// No reload needed on OK — createAccount posts UserDidAddAccount, which reloads the table.
_ = await accountsAddCloudKitWindowController.runSheetOnWindow(window)
}
case .feedbin:
let accountsFeedbinWindowController = AccountsFeedbinWindowController()
addAccountWindowController = accountsFeedbinWindowController
accountsFeedbinWindowController.runSheetOnWindow(window)
case .freshRSS, .inoreader, .bazQux, .theOldReader:
let accountsReaderAPIWindowController = AccountsReaderAPIWindowController()
addAccountWindowController = accountsReaderAPIWindowController
accountsReaderAPIWindowController.accountType = accountType
accountsReaderAPIWindowController.runSheetOnWindow(window)
case .feedly:
let addAccount = OAuthAccountAuthorizationOperation(accountType: .feedly)
addAccount.delegate = self
addAccount.presentationAnchor = window
runAwaitingFeedlyLoginAlertModal(forLifetimeOf: addAccount)
MainThreadOperationQueue.shared.add(addAccount)
case .newsBlur:
let accountsNewsBlurWindowController = AccountsNewsBlurWindowController()
addAccountWindowController = accountsNewsBlurWindowController
accountsNewsBlurWindowController.runSheetOnWindow(window)
case .miniflux:
let accountsMinifluxWindowController = AccountsMinifluxWindowController()
addAccountWindowController = accountsMinifluxWindowController
accountsMinifluxWindowController.runSheetOnWindow(window)
}
}
private func runAwaitingFeedlyLoginAlertModal(forLifetimeOf operation: OAuthAccountAuthorizationOperation) {
let alert = NSAlert()
alert.alertStyle = .informational
alert.messageText = NSLocalizedString("Waiting for access to Feedly",
comment: "Alert title when adding a Feedly account and waiting for authorization from the user.")
alert.informativeText = NSLocalizedString("A web browser will open the Feedly login for you to authorize access.",
comment: "Alert informative text when adding a Feedly account and waiting for authorization from the user.")
alert.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel button"))
let attachedWindow = self.view.window!
alert.beginSheetModal(for: attachedWindow) { response in
if response == .alertFirstButtonReturn {
operation.cancel()
}
}
operation.completionBlock = { _ in
guard alert.window.isVisible else {
return
}
attachedWindow.endSheet(alert.window)
}
}
}
// MARK: - Private
private extension AccountsPreferencesViewController {
func account(at row: Int) -> Account? {
sortedAccounts[safe: row]
}
func updateSortedAccounts() {
sortedAccounts = AccountManager.shared.sortedAccounts
}
func reloadTablePreservingSelection() {
reloadTable(selecting: selectedAccount)
}
func reloadTable(selecting accountToSelect: Account?) {
updateSortedAccounts()
isReloadingTable = true
tableView.reloadData()
if let accountToSelect, let row = sortedAccounts.firstIndex(of: accountToSelect) {
tableView.selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
}
isReloadingTable = false
updateDeleteButtonState()
updateDetailView()
}
/// Reuses the existing detail view controller when it's already showing the selected account, so an in-progress edit isn't destroyed.
func updateDetailView() {
guard let selectedAccount else {
hideController()
return
}
let accountShowingInDetailView = (children.first as? AccountsDetailViewController)?.account
if accountShowingInDetailView == selectedAccount {
return
}
showController(AccountsDetailViewController(account: selectedAccount))
}
func updateDeleteButtonState() {
guard let selectedAccount else {
deleteButton.isEnabled = false
return
}
if selectedAccount == AccountManager.shared.defaultAccount {
deleteButton.isEnabled = false
return
}
deleteButton.isEnabled = !selectedAccount.refreshInProgress
}
func showController(_ controller: NSViewController) {
hideController()
addChild(controller)
controller.view.translatesAutoresizingMaskIntoConstraints = false
detailView.addSubview(controller.view)
detailView.addFullSizeConstraints(forSubview: controller.view)
}
func hideController() {
if let controller = children.first {
children.removeAll()
controller.view.removeFromSuperview()
}
if tableView.selectedRow == -1 {
var helpText = ""
if sortedAccounts.count == 0 {
helpText = NSLocalizedString("Add an account by clicking the + button.", comment: "Add Account Explainer")
} else {
helpText = NSLocalizedString("To add an account to NetNewsWire,\nclick its icon above.\n\nOr click the + button in the lower left.", comment: "Add Account Explainer")
}
let textHostingController = NSHostingController(rootView:
AddAccountHelpView(delegate: addAccountDelegate, helpText: helpText))
addChild(textHostingController)
textHostingController.view.translatesAutoresizingMaskIntoConstraints = false
detailView.addSubview(textHostingController.view)
detailView.addConstraints([
NSLayoutConstraint(item: textHostingController.view, attribute: .top, relatedBy: .equal, toItem: detailView, attribute: .top, multiplier: 1, constant: 1),
NSLayoutConstraint(item: textHostingController.view, attribute: .bottom, relatedBy: .equal, toItem: detailView, attribute: .bottom, multiplier: 1, constant: -deleteButton.frame.height),
NSLayoutConstraint(item: textHostingController.view, attribute: .width, relatedBy: .equal, toItem: detailView, attribute: .width, multiplier: 1, constant: 1)
])
}
}
}
extension AccountsPreferencesViewController: OAuthAccountAuthorizationOperationDelegate {
func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didCreate account: Account) {
// `OAuthAccountAuthorizationOperation` is using `ASWebAuthenticationSession` which bounces the user
// to their browser on macOS for authorizing NetNewsWire to access the user's Feedly account.
// When this authorization is granted, the browser remains the foreground app which is unfortunate
// because the user probably wants to see the result of authorizing NetNewsWire to act on their behalf.
NSApp.activate(ignoringOtherApps: true)
account.triggerRefreshAll()
}
func oauthAccountAuthorizationOperation(_ operation: OAuthAccountAuthorizationOperation, didFailWith error: Error) {
// `OAuthAccountAuthorizationOperation` is using `ASWebAuthenticationSession` which bounces the user
// to their browser on macOS for authorizing NetNewsWire to access the user's Feedly account.
NSApp.activate(ignoringOtherApps: true)
view.window?.presentError(error)
}
}