diff --git a/Mac/Preferences/Accounts/AccountsDetailViewController.swift b/Mac/Preferences/Accounts/AccountsDetailViewController.swift index 0a6f69cee..507853c95 100644 --- a/Mac/Preferences/Accounts/AccountsDetailViewController.swift +++ b/Mac/Preferences/Accounts/AccountsDetailViewController.swift @@ -57,6 +57,12 @@ final class AccountsDetailViewController: NSViewController { accountsNewsBlurWindowController.account = account accountsNewsBlurWindowController.runSheetOnWindow(window) + case .miniflux: + let accountsMinifluxWindowController = AccountsMinifluxWindowController() + accountsWindowController = accountsMinifluxWindowController + accountsMinifluxWindowController.account = account + accountsMinifluxWindowController.runSheetOnWindow(window) + default: break } diff --git a/Mac/Preferences/Accounts/AccountsMiniflux.xib b/Mac/Preferences/Accounts/AccountsMiniflux.xib new file mode 100644 index 000000000..028d71d41 --- /dev/null +++ b/Mac/Preferences/Accounts/AccountsMiniflux.xib @@ -0,0 +1,304 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + + + + + + + + + + + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Mac/Preferences/Accounts/AccountsMinifluxWindowController.swift b/Mac/Preferences/Accounts/AccountsMinifluxWindowController.swift new file mode 100644 index 000000000..f2ad89ba8 --- /dev/null +++ b/Mac/Preferences/Accounts/AccountsMinifluxWindowController.swift @@ -0,0 +1,232 @@ +// +// AccountsMinifluxWindowController.swift +// NetNewsWire +// +// Copyright © 2026 Ranchero Software. All rights reserved. +// + +import AppKit +import Account +import RSWeb +import Secrets + +final class AccountsMinifluxWindowController: NSWindowController { + + @IBOutlet var titleImageView: NSImageView! + @IBOutlet var titleLabel: NSTextField! + + @IBOutlet var gridView: NSGridView! + @IBOutlet var progressIndicator: NSProgressIndicator! + @IBOutlet var usernameTextField: NSTextField! + @IBOutlet var apiURLTextField: NSTextField! + @IBOutlet var passwordTextField: NSSecureTextField! + @IBOutlet var apiTokenTextField: NSSecureTextField! + @IBOutlet var authModeControl: NSSegmentedControl! + @IBOutlet var createAccountButton: NSButton! + @IBOutlet var errorMessageLabel: NSTextField! + @IBOutlet var actionButton: NSButton! + @IBOutlet var noAccountTextField: NSTextField! + + var account: Account? + + private weak var hostWindow: NSWindow? + + /// Fixed row indices in `gridView`: API URL, Username, Password, API Token. + private let usernameRowIndex = 1 + private let passwordRowIndex = 2 + private let apiTokenRowIndex = 3 + + convenience init() { + self.init(windowNibName: NSNib.Name("AccountsMiniflux")) + } + + override func windowDidLoad() { + titleImageView.image = Assets.Images.accountMiniflux + titleLabel.stringValue = NSLocalizedString("Sign in to your Miniflux account.", comment: "Miniflux") + noAccountTextField.stringValue = NSLocalizedString("Don’t have a Miniflux instance?", comment: "No Miniflux") + createAccountButton.title = NSLocalizedString("Find out more", comment: "No Miniflux Button") + apiURLTextField.placeholderString = NSLocalizedString("https://miniflux.example.com", comment: "Miniflux API Helper") + + authModeControl.selectedSegment = 0 + + if let account { + if let tokenCredentials = try? account.retrieveCredentials(type: .minifluxAPIToken) { + apiTokenTextField.stringValue = tokenCredentials.secret + authModeControl.selectedSegment = 1 + } else if let basicCredentials = try? account.retrieveCredentials(type: .minifluxBasic) { + usernameTextField.stringValue = basicCredentials.username + authModeControl.selectedSegment = 0 + } + apiURLTextField.stringValue = account.endpointURL?.absoluteString ?? "" + actionButton.title = NSLocalizedString("Update", comment: "Update") + } else { + actionButton.title = NSLocalizedString("Add", comment: "Add button") + } + + updateAuthModeVisibility() + enableAutofill() + apiURLTextField.becomeFirstResponder() + } + + // MARK: API + + func runSheetOnWindow(_ hostWindow: NSWindow, completion: ((NSApplication.ModalResponse) -> Void)? = nil) { + guard let window else { + return + } + + self.hostWindow = hostWindow + hostWindow.beginSheet(window, completionHandler: completion) + } + + // MARK: Actions + + @IBAction func cancel(_ sender: Any) { + hostWindow!.endSheet(window!, returnCode: NSApplication.ModalResponse.cancel) + } + + @IBAction func action(_ sender: Any) { + errorMessageLabel.stringValue = "" + + guard let apiURL = normalizedEndpointURL(from: apiURLTextField.stringValue) else { + errorMessageLabel.stringValue = NSLocalizedString("Invalid API URL.", comment: "Invalid API URL") + return + } + + let isTokenMode = authModeControl.selectedSegment == 1 + let credentials: Credentials + + if isTokenMode { + let token = apiTokenTextField.stringValue.trimmingWhitespace + guard !token.isEmpty else { + errorMessageLabel.stringValue = NSLocalizedString("An API token is required.", comment: "Credentials Error") + return + } + credentials = Credentials(type: .minifluxAPIToken, username: "", secret: token) + } else { + let trimmedUsername = usernameTextField.stringValue.trimmingWhitespace + let password = passwordTextField.stringValue + guard !trimmedUsername.isEmpty, !password.isEmpty else { + errorMessageLabel.stringValue = NSLocalizedString("Username and password are required.", comment: "Credentials Error") + return + } + credentials = Credentials(type: .minifluxBasic, username: trimmedUsername, secret: password) + } + + Task { @MainActor in + actionButton.isEnabled = false + progressIndicator.isHidden = false + progressIndicator.startAnimation(self) + + @MainActor func stopAnimation() { + actionButton.isEnabled = true + progressIndicator.isHidden = true + progressIndicator.stopAnimation(self) + } + + do { + let validatedCredentials = try await Account.validateCredentials(type: .miniflux, credentials: credentials, endpoint: apiURL) + stopAnimation() + + guard let validatedCredentials else { + errorMessageLabel.stringValue = NSLocalizedString("Invalid username/password combination, or invalid API token.", comment: "Credentials Error") + return + } + + guard account != nil || !AccountManager.shared.duplicateServiceAccount(type: .miniflux, endpointURL: apiURL, username: validatedCredentials.username) else { + errorMessageLabel.stringValue = NSLocalizedString("There is already a Miniflux account for this user on this server.", comment: "Duplicate Error") + return + } + + if account == nil { + account = AccountManager.shared.createAccount(type: .miniflux) + } + + do { + account?.endpointURL = apiURL + + // Remove any credentials of the other type so a stale token or + // password doesn't take precedence after switching auth modes. + let staleCredentialsType: CredentialsType = validatedCredentials.type == .minifluxAPIToken ? .minifluxBasic : .minifluxAPIToken + try? account?.removeCredentials(type: staleCredentialsType) + try account?.storeCredentials(validatedCredentials) + + hostWindow?.endSheet(window!, returnCode: NSApplication.ModalResponse.OK) + + let refreshingAccount = account + Task { @MainActor in + do { + try await refreshingAccount?.refreshAll() + } catch { + NSApplication.shared.presentError(error) + } + } + } catch { + errorMessageLabel.stringValue = NSLocalizedString("Keychain error while storing credentials.", comment: "Credentials Error") + } + + } catch { + stopAnimation() + errorMessageLabel.stringValue = error.localizedDescription + } + } + } + + @IBAction func createAccountWithProvider(_ sender: Any) { + NSWorkspace.shared.open(URL(string: "https://miniflux.app")!) + } + + @IBAction func authModeChanged(_ sender: Any) { + updateAuthModeVisibility() + } + + // MARK: Autofill + + func enableAutofill() { + usernameTextField.contentType = .username + passwordTextField.contentType = .password + } + + // MARK: Auth Mode + + private func updateAuthModeVisibility() { + let isTokenMode = authModeControl.selectedSegment == 1 + gridView.row(at: usernameRowIndex).isHidden = isTokenMode + gridView.row(at: passwordRowIndex).isHidden = isTokenMode + gridView.row(at: apiTokenRowIndex).isHidden = !isTokenMode + } + + // MARK: URL Normalization + + /// Trims whitespace, adds a `https://` scheme if none was given, drops a + /// trailing slash, and strips a trailing `/v1` path component in case the + /// user pasted the API URL rather than the instance's base URL — + /// e.g. `https://host/v1/` becomes `https://host`. + private func normalizedEndpointURL(from string: String) -> URL? { + var trimmed = string.trimmingWhitespace + guard !trimmed.isEmpty else { + return nil + } + + if !trimmed.contains("://") { + trimmed = "https://" + trimmed + } + + if trimmed.hasSuffix("/") { + trimmed = String(trimmed.dropLast()) + } + if trimmed.hasSuffix("/v1") { + trimmed = String(trimmed.dropLast(3)) + } + if trimmed.hasSuffix("/") { + trimmed = String(trimmed.dropLast()) + } + + guard !trimmed.isEmpty else { + return nil + } + + return URL(string: trimmed) + } + +} diff --git a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift index 57168c61d..72efe1ad8 100644 --- a/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift +++ b/Mac/Preferences/Accounts/AccountsPreferencesViewController.swift @@ -201,6 +201,11 @@ extension AccountsPreferencesViewController: AccountsPreferencesAddAccountDelega let accountsNewsBlurWindowController = AccountsNewsBlurWindowController() addAccountWindowController = accountsNewsBlurWindowController accountsNewsBlurWindowController.runSheetOnWindow(window) + + case .miniflux: + let accountsMinifluxWindowController = AccountsMinifluxWindowController() + addAccountWindowController = accountsMinifluxWindowController + accountsMinifluxWindowController.runSheetOnWindow(window) } } diff --git a/Mac/Preferences/Accounts/AddAccountsView.swift b/Mac/Preferences/Accounts/AddAccountsView.swift index 3831fa107..4f619f10c 100644 --- a/Mac/Preferences/Accounts/AddAccountsView.swift +++ b/Mac/Preferences/Accounts/AddAccountsView.swift @@ -60,7 +60,7 @@ enum AddAccountSections: Int, CaseIterable { return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader] } case .selfhosted: - return [.freshRSS] + return [.freshRSS, .miniflux] case .allOrdered: return AddAccountSections.local.sectionContent + AddAccountSections.icloud.sectionContent + diff --git a/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json new file mode 100644 index 000000000..a99b60f8b --- /dev/null +++ b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json @@ -0,0 +1,26 @@ +{ + "images" : [ + { + "filename" : "accountMiniflux.pdf", + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "accountMiniflux-dark.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf new file mode 100644 index 000000000..8b5c75013 Binary files /dev/null and b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf differ diff --git a/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf new file mode 100644 index 000000000..c3ff8b257 Binary files /dev/null and b/Mac/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf differ diff --git a/Mac/Scripting/Account+Scriptability.swift b/Mac/Scripting/Account+Scriptability.swift index 11116ad84..29ce88d21 100644 --- a/Mac/Scripting/Account+Scriptability.swift +++ b/Mac/Scripting/Account+Scriptability.swift @@ -230,6 +230,8 @@ import RSCore osType = "Bzqx" case .theOldReader: osType = "Tord" + case .miniflux: + osType = "Mnfx" } return osType.fourCharCode } diff --git a/Modules/Account/Package.swift b/Modules/Account/Package.swift index ec88c2f8d..f4e8b21c1 100644 --- a/Modules/Account/Package.swift +++ b/Modules/Account/Package.swift @@ -50,7 +50,7 @@ let package = Package( ), .testTarget( name: "AccountTests", - dependencies: ["Account"], + dependencies: ["Account", "SyncDatabase"], resources: [ .copy("JSON") ], diff --git a/Modules/Account/Sources/Account/Account.swift b/Modules/Account/Sources/Account/Account.swift index f882b2e44..0b9e020c7 100644 --- a/Modules/Account/Sources/Account/Account.swift +++ b/Modules/Account/Sources/Account/Account.swift @@ -48,6 +48,7 @@ nonisolated public enum AccountType: Int, Codable, Sendable { case inoreader = 21 case bazQux = 22 case theOldReader = 23 + case miniflux = 24 public var isDeveloperRestricted: Bool { return self == .cloudKit || self == .feedbin || self == .feedly || self == .inoreader @@ -74,6 +75,8 @@ nonisolated public enum AccountType: Int, Codable, Sendable { return NSLocalizedString("BazQux", comment: "Account name") case .theOldReader: return NSLocalizedString("The Old Reader", comment: "Account name") + case .miniflux: + return "Miniflux" } } } @@ -313,6 +316,8 @@ public enum FetchType { self.delegate = ReaderAPIAccountDelegate(dataFolder: dataFolder, variant: .bazQux) case .theOldReader: self.delegate = ReaderAPIAccountDelegate(dataFolder: dataFolder, variant: .theOldReader) + case .miniflux: + self.delegate = MinifluxAccountDelegate(dataFolder: dataFolder) } self.accountID = accountID @@ -411,6 +416,8 @@ public enum FetchType { return try await NewsBlurAccountDelegate.validateCredentials(credentials: credentials, endpoint: endpoint) case .freshRSS, .inoreader, .bazQux, .theOldReader: return try await ReaderAPIAccountDelegate.validateCredentials(credentials: credentials, endpoint: endpoint) + case .miniflux: + return try await MinifluxAccountDelegate.validateCredentials(credentials: credentials, endpoint: endpoint) default: return nil } @@ -1038,6 +1045,22 @@ public enum FetchType { await database.deleteAsync(articleIDs: articleIDs) } + /// Delete the statuses for the given articleIDs. Call this only when the sync + /// service has affirmatively reported the articles as deleted server-side. + /// + /// Statuses deliberately outlive their articles — they're the memory that stops + /// old articles from reappearing as unread, so no cleanup removes them early. + /// But a status whose article is gone from the service matches the + /// statuses-without-articles query on every sync, and the delegate re-requests + /// an article the service will never return. When the service says the article + /// is deleted, removing the status is correct and ends that loop. + func deleteStatuses(articleIDs: Set) async { + guard !articleIDs.isEmpty else { + return + } + await database.deleteStatusesAsync(articleIDs: articleIDs) + } + /// Empty caches that can reasonably be emptied. Call when the app goes in the background, for instance. func emptyCaches() { database.emptyCaches() diff --git a/Modules/Account/Sources/Account/AccountManager.swift b/Modules/Account/Sources/Account/AccountManager.swift index cedffe546..5a9e1de98 100644 --- a/Modules/Account/Sources/Account/AccountManager.swift +++ b/Modules/Account/Sources/Account/AccountManager.swift @@ -255,6 +255,33 @@ import ActivityLog return false } + public func duplicateServiceAccount(type: AccountType, endpointURL: URL?, username: String?) -> Bool { + Self.duplicateServiceAccount(type: type, endpointURL: endpointURL, username: username, among: accounts) + } + + /// A self-hosted server can have several users, so only the same user on the same server is a duplicate. + static func duplicateServiceAccount(type: AccountType, endpointURL: URL?, username: String?, among accounts: [Account]) -> Bool { + guard type != .onMyMac, let normalizedEndpoint = Self.normalizedEndpointForComparison(endpointURL) else { + return false + } + return accounts.contains { $0.type == type && $0.username == username && Self.normalizedEndpointForComparison($0.endpointURL) == normalizedEndpoint } + } + + /// Normalizes for duplicate-server comparison: lowercases scheme/host (case-insensitive + /// per RFC 3986) and drops a trailing slash from the path, so `https://Host.example/` and + /// `https://host.example` compare equal. + static func normalizedEndpointForComparison(_ url: URL?) -> String? { + guard var components = url.flatMap({ URLComponents(url: $0, resolvingAgainstBaseURL: false) }) else { + return nil + } + components.scheme = components.scheme?.lowercased() + components.host = components.host?.lowercased() + if components.path.hasSuffix("/") { + components.path.removeLast() + } + return components.string + } + public func existingAccount(accountID: String) -> Account? { return accountsDictionary[accountID] } diff --git a/Modules/Account/Sources/Account/AccountSettings.swift b/Modules/Account/Sources/Account/AccountSettings.swift index f3bb39838..4486c9bec 100644 --- a/Modules/Account/Sources/Account/AccountSettings.swift +++ b/Modules/Account/Sources/Account/AccountSettings.swift @@ -21,6 +21,7 @@ import RSWeb case lastArticleFetchStartTime case lastRefreshCompletedDate case endpointURL + case detectedServerVersion case externalID case imported } @@ -130,6 +131,17 @@ import RSWeb } } + /// The sync server's self-reported version string (e.g. "2.4.1"), for services whose + /// available endpoints vary by version. `nil` until the first successful detection. + var detectedServerVersion: String? { + get { + UserDefaults.standard.string(forKey: defaultsKey(.detectedServerVersion)) + } + set { + UserDefaults.standard.set(newValue, forKey: defaultsKey(.detectedServerVersion)) + } + } + var externalID: String? { get { UserDefaults.standard.string(forKey: defaultsKey(.externalID)) diff --git a/Modules/Account/Sources/Account/Miniflux/Miniflux.swift b/Modules/Account/Sources/Account/Miniflux/Miniflux.swift new file mode 100644 index 000000000..9edffe39e --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/Miniflux.swift @@ -0,0 +1,15 @@ +// +// Miniflux.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import os + +struct Miniflux { + // Convention with this logger is to put "Miniflux: " at the beginning of each message. + static let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "NetNewsWire", category: "Miniflux") +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxAPICaller.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxAPICaller.swift new file mode 100644 index 000000000..3bb43dc3b --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxAPICaller.swift @@ -0,0 +1,419 @@ +// +// MinifluxAPICaller.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import RSWeb +import Secrets + +@MainActor final class MinifluxAPICaller { + + // Miniflux rejects limit values above 1000 for /v1/entries with HTTP 400, so stay under that. + static let entriesPageSize = 500 + // Miniflux caps /v1/entries/ids at MaxEntryIDsLimit (10000) per response, so page at that size. + static let entryIDsPageSize = 10000 + static let statusChunkSize = 1000 + + private static let minimumVersion = MinifluxVersion(2, 0, 49) + // /v1/entries/ids and batch starred updates require this newer version; below it, + // MinifluxAPICaller transparently falls back to paged /v1/entries and per-entry toggles. + private static let entryIDsMinimumVersion = MinifluxVersion(2, 3, 2) + + private let session = URLSession.makeWebserviceSession() + private var suspended = false + + var credentials: Credentials? + var accountSettings: AccountSettings? + + var server: String? { + apiBaseURL?.host + } + + private var apiBaseURL: URL? { + accountSettings?.endpointURL + } + + /// Cancels all pending requests and rejects any that come in later. + func suspend() { + session.cancelAll() + suspended = true + } + + func resume() { + suspended = false + } + + /// Validates credentials against a caller-supplied endpoint. This runs before an Account exists, + /// so it can’t rely on `accountSettings` (and thus not on `makeRequest`). + func validateCredentials(endpoint: URL) async throws -> Credentials? { + if suspended { + throw WebserviceError.suspended + } + guard let credentials else { + throw CredentialsError.missingUsername + } + + let callURL = endpoint.appendingPathComponent("v1/me") + let request = URLRequest(url: callURL, credentials: credentials) + + let validatedCredentials: Credentials + do { + let (_, me) = try await session.send(request: request, resultType: MinifluxUser.self) + guard let me else { + throw WebserviceError.noData + } + + validatedCredentials = credentials.username.isEmpty ? Credentials(type: credentials.type, username: me.username, secret: credentials.secret) : credentials + } catch { + if case WebserviceError.httpError(let status, _) = error { + if status == HTTPResponseCode.unauthorized { + return nil + } + if status == HTTPResponseCode.notFound { + throw AccountError.urlNotFound + } + } + throw error + } + + try await validateServerVersion(endpoint: endpoint) + + return validatedCredentials + } + + /// Re-detects the server version and persists it to account settings, so + /// `supportsEntryIDsEndpoint`/`supportsBatchStarredUpdates` pick up a server upgrade + /// without the account being recreated. Called once per `refreshAll()`, from a point + /// where `accountSettings` is guaranteed set. Best-effort: any failure just leaves the + /// previously detected version (if any) in place, and gating already treats an unknown + /// version conservatively. + func detectServerVersion() async { + guard let apiBaseURL else { + return + } + guard let response = try? await fetchVersionResponse(endpoint: apiBaseURL) else { + return + } + accountSettings?.detectedServerVersion = response.version + } + + func retrieveCategories() async throws -> [MinifluxCategory] { + try await fetch("categories") + } + + func createCategory(title: String) async throws -> MinifluxCategory { + var request = try makeRequest(path: "categories") + request.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType) + + let payload = try JSONEncoder().encode(MinifluxCategoryPayload(title: title)) + let (_, category) = try await session.send(request: request, method: HTTPMethod.post, data: payload, resultType: MinifluxCategory.self) + + guard let category else { + throw WebserviceError.noData + } + return category + } + + func renameCategory(categoryID: Int64, title: String) async throws { + try await session.send(request: makeRequest(path: "categories/\(categoryID)"), method: HTTPMethod.put, payload: MinifluxCategoryPayload(title: title)) + } + + func deleteCategory(categoryID: Int64) async throws { + try await session.send(request: makeRequest(path: "categories/\(categoryID)"), method: HTTPMethod.delete) + } + + func retrieveFeeds() async throws -> [MinifluxFeed] { + try await fetch("feeds") + } + + /// On failure, attempts to decode a `MinifluxErrorResponse` from the response body to distinguish + /// “feed already exists” from other errors. Miniflux has no machine-readable error code for this, + /// so this is a heuristic based on the human-readable `error_message` text. Any other decodable + /// server error is surfaced as `MinifluxError.serverError` with the server's message; otherwise + /// the failure is reported as a plain HTTP error. + func createFeed(url urlString: String, categoryID: Int64) async throws -> Int64 { + var request = try makeRequest(path: "feeds") + request.addValue("application/json; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType) + request.httpMethod = HTTPMethod.post + request.httpBody = try JSONEncoder().encode(MinifluxCreateFeed(feedURL: urlString, categoryID: categoryID)) + + let (data, urlResponse) = try await session.data(for: request) + + guard (200...399).contains(urlResponse.forcedStatusCode) else { + if let errorResponse = try? JSONDecoder().decode(MinifluxErrorResponse.self, from: data) { + if errorResponse.errorMessage.contains("already exists") { + throw AccountError.createErrorAlreadySubscribed + } + throw MinifluxError.serverError(message: errorResponse.errorMessage) + } + throw WebserviceError.httpError(status: urlResponse.forcedStatusCode, responseBody: nil) + } + + guard !data.isEmpty else { + throw WebserviceError.noData + } + let response = try JSONDecoder().decode(MinifluxCreateFeedResponse.self, from: data) + return response.feedID + } + + func retrieveFeed(feedID: Int64) async throws -> MinifluxFeed { + try await fetch("feeds/\(feedID)") + } + + func renameFeed(feedID: Int64, title: String) async throws { + try await session.send(request: makeRequest(path: "feeds/\(feedID)"), method: HTTPMethod.put, payload: MinifluxUpdateFeed(title: title, categoryID: nil)) + } + + func moveFeed(feedID: Int64, categoryID: Int64) async throws { + try await session.send(request: makeRequest(path: "feeds/\(feedID)"), method: HTTPMethod.put, payload: MinifluxUpdateFeed(title: nil, categoryID: categoryID)) + } + + func deleteFeed(feedID: Int64) async throws { + try await session.send(request: makeRequest(path: "feeds/\(feedID)"), method: HTTPMethod.delete) + } + + func retrieveEntries(offset: Int, changedAfter: Date?, publishedAfter: Date?) async throws -> MinifluxEntriesResponse { + var query = Self.entriesPageQueryItems(offset: offset) + if let changedAfter { + query.append(URLQueryItem(name: "changed_after", value: String(Int(changedAfter.timeIntervalSince1970)))) + } + if let publishedAfter { + query.append(URLQueryItem(name: "published_after", value: String(Int(publishedAfter.timeIntervalSince1970)))) + } + + return try await fetch("entries", query: query) + } + + func retrieveEntries(feedID: Int64, offset: Int) async throws -> MinifluxEntriesResponse { + try await fetch("feeds/\(feedID)/entries", query: Self.entriesPageQueryItems(offset: offset)) + } + + /// Returns `nil` if the entry has been removed server-side. + func retrieveEntry(entryID: Int64) async throws -> MinifluxEntry? { + do { + return try await fetch("entries/\(entryID)") + } catch { + if case WebserviceError.httpError(let status, _) = error, status == HTTPResponseCode.notFound { + return nil + } + throw error + } + } + + func retrieveUnreadEntryIDs() async throws -> Set { + try await retrieveEntryIDs(matching: [URLQueryItem(name: "status", value: "unread")]) + } + + func retrieveStarredEntryIDs() async throws -> Set { + try await retrieveEntryIDs(matching: [URLQueryItem(name: "starred", value: "true")]) + } + + func updateEntries(entryIDs: [Int64], read: Bool) async throws { + try await updateEntries(entryIDs: entryIDs, payload: MinifluxUpdateEntriesPayload(entryIDs: entryIDs, status: read ? "read" : "unread", starred: nil)) + } + + /// Uses the batch endpoint on servers that support it (2.3.2+), where `starred` is + /// absolute state, not a toggle. Older servers (down to the 2.0.49 floor) only expose a + /// per-entry bookmark *toggle* (`PUT /v1/entries/{id}/bookmark`), which flips state + /// rather than setting it — see `updateEntriesStarredFallback`. + func updateEntries(entryIDs: [Int64], starred: Bool) async throws { + guard !entryIDs.isEmpty else { + return + } + if supportsBatchStarredUpdates { + try await updateEntries(entryIDs: entryIDs, payload: MinifluxUpdateEntriesPayload(entryIDs: entryIDs, status: nil, starred: starred)) + } else { + try await updateEntriesStarredFallback(entryIDs: entryIDs, starred: starred) + } + } + + /// Synchronous — Miniflux’s OPML import doesn’t require polling for completion. + func importOPML(opmlData: Data) async throws { + var request = try makeRequest(path: "import") + request.addValue("text/xml; charset=utf-8", forHTTPHeaderField: HTTPRequestHeader.contentType) + + _ = try await session.send(request: request, method: HTTPMethod.post, payload: opmlData) + } +} + +// MARK: Private + +private extension MinifluxAPICaller { + + /// Builds an authenticated request for `v1/`, honoring `suspend()`. Auth for both + /// `.minifluxBasic` and `.minifluxAPIToken` is applied inside `URLRequest(url:credentials:)`. + func makeRequest(path: String, query: [URLQueryItem] = []) throws -> URLRequest { + if suspended { + throw WebserviceError.suspended + } + return URLRequest(url: try apiURL(path: path, queryItems: query), credentials: credentials) + } + + /// Sends a GET for `v1/` and decodes the JSON body. + func fetch(_ path: String, query: [URLQueryItem] = []) async throws -> R { + let (_, result) = try await session.send(request: makeRequest(path: path, query: query), resultType: R.self) + guard let result else { + throw WebserviceError.noData + } + return result + } + + /// Pages through `/v1/entries/ids` on servers that support it (2.3.2+), which caps each + /// response at `entryIDsPageSize`; older servers (down to the 2.0.49 floor) fall back to + /// paging `/v1/entries` instead. `filter` is `status=unread`, `starred=true`, etc. — the + /// same filter works on both endpoints. + func retrieveEntryIDs(matching filter: [URLQueryItem]) async throws -> Set { + guard supportsEntryIDsEndpoint else { + return try await retrieveEntryIDsByPagingEntries(matching: filter) + } + + var entryIDs = Set() + var offset = 0 + + while true { + let query = filter + [ + URLQueryItem(name: "limit", value: String(Self.entryIDsPageSize)), + URLQueryItem(name: "offset", value: String(offset)) + ] + let response: MinifluxEntryIDsResponse = try await fetch("entries/ids", query: query) + + entryIDs.formUnion(response.entryIDs) + offset += response.entryIDs.count + if response.entryIDs.isEmpty || offset >= response.total { + break + } + } + + return entryIDs + } + + /// Fallback for servers below `entryIDsMinimumVersion`, which lack `/v1/entries/ids`. + /// Used only for the initial sync's one-time reconciliation (see + /// `MinifluxAccountDelegate.reconcileAllArticleStatuses`) — never on routine refreshes — + /// so a full paginated scan here is a one-time cost, not a recurring one. + func retrieveEntryIDsByPagingEntries(matching filter: [URLQueryItem]) async throws -> Set { + var entryIDs = Set() + var offset = 0 + + while true { + let response: MinifluxEntriesResponse = try await fetch("entries", query: filter + Self.entriesPageQueryItems(offset: offset)) + entryIDs.formUnion(response.entries.map { $0.entryID }) + offset += response.entries.count + if response.entries.isEmpty || offset >= response.total { + break + } + } + + return entryIDs + } + + func updateEntries(entryIDs: [Int64], payload: MinifluxUpdateEntriesPayload) async throws { + guard !entryIDs.isEmpty else { + return + } + try await session.send(request: makeRequest(path: "entries"), method: HTTPMethod.put, payload: payload) + } + + /// Fallback for servers below `entryIDsMinimumVersion`: fetches each entry's current + /// starred state and only calls the toggle when it actually differs from `starred`. + /// This is the important part — the toggle endpoint flips state, so blindly calling it + /// on an entry already in the desired state would set it *wrong*. Fetch-then-compare + /// also makes retries safe: if this throws partway through and the caller resets the + /// whole chunk for a retry, re-running re-checks each entry's now-current state and + /// skips the ones already fixed, rather than toggling them a second time. + func updateEntriesStarredFallback(entryIDs: [Int64], starred: Bool) async throws { + for entryID in entryIDs { + guard let entry = try await retrieveEntry(entryID: entryID) else { + continue // Gone server-side; nothing to update. + } + guard entry.starred != starred else { + continue // Already correct — toggling would flip it the wrong way. + } + try await toggleBookmark(entryID: entryID) + } + } + + func toggleBookmark(entryID: Int64) async throws { + try await session.send(request: makeRequest(path: "entries/\(entryID)/bookmark"), method: HTTPMethod.put) + } + + static func entriesPageQueryItems(offset: Int) -> [URLQueryItem] { + [ + URLQueryItem(name: "order", value: "id"), + URLQueryItem(name: "direction", value: "asc"), + URLQueryItem(name: "limit", value: String(entriesPageSize)), + URLQueryItem(name: "offset", value: String(offset)) + ] + } + + /// Requires the server response before this call to have already confirmed credentials + /// are valid — a plain 404 here means the server predates `/v1/version` (< 2.0.49). + func validateServerVersion(endpoint: URL) async throws { + let response: MinifluxVersionResponse + do { + response = try await fetchVersionResponse(endpoint: endpoint) + } catch { + if case WebserviceError.httpError(let status, _) = error, status == HTTPResponseCode.notFound { + throw MinifluxError.serverVersionTooOld(foundVersion: nil) + } + throw error + } + + guard let version = MinifluxVersion(string: response.version) else { + return + } + guard version >= Self.minimumVersion else { + throw MinifluxError.serverVersionTooOld(foundVersion: response.version) + } + } + + func fetchVersionResponse(endpoint: URL) async throws -> MinifluxVersionResponse { + let callURL = endpoint.appendingPathComponent("v1/version") + let request = URLRequest(url: callURL, credentials: credentials) + let (_, versionResponse) = try await session.send(request: request, resultType: MinifluxVersionResponse.self) + guard let versionResponse else { + throw WebserviceError.noData + } + return versionResponse + } + + /// `nil` until a `detectServerVersion()` call has succeeded at least once this app + /// session (or in a previous one, since it's persisted). + var detectedVersion: MinifluxVersion? { + accountSettings?.detectedServerVersion.flatMap(MinifluxVersion.init(string:)) + } + + /// `false` (the safe default) when the version hasn't been detected yet, failed to + /// parse, or is below `entryIDsMinimumVersion` — the fallback works on every server + /// this app supports (down to the 2.0.49 floor), so "unknown" must resolve to "fall back." + var supportsEntryIDsEndpoint: Bool { + guard let detectedVersion else { + return false + } + return detectedVersion >= Self.entryIDsMinimumVersion + } + + var supportsBatchStarredUpdates: Bool { + supportsEntryIDsEndpoint // Same 2.3.2 threshold as the ids endpoint. + } + + func apiURL(path: String, queryItems: [URLQueryItem] = []) throws -> URL { + guard let apiBaseURL else { + throw CredentialsError.missingEndpointURL + } + + let base = apiBaseURL.appendingPathComponent("v1/\(path)") + guard !queryItems.isEmpty else { + return base + } + + guard let url = base.appendingQueryItems(queryItems) else { + throw WebserviceError.noURL + } + return url + } +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxAccountDelegate.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxAccountDelegate.swift new file mode 100644 index 000000000..bf2cd7622 --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxAccountDelegate.swift @@ -0,0 +1,1065 @@ +// +// MinifluxAccountDelegate.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import ActivityLog +import Articles +import ErrorLog +import FeedFinder +import RSCore +import RSParser +import RSWeb +import SyncDatabase +import os +import Secrets + +@MainActor final class MinifluxAccountDelegate: AccountDelegate { + weak var account: Account? + let behaviors: AccountBehaviors = [.disallowFeedInRootFolder, .disallowFeedInMultipleFolders] + var isOPMLImportInProgress = false + + var server: String? { + caller.server + } + + var progressInfo = ProgressInfo() { + didSet { + if progressInfo != oldValue { + postProgressInfoDidChangeNotification() + } + } + } + let refreshProgress = RSProgress() + + var credentials: Credentials? { + didSet { + caller.credentials = credentials + } + } + + var accountSettings: AccountSettings? { + didSet { + caller.accountSettings = accountSettings + } + } + + private let syncDatabase: SyncDatabase + private let caller: MinifluxAPICaller + private static let logger = Miniflux.logger + /// Send statuses immediately once this many are queued, rather than waiting for the next scheduled sync. + private static let sendStatusBatchThreshold = 100 + + init(dataFolder: String) { + let databaseFilePath = (dataFolder as NSString).appendingPathComponent("Sync.sqlite3") + syncDatabase = SyncDatabase(databasePath: databaseFilePath) + caller = MinifluxAPICaller() + + NotificationCenter.default.addObserver(self, selector: #selector(progressInfoDidChange(_:)), name: .progressInfoDidChange, object: refreshProgress) + } + + func receiveRemoteNotification(userInfo: [AnyHashable: Any]) async { + } + + func refreshAll() async throws { + guard let account else { + return + } + retrieveCredentialsIfNeeded(account) + + refreshProgress.reset() + // Five tasks completed across refreshAccount and refreshArticlesAndStatuses: + // categories fetch, feeds fetch, local folder/feed sync, the first page of + // articles, and missing articles. Continuation article pages add their own + // tasks as they're fetched. + refreshProgress.addTasks(5) + + do { + try await account.logActivity(kind: .refreshAll) { + try await refreshAccount(account) + try await refreshArticlesAndStatuses(account) + } + } catch { + refreshProgress.reset() + throw AccountError.wrapped(error, account) + } + } + + func syncArticleStatus() async throws -> Bool { + guard let account else { + return false + } + let sentCount = try await sendArticleStatusReturningCount(for: account) + let refreshedCount = try await refreshArticles(account) + return sentCount > 0 || refreshedCount > 0 + } + + func sendArticleStatus() async throws { + guard let account else { + return + } + _ = try await sendArticleStatusReturningCount(for: account) + } + + /// Sends queued local status changes upstream. Returns the count successfully sent. + private func sendArticleStatusReturningCount(for account: Account) async throws -> Int { + Self.logger.info("Miniflux: Sending article statuses") + defer { + Self.logger.info("Miniflux: Finished sending article statuses") + } + + do { + return try await account.logActivity(kind: .sendArticleStatuses) { () -> Int in + guard let syncStatuses = try? await syncDatabase.selectForProcessing() else { + Self.logger.error("Miniflux: Sync database selectForProcessing failed") + return 0 + } + + var sentCount = 0 + + sentCount += try await sendEntryStatuses(pendingEntryIDs(in: syncStatuses, key: .read, flag: true), key: .read) { + try await caller.updateEntries(entryIDs: $0, read: true) + } + sentCount += try await sendEntryStatuses(pendingEntryIDs(in: syncStatuses, key: .read, flag: false), key: .read) { + try await caller.updateEntries(entryIDs: $0, read: false) + } + sentCount += try await sendEntryStatuses(pendingEntryIDs(in: syncStatuses, key: .starred, flag: true), key: .starred) { + try await caller.updateEntries(entryIDs: $0, starred: true) + } + sentCount += try await sendEntryStatuses(pendingEntryIDs(in: syncStatuses, key: .starred, flag: false), key: .starred) { + try await caller.updateEntries(entryIDs: $0, starred: false) + } + + return sentCount + } + } catch { + postSyncError(error, account: account, operation: "Sending article status") + throw error + } + } + + /// Status changes arrive via the changed_after entries fetch (statuses ride along + /// with content), so refreshing statuses is the same operation as refreshing articles. + func refreshArticleStatus() async throws { + guard let account else { + return + } + _ = try await refreshArticles(account) + } + + /// Full reconciliation against the server's complete unread/starred ID sets. Used only + /// on initial sync now — routine refreshes get status changes from the changed_after + /// entries fetch. Returns the count of articles whose local state actually changed. + private func reconcileAllArticleStatuses(for account: Account) async throws -> Int { + Self.logger.info("Miniflux: Refreshing article statuses") + + return try await account.logActivity(kind: .refreshArticleStatuses) { () -> Int in + var changedCount = 0 + var refreshError: Error? + + async let pendingUnreadEntryIDs = caller.retrieveUnreadEntryIDs() + async let pendingStarredEntryIDs = caller.retrieveStarredEntryIDs() + + do { + let entryIDs = try await pendingUnreadEntryIDs + changedCount += await self.syncArticleReadState(account: account, entryIDs: entryIDs) + } catch { + refreshError = error + Self.logger.error("Miniflux: Retrieving unread entries failed: \(error.localizedDescription)") + } + + do { + let entryIDs = try await pendingStarredEntryIDs + changedCount += await self.syncArticleStarredState(account: account, entryIDs: entryIDs) + } catch { + refreshError = error + Self.logger.error("Miniflux: Retrieving starred entries failed: \(error.localizedDescription)") + } + + Self.logger.info("Miniflux: Finished refreshing article statuses") + if let refreshError { + postSyncError(refreshError, account: account, operation: "Refreshing article status") + throw refreshError + } + return changedCount + } + } + + func importOPML(opmlFile: URL) async throws { + guard let account else { + return + } + let opmlData = try Data(contentsOf: opmlFile) + guard !opmlData.isEmpty else { + return + } + + Self.logger.info("Miniflux: Did begin importing OPML") + isOPMLImportInProgress = true + refreshProgress.addTask() + defer { + isOPMLImportInProgress = false + refreshProgress.completeTask() + } + + do { + try await account.logActivity(kind: .importOPML, detail: opmlFile.lastPathComponent) { + try await caller.importOPML(opmlData: opmlData) + Self.logger.info("Miniflux: Finished importing OPML") + } + } catch { + Self.logger.info("Miniflux: OPML import failed: \(error.localizedDescription)") + throw AccountError.wrapped(error, account) + } + } + + func createFolder(name: String) async throws -> Folder { + guard let account else { + throw AccountError.invalidParameter + } + guard !name.isEmpty else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + return try await account.logActivity(kind: .createFolder, detail: name) { + let category = try await caller.createCategory(title: name) + guard let folder = account.ensureFolder(with: name) else { + throw AccountError.invalidParameter + } + folder.externalID = String(category.categoryID) + return folder + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func renameFolder(with folder: Folder, to name: String) async throws { + guard let account else { + return + } + guard let externalID = folder.externalID, let categoryID = Int64(externalID) else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + try await account.logActivity(kind: .renameFolder, detail: folder.name) { + try await caller.renameCategory(categoryID: categoryID, title: name) + folder.name = name + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func removeFolder(with folder: Folder) async throws { + guard let account else { + return + } + guard let externalID = folder.externalID, let categoryID = Int64(externalID) else { + throw AccountError.invalidParameter + } + + try await account.logActivity(kind: .removeFolder, detail: folder.name) { + refreshProgress.addTasks(folder.topLevelFeeds.count) + + for feed in folder.topLevelFeeds { + defer { refreshProgress.completeTask() } + + guard let feedExternalID = feed.externalID, let feedID = Int64(feedExternalID) else { + continue + } + do { + try await caller.deleteFeed(feedID: feedID) + account.clearFeedSettings(feed) + } catch { + Self.logger.error("Miniflux: Remove feed error: \(error.localizedDescription)") + postSyncError(error, account: account, operation: "Removing feed") + } + } + + // Miniflux refuses to delete a category that still has feeds — throw rather than + // silently leaving the folder gone locally but present on the server. + try await caller.deleteCategory(categoryID: categoryID) + account.removeFolderFromTree(folder) + } + } + + @discardableResult + func createFeed(url urlString: String, name: String?, container: Container, validateFeed: Bool) async throws -> Feed { + guard let account else { + throw AccountError.invalidParameter + } + guard let url = URL(string: urlString) else { + throw AccountError.invalidParameter + } + + refreshProgress.addTasks(2) + var uncompletedTasks = 2 + defer { + while uncompletedTasks > 0 { + refreshProgress.completeTask() + uncompletedTasks -= 1 + } + } + + do { + return try await account.logActivity(kind: .subscribeFeed, detail: url.absoluteString) { + let feedSpecifiers = try await FeedFinder.find(url: url) + refreshProgress.completeTask() + uncompletedTasks -= 1 + + guard let bestFeedSpecifier = FeedSpecifier.bestFeed(in: feedSpecifiers) else { + throw AccountError.createErrorNotFound + } + + let categoryID = try await categoryID(for: container) + let feedID = try await caller.createFeed(url: bestFeedSpecifier.urlString, categoryID: categoryID) + refreshProgress.completeTask() + uncompletedTasks -= 1 + + return try await createFeed(account: account, feedID: feedID, name: name, container: container) + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func renameFeed(with feed: Feed, to name: String) async throws { + guard let account else { + return + } + guard let externalID = feed.externalID, let feedID = Int64(externalID) else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + try await account.logActivity(kind: .renameFeed, detail: feed.url) { + try await caller.renameFeed(feedID: feedID, title: name) + feed.editedName = name + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func removeFeed(feed: Feed, container: Container) async throws { + guard let account else { + return + } + guard let externalID = feed.externalID, let feedID = Int64(externalID) else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + try await account.logActivity(kind: .removeFeed, detail: feed.url) { + try await caller.deleteFeed(feedID: feedID) + account.clearFeedSettings(feed) + account.removeAllInstancesOfFeedFromTreeAtAllLevels(feed) + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func moveFeed(feed: Feed, sourceContainer: Container, destinationContainer: Container) async throws { + guard let account else { + return + } + guard + let feedExternalID = feed.externalID, + let feedID = Int64(feedExternalID), + let destinationExternalID = (destinationContainer as? Folder)?.externalID, + let destinationCategoryID = Int64(destinationExternalID) + else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + try await account.logActivity(kind: .moveFeed, detail: feed.url) { + try await caller.moveFeed(feedID: feedID, categoryID: destinationCategoryID) + sourceContainer.removeFeedFromTreeAtTopLevel(feed) + destinationContainer.addFeedToTreeAtTopLevel(feed) + } + } catch { + throw AccountError.wrapped(error, account) + } + } + + func addFeed(feed: Feed, container: Container) async throws { + guard let account else { + return + } + try await account.logActivity(kind: .addFeed, detail: feed.url) { + if let folder = container as? Folder { + guard + let feedExternalID = feed.externalID, + let feedID = Int64(feedExternalID), + let folderExternalID = folder.externalID, + let destinationCategoryID = Int64(folderExternalID) + else { + throw AccountError.invalidParameter + } + + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + do { + try await caller.moveFeed(feedID: feedID, categoryID: destinationCategoryID) + account.removeFeedFromTreeAtTopLevel(feed) + folder.addFeedToTreeAtTopLevel(feed) + } catch { + throw AccountError.wrapped(error, account) + } + } else if let containerAccount = container as? Account { + containerAccount.addFeedIfNotInAnyFolder(feed) + } + } + } + + func restoreFeed(feed: Feed, container: Container) async throws { + guard let account else { + return + } + if let existingFeed = account.existingFeed(withURL: feed.url) { + try await account.addFeed(existingFeed, container: container) + } else { + try await createFeed(url: feed.url, name: feed.editedName, container: container, validateFeed: true) + } + } + + func restoreFolder(folder: Folder) async throws { + guard let account else { + return + } + await account.logActivity(kind: .restoreFolder, detail: folder.name ?? "") { + // The category was deleted server-side along with the folder — re-create it and + // point the folder at the new externalID before restoring its member feeds. + do { + let category = try await caller.createCategory(title: folder.name ?? "") + folder.externalID = String(category.categoryID) + } catch { + Self.logger.error("Miniflux: Restore folder category error: \(error.localizedDescription)") + postSyncError(error, account: account, operation: "Restoring folder") + return + } + + for feed in folder.topLevelFeeds { + folder.topLevelFeeds.remove(feed) + + do { + try await restoreFeed(feed: feed, container: folder) + } catch { + Self.logger.error("Miniflux: Restore folder feed error: \(error.localizedDescription)") + postSyncError(error, account: account, operation: "Restoring feed") + } + } + + account.addFolderToTree(folder) + } + } + + func markArticles(articleIDs: Set, statusKey: ArticleStatus.Key, flag: Bool) async throws { + guard let account else { + return + } + let changedArticleIDs = await account.updateStatusesAsync(articleIDs: articleIDs, statusKey: statusKey, flag: flag) + let syncStatuses = Set(changedArticleIDs.map { articleID in + SyncStatus(articleID: articleID, key: SyncStatus.Key(statusKey), flag: flag) + }) + + await syncDatabase.insertStatuses(syncStatuses) + if !syncStatuses.isEmpty { + NotificationCenter.default.post(name: .AccountDidQueueArticleStatuses, object: account) + } + if let count = try? await syncDatabase.selectPendingCount(), count > Self.sendStatusBatchThreshold { + try await sendArticleStatus() + } + } + + func accountDidInitialize() { + guard let account else { + return + } + retrieveCredentialsIfNeeded(account) + } + + func accountWillBeDeleted() { + } + + static func validateCredentials(credentials: Credentials, endpoint: URL?) async throws -> Credentials? { + guard let endpoint else { + throw WebserviceError.noURL + } + + let caller = MinifluxAPICaller() + caller.credentials = credentials + return try await caller.validateCredentials(endpoint: endpoint) + } + + func vacuumDatabases() async { + guard let account else { + return + } + await account.logActivity(kind: .vacuumDatabase, detail: AppConfig.relativeDataPath(syncDatabase.databasePath)) { + await syncDatabase.vacuum() + } + } + + // MARK: Suspend and Resume + + /// Suspend all network activity + func suspendNetwork() { + caller.suspend() + } + + /// Resume network activity after a previous `suspendNetwork()`. + func resume() { + if let account { + retrieveCredentialsIfNeeded(account) + } + caller.resume() + } + + // MARK: - Notifications + @objc func progressInfoDidChange(_ notification: Notification) { + progressInfo = refreshProgress.progressInfo + } +} + +// MARK: Private + +private extension MinifluxAccountDelegate { + + func retrieveCredentialsIfNeeded(_ account: Account) { + guard credentials == nil else { + return + } + credentials = (try? account.retrieveCredentials(type: .minifluxAPIToken)) ?? (try? account.retrieveCredentials(type: .minifluxBasic)) + } + + func refreshAccount(_ account: Account) async throws { + do { + try await account.logActivity(kind: .refreshFeedList, successMessage: { "\($0.feeds) feeds, \($0.folders) folders" }, { () -> (folders: Int, feeds: Int) in + await self.caller.detectServerVersion() + + async let pendingCategories = self.caller.retrieveCategories() + async let pendingFeeds = self.caller.retrieveFeeds() + + let categories = try await pendingCategories + self.refreshProgress.completeTask() + + let feeds = try await pendingFeeds + self.refreshProgress.completeTask() + + BatchUpdate.shared.perform { + self.syncFolders(account, categories) + self.syncFeeds(account, feeds) + self.syncFeedFolderRelationship(account, feeds) + } + self.refreshProgress.completeTask() + return (folders: categories.count, feeds: feeds.count) + }) + } catch { + postSyncError(error, account: account, operation: "Refreshing account") + throw error + } + } + + func refreshArticlesAndStatuses(_ account: Account) async throws { + let isInitialSync = accountSettings?.lastRefreshCompletedDate == nil + + try await sendArticleStatus() + _ = try await refreshArticles(account, reportProgress: true) + + if isInitialSync { + // The first sync's published_after window misses older unread/starred entries; + // a one-time full ID reconciliation (plus refreshMissingArticles right after) + // pulls them in. Order matters: reconcile must run before refreshMissingArticles + // so the statuses it creates get their articles downloaded. + _ = try await reconcileAllArticleStatuses(for: account) + } + + try await refreshMissingArticles(account) + accountSettings?.lastRefreshCompletedDate = Date() + refreshProgress.reset() + } + + /// Every Miniflux category maps to exactly one NNW folder, matched by externalID + /// (the category's server-side id), not by name — so a category rename doesn't + /// orphan the folder. + func syncFolders(_ account: Account, _ categories: [MinifluxCategory]) { + assert(Thread.isMainThread) + + Self.logger.info("Miniflux: Syncing folders with \(categories.count) categories") + + let categoryExternalIDs = Set(categories.map { String($0.categoryID) }) + + // Delete any folders whose category is gone. + if let folders = account.folders { + for folder in folders { + if !categoryExternalIDs.contains(folder.externalID ?? "") { + account.removeFolderFromTree(folder) + } + } + } + + let folderDict = externalIDToFolderDictionary(with: account.folders) + + for category in categories { + let externalID = String(category.categoryID) + if let folder = folderDict[externalID] { + if folder.name != category.title { + folder.name = category.title + } + } else { + let folder = account.ensureFolder(with: category.title) + folder?.externalID = externalID + } + } + } + + func syncFeeds(_ account: Account, _ feeds: [MinifluxFeed]) { + assert(Thread.isMainThread) + + Self.logger.info("Miniflux: Syncing feeds with \(feeds.count) feeds") + + let feedExternalIDs = Set(feeds.map { String($0.feedID) }) + + // Remove any feeds that are no longer on the server. Miniflux guarantees every + // feed has a category, so feeds only ever live inside folders — never at the + // account top level. + if let folders = account.folders { + for folder in folders { + for feed in folder.topLevelFeeds { + if !feedExternalIDs.contains(feed.feedID) { + // Clear settings before removing so a feed re-added at this URL — which + // Miniflux assigns a new numeric feedID — doesn't inherit the stale + // feedID from the settings cache/database and end up unable to match + // incoming articles. + account.clearFeedSettings(feed) + folder.removeFeedFromTreeAtTopLevel(feed) + } + } + } + } + + // Add any feeds we don't have and update any we do. New feeds are added directly + // to their folder in syncFeedFolderRelationship — Miniflux guarantees every feed + // has exactly one category. + for feed in feeds { + let feedExternalID = String(feed.feedID) + if let existingFeed = account.existingFeed(withFeedID: feedExternalID) { + existingFeed.name = feed.title + existingFeed.editedName = nil + existingFeed.homePageURL = feed.siteURL + existingFeed.externalID = feedExternalID + } + } + } + + /// No `folderRelationship` bookkeeping — a feed's folder membership is derived + /// entirely from its `category.id` on each refresh. + func syncFeedFolderRelationship(_ account: Account, _ feeds: [MinifluxFeed]) { + assert(Thread.isMainThread) + + Self.logger.info("Miniflux: Syncing feed folder relationships") + + let folderDict = externalIDToFolderDictionary(with: account.folders) + let feedsByCategoryID = feeds.reduce(into: [String: [MinifluxFeed]]()) { dict, feed in + guard let categoryID = feed.category?.categoryID else { return } + dict[String(categoryID), default: []].append(feed) + } + + // Feeds with no category (a lenient decode) must not be silently pulled out of + // their existing folder — track them so the removal loop below leaves them alone. + var feedIDsWithNoCategory = Set() + for feed in feeds where feed.category == nil { + feedIDsWithNoCategory.insert(String(feed.feedID)) + Self.logger.error("Miniflux: Feed \(feed.feedID) has no category; leaving local folder placement unchanged") + } + + for (categoryExternalID, folder) in folderDict { + let categoryFeeds = feedsByCategoryID[categoryExternalID] ?? [] + let categoryFeedExternalIDs = Set(categoryFeeds.map { String($0.feedID) }) + + // Remove any feeds no longer in this category. + for feed in folder.topLevelFeeds { + if feedIDsWithNoCategory.contains(feed.feedID) { + continue + } + if !categoryFeedExternalIDs.contains(feed.feedID) { + folder.removeFeedFromTreeAtTopLevel(feed) + } + } + + // Add any feeds not yet in this folder. + let folderFeedExternalIDs = Set(folder.topLevelFeeds.map { $0.feedID }) + for feed in categoryFeeds { + let feedExternalID = String(feed.feedID) + guard !folderFeedExternalIDs.contains(feedExternalID) else { + continue + } + if let existingFeed = account.existingFeed(withFeedID: feedExternalID) { + folder.addFeedToTreeAtTopLevel(existingFeed) + } else { + let newFeed = account.createFeed(with: feed.title, url: feed.feedURL, feedID: feedExternalID, homePageURL: feed.siteURL) + newFeed.externalID = feedExternalID + folder.addFeedToTreeAtTopLevel(newFeed) + } + } + } + } + + func externalIDToFolderDictionary(with folders: Set?) -> [String: Folder] { + guard let folders else { + return [:] + } + + let pairs = folders.compactMap { folder -> (String, Folder)? in + guard let externalID = folder.externalID else { + return nil + } + return (externalID, folder) + } + return Dictionary(pairs, uniquingKeysWith: { first, _ in first }) + } + + @discardableResult + func refreshArticles(_ account: Account, reportProgress: Bool = false) async throws -> Int { + Self.logger.info("Miniflux: Refreshing articles") + + do { + let fetchStartDate = Date() + let isInitialSync = accountSettings?.lastRefreshCompletedDate == nil + let changedAfter = isInitialSync ? nil : accountSettings?.lastArticleFetchStartTime + let publishedAfter = isInitialSync ? Calendar.current.date(byAdding: .month, value: -3, to: fetchStartDate) : nil + + let processedCount = try await account.logActivity(kind: .refreshArticles, successMessage: { "\($0) articles" }, { + try await refreshArticlesPage(account: account, changedAfter: changedAfter, publishedAfter: publishedAfter, reportProgress: reportProgress) + }) + + accountSettings?.lastArticleFetchStartTime = fetchStartDate + return processedCount + } catch { + postSyncError(error, account: account, operation: "Refreshing articles") + throw error + } + } + + /// When `reportProgress` is true, the caller must have pre-added one task for the + /// first page (keeping the progress denominator stable for single-page refreshes); + /// continuation pages add their own. Background status syncs pass false so the + /// progress UI stays quiet. + func refreshArticlesPage(account: Account, changedAfter: Date?, publishedAfter: Date?, reportProgress: Bool) async throws -> Int { + var offset = 0 + var totalEntriesProcessed = 0 + var isFirstPage = true + + while true { + if reportProgress && !isFirstPage { + refreshProgress.addTask() + } + isFirstPage = false + // Complete the task on every exit from this iteration — including a thrown + // fetch error — so a task is never stranded. + defer { + if reportProgress { + refreshProgress.completeTask() + } + } + + let pageOffset = offset + let response = try await account.logActivity(kind: .refreshArticles, detail: ActivityLog.shared.nextTaskNumberString(), successMessage: { "\($0.entries.count) articles" }, { + try await caller.retrieveEntries(offset: pageOffset, changedAfter: changedAfter, publishedAfter: publishedAfter) + }) + + totalEntriesProcessed += response.entries.count + await processEntries(account: account, entries: response.entries) + + offset += response.entries.count + if response.entries.isEmpty || offset >= response.total { + break + } + } + + return totalEntriesProcessed + } + + func refreshMissingArticles(_ account: Account) async throws { + Self.logger.info("Miniflux: Refreshing missing articles") + defer { + refreshProgress.completeTask() + Self.logger.info("Miniflux: Finished refreshing missing articles") + } + + try await account.logActivity(kind: .refreshMissingArticles) { + var savedError: Error? + + let fetchedArticleIDs = await account.fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDateAsync() + let entryIDs = fetchedArticleIDs.compactMap { Int64($0) } + let chunkedEntryIDs = entryIDs.chunked(into: 100) + var serverDeletedArticleIDs = Set() + + for chunk in chunkedEntryIDs { + do { + var entries = [MinifluxEntry]() + for entryID in chunk { + if let entry = try await caller.retrieveEntry(entryID: entryID) { + entries.append(entry) + } else { + serverDeletedArticleIDs.insert(String(entryID)) + } + } + await processEntries(account: account, entries: entries) + } catch { + savedError = error + Self.logger.error("Miniflux: Refresh missing articles error: \(error.localizedDescription)") + } + } + + // A 404 from retrieveEntry means the entry is gone server-side (feed deleted, + // server cleanup). Delete those statuses — otherwise they match the + // statuses-without-articles query again on every refresh, and we re-request + // articles the server will never return. + if !serverDeletedArticleIDs.isEmpty { + Self.logger.info("Miniflux: Deleting statuses for \(serverDeletedArticleIDs.count) entries removed on the server") + await account.deleteStatuses(articleIDs: serverDeletedArticleIDs) + } + + if let savedError { + postSyncError(savedError, account: account, operation: "Refreshing missing articles") + throw savedError + } + } + } + + func processEntries(account: Account, entries: [MinifluxEntry]) async { + let parsedItems = mapEntriesToParsedItems(entries: entries) + let feedIDsAndItems = Dictionary(grouping: parsedItems, by: { item in item.feedURL }).mapValues { Set($0) } + await account.updateAsync(feedIDsAndItems: feedIDsAndItems, defaultRead: true) + await applyEntryStatuses(account: account, entries: entries) + } + + /// Statuses ride along on the changed_after entries fetch — Miniflux bumps changed_at + /// whenever an entry's status or starred state changes — so applying them per page + /// replaces the per-refresh full ID scans. Pending local changes are always excluded: + /// they must win, so server state is never applied without first knowing what's pending. + func applyEntryStatuses(account: Account, entries: [MinifluxEntry]) async { + guard !entries.isEmpty else { + return + } + + let pendingReadArticleIDs = try? await syncDatabase.selectPendingReadStatusArticleIDs() + let pendingStarredArticleIDs = try? await syncDatabase.selectPendingStarredStatusArticleIDs() + + if pendingReadArticleIDs == nil { + Self.logger.error("Miniflux: Sync database selectPendingReadStatusArticleIDs failed; skipping read status application") + } + if pendingStarredArticleIDs == nil { + Self.logger.error("Miniflux: Sync database selectPendingStarredStatusArticleIDs failed; skipping starred status application") + } + + var unreadIDs = Set() + var readIDs = Set() + var starredIDs = Set() + var unstarredIDs = Set() + + for entry in entries { + let articleID = String(entry.entryID) + if entry.status == "unread" { + unreadIDs.insert(articleID) + } else if entry.status == "read" { + readIDs.insert(articleID) + } + if entry.starred == true { + starredIDs.insert(articleID) + } else if entry.starred == false { + unstarredIDs.insert(articleID) + } + } + + if let pendingReadArticleIDs { + _ = await account.markAsUnreadAsync(articleIDs: unreadIDs.subtracting(pendingReadArticleIDs)) + _ = await account.markAsReadAsync(articleIDs: readIDs.subtracting(pendingReadArticleIDs)) + } + if let pendingStarredArticleIDs { + _ = await account.markAsStarredAsync(articleIDs: starredIDs.subtracting(pendingStarredArticleIDs)) + _ = await account.markAsUnstarredAsync(articleIDs: unstarredIDs.subtracting(pendingStarredArticleIDs)) + } + } + + func mapEntriesToParsedItems(entries: [MinifluxEntry]) -> Set { + let parsedItems: [ParsedItem] = entries.map { entry in + let authors = entry.author.map { Set([ParsedAuthor(name: $0, url: nil, avatarURL: nil, emailAddress: nil)]) } + return ParsedItem(syncServiceID: String(entry.entryID), uniqueID: String(entry.entryID), feedURL: String(entry.feedID), url: entry.url, externalURL: nil, title: entry.title, language: nil, contentHTML: entry.contentHTML, contentText: nil, markdown: nil, summary: nil, imageURL: entry.imageURL, thumbnailURL: nil, bannerImageURL: nil, datePublished: entry.parsedDatePublished, dateModified: nil, authors: authors, tags: nil, attachments: entry.attachments) + } + + return Set(parsedItems) + } + + func syncArticleReadState(account: Account, entryIDs: Set) async -> Int { + guard let pendingArticleIDs = try? await syncDatabase.selectPendingReadStatusArticleIDs() else { + Self.logger.error("Miniflux: Sync database selectPendingReadStatusArticleIDs failed") + return 0 + } + + return await syncArticleState( + entryIDs: entryIDs, + pendingArticleIDs: pendingArticleIDs, + currentArticleIDs: { await account.fetchUnreadArticleIDsAsync() }, + markOn: { await account.markAsUnreadAsync(articleIDs: $0) }, + markOff: { await account.markAsReadAsync(articleIDs: $0) } + ) + } + + func syncArticleStarredState(account: Account, entryIDs: Set) async -> Int { + guard let pendingArticleIDs = try? await syncDatabase.selectPendingStarredStatusArticleIDs() else { + Self.logger.error("Miniflux: Sync database selectPendingStarredStatusArticleIDs failed") + return 0 + } + + return await syncArticleState( + entryIDs: entryIDs, + pendingArticleIDs: pendingArticleIDs, + currentArticleIDs: { await account.fetchStarredArticleIDsAsync() }, + markOn: { await account.markAsStarredAsync(articleIDs: $0) }, + markOff: { await account.markAsUnstarredAsync(articleIDs: $0) } + ) + } + + /// Read/unread and starred/unstarred changes all funnel through here. Chunks `entryIDs`, + /// pushes each chunk via `update`, then clears the sync-database rows on success or resets + /// them on failure. Miniflux’s update-entries call is absolute state (not a toggle), so + /// repeated sends are idempotent. Returns the count successfully sent. + func sendEntryStatuses(_ entryIDs: [Int64], key: SyncStatus.Key, update: (_ chunk: [Int64]) async throws -> Void) async throws -> Int { + guard !entryIDs.isEmpty else { + return 0 + } + + var savedError: Error? + var sentCount = 0 + + for chunk in entryIDs.chunked(into: MinifluxAPICaller.statusChunkSize) { + let articleIDs = Set(chunk.map { String($0) }) + do { + try await update(chunk) + await syncDatabase.deleteSelectedForProcessing(articleIDs, key: key) + sentCount += chunk.count + } catch { + savedError = error + Self.logger.error("Miniflux: Status sync call failed: \(error.localizedDescription)") + await syncDatabase.resetSelectedForProcessing(articleIDs, key: key) + } + } + + if let savedError { + throw savedError + } + return sentCount + } + + /// Numeric entry IDs of the pending sync statuses matching `key`/`flag`. + func pendingEntryIDs(in statuses: some Sequence, key: SyncStatus.Key, flag: Bool) -> [Int64] { + statuses.filter { $0.key == key && $0.flag == flag }.compactMap { Int64($0.articleID) } + } + + /// Resolves the category to use when creating a feed into `container`: the folder's + /// externalID if `container` is a Folder, otherwise the lowest-id category (used when + /// the UI hands us the account itself as the container, which Miniflux has no concept + /// of — every feed must belong to a category). + func categoryID(for container: Container) async throws -> Int64 { + if let folder = container as? Folder, let externalID = folder.externalID, let categoryID = Int64(externalID) { + return categoryID + } + + let categories = try await caller.retrieveCategories() + guard let lowestCategory = categories.min(by: { $0.categoryID < $1.categoryID }) else { + throw AccountError.invalidParameter + } + return lowestCategory.categoryID + } + + @discardableResult + func createFeed(account: Account, feedID: Int64, name: String?, container: Container) async throws -> Feed { + let minifluxFeed = try await caller.retrieveFeed(feedID: feedID) + + let feed = account.createFeed(with: minifluxFeed.title, url: minifluxFeed.feedURL, feedID: String(feedID), homePageURL: minifluxFeed.siteURL) + feed.externalID = String(feedID) + + try await account.addFeed(feed, container: container) + if let name { + try await renameFeed(with: feed, to: name) + } + + Task { + do { + try await initialFeedDownload(account: account, feed: feed, feedID: feedID) + } catch { + Self.logger.error("Miniflux: Initial feed download failed: \(error.localizedDescription)") + postSyncError(error, account: account, operation: "Downloading feed articles") + } + } + + return feed + } + + func initialFeedDownload(account: Account, feed: Feed, feedID: Int64) async throws { + refreshProgress.addTask() + defer { refreshProgress.completeTask() } + + try await account.logActivity(kind: .refreshFeedContent(feedURL: feed.url), detail: feed.nameForDisplay) { + var offset = 0 + while true { + let response = try await caller.retrieveEntries(feedID: feedID, offset: offset) + await processEntries(account: account, entries: response.entries) + + offset += response.entries.count + if offset >= response.total || response.entries.isEmpty { + break + } + } + } + } + + func postSyncError(_ error: Error, account: Account, operation: String, fileName: String = #fileID, functionName: String = #function, lineNumber: Int = #line) { + let errorLogUserInfo = ErrorLogUserInfoKey.userInfo(sourceName: account.nameForDisplay, sourceID: account.type.rawValue, operation: operation, errorMessage: AccountError.detailedErrorMessage(error), fileName: fileName, functionName: functionName, lineNumber: lineNumber) + NotificationCenter.default.post(name: .appDidEncounterError, object: self, userInfo: errorLogUserInfo) + } +} + +extension MinifluxAccountDelegate { + func syncArticleState(entryIDs: Set, pendingArticleIDs: Set, currentArticleIDs: () async -> Set, markOn: (Set) async -> Set, markOff: (Set) async -> Set) async -> Int { + let serverArticleIDs = Set(entryIDs.map { String($0) }) + let updatableArticleIDs = serverArticleIDs.subtracting(pendingArticleIDs) + + let currentIDs = await currentArticleIDs() + let deltaOnArticleIDs = updatableArticleIDs.subtracting(currentIDs) + let markedOn = await markOn(deltaOnArticleIDs) + + let deltaOffArticleIDs = currentIDs.subtracting(updatableArticleIDs).subtracting(pendingArticleIDs) + let markedOff = await markOff(deltaOffArticleIDs) + + return markedOn.count + markedOff.count + } +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxCategory.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxCategory.swift new file mode 100644 index 000000000..807fbe9cb --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxCategory.swift @@ -0,0 +1,34 @@ +// +// MinifluxCategory.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation + +// GET /v1/categories → [{"id":38,"title":"All","user_id":35,"hide_globally":false},...] +// A Miniflux category maps one-to-one to an NNW folder. +struct MinifluxCategory: Decodable, Sendable, Hashable { + let categoryID: Int64 + let title: String + + enum CodingKeys: String, CodingKey { + case categoryID = "id" + case title + } + + static func == (lhs: MinifluxCategory, rhs: MinifluxCategory) -> Bool { + lhs.categoryID == rhs.categoryID + } + + func hash(into hasher: inout Hasher) { + hasher.combine(categoryID) + } +} + +// Used for both category creation and rename — Miniflux takes the same body for both. +struct MinifluxCategoryPayload: Encodable, Sendable { + let title: String +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxEntry.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxEntry.swift new file mode 100644 index 000000000..c24e221bc --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxEntry.swift @@ -0,0 +1,136 @@ +// +// MinifluxEntry.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation +import RSParser + +// GET /v1/entries?limit=1 → {"total":2043,"entries":[{"id":121624,"feed_id":310,"status":"unread", +// "hash":"...","title":"...","url":"...","published_at":"2026-07-07T05:12:06Z", +// "created_at":"2026-07-07T05:13:22.668113Z","changed_at":"2026-07-07T05:13:22.668113Z", +// "content":"...","author":"...","starred":false,"reading_time":1,"enclosures":[], +// "feed":{...},"tags":[...]}]} +struct MinifluxEntry: Decodable, Sendable { + let entryID: Int64 + let feedID: Int64 + let title: String? + let url: String? + let author: String? + let contentHTML: String? + let datePublished: String? + let enclosures: [MinifluxEnclosure]? + let status: String? + let starred: Bool? + + // Miniflux emits ISO8601 dates with fractional seconds and offsets, which JSONDecoder’s + // .iso8601 strategy can’t parse. Rather than lose the whole entry, decode the date as a + // String and let DateParser take care of it — exactly like FeedbinEntry.parsedDatePublished. + var parsedDatePublished: Date? { + datePublished.flatMap { DateParser.date(from: $0) } + } + + var attachments: [ParsedAttachment]? { + let attachments = enclosures?.compactMap { $0.parsedAttachment } ?? [] + return attachments.isEmpty ? nil : attachments + } + + var imageURL: String? { + enclosures?.first { $0.isImage }?.url + } + + enum CodingKeys: String, CodingKey { + case entryID = "id" + case feedID = "feed_id" + case title + case url + case author + case contentHTML = "content" + case datePublished = "published_at" + case enclosures + case status + case starred + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + entryID = try container.decode(Int64.self, forKey: .entryID) + feedID = try container.decode(Int64.self, forKey: .feedID) + title = try? container.decode(String.self, forKey: .title) + url = try? container.decode(String.self, forKey: .url) + author = try? container.decode(String.self, forKey: .author) + contentHTML = try? container.decode(String.self, forKey: .contentHTML) + datePublished = try? container.decode(String.self, forKey: .datePublished) + enclosures = try? container.decode([MinifluxEnclosure].self, forKey: .enclosures) + status = try? container.decode(String.self, forKey: .status) + starred = try? container.decode(Bool.self, forKey: .starred) + } +} + +struct MinifluxEnclosure: Decodable, Sendable { + let url: String? + let mimeType: String? + let size: Int? + + var parsedAttachment: ParsedAttachment? { + guard let url else { + return nil + } + return ParsedAttachment(url: url, mimeType: mimeType, title: nil, sizeInBytes: sizeInBytes, durationInSeconds: nil, width: nil, height: nil, medium: nil) + } + + var isImage: Bool { + mimeType?.lowercased().hasPrefix("image/") == true + } + + private var sizeInBytes: Int? { + guard let size, size > 0 else { + return nil + } + return size + } + + enum CodingKeys: String, CodingKey { + case url + case mimeType = "mime_type" + case size + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + url = try? container.decodeIfPresent(String.self, forKey: .url) + mimeType = try? container.decodeIfPresent(String.self, forKey: .mimeType) + size = try? container.decodeIfPresent(Int.self, forKey: .size) + } +} + +struct MinifluxEntriesResponse: Decodable, Sendable { + let total: Int + let entries: [MinifluxEntry] +} + +// GET /v1/entries/ids?status=unread → {"total":1960,"entry_ids":[121634,121624,...]} +struct MinifluxEntryIDsResponse: Decodable, Sendable { + let total: Int + let entryIDs: [Int64] + + enum CodingKeys: String, CodingKey { + case total = "total" + case entryIDs = "entry_ids" + } +} + +struct MinifluxUpdateEntriesPayload: Encodable, Sendable { + let entryIDs: [Int64] + let status: String? + let starred: Bool? + + enum CodingKeys: String, CodingKey { + case entryIDs = "entry_ids" + case status + case starred + } +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxError.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxError.swift new file mode 100644 index 000000000..d162cae77 --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxError.swift @@ -0,0 +1,38 @@ +// +// MinifluxError.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation + +// Miniflux error responses look like: {"error_message": "This feed already exists (feed_id: 123)"} +struct MinifluxErrorResponse: Decodable, Sendable { + let errorMessage: String + + enum CodingKeys: String, CodingKey { + case errorMessage = "error_message" + } +} + +enum MinifluxError: LocalizedError { + + case serverVersionTooOld(foundVersion: String?) + case serverError(message: String) + + var errorDescription: String? { + switch self { + case .serverVersionTooOld(let foundVersion): + guard let foundVersion else { + return NSLocalizedString("NetNewsWire requires Miniflux 2.0.49 or later.", comment: "Server version too old") + } + let localizedText = NSLocalizedString("This Miniflux server is version %@, but NetNewsWire requires Miniflux 2.0.49 or later.", comment: "Server version too old") + return NSString.localizedStringWithFormat(localizedText as NSString, foundVersion) as String + case .serverError(let message): + let localizedText = NSLocalizedString("The Miniflux server reported an error: %@", comment: "Server error") + return NSString.localizedStringWithFormat(localizedText as NSString, message) as String + } + } +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxFeed.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxFeed.swift new file mode 100644 index 000000000..544fc9f58 --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxFeed.swift @@ -0,0 +1,72 @@ +// +// MinifluxFeed.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation + +// GET /v1/feeds → [{"id":311,"feed_url":"...","site_url":"...","title":"...", +// "category":{"id":39,...},"icon":{"feed_id":311,...},...}] +struct MinifluxFeed: Decodable, Sendable { + let feedID: Int64 + let feedURL: String + let siteURL: String? + let title: String? + let category: MinifluxCategory? + + enum CodingKeys: String, CodingKey { + case feedID = "id" + case feedURL = "feed_url" + case siteURL = "site_url" + case title + case category + } + + init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + feedID = try container.decode(Int64.self, forKey: .feedID) + feedURL = try container.decode(String.self, forKey: .feedURL) + siteURL = try? container.decode(String.self, forKey: .siteURL) + title = try? container.decode(String.self, forKey: .title) + // Decoded leniently: older servers, or feeds mid-import, may omit or malform this. + category = try? container.decode(MinifluxCategory.self, forKey: .category) + } +} + +struct MinifluxCreateFeed: Encodable, Sendable { + let feedURL: String + let categoryID: Int64 + + enum CodingKeys: String, CodingKey { + case feedURL = "feed_url" + case categoryID = "category_id" + } +} + +struct MinifluxCreateFeedResponse: Decodable, Sendable { + let feedID: Int64 + + enum CodingKeys: String, CodingKey { + case feedID = "feed_id" + } +} + +// Only non-nil properties are encoded, so callers can send a title-only or category-only update. +struct MinifluxUpdateFeed: Encodable, Sendable { + let title: String? + let categoryID: Int64? + + enum CodingKeys: String, CodingKey { + case title + case categoryID = "category_id" + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(title, forKey: .title) + try container.encodeIfPresent(categoryID, forKey: .categoryID) + } +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxUser.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxUser.swift new file mode 100644 index 000000000..43455f81c --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxUser.swift @@ -0,0 +1,15 @@ +// +// MinifluxUser.swift +// Account +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation + +// GET /v1/me → {"id":35,"username":"claude","is_admin":false,...} +struct MinifluxUser: Decodable, Sendable { + let id: Int64 + let username: String +} diff --git a/Modules/Account/Sources/Account/Miniflux/MinifluxVersion.swift b/Modules/Account/Sources/Account/Miniflux/MinifluxVersion.swift new file mode 100644 index 000000000..ba6def30c --- /dev/null +++ b/Modules/Account/Sources/Account/Miniflux/MinifluxVersion.swift @@ -0,0 +1,63 @@ +// +// MinifluxVersion.swift +// Account +// +// Created by Dave Marquard on 7/8/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import Foundation + +// GET /v1/version → {"version":"2.3.2","commit":"...","build_date":"...",...} +struct MinifluxVersionResponse: Decodable, Sendable { + let version: String +} + +/// A dotted numeric version, e.g. "2.3.2". Tolerates a non-numeric suffix on the last +/// component, e.g. "2.3.2-dev", but fails to parse a wholly non-numeric component. +struct MinifluxVersion: Comparable, Sendable { + + private let components: [Int] + + init(_ components: Int...) { + self.components = components + } + + init?(string: String) { + let parts = string.split(separator: ".") + guard !parts.isEmpty else { + return nil + } + + var parsedComponents = [Int]() + for part in parts { + let digits = part.prefix { $0.isNumber } + guard let value = Int(digits) else { + return nil + } + parsedComponents.append(value) + } + + components = parsedComponents + } + + static func == (lhs: MinifluxVersion, rhs: MinifluxVersion) -> Bool { + lhs.compare(rhs) == .orderedSame + } + + static func < (lhs: MinifluxVersion, rhs: MinifluxVersion) -> Bool { + lhs.compare(rhs) == .orderedAscending + } + + private func compare(_ other: MinifluxVersion) -> ComparisonResult { + let count = max(components.count, other.components.count) + for i in 0..Body of the unread starred entry.

