Create FeedFinder module.

This commit is contained in:
Brent Simmons committed 2025-11-10 09:40:25 -08:00
1 parent 02bddb792d
commit 86625063b8
12 files changed
+155 -95

No files matched your search

+2 -1
View File
@@ -21,7 +21,8 @@
"Bash(cat:*)",
"Bash(dd:*)",
"Bash(xcrun simctl list:*)",
"Bash(timeout 600 ./buildscripts/quiet_build_and_test.sh:*)"
"Bash(timeout 600 ./buildscripts/quiet_build_and_test.sh:*)",
"Bash(mkdir:*)"
],
"deny": []
}
+2
View File
@@ -14,6 +14,7 @@ let package = Package(
.package(path: "../Articles"),
.package(path: "../ArticlesDatabase"),
.package(path: "../CloudKitSync"),
.package(path: "../FeedFinder"),
.package(path: "../Secrets"),
.package(path: "../SyncDatabase"),
.package(path: "../RSWeb"),
@@ -32,6 +33,7 @@ let package = Package(
"Articles",
"ArticlesDatabase",
"CloudKitSync",
"FeedFinder",
"Secrets",
"SyncDatabase",
]),
@@ -18,6 +18,7 @@ import ArticlesDatabase
import RSWeb
import Secrets
import CloudKitSync
import FeedFinder
enum CloudKitAccountDelegateError: LocalizedError {
case invalidParameter
@@ -7,6 +7,7 @@
//
import Articles
import FeedFinder
import RSCore
import RSDatabase
import RSParser
@@ -11,6 +11,7 @@ import RSCore
import RSParser
import Articles
import ArticlesDatabase
import FeedFinder
import RSWeb
import Secrets
@@ -10,6 +10,7 @@ import Articles
import RSCore
import RSParser
import RSWeb
import FeedFinder
import SyncDatabase
import os.log
import Secrets
+35
View File
@@ -0,0 +1,35 @@
// swift-tools-version:6.2
import PackageDescription
let package = Package(
name: "FeedFinder",
platforms: [.macOS(.v14), .iOS(.v17)],
products: [
.library(
name: "FeedFinder",
type: .dynamic,
targets: ["FeedFinder"])
],
dependencies: [
.package(path: "../RSWeb"),
.package(path: "../RSParser"),
.package(path: "../RSCore")
],
targets: [
.target(
name: "FeedFinder",
dependencies: [
"RSWeb",
"RSParser",
"RSCore"
],
swiftSettings: [
.swiftLanguageMode(.v5),
.unsafeFlags(["-warnings-as-errors"])
]
),
.testTarget(
name: "FeedFinderTests",
dependencies: ["FeedFinder"])
]
)
@@ -12,76 +12,64 @@ import RSParser
import RSWeb
import RSCore
final class FeedFinder {
public enum FeedFinderError: LocalizedError {
case feedNotFound
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedFinder")
static func find(url: URL) async throws -> Set<FeedSpecifier> {
try await withCheckedThrowingContinuation { continuation in
find(url: url) { result in
continuation.resume(with: result)
}
}
}
static func find(url: URL, completion: @escaping (Result<Set<FeedSpecifier>, Error>) -> Void) {
Task { @MainActor in
// Check special cases first.
if let feedSpecifier = FeedSpecifier.knownFeedSpecifier(url: url) {
logger.info("FeedFinder: found special case feed URL: \(url.absoluteString) - \(feedSpecifier.urlString)")
completion(.success(Set([feedSpecifier])))
return
}
Downloader.shared.download(url) { (data, response, error) in
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)
completion(.success(Set([microblogFeedSpecifier])))
}
} else {
completion(.failure(AccountError.createErrorNotFound))
}
return
}
if let error = error {
completion(.failure(error))
return
}
guard let data = data, let response = response else {
completion(.failure(AccountError.createErrorNotFound))
return
}
if !response.statusIsOK || data.isEmpty {
completion(.failure(AccountError.createErrorNotFound))
return
}
if FeedFinder.isFeed(data, url.absoluteString) {
let feedSpecifier = FeedSpecifier(title: nil, urlString: url.absoluteString, source: .UserEntered, orderFound: 1)
completion(.success(Set([feedSpecifier])))
return
}
if !FeedFinder.isHTML(data) {
completion(.failure(AccountError.createErrorNotFound))
return
}
FeedFinder.findFeedsInHTMLPage(htmlData: data, urlString: url.absoluteString, completion: completion)
}
public var errorDescription: String? {
switch self {
case .feedNotFound:
return NSLocalizedString("The feed couldn’t be found and can’t be added.", comment: "Not found")
}
}
}
private extension FeedFinder {
public final class FeedFinder {
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "FeedFinder")
public static func find(url: URL) async throws -> Set<FeedSpecifier> {
// 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])
}
let (data, response) = try await Downloader.shared.download(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])
}
}
throw FeedFinderError.feedNotFound
}
guard let data, let response else {
throw FeedFinderError.feedNotFound
}
if !response.statusIsOK || data.isEmpty {
throw FeedFinderError.feedNotFound
}
if FeedFinder.isFeed(data, url.absoluteString) {
let feedSpecifier = FeedSpecifier(title: nil, urlString: url.absoluteString, source: .UserEntered, orderFound: 1)
return Set([feedSpecifier])
}
if !FeedFinder.isHTML(data) {
throw FeedFinderError.feedNotFound
}
return try await FeedFinder.findFeedsInHTMLPage(htmlData: data, urlString: url.absoluteString)
}
}
private extension FeedFinder {
static func addFeedSpecifier(_ feedSpecifier: FeedSpecifier, feedSpecifiers: inout [String: FeedSpecifier]) {
// If there’s an existing feed specifier, merge the two so that we have the best data. If one has a title and one doesn’t, use that non-nil title. Use the better source.
@@ -94,7 +82,7 @@ private extension FeedFinder {
}
}
static func findFeedsInHTMLPage(htmlData: Data, urlString: String, completion: @escaping (Result<Set<FeedSpecifier>, Error>) -> Void) {
static func findFeedsInHTMLPage(htmlData: Data, urlString: String) async throws -> Set<FeedSpecifier> {
// 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
@@ -119,15 +107,13 @@ private extension FeedFinder {
}
if didFindFeedInHTMLHead {
completion(.success(Set(feedSpecifiers.values)))
return
return Set(feedSpecifiers.values)
}
else if feedSpecifiersToDownload.isEmpty {
completion(.failure(AccountError.createErrorNotFound))
return
throw FeedFinderError.feedNotFound
}
else {
downloadFeedSpecifiers(feedSpecifiersToDownload, feedSpecifiers: feedSpecifiers, completion: completion)
return await downloadFeedSpecifiers(feedSpecifiersToDownload, feedSpecifiers: feedSpecifiers)
}
}
@@ -156,32 +142,39 @@ private extension FeedFinder {
return data.isProbablyHTML
}
static func downloadFeedSpecifiers(_ downloadFeedSpecifiers: Set<FeedSpecifier>, feedSpecifiers: [String: FeedSpecifier], completion: @escaping (Result<Set<FeedSpecifier>, Error>) -> Void) {
static func downloadFeedSpecifiers(_ downloadFeedSpecifiers: Set<FeedSpecifier>, feedSpecifiers: [String: FeedSpecifier]) async -> Set<FeedSpecifier> {
var resultFeedSpecifiers = feedSpecifiers
let group = DispatchGroup()
for downloadFeedSpecifier in downloadFeedSpecifiers {
guard let url = URL(string: downloadFeedSpecifier.urlString) else {
continue
await withTaskGroup(of: FeedSpecifier?.self) { group in
for downloadFeedSpecifier in downloadFeedSpecifiers {
guard let url = URL(string: downloadFeedSpecifier.urlString) else {
continue
}
group.addTask {
do {
let (data, response) = try await Downloader.shared.download(url)
if let data, let response, response.statusIsOK {
if self.isFeed(data, downloadFeedSpecifier.urlString) {
return downloadFeedSpecifier
}
}
} catch {
// Ignore download errors for individual feeds
}
return nil
}
}
group.enter()
Task { @MainActor in
Downloader.shared.download(url) { (data, response, error) in
if let data = data, let response = response, response.statusIsOK, error == nil {
if self.isFeed(data, downloadFeedSpecifier.urlString) {
addFeedSpecifier(downloadFeedSpecifier, feedSpecifiers: &resultFeedSpecifiers)
}
}
group.leave()
for await feedSpecifier in group {
if let feedSpecifier {
addFeedSpecifier(feedSpecifier, feedSpecifiers: &resultFeedSpecifiers)
}
}
}
group.notify(queue: DispatchQueue.main) {
completion(.success(Set(resultFeedSpecifiers.values)))
}
return Set(resultFeedSpecifiers.values)
}
static func isFeed(_ data: Data, _ urlString: String) -> Bool {
@@ -9,9 +9,9 @@
import Foundation
import RSWeb
struct FeedSpecifier: Hashable {
public struct FeedSpecifier: Hashable {
enum Source: Int {
public enum Source: Int {
case UserEntered = 0, HTMLHead, HTMLLink
func equalToOrBetterThan(_ otherSource: Source) -> Bool {
@@ -27,6 +27,13 @@ struct FeedSpecifier: Hashable {
return calculatedScore()
}
public init(title: String?, urlString: String, source: Source, orderFound: Int) {
self.title = title
self.urlString = urlString
self.source = source
self.orderFound = orderFound
}
/// Some feed URLs are known in advance. Save time/bandwidth by special-casing those.
static func knownFeedSpecifier(url: URL) -> FeedSpecifier? {
if url.isRachelByTheBayURL {
@@ -0,0 +1,18 @@
//
// FeedFinderTests.swift
// FeedFinderTests
//
// Created by Brent Simmons on 11/9/24.
// Copyright © 2024 Ranchero Software. All rights reserved.
//
import XCTest
@testable import FeedFinder
final class FeedFinderTests: XCTestCase {
func testExample() throws {
let feedFinder = FeedFinder()
XCTAssertNotNil(feedFinder)
}
}
@@ -1,5 +1,5 @@
{
"originHash" : "d126877be4ee0ff77baa0e72041e3148c97eca9e4a56e41f57c18ae4a25e6ac2",
"originHash" : "47242d50e8c3b0119beec15ccedb589ba580577a79e10a506ca130e4dfdebedd",
"pins" : [
{
"identity" : "plcrashreporter",
@@ -24,8 +24,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/swiftlang/swift-cmark.git",
"state" : {
"revision" : "b97d09472e847a416629f026eceae0e2afcfad65",
"version" : "0.7.0"
"revision" : "5d9bdaa4228b381639fff09403e39a04926e2dbe",
"version" : "0.7.1"
}
},
{
@@ -33,8 +33,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-markdown.git",
"state" : {
"revision" : "d8cf111c276ed18cff82d3cad563d2ca5903b982",
"version" : "0.7.1"
"revision" : "7d9a5ce307528578dfa777d505496bd5f544ad94",
"version" : "0.7.3"
}
},
{