Add more activity detail to feed finding.

This commit is contained in:
Brent Simmons committed 2026-05-30 10:34:05 -07:00
1 parent d297501e19
commit d1fc7b4822
5 files changed
+132 -16

No files matched your search

@@ -491,6 +491,8 @@ private extension ActivityLogWindowController {
return "Importing OPML"
case .findFeed(let urlString):
return "Finding feed \(urlString)"
case .fetchFeedCandidate(let urlString):
return "Fetching \(urlString)"
case .downloadFeedImage(let feedURL):
return "Downloading image \(feedURL)"
case .downloadFavicon(let faviconURL):
+6 -1
View File
@@ -422,6 +422,11 @@ private extension ActivityWindowController {
let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes)
result.append(NSAttributedString(string: urlString, attributes: secondaryAttributes))
return result
case .fetchFeedCandidate(let urlString):
let prefix = NSLocalizedString("Fetching", comment: "Activity kind — fetching a candidate URL during feed finding")
let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes)
result.append(NSAttributedString(string: urlString, attributes: secondaryAttributes))
return result
case .downloadFeedImage(let feedURL):
let prefix = NSLocalizedString("Downloading image", comment: "Activity kind — downloading feed image")
let result = NSMutableAttributedString(string: "\(prefix) ", attributes: primaryAttributes)
@@ -501,7 +506,7 @@ private extension ActivityWindowController {
return NSLocalizedString("Validating credentials", comment: "Activity kind")
case .exportOPML:
return NSLocalizedString("Exporting OPML", comment: "Activity kind")
case .refreshFeedContent, .findFeed, .downloadFeedImage, .downloadFavicon, .downloadAvatar, .downloadHTMLMetadata:
case .refreshFeedContent, .findFeed, .fetchFeedCandidate, .downloadFeedImage, .downloadFavicon, .downloadAvatar, .downloadHTMLMetadata:
return ""
}
}
@@ -9,11 +9,14 @@
import Foundation
import RSParser
import RSWeb
import FeedFinder
struct InitialFeedDownloader {
@MainActor static func download(_ url: URL) async throws -> (ParsedFeed?, URLResponse?) {
let (data, response) = try await Downloader.shared.download(url)
// Route through FeedFinder.downloadAndLog so the fetch shows up in the
// activity log alongside the candidate fetches that preceded it.
let (data, response) = try await FeedFinder.downloadAndLog(url)
guard let data else {
return (nil, response)
}
@@ -51,6 +51,7 @@ public enum ActivityKind: Sendable, Hashable {
// Non-account
case findFeed(urlString: String)
case fetchFeedCandidate(urlString: String)
case downloadFeedImage(feedURL: String)
case downloadFavicon(faviconURL: String)
case downloadAvatar(avatarURL: String)
@@ -27,11 +27,21 @@ public enum FeedFinderError: LocalizedError {
public final class FeedFinder {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedFinder")
/// Which discovery path produced the result. Used to write a more useful
/// completion message on the parent `findFeed` activity.
enum FindStrategy {
case specialCase
case microblogJSON
case directFeed
case htmlHead
case candidates
}
@concurrent public static func find(url: URL) async throws -> Set<FeedSpecifier> {
let activityID = await activityStart(url: url)
do {
let result = try await performFind(url: url)
await activityComplete(id: activityID, result: result)
let (result, strategy) = try await performFind(url: url)
await activityComplete(id: activityID, result: result, strategy: strategy)
return result
} catch {
await activityFail(id: activityID, error: error)
@@ -39,21 +49,21 @@ public final class FeedFinder {
}
}
@concurrent private static func performFind(url: URL) async throws -> Set<FeedSpecifier> {
@concurrent private static func performFind(url: URL) async throws -> (Set<FeedSpecifier>, FindStrategy) {
// Check special cases first.
if let feedSpecifier = FeedSpecifier.knownFeedSpecifier(url: url) {
logger.info("FeedFinder: found special case feed URL: \(url.absoluteString) - \(feedSpecifier.urlString)")
return Set([feedSpecifier])
return (Set([feedSpecifier]), .specialCase)
}
let (data, response) = try await Downloader.shared.download(url)
let (data, response) = try await downloadAndLog(url)
if response?.forcedStatusCode == 404 {
if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), urlComponents.host == "micro.blog" {
urlComponents.path = "\(urlComponents.path).json"
if let newURLString = urlComponents.url?.absoluteString {
let microblogFeedSpecifier = FeedSpecifier(title: nil, urlString: newURLString, source: .HTMLLink, orderFound: 1)
return Set([microblogFeedSpecifier])
return (Set([microblogFeedSpecifier]), .microblogJSON)
}
}
throw FeedFinderError.feedNotFound
@@ -69,7 +79,7 @@ public final class FeedFinder {
if FeedFinder.isFeed(data, url.absoluteString) {
let feedSpecifier = FeedSpecifier(title: nil, urlString: url.absoluteString, source: .userEntered, orderFound: 1)
return Set([feedSpecifier])
return (Set([feedSpecifier]), .directFeed)
}
if !FeedFinder.isHTML(data) {
@@ -79,6 +89,27 @@ public final class FeedFinder {
return try await FeedFinder.findFeedsInHTMLPage(htmlData: data, urlString: url.absoluteString)
}
/// Wraps `Downloader.shared.download(url)` with a per-URL activity entry so
/// the activity log shows every URL that was tried and what came back.
/// HTTP non-2xx is recorded as a *completed* activity (the network call
/// worked, the server returned a status); a thrown error (network failure,
/// timeout, DNS) records as `failed`.
///
/// Public so callers performing feed-finding-adjacent fetches (e.g. the
/// post-find download that validates the chosen feed) can have their
/// fetches appear in the same Feed Finder activity stream.
public static func downloadAndLog(_ url: URL) async throws -> (Data?, URLResponse?) {
let id = await activityFetchStart(url: url)
do {
let (data, response) = try await Downloader.shared.download(url)
await activityFetchComplete(id: id, data: data, response: response)
return (data, response)
} catch {
await activityFetchFail(id: id, error: error)
throw error
}
}
@MainActor private static func activityStart(url: URL) -> Int {
let activityLog = ActivityLog.shared
let id = activityLog.createActivity(owner: .feedFinder, kind: .findFeed(urlString: url.absoluteString))
@@ -86,14 +117,31 @@ public final class FeedFinder {
return id
}
@MainActor private static func activityComplete(id: Int, result: Set<FeedSpecifier>) {
let message = result.isEmpty ? "No feeds found" : "\(result.count) feed\(result.count == 1 ? "" : "s") found"
@MainActor private static func activityComplete(id: Int, result: Set<FeedSpecifier>, strategy: FindStrategy) {
let message = parentCompletionMessage(result: result, strategy: strategy)
ActivityLog.shared.didComplete(id: id, message: message)
}
@MainActor private static func activityFail(id: Int, error: any Error) {
ActivityLog.shared.didFail(id: id, error: error)
}
@MainActor private static func activityFetchStart(url: URL) -> Int {
let activityLog = ActivityLog.shared
let id = activityLog.createActivity(owner: .feedFinder, kind: .fetchFeedCandidate(urlString: url.absoluteString))
activityLog.didStart(id: id)
return id
}
@MainActor private static func activityFetchComplete(id: Int, data: Data?, response: URLResponse?) {
let message = fetchCompletionMessage(data: data, response: response)
// A cached fetch can complete in zero seconds; suppress the misleading "(0.00s)".
ActivityLog.shared.didComplete(id: id, message: message, durationIsSignificant: false)
}
@MainActor private static func activityFetchFail(id: Int, error: any Error) {
ActivityLog.shared.didFail(id: id, error: error)
}
}
private extension FeedFinder {
@@ -109,7 +157,7 @@ private extension FeedFinder {
}
}
static func findFeedsInHTMLPage(htmlData: Data, urlString: String) async throws -> Set<FeedSpecifier> {
static func findFeedsInHTMLPage(htmlData: Data, urlString: String) async throws -> (Set<FeedSpecifier>, FindStrategy) {
// Feeds in the <head> section we automatically assume are feeds.
// If there are none from the <head> section,
// then possible feeds in <body> section are downloaded individually
@@ -133,11 +181,12 @@ private extension FeedFinder {
}
if didFindFeedInHTMLHead {
return Set(feedSpecifiers.values)
return (Set(feedSpecifiers.values), .htmlHead)
} else if feedSpecifiersToDownload.isEmpty {
throw FeedFinderError.feedNotFound
} else {
return await downloadFeedSpecifiers(feedSpecifiersToDownload, feedSpecifiers: feedSpecifiers)
let result = await downloadFeedSpecifiers(feedSpecifiersToDownload, feedSpecifiers: feedSpecifiers)
return (result, .candidates)
}
}
@@ -178,14 +227,15 @@ private extension FeedFinder {
group.addTask {
do {
let (data, response) = try await Downloader.shared.download(url)
let (data, response) = try await downloadAndLog(url)
if let data, let response, response.statusIsOK {
if self.isFeed(data, downloadFeedSpecifier.urlString) {
return downloadFeedSpecifier
}
}
} catch {
// Ignore download errors for individual feeds
// The per-URL activity has already recorded the failure;
// one bad candidate shouldn't fail the whole find.
}
return nil
}
@@ -205,4 +255,59 @@ private extension FeedFinder {
let parserData = ParserData(url: urlString, data: data)
return FeedParser.canParse(parserData)
}
static func parentCompletionMessage(result: Set<FeedSpecifier>, strategy: FindStrategy) -> String {
let count = result.count
if count == 0 {
switch strategy {
case .candidates:
return "No feeds found in candidate URLs"
default:
return "No feeds found"
}
}
let plural = count == 1 ? "feed" : "feeds"
switch strategy {
case .specialCase:
return "\(count) \(plural) (special case match)"
case .microblogJSON:
return "\(count) \(plural) via Micro.blog .json fallback"
case .directFeed:
return "Direct feed"
case .htmlHead:
return "\(count) \(plural) via HTML <head>"
case .candidates:
return "\(count) \(plural) via candidate URLs"
}
}
static func fetchCompletionMessage(data: Data?, response: URLResponse?) -> String {
guard let response else {
return "No response"
}
let statusPart = formattedStatus(response.forcedStatusCode)
if response.statusIsOK, let data, !data.isEmpty {
let sizeText = ByteCountFormatter.string(fromByteCount: Int64(data.count), countStyle: .file)
return "\(statusPart) · \(sizeText)"
}
return statusPart
}
static func formattedStatus(_ statusCode: Int) -> String {
if statusCode == 0 {
return "No status"
}
// HTTPURLResponse.localizedString returns lowercase phrases like "not found".
// 200 maps to "no error" in some Foundation builds; spell out "OK" ourselves.
let phrase: String
switch statusCode {
case 200:
phrase = "OK"
case 304:
phrase = "Not Modified"
default:
phrase = HTTPURLResponse.localizedString(forStatusCode: statusCode).capitalized
}
return "\(statusCode) \(phrase)"
}
}