", + "author": "Jane Doe", + "starred": true, + "reading_time": 2, + "feed_id_str": "101" + }, + { + "id": 5002, + "feed_id": 102, + "status": "read", + "hash": "hash5002", + "title": "Read entry", + "url": "https://tech-a.example/posts/2", + "published_at": "2026-07-06T09:00:00Z", + "created_at": "2026-07-06T09:05:00Z", + "changed_at": "2026-07-06T09:05:00Z", + "content": "

Body of the read entry.

", + "author": "John Smith", + "starred": false, + "reading_time": 4 + }, + { + "id": 5003, + "feed_id": 103, + "status": "unread", + "hash": "hash5003", + "title": "Entry with no author", + "url": "https://tech-b.example/posts/3", + "published_at": "2026-07-05T12:30:00Z", + "created_at": "2026-07-05T12:31:00Z", + "changed_at": "2026-07-05T12:31:00Z", + "content": "

Body of the entry with no author.

", + "starred": false, + "reading_time": 1 + }, + { + "id": 5004, + "feed_id": 104, + "status": "unread", + "hash": "hash5004", + "title": "Entry with empty enclosures", + "url": "https://news-a.example/posts/4", + "published_at": "2026-07-04T08:15:00Z", + "created_at": "2026-07-04T08:16:00Z", + "changed_at": "2026-07-04T08:16:00Z", + "content": "

