From 381f84245a065c270c0607be2032679d031c819a Mon Sep 17 00:00:00 2001 From: Brent Simmons Date: Mon, 20 Apr 2026 10:56:26 -0700 Subject: [PATCH] Add HTML scanner and link and metadata parsers. --- .../Sources/Swift/HTML/HTMLAttributes.swift | 65 +++ .../Sources/Swift/HTML/HTMLLink.swift | 21 + .../Sources/Swift/HTML/HTMLLinkParser.swift | 102 ++++ .../Sources/Swift/HTML/HTMLMetadata.swift | 323 +++++++++++ .../Swift/HTML/HTMLMetadataParser.swift | 101 ++++ .../Sources/Swift/HTML/HTMLScanner.swift | 513 ++++++++++++++++++ .../RSParser/Sources/Swift/HTML/HTMLTag.swift | 26 + 7 files changed, 1151 insertions(+) create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLAttributes.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLLink.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLLinkParser.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLMetadata.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLMetadataParser.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLScanner.swift create mode 100644 Modules/RSParser/Sources/Swift/HTML/HTMLTag.swift diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLAttributes.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLAttributes.swift new file mode 100644 index 000000000..e2550c26a --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLAttributes.swift @@ -0,0 +1,65 @@ +// +// HTMLAttributes.swift +// RSParser +// +// Created by Brent Simmons on 4/19/26. +// + +// Lightweight view over attributes parsed from an HTML start tag. +// +// HTML attribute names are case-insensitive; values are kept as-is (already +// entity-decoded by the scanner). Lookups are case-insensitive against an +// all-lowercase literal. `dictionary()` returns a String-keyed dict with +// the original-case names — preserves the shape the existing `RSHTMLTag` +// consumer expects. + +public struct HTMLAttributes: Sendable { + + let attributes: [(name: ArraySlice, value: String)] + + init(attributes: [(name: ArraySlice, value: String)]) { + self.attributes = attributes + } + + public static let empty = HTMLAttributes(attributes: []) + + public var count: Int { + attributes.count + } + + public var isEmpty: Bool { + attributes.isEmpty + } + + /// Case-insensitive lookup. `name` must be all lowercase. + public subscript(name: String) -> String? { + let needle = Array(name.utf8) + for attribute in attributes { + if attribute.name.count != needle.count { + continue + } + var match = true + for (ai, bi) in zip(attribute.name, needle) { + if ai.asciiLowercased != bi { + match = false + break + } + } + if match { + return attribute.value + } + } + return nil + } + + /// Materialize a `[String: String]` dictionary with original-case names. + public func dictionary() -> [String: String] { + var dict = [String: String]() + dict.reserveCapacity(attributes.count) + for attribute in attributes { + let key = String(decoding: attribute.name, as: UTF8.self) + dict[key] = attribute.value + } + return dict + } +} diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLLink.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLLink.swift new file mode 100644 index 000000000..55b8c0c18 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLLink.swift @@ -0,0 +1,21 @@ +// +// HTMLLink.swift +// RSParser +// +// Created by Brent Simmons on 4/20/26. +// + +// A single `` element harvested from an HTML document. +// Any field may be nil because HTML can be malformed. + +public struct HTMLLink: Sendable { + public let urlString: String? // absolute, resolved against the document's base URL + public let text: String? // inner text, trimmed + public let title: String? // title attribute + + public init(urlString: String?, text: String?, title: String?) { + self.urlString = urlString + self.text = text + self.title = title + } +} diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLLinkParser.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLLinkParser.swift new file mode 100644 index 000000000..9950ff554 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLLinkParser.swift @@ -0,0 +1,102 @@ +// +// HTMLLinkParser.swift +// RSParser +// +// Created by Brent Simmons on 4/19/26. +// + +import Foundation +#if SWIFT_PACKAGE +import RSParserObjC +#endif + +// Swift replacement for the ObjC RSHTMLLinkParser. +// Extracts every `` element from an HTML document and returns an array of +// `HTMLLink` with absolute URL, title attribute, and trimmed inner text. +// +// Text accumulation follows the libxml2 behavior the original parser was +// measured against: a nested start tag resets the character buffer, so the +// text of `before after` is "after", not "before after". + +public enum HTMLLinkParser { + + public static func htmlLinks(with parserData: ParserData) -> [HTMLLink] { + let delegate = LinkParserDelegate(baseURL: URL(string: parserData.url)) + let scanner = HTMLScanner(delegate: delegate) + scanner.parse(Array(parserData.data)) + delegate.flushPending() + return delegate.links + } +} + +// MARK: - Delegate + +private final class LinkParserDelegate: HTMLScannerDelegate { + + private let baseURL: URL? + private(set) var links: [HTMLLink] = [] + + private var collectingText = false + private var pendingURLString: String? + private var pendingTitle: String? + private var pendingText: [UInt8] = [] + + init(baseURL: URL?) { + self.baseURL = baseURL + } + + func htmlScanner(_ scanner: HTMLScanner, + didStartTag name: ArraySlice, + attributes: HTMLAttributes, + selfClosing: Bool) { + if isAnchorTag(name) { + // A new always starts a fresh pending link, flushing any still-open one. + flushPending() + pendingURLString = attributes["href"].flatMap { URL(string: $0, relativeTo: baseURL)?.absoluteString } + pendingTitle = attributes["title"] + pendingText.removeAll(keepingCapacity: true) + collectingText = true + return + } + // A nested tag inside an anchor resets the text buffer, matching libxml2 + // SAX behavior (which fires startElement on nested tags and clears the + // characters buffer). `xy` yields text "y". + if collectingText { + pendingText.removeAll(keepingCapacity: true) + } + } + + func htmlScanner(_ scanner: HTMLScanner, + didEndTag name: ArraySlice) { + if isAnchorTag(name) && collectingText { + flushPending() + } + } + + func htmlScanner(_ scanner: HTMLScanner, + didFindCharacters bytes: ArraySlice) { + if collectingText { + pendingText.append(contentsOf: bytes) + } + } + + // MARK: Helpers + + func flushPending() { + guard collectingText else { + return + } + let decoded = String(decoding: pendingText, as: UTF8.self) + .trimmingCharacters(in: .whitespacesAndNewlines) + let text: String? = decoded.isEmpty ? nil : decoded + links.append(HTMLLink(urlString: pendingURLString, text: text, title: pendingTitle)) + pendingURLString = nil + pendingTitle = nil + pendingText.removeAll(keepingCapacity: true) + collectingText = false + } + + private func isAnchorTag(_ name: ArraySlice) -> Bool { + name.count == 1 && (name[name.startIndex] == .asciiLowerA || name[name.startIndex] == .asciiUpperA) + } +} diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLMetadata.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLMetadata.swift new file mode 100644 index 000000000..2acf9cdef --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLMetadata.swift @@ -0,0 +1,323 @@ +// +// HTMLMetadata.swift +// RSParser +// +// Created by Brent Simmons on 4/20/26. +// + +import CoreGraphics +import Foundation + +// Structured view of the data gathered from an HTML document by `HTMLMetadataParser`. +// Sendable plain-value types throughout. + +public struct HTMLMetadata: Sendable { + + public let baseURLString: String + public let tags: [HTMLTag] + public let favicons: [HTMLMetadataFavicon] + public let appleTouchIcons: [HTMLMetadataAppleTouchIcon] + public let feedLinks: [HTMLMetadataFeedLink] + public let openGraphProperties: HTMLOpenGraphProperties + public let twitterProperties: HTMLTwitterProperties + + public init(urlString: String, tags: [HTMLTag]) { + self.baseURLString = urlString + self.tags = tags + self.favicons = Self.resolveFavicons(tags: tags, baseURLString: urlString) + self.appleTouchIcons = Self.resolveAppleTouchIcons(tags: tags, baseURLString: urlString) + self.feedLinks = Self.resolveFeedLinks(tags: tags, baseURLString: urlString) + self.openGraphProperties = HTMLOpenGraphProperties(tags: tags) + self.twitterProperties = HTMLTwitterProperties(tags: tags) + } +} + +public struct HTMLMetadataFeedLink: Sendable { + public let title: String? + public let type: String? + public let urlString: String? // absolute +} + +public struct HTMLMetadataFavicon: Sendable { + public let type: String? + public let urlString: String? // absolute +} + +public struct HTMLMetadataAppleTouchIcon: Sendable { + public let rel: String? + public let sizes: String? + public let size: CGSize + public let urlString: String? // absolute +} + +public struct HTMLOpenGraphProperties: Sendable { + public let images: [HTMLOpenGraphImage] + + init(tags: [HTMLTag]) { + self.images = HTMLOpenGraphProperties.parse(tags: tags) + } +} + +public struct HTMLOpenGraphImage: Sendable { + public var url: String? + public var secureURL: String? + public var mimeType: String? + public var width: CGFloat + public var height: CGFloat + public var altText: String? +} + +public struct HTMLTwitterProperties: Sendable { + public let imageURL: String? + + init(tags: [HTMLTag]) { + self.imageURL = HTMLTwitterProperties.findImageURL(tags: tags) + } +} + +// MARK: - Categorization + +private extension HTMLMetadata { + + static let iconRel = "icon" + static let appleTouchIcon = "apple-touch-icon" + static let appleTouchIconPrecomposed = "apple-touch-icon-precomposed" + static let alternateRel = "alternate" + static let feedTypeSuffixes = ["/rss+xml", "/atom+xml", "/json"] + + static func resolveFavicons(tags: [HTMLTag], baseURLString: String) -> [HTMLMetadataFavicon] { + let matching = tags.filter { tag in + tag.type == .link + && !(urlString(from: tag.attributes) ?? "").isEmpty + && relValues(in: tag.attributes).contains { $0.caseInsensitiveCompare(iconRel) == .orderedSame } + } + + var seen = Set() + var result = [HTMLMetadataFavicon]() + for tag in matching { + let absolute = absoluteURLString(from: tag.attributes, baseURLString: baseURLString) + guard let absolute, !seen.contains(absolute) else { + continue + } + seen.insert(absolute) + let type = tag.attributes.caseInsensitiveValue(forKey: "type") + result.append(HTMLMetadataFavicon(type: type, urlString: absolute)) + } + return result + } + + static func resolveAppleTouchIcons(tags: [HTMLTag], baseURLString: String) -> [HTMLMetadataAppleTouchIcon] { + let matching = tags.filter { tag in + guard tag.type == .link else { + return false + } + let rel = (tag.attributes.caseInsensitiveValue(forKey: "rel") ?? "").lowercased() + return rel == appleTouchIcon || rel == appleTouchIconPrecomposed + } + + return matching.map { tag in + let absolute = absoluteURLString(from: tag.attributes, baseURLString: baseURLString) + let sizes = tag.attributes.caseInsensitiveValue(forKey: "sizes") + let rel = tag.attributes.caseInsensitiveValue(forKey: "rel") + let size = parsedSize(sizes: sizes) + return HTMLMetadataAppleTouchIcon(rel: rel, sizes: sizes, size: size, urlString: absolute) + } + } + + static func resolveFeedLinks(tags: [HTMLTag], baseURLString: String) -> [HTMLMetadataFeedLink] { + let matching = tags.filter { tag in + guard tag.type == .link else { + return false + } + let rel = (tag.attributes.caseInsensitiveValue(forKey: "rel") ?? "").lowercased() + guard rel == alternateRel else { + return false + } + // Exclude `rel="alternate"` variants that are definitely-not-feeds — + // responsive-design mobile links use `media=`, i18n variants use + // `hreflang=`. Without this, pages that advertise mobile alternates + // (YouTube) would leak those into feed auto-discovery when we + // loosened the type requirement below. + if let media = tag.attributes.caseInsensitiveValue(forKey: "media"), !media.isEmpty { + return false + } + if let hreflang = tag.attributes.caseInsensitiveValue(forKey: "hreflang"), !hreflang.isEmpty { + return false + } + // Accept feed-typed alternates AND typeless alternates — some pages + // advertise their RSS/Atom feed with `` + // and no type attribute. Excluding those made auto-discovery fail + // for such sites. An explicit non-feed type (e.g. `text/html`) is + // still filtered out. + if let type = tag.attributes.caseInsensitiveValue(forKey: "type"), !type.isEmpty { + guard isFeedType(type) else { + return false + } + } + // Require an http(s) URL — skip app-scheme alternates like + // `android-app://` / `ios-app://` which aren't feed URLs. + guard let url = urlString(from: tag.attributes), !url.isEmpty else { + return false + } + let lower = url.lowercased() + return lower.hasPrefix("http://") || lower.hasPrefix("https://") || lower.hasPrefix("/") || lower.hasPrefix(".") || !lower.contains(":") + } + + return matching.map { tag in + let absolute = absoluteURLString(from: tag.attributes, baseURLString: baseURLString) + let title = tag.attributes.caseInsensitiveValue(forKey: "title") + let type = tag.attributes.caseInsensitiveValue(forKey: "type") + return HTMLMetadataFeedLink(title: title, type: type, urlString: absolute) + } + } + + static func relValues(in attributes: [String: String]) -> [String] { + guard let rel = attributes.caseInsensitiveValue(forKey: "rel") else { + return [] + } + return rel.components(separatedBy: .whitespacesAndNewlines).filter { !$0.isEmpty } + } + + static func urlString(from attributes: [String: String]) -> String? { + attributes.caseInsensitiveValue(forKey: "href") + ?? attributes.caseInsensitiveValue(forKey: "src") + } + + static func absoluteURLString(from attributes: [String: String], baseURLString: String) -> String? { + guard let relative = urlString(from: attributes), !relative.isEmpty else { + return nil + } + guard let baseURL = URL(string: baseURLString), + let absoluteURL = URL(string: relative, relativeTo: baseURL) else { + return nil + } + return absoluteURL.absoluteURL.standardized.absoluteString + } + + static func isFeedType(_ type: String) -> Bool { + let lowered = type.lowercased() + return feedTypeSuffixes.contains { lowered.hasSuffix($0) } + } + + static func parsedSize(sizes: String?) -> CGSize { + guard let sizes else { + return .zero + } + let parts = sizes.components(separatedBy: "x") + guard parts.count == 2, + let width = Double(parts[0]), + let height = Double(parts[1]) else { + return .zero + } + return CGSize(width: width, height: height) + } +} + +// MARK: - Open Graph + +private extension HTMLOpenGraphProperties { + + static let ogPrefix = "og:" + static let ogImage = "og:image" + static let ogImageURL = "og:image:url" + static let ogImageSecureURL = "og:image:secure_url" + static let ogImageType = "og:image:type" + static let ogImageWidth = "og:image:width" + static let ogImageHeight = "og:image:height" + static let ogImageAlt = "og:image:alt" + + static func parse(tags: [HTMLTag]) -> [HTMLOpenGraphImage] { + var images: [HTMLOpenGraphImage] = [] + + func currentImage() -> HTMLOpenGraphImage? { + images.last + } + + func pushImage() -> Int { + images.append(HTMLOpenGraphImage(url: nil, secureURL: nil, mimeType: nil, width: 0, height: 0, altText: nil)) + return images.count - 1 + } + + func ensureImageIndex() -> Int { + if images.isEmpty { + return pushImage() + } + return images.count - 1 + } + + for tag in tags { + guard tag.type == .meta else { + continue + } + guard let propertyName = tag.attributes["property"], + propertyName.hasPrefix(ogPrefix) else { + continue + } + guard let content = tag.attributes["content"] else { + continue + } + + switch propertyName { + case ogImage: + // Most likely case: og:image starts a fresh image entry. + if let image = currentImage(), image.url == nil { + images[images.count - 1].url = content + } else { + _ = pushImage() + images[images.count - 1].url = content + } + case ogImageURL: + images[ensureImageIndex()].url = content + case ogImageSecureURL: + images[ensureImageIndex()].secureURL = content + case ogImageType: + images[ensureImageIndex()].mimeType = content + case ogImageAlt: + images[ensureImageIndex()].altText = content + case ogImageWidth: + images[ensureImageIndex()].width = CGFloat(Double(content) ?? 0) + case ogImageHeight: + images[ensureImageIndex()].height = CGFloat(Double(content) ?? 0) + default: + break + } + } + + return images + } +} + +// MARK: - Twitter + +private extension HTMLTwitterProperties { + + static let twitterImageSrc = "twitter:image:src" + + static func findImageURL(tags: [HTMLTag]) -> String? { + for tag in tags { + guard tag.type == .meta, + tag.attributes["name"] == twitterImageSrc, + let content = tag.attributes["content"], + !content.isEmpty else { + continue + } + return content + } + return nil + } +} + +// MARK: - Dictionary case-insensitive lookup + +private extension Dictionary where Key == String, Value == String { + + func caseInsensitiveValue(forKey key: String) -> String? { + if let value = self[key] { + return value + } + for (k, v) in self where k.caseInsensitiveCompare(key) == .orderedSame { + return v + } + return nil + } +} diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLMetadataParser.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLMetadataParser.swift new file mode 100644 index 000000000..809394b88 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLMetadataParser.swift @@ -0,0 +1,101 @@ +// +// HTMLMetadataParser.swift +// RSParser +// +// Created by Brent Simmons on 4/19/26. +// + +import Foundation +#if SWIFT_PACKAGE +import RSParserObjC +#endif + +// Swift replacement for the ObjC RSHTMLMetadataParser. +// Collects `` and `` tags from the HTML `` and hands them +// to `HTMLMetadata.init(urlString:tags:)` for categorization (favicons, +// apple-touch-icons, feed links, OG, Twitter). +// +// Stops at the opening `` tag, except for YouTube URLs — which are +// known to put feed-link tags in the body. The match is case-insensitive +// on the URL; matches like "youtubers" are harmless false positives. + +public enum HTMLMetadataParser { + + public static func htmlMetadata(with parserData: ParserData) -> HTMLMetadata { + let scanPastHead = parserData.url.range(of: "youtube", options: .caseInsensitive) != nil + let delegate = MetadataParserDelegate(scanPastHead: scanPastHead) + let scanner = HTMLScanner(delegate: delegate) + scanner.parse(Array(parserData.data)) + return HTMLMetadata(urlString: parserData.url, tags: delegate.tags) + } +} + +// MARK: - Delegate + +private final class MetadataParserDelegate: HTMLScannerDelegate { + + private let scanPastHead: Bool + private var finished = false + private(set) var tags: [HTMLTag] = [] + + init(scanPastHead: Bool) { + self.scanPastHead = scanPastHead + } + + func htmlScanner(_ scanner: HTMLScanner, + didStartTag name: ArraySlice, + attributes: HTMLAttributes, + selfClosing: Bool) { + if finished { + return + } + + if !scanPastHead && tagNameEqualsIgnoringCase(name, Self.bodyBytes) { + finished = true + return + } + + if tagNameEqualsIgnoringCase(name, Self.linkBytes) { + if attributes.isEmpty { + return + } + // Match the ObjC parser: only collect tags that carry both `rel` + // and (`href` or `src`). + guard let rel = attributes["rel"], !rel.isEmpty else { + return + } + let link = attributes["href"] ?? attributes["src"] + guard let link, !link.isEmpty else { + return + } + _ = rel + tags.append(HTMLTag(type: .link, attributes: attributes.dictionary())) + return + } + + if tagNameEqualsIgnoringCase(name, Self.metaBytes) { + if attributes.isEmpty { + return + } + tags.append(HTMLTag(type: .meta, attributes: attributes.dictionary())) + } + } + + // MARK: Helpers + + static let bodyBytes: [UInt8] = Array("body".utf8) + static let linkBytes: [UInt8] = Array("link".utf8) + static let metaBytes: [UInt8] = Array("meta".utf8) + + private func tagNameEqualsIgnoringCase(_ name: ArraySlice, _ lowercased: [UInt8]) -> Bool { + guard name.count == lowercased.count else { + return false + } + for (a, b) in zip(name, lowercased) { + if a.asciiLowercased != b { + return false + } + } + return true + } +} diff --git a/Modules/RSParser/Sources/Swift/HTML/HTMLScanner.swift b/Modules/RSParser/Sources/Swift/HTML/HTMLScanner.swift new file mode 100644 index 000000000..7288b1478 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/HTML/HTMLScanner.swift @@ -0,0 +1,513 @@ +// +// HTMLScanner.swift +// RSParser +// +// Created by Brent Simmons on 4/19/26. +// + +// Liberal, byte-oriented HTML scanner with a SAX-style delegate. +// +// Byte slices throughout. Entity references (named, decimal, hex) are expanded +// via `XMLEntities.decode`. Comments, DOCTYPE, and PIs are silently consumed. +// +// Differs from the XML scanner in ways HTML requires: +// - Tag names compared case-insensitively (but emitted as they appear). +// - Content of `` / `` ends the block. +// - Attributes may have no value (``), single-quoted values, +// or unquoted values (``). +// - No void-element tracking. Consumers that care (both of ours don't) +// apply their own void-element list at the delegate level. +// +// Not re-entrant. Callbacks happen on the thread that called `parse(_:)`. + +public final class HTMLScanner { + + public weak var delegate: HTMLScannerDelegate? + + public init(delegate: HTMLScannerDelegate) { + self.delegate = delegate + } + + public func parse(_ bytes: [UInt8]) { + self.input = bytes + self.pos = 0 + drive() + delegate?.htmlScannerDidEnd(self) + } + + // MARK: - Private state + + private var input: [UInt8] = [] + private var pos: Int = 0 +} + +// MARK: - Private + +private extension HTMLScanner { + + // Tag names that enter raw-text mode. Their content isn't parsed as markup; + // only the matching or ends the block. + static let scriptBytes: [UInt8] = Array("script".utf8) + static let styleBytes: [UInt8] = Array("style".utf8) + + func drive() { + while pos < input.count { + let b = input[pos] + if b == .asciiLessThan { + scanMarkup() + } else { + scanCharacters() + } + } + } + + // MARK: - Markup dispatch + + /// Handle everything starting with `<`. Consumes silent markup in place, + /// emits delegate callbacks for tags and character content. + func scanMarkup() { + assert(input[pos] == .asciiLessThan) + let next = peek(1) + + if next == .asciiExclamation { + if matchPrefix("