Body of the entry with empty enclosures.

", + "author": "News Desk", + "starred": false, + "reading_time": 3, + "enclosures": [] + }, + { + "id": 5005, + "feed_id": 105, + "status": "read", + "hash": "hash5005", + "title": "Entry with an enclosure", + "url": "https://general-b.example/posts/5", + "published_at": "2026-07-03T18:45:00Z", + "created_at": "2026-07-03T18:46:00Z", + "changed_at": "2026-07-03T18:46:00Z", + "content": "

Body of the entry with an enclosure.

", + "author": "Jane Doe", + "starred": false, + "reading_time": 5, + "enclosures": [ + { + "url": "https://media.example/ep1.mp3", + "mime_type": "audio/mpeg", + "size": 1234567 + }, + { + "url": "https://media.example/ep1.jpg", + "mime_type": "image/jpeg", + "size": 0 + } + ] + } + ] +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5001_starred.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5001_starred.json new file mode 100644 index 000000000..f68d6fd49 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5001_starred.json @@ -0,0 +1,15 @@ +{ + "id": 5001, + "feed_id": 101, + "status": "unread", + "hash": "hash5001", + "title": "Unread and starred entry", + "url": "https://general.example/posts/1", + "published_at": "2026-07-07T05:12:06.668113Z", + "created_at": "2026-07-07T05:13:22.668113Z", + "changed_at": "2026-07-07T05:13:22.668113Z", + "content": "

Body of the unread starred entry.

", + "author": "Jane Doe", + "starred": true, + "reading_time": 2 +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5002_unstarred.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5002_unstarred.json new file mode 100644 index 000000000..9c88f7677 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_5002_unstarred.json @@ -0,0 +1,15 @@ +{ + "id": 5002, + "feed_id": 102, + "status": "read", + "hash": "hash5002", + "title": "Read entry", + "url": "https://tech-a.example/posts/2", + "published_at": "2026-07-06T09:00:00Z", + "created_at": "2026-07-06T09:05:00Z", + "changed_at": "2026-07-06T09:05:00Z", + "content": "

Body of the read entry.

", + "author": "John Smith", + "starred": false, + "reading_time": 4 +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_ids.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_ids.json new file mode 100644 index 000000000..30b982533 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_entry_ids.json @@ -0,0 +1,4 @@ +{ + "total": 3, + "entry_ids": [5001, 5003, 5004] +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_feeds_initial.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_feeds_initial.json new file mode 100644 index 000000000..d4b347464 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_feeds_initial.json @@ -0,0 +1,87 @@ +[ + { + "id": 101, + "feed_url": "https://miniflux.test/feeds/general.xml", + "site_url": "https://general.example", + "title": "General Feed", + "checked_at": "2026-07-07T05:00:00Z", + "category": { + "id": 1, + "title": "All", + "user_id": 35, + "hide_globally": false + }, + "icon": { + "feed_id": 101, + "icon_id": 201, + "external_icon_id": "abc101" + } + }, + { + "id": 102, + "feed_url": "https://tech-a.example/rss.xml", + "site_url": "https://tech-a.example", + "title": "Tech Feed A", + "checked_at": "2026-07-07T05:00:00Z", + "category": { + "id": 2, + "title": "Tech", + "user_id": 35, + "hide_globally": false + }, + "icon": { + "feed_id": 102, + "icon_id": 202, + "external_icon_id": "abc102" + } + }, + { + "id": 103, + "feed_url": "https://tech-b.example/feed", + "site_url": "https://tech-b.example", + "title": "Tech Feed B", + "checked_at": "2026-07-07T05:00:00Z", + "category": { + "id": 2, + "title": "Tech", + "user_id": 35, + "hide_globally": false + }, + "icon": { + "feed_id": 103, + "icon_id": 203, + "external_icon_id": "abc103" + } + }, + { + "id": 104, + "feed_url": "https://news-a.example/atom.xml", + "site_url": "https://news-a.example", + "title": "News Feed A", + "checked_at": "2026-07-07T05:00:00Z", + "category": { + "id": 3, + "title": "News", + "user_id": 35, + "hide_globally": false + }, + "icon": { + "feed_id": 104, + "icon_id": 204, + "external_icon_id": "abc104" + } + }, + { + "id": 105, + "feed_url": "https://general-b.example/feed.json", + "site_url": "https://general-b.example", + "title": "General Feed B", + "checked_at": "2026-07-07T05:00:00Z", + "category": { + "id": 1, + "title": "All", + "user_id": 35, + "hide_globally": false + } + } +] diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_me.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_me.json new file mode 100644 index 000000000..770d08f03 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_me.json @@ -0,0 +1,8 @@ +{ + "id": 35, + "username": "testuser", + "is_admin": false, + "theme": "light_serif", + "language": "en_US", + "timezone": "UTC" +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_version.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_version.json new file mode 100644 index 000000000..fec4f767c --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_version.json @@ -0,0 +1,9 @@ +{ + "version": "2.3.2", + "commit": "abc1234", + "build_date": "2026-06-01T00:00:00Z", + "go_version": "go1.24.0", + "compiler": "gc", + "arch": "arm64", + "os": "linux" +} diff --git a/Modules/Account/Tests/AccountTests/JSON/miniflux_version_old.json b/Modules/Account/Tests/AccountTests/JSON/miniflux_version_old.json new file mode 100644 index 000000000..df7670aac --- /dev/null +++ b/Modules/Account/Tests/AccountTests/JSON/miniflux_version_old.json @@ -0,0 +1,9 @@ +{ + "version": "2.1.0", + "commit": "def5678", + "build_date": "2026-01-01T00:00:00Z", + "go_version": "go1.23.0", + "compiler": "gc", + "arch": "amd64", + "os": "linux" +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/AccountMinifluxFolderSyncTest.swift b/Modules/Account/Tests/AccountTests/Miniflux/AccountMinifluxFolderSyncTest.swift new file mode 100644 index 000000000..2ec6939bb --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/AccountMinifluxFolderSyncTest.swift @@ -0,0 +1,162 @@ +// +// AccountMinifluxFolderSyncTest.swift +// AccountTests +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +import RSWeb +@testable import Account + +@MainActor final class AccountMinifluxFolderSyncTest: XCTestCase { + + override func setUp() { + TestingURLProtocol.reset() + } + + func testDownloadSync() async throws { + + TestingURLProtocol.setResponse("/v1/version", file: "JSON/miniflux_version.json") + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_initial.json") + TestingURLProtocol.setResponse("/v1/feeds", file: "JSON/miniflux_feeds_initial.json") + TestingURLProtocol.setResponse("/v1/entries/ids", file: "JSON/miniflux_entry_ids.json") + TestingURLProtocol.setResponse("/v1/entries?", file: "JSON/miniflux_entries_page1.json") + + let account = TestAccountManager.shared.createAccount(type: .miniflux) + account.endpointURL = URL(string: "https://miniflux.test") + + // Test initial folders + + try await account.refreshAll() + + guard let initialFolders = account.folders else { + XCTFail() + return + } + + XCTAssertEqual(3, initialFolders.count) + + guard let all = initialFolders.first(where: { $0.name == "All" }) else { + XCTFail("Expected an “All” folder") + return + } + XCTAssertEqual("1", all.externalID) + + guard let tech = initialFolders.first(where: { $0.name == "Tech" }) else { + XCTFail("Expected a “Tech” folder") + return + } + XCTAssertEqual("2", tech.externalID) + + guard let news = initialFolders.first(where: { $0.name == "News" }) else { + XCTFail("Expected a “News” folder") + return + } + XCTAssertEqual("3", news.externalID) + + // Test removing a folder + + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_delete.json") + + try await account.refreshAll() + + guard let deleteFolders = account.folders else { + XCTFail() + return + } + + XCTAssertEqual(2, deleteFolders.count) + let deleteFolderNames = deleteFolders.map { $0.name ?? "" } + XCTAssertTrue(deleteFolderNames.contains("All")) + XCTAssertTrue(deleteFolderNames.contains("Tech")) + XCTAssertFalse(deleteFolderNames.contains("News")) + + // Test adding a folder + + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_add.json") + + try await account.refreshAll() + + guard let addFolders = account.folders else { + XCTFail() + return + } + + XCTAssertEqual(4, addFolders.count) + let addFolderNames = addFolders.map { $0.name ?? "" } + XCTAssertTrue(addFolderNames.contains("News")) + XCTAssertTrue(addFolderNames.contains("Reviews")) + + guard let reviews = addFolders.first(where: { $0.name == "Reviews" }) else { + XCTFail("Expected a “Reviews” folder") + return + } + XCTAssertEqual("4", reviews.externalID) + + TestAccountManager.shared.deleteAccount(account) + } + + func testFeedsLandInCorrectFolders() async throws { + + TestingURLProtocol.setResponse("/v1/version", file: "JSON/miniflux_version.json") + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_initial.json") + TestingURLProtocol.setResponse("/v1/feeds", file: "JSON/miniflux_feeds_initial.json") + TestingURLProtocol.setResponse("/v1/entries/ids", file: "JSON/miniflux_entry_ids.json") + TestingURLProtocol.setResponse("/v1/entries?", file: "JSON/miniflux_entries_page1.json") + + let account = TestAccountManager.shared.createAccount(type: .miniflux) + account.endpointURL = URL(string: "https://miniflux.test") + + try await account.refreshAll() + + guard let folders = account.folders else { + XCTFail() + return + } + XCTAssertEqual(3, folders.count) + + guard let all = folders.first(where: { $0.name == "All" }) else { + XCTFail("Expected an “All” folder") + return + } + guard let tech = folders.first(where: { $0.name == "Tech" }) else { + XCTFail("Expected a “Tech” folder") + return + } + guard let news = folders.first(where: { $0.name == "News" }) else { + XCTFail("Expected a “News” folder") + return + } + + // Feeds 101 and 105 belong to category 1 (“All”). + XCTAssertEqual(2, all.topLevelFeeds.count) + let allFeedExternalIDs = Set(all.topLevelFeeds.map { $0.externalID }) + XCTAssertEqual(Set(["101", "105"]), allFeedExternalIDs) + + // Feeds 102 and 103 belong to category 2 (“Tech”). + XCTAssertEqual(2, tech.topLevelFeeds.count) + let techFeedExternalIDs = Set(tech.topLevelFeeds.map { $0.externalID }) + XCTAssertEqual(Set(["102", "103"]), techFeedExternalIDs) + + // Feed 104 belongs to category 3 (“News”). + XCTAssertEqual(1, news.topLevelFeeds.count) + let newsFeedExternalIDs = Set(news.topLevelFeeds.map { $0.externalID }) + XCTAssertEqual(Set(["104"]), newsFeedExternalIDs) + + // Miniflux feeds always belong to exactly one category, so nothing should land + // at the account's top level. + XCTAssertEqual(0, account.topLevelFeeds.count) + + guard let generalFeed = all.topLevelFeeds.first(where: { $0.externalID == "101" }) else { + XCTFail("Expected feed 101 in the “All” folder") + return + } + XCTAssertEqual("https://miniflux.test/feeds/general.xml", generalFeed.url) + XCTAssertEqual("General Feed", generalFeed.name) + + TestAccountManager.shared.deleteAccount(account) + } + +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/MinifluxModelDecodingTests.swift b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxModelDecodingTests.swift new file mode 100644 index 000000000..056d1b619 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxModelDecodingTests.swift @@ -0,0 +1,157 @@ +// +// MinifluxModelDecodingTests.swift +// AccountTests +// +// Created by Dave Marquard on 7/7/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +@testable import Account + +@MainActor final class MinifluxModelDecodingTests: XCTestCase { + + func testDecodeUser() throws { + let user = try decode(MinifluxUser.self, from: "miniflux_me.json") + XCTAssertEqual(35, user.id) + XCTAssertEqual("testuser", user.username) + } + + func testDecodeCategories() throws { + let categories = try decode([MinifluxCategory].self, from: "miniflux_categories_initial.json") + XCTAssertEqual(3, categories.count) + + guard let all = categories.first(where: { $0.title == "All" }) else { + XCTFail("Expected an “All” category") + return + } + XCTAssertEqual(1, all.categoryID) + + guard let tech = categories.first(where: { $0.title == "Tech" }) else { + XCTFail("Expected a “Tech” category") + return + } + XCTAssertEqual(2, tech.categoryID) + + guard let news = categories.first(where: { $0.title == "News" }) else { + XCTFail("Expected a “News” category") + return + } + XCTAssertEqual(3, news.categoryID) + } + + func testDecodeCategoriesAfterDelete() throws { + let categories = try decode([MinifluxCategory].self, from: "miniflux_categories_delete.json") + XCTAssertEqual(2, categories.count) + XCTAssertFalse(categories.contains { $0.title == "News" }) + } + + func testDecodeFeeds() throws { + let feeds = try decode([MinifluxFeed].self, from: "miniflux_feeds_initial.json") + XCTAssertEqual(5, feeds.count) + + guard let feed = feeds.first(where: { $0.feedID == 101 }) else { + XCTFail("Expected feed 101") + return + } + XCTAssertEqual("https://miniflux.test/feeds/general.xml", feed.feedURL) + XCTAssertEqual("https://general.example", feed.siteURL) + XCTAssertEqual("General Feed", feed.title) + XCTAssertEqual(1, feed.category?.categoryID) + XCTAssertEqual("All", feed.category?.title) + + // Feed 105 has no "icon" key at all — confirms lenient decoding tolerates its absence. + guard let feedWithoutIcon = feeds.first(where: { $0.feedID == 105 }) else { + XCTFail("Expected feed 105") + return + } + XCTAssertEqual(1, feedWithoutIcon.category?.categoryID) + + let categoryIDs = Set(feeds.compactMap { $0.category?.categoryID }) + XCTAssertEqual(Set([1, 2, 3]), categoryIDs) + } + + func testDecodeEntriesResponse() throws { + let response = try decode(MinifluxEntriesResponse.self, from: "miniflux_entries_page1.json") + XCTAssertEqual(5, response.total) + XCTAssertEqual(5, response.entries.count) + + guard let unreadStarred = response.entries.first(where: { $0.entryID == 5001 }) else { + XCTFail("Expected entry 5001") + return + } + XCTAssertEqual(101, unreadStarred.feedID) + XCTAssertEqual("Jane Doe", unreadStarred.author) + XCTAssertEqual("unread", unreadStarred.status) + XCTAssertEqual(true, unreadStarred.starred) + // published_at has fractional seconds — confirms DateParser (not JSONDecoder's + // .iso8601 strategy) is what's doing the parsing. + XCTAssertNotNil(unreadStarred.parsedDatePublished) + + guard let readEntry = response.entries.first(where: { $0.entryID == 5002 }) else { + XCTFail("Expected entry 5002") + return + } + XCTAssertEqual("read", readEntry.status) + XCTAssertEqual(false, readEntry.starred) + + guard let missingAuthor = response.entries.first(where: { $0.entryID == 5003 }) else { + XCTFail("Expected entry 5003") + return + } + XCTAssertNil(missingAuthor.author) + + guard let emptyEnclosures = response.entries.first(where: { $0.entryID == 5004 }) else { + XCTFail("Expected entry 5004") + return + } + XCTAssertNotNil(emptyEnclosures.enclosures) + XCTAssertEqual(0, emptyEnclosures.enclosures?.count ?? -1) + XCTAssertNil(emptyEnclosures.attachments) + + guard let withEnclosure = response.entries.first(where: { $0.entryID == 5005 }) else { + XCTFail("Expected entry 5005") + return + } + guard let enclosure = withEnclosure.enclosures?.first else { + XCTFail("Expected an enclosure on entry 5005") + return + } + XCTAssertEqual("https://media.example/ep1.mp3", enclosure.url) + XCTAssertEqual("audio/mpeg", enclosure.mimeType) + + let attachments = withEnclosure.attachments ?? [] + XCTAssertEqual(["https://media.example/ep1.mp3", "https://media.example/ep1.jpg"], attachments.map(\.url)) + XCTAssertEqual(1234567, attachments.first?.sizeInBytes) + XCTAssertNil(attachments.last?.sizeInBytes) + XCTAssertEqual("https://media.example/ep1.jpg", withEnclosure.imageURL) + } + + func testDecodeEntryIDsResponse() throws { + let response = try decode(MinifluxEntryIDsResponse.self, from: "miniflux_entry_ids.json") + XCTAssertEqual(3, response.total) + XCTAssertEqual([5001, 5003, 5004], response.entryIDs) + } + + func testDecodeErrorResponse() throws { + let json = Data(#"{"error_message": "This feed already exists (feed_id: 123)"}"#.utf8) + let error = try JSONDecoder().decode(MinifluxErrorResponse.self, from: json) + XCTAssertEqual("This feed already exists (feed_id: 123)", error.errorMessage) + } + + func testDecodeVersionResponse() throws { + let response = try decode(MinifluxVersionResponse.self, from: "miniflux_version.json") + XCTAssertEqual("2.3.2", response.version) + } +} + +// MARK: - Fixture loading + +private extension MinifluxModelDecodingTests { + + func decode(_ type: T.Type, from fileName: String) throws -> T { + let fileURL = Bundle.module.resourceURL!.appendingPathComponent("JSON/\(fileName)") + let data = try Data(contentsOf: fileURL) + return try JSONDecoder().decode(T.self, from: data) + } +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/MinifluxStarredFallbackTests.swift b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxStarredFallbackTests.swift new file mode 100644 index 000000000..7aa622d64 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxStarredFallbackTests.swift @@ -0,0 +1,38 @@ +// +// MinifluxStarredFallbackTests.swift +// AccountTests +// +// Created by Dave Marquard on 7/15/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +import RSWeb +import Secrets +@testable import Account + +@MainActor final class MinifluxStarredFallbackTests: XCTestCase { + + override func setUp() { + TestingURLProtocol.reset() + } + + func testFallbackOnlyTogglesEntriesWhoseStateDiffers() async throws { + let accountSettings = AccountSettings(accountID: UUID().uuidString, dataFolder: NSTemporaryDirectory()) + accountSettings.endpointURL = URL(string: "https://miniflux.test") + accountSettings.detectedServerVersion = "2.1.0" // Below entryIDsMinimumVersion. + + let caller = MinifluxAPICaller() + caller.credentials = Credentials(type: .minifluxAPIToken, username: "", secret: "token") + caller.accountSettings = accountSettings + + // 5001 is already starred; 5002 is not. + TestingURLProtocol.setResponse("/v1/entries/5001", file: "JSON/miniflux_entry_5001_starred.json") + TestingURLProtocol.setResponse("/v1/entries/5002", file: "JSON/miniflux_entry_5002_unstarred.json") + + try await caller.updateEntries(entryIDs: [5001, 5002], starred: true) + + XCTAssertEqual(TestingURLProtocol.requestCount(forURLContaining: "/entries/5001/bookmark"), 0) + XCTAssertGreaterThan(TestingURLProtocol.requestCount(forURLContaining: "/entries/5002/bookmark"), 0) + } +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/MinifluxSyncRegressionTests.swift b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxSyncRegressionTests.swift new file mode 100644 index 000000000..31915a564 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxSyncRegressionTests.swift @@ -0,0 +1,89 @@ +// +// MinifluxSyncRegressionTests.swift +// AccountTests +// +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +import RSWeb +import SyncDatabase +@testable import Account + +@MainActor final class MinifluxSyncRegressionTests: XCTestCase { + + override func setUp() { + TestingURLProtocol.reset() + } + + func testFailedStarredSendKeepsItsQueuedStatusAfterReadSendSucceeds() async throws { + let account = TestAccountManager.shared.createAccount(type: .miniflux) + defer { TestAccountManager.shared.deleteAccount(account) } + account.endpointURL = URL(string: "https://miniflux.test") + (account.delegate as! MinifluxAccountDelegate).accountSettings?.detectedServerVersion = "2.1.0" + + let databasePath = (account.dataFolder as NSString).appendingPathComponent("Sync.sqlite3") + let database = SyncDatabase(databasePath: databasePath) + await database.insertStatuses([ + SyncStatus(articleID: "5001", key: .read, flag: true), + SyncStatus(articleID: "5001", key: .starred, flag: true) + ]) + TestingURLProtocol.setResponse(.init(statusCode: 204), forURLContaining: "/v1/entries", httpMethod: "PUT") + TestingURLProtocol.setResponse(.init(statusCode: 500), forURLContaining: "/v1/entries/5001", httpMethod: "GET") + + do { + try await account.sendArticleStatus() + XCTFail("Expected the starred update to fail") + } catch { + let pendingRead = try await database.selectPendingReadStatusArticleIDs() + let pendingStarred = try await database.selectPendingStarredStatusArticleIDs() + XCTAssertEqual(pendingRead, []) + XCTAssertEqual(pendingStarred, ["5001"]) + } + } + + func testFailedInitialReconciliationIsRetried() async throws { + TestingURLProtocol.setResponse("/v1/version", file: "JSON/miniflux_version.json") + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_initial.json") + TestingURLProtocol.setResponse("/v1/feeds", file: "JSON/miniflux_feeds_initial.json") + TestingURLProtocol.setResponse("/v1/entries?", file: "JSON/miniflux_entries_page1.json") + TestingURLProtocol.setResponse(.init(statusCode: 500), forURLContaining: "/v1/entries/ids") + + let account = TestAccountManager.shared.createAccount(type: .miniflux) + defer { TestAccountManager.shared.deleteAccount(account) } + account.endpointURL = URL(string: "https://miniflux.test") + + do { + try await account.refreshAll() + XCTFail("Expected initial reconciliation to fail") + } catch {} + let firstAttemptCount = TestingURLProtocol.requestCount(forURLContaining: "/v1/entries/ids") + XCTAssertGreaterThan(firstAttemptCount, 0) + + TestingURLProtocol.setResponse("/v1/entries/ids", file: "JSON/miniflux_entry_ids.json") + try await account.refreshAll() + + XCTAssertGreaterThan(TestingURLProtocol.requestCount(forURLContaining: "/v1/entries/ids"), firstAttemptCount) + } + + func testInitialReconciliationPreservesPendingLocalStatus() async { + let account = TestAccountManager.shared.createAccount(type: .miniflux) + defer { TestAccountManager.shared.deleteAccount(account) } + let delegate = account.delegate as! MinifluxAccountDelegate + var markedOff = Set() + + let changedCount = await delegate.syncArticleState( + entryIDs: [], + pendingArticleIDs: ["5001"], + currentArticleIDs: { ["5001"] }, + markOn: { $0 }, + markOff: { articleIDs in + markedOff = articleIDs + return articleIDs + } + ) + + XCTAssertTrue(markedOff.isEmpty) + XCTAssertEqual(changedCount, 0) + } +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionFallbackTests.swift b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionFallbackTests.swift new file mode 100644 index 000000000..dbd6b1c1f --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionFallbackTests.swift @@ -0,0 +1,64 @@ +// +// MinifluxVersionFallbackTests.swift +// AccountTests +// +// Created by Dave Marquard on 7/15/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +import RSWeb +@testable import Account + +@MainActor final class MinifluxVersionFallbackTests: XCTestCase { + + override func setUp() { + TestingURLProtocol.reset() + } + + /// On a server older than `entryIDsMinimumVersion`, `/v1/entries/ids` isn’t stubbed at + /// all — if the gating logic wrongly tried to use it, `refreshAll()` would throw. Instead + /// the initial sync's reconciliation must fall back to paging `/v1/entries`. + func testInitialSyncOnOldServerFallsBackToPagedEntries() async throws { + TestingURLProtocol.setResponse("/v1/version", file: "JSON/miniflux_version_old.json") + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_initial.json") + TestingURLProtocol.setResponse("/v1/feeds", file: "JSON/miniflux_feeds_initial.json") + TestingURLProtocol.setResponse("/v1/entries?", file: "JSON/miniflux_entries_page1.json") + + let account = TestAccountManager.shared.createAccount(type: .miniflux) + account.endpointURL = URL(string: "https://miniflux.test") + + try await account.refreshAll() + + let unreadArticleIDs = await account.fetchUnreadArticleIDsAsync() + let starredArticleIDs = await account.fetchStarredArticleIDsAsync() + XCTAssertTrue(unreadArticleIDs.contains("5001")) + XCTAssertTrue(starredArticleIDs.contains("5001")) + + TestAccountManager.shared.deleteAccount(account) + } + + /// On a current server, the initial sync's reconciliation should still use + /// `/v1/entries/ids` rather than the paged fallback. + func testInitialSyncOnCurrentServerStillUsesEntryIDsEndpoint() async throws { + TestingURLProtocol.setResponse("/v1/version", file: "JSON/miniflux_version.json") + TestingURLProtocol.setResponse("/v1/categories", file: "JSON/miniflux_categories_initial.json") + TestingURLProtocol.setResponse("/v1/feeds", file: "JSON/miniflux_feeds_initial.json") + TestingURLProtocol.setResponse("/v1/entries/ids", file: "JSON/miniflux_entry_ids.json") + TestingURLProtocol.setResponse("/v1/entries?", file: "JSON/miniflux_entries_page1.json") + + let account = TestAccountManager.shared.createAccount(type: .miniflux) + account.endpointURL = URL(string: "https://miniflux.test") + + try await account.refreshAll() + + XCTAssertGreaterThan(TestingURLProtocol.requestCount(forURLContaining: "/v1/entries/ids"), 0) + + let unreadArticleIDs = await account.fetchUnreadArticleIDsAsync() + let starredArticleIDs = await account.fetchStarredArticleIDsAsync() + XCTAssertTrue(unreadArticleIDs.contains("5001")) + XCTAssertTrue(starredArticleIDs.contains("5001")) + + TestAccountManager.shared.deleteAccount(account) + } +} diff --git a/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionTests.swift b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionTests.swift new file mode 100644 index 000000000..1c88ecc28 --- /dev/null +++ b/Modules/Account/Tests/AccountTests/Miniflux/MinifluxVersionTests.swift @@ -0,0 +1,41 @@ +// +// MinifluxVersionTests.swift +// AccountTests +// +// Created by Dave Marquard on 7/8/26. +// Copyright © 2026 Ranchero Software, LLC. All rights reserved. +// + +import XCTest +@testable import Account + +final class MinifluxVersionTests: XCTestCase { + + func testParsesSimpleVersionString() throws { + let version = try XCTUnwrap(MinifluxVersion(string: "2.3.2")) + XCTAssertGreaterThanOrEqual(version, MinifluxVersion(2, 3, 2)) + XCTAssertEqual(version, MinifluxVersion(2, 3, 2)) + } + + func testComparesNumericallyNotLexicographically() { + XCTAssertGreaterThan(MinifluxVersion(2, 3, 10), MinifluxVersion(2, 3, 2)) + } + + func testOlderMinorVersionIsLess() { + XCTAssertLessThan(MinifluxVersion(2, 2, 17), MinifluxVersion(2, 3, 2)) + } + + func testParsesNonNumericSuffixOnLastComponent() throws { + let version = try XCTUnwrap(MinifluxVersion(string: "2.3.2-dev")) + XCTAssertEqual(version, MinifluxVersion(2, 3, 2)) + } + + func testMissingComponentIsTreatedAsZero() throws { + let version = try XCTUnwrap(MinifluxVersion(string: "2.3")) + XCTAssertEqual(version, MinifluxVersion(2, 3, 0)) + } + + func testWhollyNonNumericStringFailsToParse() { + XCTAssertNil(MinifluxVersion(string: "dev")) + } +} diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift index 2b3474b5c..90145b7e0 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesDatabase.swift @@ -352,6 +352,18 @@ public struct ArticleCounts: Sendable { } } + /// Delete statuses — only for articles the sync service has affirmatively reported + /// as deleted. Statuses intentionally outlive their articles (see + /// `ArticlesTable.deleteStatuses`); deleting one on any weaker signal reintroduces + /// the old-articles-reappear-as-unread class of bugs. + public func deleteStatusesAsync(articleIDs: Set) async { + await withCheckedContinuation { continuation in + _deleteStatuses(articleIDs: articleIDs) { + continuation.resume() + } + } + } + // MARK: - ArticleIDs /// Fetch the articleIDs of unread articles. @@ -556,6 +568,11 @@ private extension ArticlesDatabase { articlesTable.delete(articleIDs: articleIDs, completion: completion) } + func _deleteStatuses(articleIDs: Set, completion: DatabaseCompletionBlock?) { + Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") + articlesTable.deleteStatuses(articleIDs: articleIDs, completion: completion) + } + func _fetchUnreadArticleIDsAsync(completion: @escaping ArticleIDsCompletionBlock) { Self.logger.debug("ArticlesDatabase: \(#function, privacy: .public) \(self.accountID, privacy: .public)") articlesTable.fetchUnreadArticleIDsAsync(completion) diff --git a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift index 555430122..9f73e1534 100644 --- a/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift +++ b/Modules/ArticlesDatabase/Sources/ArticlesDatabase/ArticlesTable.swift @@ -352,6 +352,29 @@ final class ArticlesTable: DatabaseTable, Sendable { } } + /// Delete statuses for articles the sync service reports as deleted. + /// + /// Statuses deliberately outlive their articles: they're what lets + /// `articleIsIgnorable` drop a re-appearing old article instead of resurrecting + /// it, and what keeps long-lived feed items from coming back as unread. So + /// nothing else — not article deletion, not the retention cleanups — removes a + /// status before its own aging window ends. + /// + /// The flip side: a status whose article no longer exists on the sync service + /// matches `fetchArticleIDsForStatusesWithoutArticlesNewerThanCutoffDate` + /// on every sync, so the account delegate re-requests the article forever and + /// the service keeps saying it's gone. Deleting the status is the terminal state + /// for that loop — and it's only safe here, when the service has affirmatively + /// reported the article deleted. + public func deleteStatuses(articleIDs: Set, completion: DatabaseCompletionBlock?) { + self.queue.runInTransaction { database in + self.statusesTable.removeStatuses(articleIDs, database) + DispatchQueue.main.async { + completion?() + } + } + } + // MARK: - Unread Counts /// Calls `completion` with nil if the query fails, so a failure doesn’t zero every unread count. diff --git a/Modules/Secrets/Sources/Secrets/Credentials.swift b/Modules/Secrets/Sources/Secrets/Credentials.swift index 96b32d4f6..025fad3b2 100644 --- a/Modules/Secrets/Sources/Secrets/Credentials.swift +++ b/Modules/Secrets/Sources/Secrets/Credentials.swift @@ -58,6 +58,8 @@ public enum CredentialsType: String, CaseIterable, Sendable { case newsBlurSessionID = "newsBlurSessionId" case readerBasic = "readerBasic" case readerAPIKey = "readerAPIKey" + case minifluxBasic = "minifluxBasic" + case minifluxAPIToken = "minifluxAPIToken" case oauthAccessToken = "oauthAccessToken" case oauthAccessTokenSecret = "oauthAccessTokenSecret" case oauthRefreshToken = "oauthRefreshToken" diff --git a/Shared/AccountType+Helpers.swift b/Shared/AccountType+Helpers.swift index 632d9f861..6d9211905 100644 --- a/Shared/AccountType+Helpers.swift +++ b/Shared/AccountType+Helpers.swift @@ -36,6 +36,8 @@ extension AccountType { return .systemTeal case .inoreader: return .systemBrown + case .miniflux: + return .systemMint case .bazQux: return .systemIndigo case .theOldReader: @@ -59,6 +61,8 @@ extension AccountType { return .teal case .inoreader: return .brown + case .miniflux: + return .mint case .bazQux: return .indigo case .theOldReader: @@ -93,6 +97,8 @@ extension AccountType { return Image("accountFreshRSS") case .inoreader: return Image("accountInoreader") + case .miniflux: + return Image("accountMiniflux") case .newsBlur: return Image("accountNewsBlur") case .theOldReader: diff --git a/Shared/Assets.swift b/Shared/Assets.swift index ee6b7fae7..aec49360e 100644 --- a/Shared/Assets.swift +++ b/Shared/Assets.swift @@ -30,6 +30,7 @@ struct Assets { static var accountFeedly: RSImage { RSImage(named: "accountFeedly")! } static var accountFreshRSS: RSImage { RSImage(named: "accountFreshRSS")! } static var accountInoreader: RSImage { RSImage(named: "accountInoreader")! } + static var accountMiniflux: RSImage { RSImage(named: "accountMiniflux")! } static var accountNewsBlur: RSImage { RSImage(named: "accountNewsBlur")! } static var accountTheOldReader: RSImage { RSImage(named: "accountTheOldReader")! } @@ -179,6 +180,8 @@ struct Assets { return Assets.Images.accountFreshRSS case .inoreader: return Assets.Images.accountInoreader + case .miniflux: + return Assets.Images.accountMiniflux case .newsBlur: return Assets.Images.accountNewsBlur case .theOldReader: diff --git a/Shared/Localizable.xcstrings b/Shared/Localizable.xcstrings index f05fa3540..cc08003d1 100644 --- a/Shared/Localizable.xcstrings +++ b/Shared/Localizable.xcstrings @@ -48,6 +48,9 @@ } } }, + "A username and password are required." : { + "comment" : "Credentials Error" + }, "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.", "localizations" : { @@ -182,9 +185,18 @@ "Always Use Reader View" : { "comment" : "Always Use Reader View" }, + "An API token is required." : { + "comment" : "Credentials Error" + }, + "API Token" : { + "comment" : "Miniflux authentication mode and token field" + }, "API URL: https://fresh.rss.net/api/greader.php" : { "comment" : "FreshRSS API Helper" }, + "API URL: https://miniflux.example.com" : { + "comment" : "Miniflux API Helper" + }, "Appearance" : { "comment" : "Preferences" }, @@ -258,6 +270,9 @@ "Author’s website:\n%@" : { "comment" : "Authors website" }, + "Authentication" : { + "comment" : "Miniflux authentication mode picker" + }, "Automatic" : { "comment" : "Automatic" }, @@ -516,6 +531,9 @@ "Don’t have a FreshRSS instance?" : { "comment" : "No FreshRSS" }, + "Don’t have a Miniflux instance?" : { + "comment" : "No Miniflux" + }, "Don’t have a The Old Reader account?" : { "comment" : "No OldReader" }, @@ -654,7 +672,7 @@ "comment" : "Find in Article" }, "Find out more" : { - "comment" : "No FreshRSS Button" + "comment" : "No FreshRSS Button\nNo Miniflux Button" }, "Find Out More" : { "comment" : "Find Out More" @@ -760,6 +778,9 @@ "https://fresh.rss.net/api/greader.php" : { "comment" : "FreshRSS API Helper" }, + "https://miniflux.example.com" : { + "comment" : "Miniflux API Helper" + }, "iCloud" : { "comment" : "iCloud Account", "localizations" : { @@ -806,9 +827,15 @@ "Invalid API URL." : { "comment" : "Invalid API URL" }, + "Invalid credentials." : { + "comment" : "Credentials Error" + }, "Invalid email/password combination." : { "comment" : "Credentials Error" }, + "Invalid username/password combination, or invalid API token." : { + "comment" : "Credentials Error" + }, "Invalid username/password combination." : { "comment" : "Credentials Error" }, @@ -1367,6 +1394,12 @@ "Sign in to your Inoreader account." : { "comment" : "Inoreader" }, + "Sign in to your Miniflux account." : { + "comment" : "Miniflux" + }, + "Sign in to your Miniflux instance and sync your feeds across your devices. Your credentials will be encrypted and stored in Keychain.\n\nDon’t have a Miniflux instance?" : { + "comment" : "Miniflux" + }, "Sign in to your NewsBlur account and sync your feeds across your devices. Your username and password will be encrypted and stored in Keychain.\n\nDon’t have a NewsBlur account?" : { "comment" : "NewsBlur" }, @@ -1504,6 +1537,9 @@ "There is already a Feedbin account with that username created." : { "comment" : "Duplicate Error" }, + "There is already a Miniflux account for this user on this server." : { + "comment" : "Duplicate Error" + }, "There is already a NewsBlur account with that username created." : { "comment" : "Duplicate Error" }, @@ -1720,6 +1756,9 @@ "Username and password are required." : { "comment" : "Credentials Error" }, + "Username and Password" : { + "comment" : "Miniflux authentication mode" + }, "Username or Email" : { "comment" : "Username field placeholder" }, @@ -1807,4 +1846,4 @@ } }, "version" : "1.1" -} \ No newline at end of file +} diff --git a/iOS/Account/MinifluxAccountView.swift b/iOS/Account/MinifluxAccountView.swift new file mode 100644 index 000000000..8ba5a2578 --- /dev/null +++ b/iOS/Account/MinifluxAccountView.swift @@ -0,0 +1,144 @@ +// +// MinifluxAccountView.swift +// NetNewsWire-iOS +// +// Copyright © 2026 Ranchero Software. All rights reserved. +// + +import SwiftUI +import RSCore +import Account +import Secrets + +/// Miniflux supports either a username and password or an API token. +struct MinifluxAccountView: View { + + let account: Account? + let didAddAccount: (() -> Void)? + + @Environment(\.dismiss) private var dismiss + @State private var username = "" + @State private var password = "" + @State private var apiToken = "" + @State private var apiURLString = "" + @State private var usesAPIToken = false + @State private var isValidating = false + @State private var errorMessage: String? + @State private var isShowingSignUp = false + + var body: some View { + AccountSetupSheet(accountType: .miniflux, isWorking: isValidating) { + Section { + Picker(NSLocalizedString("Authentication", comment: "Miniflux authentication mode"), selection: $usesAPIToken) { + Text(NSLocalizedString("Username and Password", comment: "Miniflux authentication mode")).tag(false) + Text(NSLocalizedString("API Token", comment: "Miniflux authentication mode")).tag(true) + } + if usesAPIToken { + SecureField(NSLocalizedString("API Token", comment: "Miniflux API token"), text: $apiToken) + } else { + TextField(NSLocalizedString("Username or Email", comment: "Username field placeholder"), text: $username) + .textContentType(.username) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + SecureField(NSLocalizedString("Password", comment: "Password field placeholder"), text: $password) + } + TextField(NSLocalizedString("API URL: https://miniflux.example.com", comment: "Miniflux API Helper"), text: $apiURLString) + .textContentType(.URL) + .keyboardType(.URL) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } header: { + AccountIconHeader(accountType: .miniflux) + } + Section { + Button(account == nil ? NSLocalizedString("Add Account", comment: "Add Account") : NSLocalizedString("Update Credentials", comment: "Update Credentials")) { + Task { await submit() } + } + .frame(maxWidth: .infinity) + .disabled(!canSubmit || isValidating) + } footer: { + AccountSheetFooter(text: NSLocalizedString("Sign in to your Miniflux instance and sync your feeds across your devices. Your credentials will be encrypted and stored in Keychain.\n\nDon’t have a Miniflux instance?", comment: "Miniflux"), linkTitle: NSLocalizedString("Find Out More", comment: "Find Out More")) { + isShowingSignUp = true + } + } + } + .errorAlert(message: $errorMessage) + .sheet(isPresented: $isShowingSignUp) { + if let signUpURL = URL(string: "https://miniflux.app") { + SafariView(url: signUpURL) + } + } + .onAppear { loadExistingCredentials() } + } + + private var canSubmit: Bool { + guard !apiURLString.trimmingWhitespace.isEmpty else { + return false + } + return usesAPIToken + ? !apiToken.trimmingWhitespace.isEmpty + : !username.trimmingWhitespace.isEmpty && !password.isEmpty + } + + private func loadExistingCredentials() { + guard let account else { + return + } + apiURLString = account.endpointURL?.absoluteString ?? "" + if let credentials = try? account.retrieveCredentials(type: .minifluxAPIToken) { + usesAPIToken = true + apiToken = credentials.secret + } else if let credentials = try? account.retrieveCredentials(type: .minifluxBasic) { + username = credentials.username + password = credentials.secret + } + } + + @MainActor private func submit() async { + guard let endpoint = normalizedEndpointURL else { + errorMessage = NSLocalizedString("Invalid API URL.", comment: "Invalid API URL") + return + } + let credentials = usesAPIToken + ? Credentials(type: .minifluxAPIToken, username: "", secret: apiToken.trimmingWhitespace) + : Credentials(type: .minifluxBasic, username: username.trimmingWhitespace, secret: password) + + isValidating = true + defer { isValidating = false } + + do { + guard let validatedCredentials = try await Account.validateCredentials(type: .miniflux, credentials: credentials, endpoint: endpoint) else { + errorMessage = NSLocalizedString("Invalid username/password combination, or invalid API token.", comment: "Credentials Error") + return + } + if account == nil && AccountManager.shared.duplicateServiceAccount(type: .miniflux, endpointURL: endpoint, username: validatedCredentials.username) { + errorMessage = NSLocalizedString("There is already a Miniflux account for this user on this server.", comment: "Duplicate Error") + return + } + + let account = self.account ?? AccountManager.shared.createAccount(type: .miniflux) + account.endpointURL = endpoint + let staleType: CredentialsType = validatedCredentials.type == .minifluxAPIToken ? .minifluxBasic : .minifluxAPIToken + try? account.removeCredentials(type: staleType) + try account.storeCredentials(validatedCredentials) + + account.triggerRefreshAll() + dismiss() + didAddAccount?() + } catch { + errorMessage = error.localizedDescription + } + } + + private var normalizedEndpointURL: URL? { + var text = apiURLString.trimmingWhitespace + while text.hasSuffix("/") { text.removeLast() } + if text.hasSuffix("/v1") { text.removeLast(3) } + while text.hasSuffix("/") { text.removeLast() } + guard !text.isEmpty else { + return nil + } + if !text.contains("://") { text = "https://" + text } + return URL(string: text) + } +} diff --git a/iOS/Inspector/AccountInspectorView.swift b/iOS/Inspector/AccountInspectorView.swift index fca3270ba..bafdfa98a 100644 --- a/iOS/Inspector/AccountInspectorView.swift +++ b/iOS/Inspector/AccountInspectorView.swift @@ -94,7 +94,7 @@ struct AccountInspectorView: View { AccountManager.shared.syncArticleContentForUnreadArticles = syncContentOfUnreadArticles } .sheet(isPresented: $isShowingCredentials) { - CredentialsAccountView(accountType: account.type, account: account, didAddAccount: nil) + credentialsView } .sheet(isPresented: $isShowingLimitationsAndSolutions) { SafariView(url: CloudKitWebDocumentation.limitationsAndSolutionsURL) @@ -120,7 +120,15 @@ private extension AccountInspectorView { } var showsCredentials: Bool { - !isDefaultAccount && CredentialsAccountView.accountTypes.contains(account.type) + !isDefaultAccount && (account.type == .miniflux || CredentialsAccountView.accountTypes.contains(account.type)) + } + + @ViewBuilder var credentialsView: some View { + if account.type == .miniflux { + MinifluxAccountView(account: account, didAddAccount: nil) + } else { + CredentialsAccountView(accountType: account.type, account: account, didAddAccount: nil) + } } var showsSyncContent: Bool { diff --git a/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json new file mode 100644 index 000000000..a99b60f8b --- /dev/null +++ b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/Contents.json @@ -0,0 +1,26 @@ +{ + "images" : [ + { + "filename" : "accountMiniflux.pdf", + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "filename" : "accountMiniflux-dark.pdf", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "preserves-vector-representation" : true, + "template-rendering-intent" : "original" + } +} diff --git a/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf new file mode 100644 index 000000000..8b5c75013 Binary files /dev/null and b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux-dark.pdf differ diff --git a/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf new file mode 100644 index 000000000..c3ff8b257 Binary files /dev/null and b/iOS/Resources/Assets.xcassets/accountMiniflux.imageset/accountMiniflux.pdf differ diff --git a/iOS/Settings/AddAccountView.swift b/iOS/Settings/AddAccountView.swift index bf68330c8..097fbec8c 100644 --- a/iOS/Settings/AddAccountView.swift +++ b/iOS/Settings/AddAccountView.swift @@ -66,7 +66,7 @@ struct AddAccountView: View { case .web: return [.bazQux, .feedbin, .feedly, .inoreader, .newsBlur, .theOldReader] case .selfhosted: - return [.freshRSS] + return [.freshRSS, .miniflux] } } } @@ -100,6 +100,8 @@ struct AddAccountView: View { LocalAccountView(didAddAccount: didAddAccount) case .cloudKit: CloudKitAccountView(didAddAccount: didAddAccount) + case .miniflux: + MinifluxAccountView(account: nil, didAddAccount: didAddAccount) default: CredentialsAccountView(accountType: sheet.accountType, account: nil, didAddAccount: didAddAccount) } diff --git a/iOS/UIKit Extensions/UIViewController+Extras.swift b/iOS/UIKit Extensions/UIViewController+Extras.swift index 09b9b23ee..829f7f33d 100644 --- a/iOS/UIKit Extensions/UIViewController+Extras.swift +++ b/iOS/UIKit Extensions/UIViewController+Extras.swift @@ -16,6 +16,17 @@ extension UIViewController { /// Size of form sheets on iPad. static let formSheetSize = CGSize(width: 460, height: 400) + /// The sheet for updating an account's credentials, or nil if its type has none. + static func credentialsViewController(for account: Account) -> UIViewController? { + if account.type == .miniflux { + return UIHostingController(rootView: MinifluxAccountView(account: account, didAddAccount: nil)) + } + guard CredentialsAccountView.accountTypes.contains(account.type) else { + return nil + } + return UIHostingController(rootView: CredentialsAccountView(accountType: account.type, account: account, didAddAccount: nil)) + } + func presentError(_ error: Error, dismiss: (() -> Void)? = nil) { if let accountError = error as? AccountError, accountError.isCredentialsError { presentAccountError(accountError, dismiss: dismiss) @@ -35,12 +46,11 @@ private extension UIViewController { let title = NSLocalizedString("Account Error", comment: "Account Error") let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert) - if let account = AccountError.account(from: error), CredentialsAccountView.accountTypes.contains(account.type) { + if let account = AccountError.account(from: error), let hostingController = UIViewController.credentialsViewController(for: account) { let credentialsTitle = NSLocalizedString("Update Credentials", comment: "Update Credentials") let credentialsAction = UIAlertAction(title: credentialsTitle, style: .default) { [weak self] _ in dismiss?() - let hostingController = UIHostingController(rootView: CredentialsAccountView(accountType: account.type, account: account, didAddAccount: nil)) hostingController.modalPresentationStyle = .formSheet hostingController.preferredContentSize = UIViewController.formSheetSize self?.present(hostingController, animated: true)