diff --git a/Modules/RSParser/Sources/Swift/Feeds/XML/OPMLParser.swift b/Modules/RSParser/Sources/Swift/Feeds/XML/OPMLParser.swift new file mode 100644 index 000000000..589f5e839 --- /dev/null +++ b/Modules/RSParser/Sources/Swift/Feeds/XML/OPMLParser.swift @@ -0,0 +1,122 @@ +// +// OPMLParser.swift +// RSParser +// +// Created by Brent Simmons on 4/18/26. +// + +import Foundation +#if SWIFT_PACKAGE +import RSParserObjC +#endif + +// Swift replacement for the ObjC RSOPMLParser. +// Same public entry point (`RSOPMLParser.parseOPML(with:)`) and returns the +// same ObjC RSOPMLDocument type so the Account module keeps working unchanged. +// Parsing is driven by the pure-Swift XMLSAXParser. + +public final class RSOPMLParser: NSObject { + + /// Parse OPML data. Throws `RSOPMLWrongFormatError` if the data doesn't look like OPML. + public static func parseOPML(with parserData: ParserData) throws -> RSOPMLDocument { + let bytes = Array(parserData.data) + try validateLooksLikeOPML(bytes: bytes, urlString: parserData.url) + + let delegate = OPMLParserDelegate(urlString: parserData.url) + let parser = XMLSAXParser(delegate: delegate) + parser.parse(bytes) + return delegate.document + } + + private static func validateLooksLikeOPML(bytes: [UInt8], urlString: String) throws { + // Same heuristic as the old parser: look for `, + namespace: XMLNamespace, + attributes: XMLAttributes) { + if localName.equals("title") { + parser.beginStoringCharacters() + collectingTitleOnDocument = (itemStack.count == 1) // only document-level title matters + return + } + + if !localName.equals("outline") { + return + } + + let item = RSOPMLItem() + item.attributes = attributes.dictionary() + currentItem.addChild(item) + itemStack.append(item) + } + + // MARK: End + + func xmlSAXParser(_ parser: XMLSAXParser, + didEndElement localName: ArraySlice, + namespace: XMLNamespace) { + if localName.equals("title") { + if collectingTitleOnDocument { + document.title = parser.currentStringWithTrimmedWhitespace + } + collectingTitleOnDocument = false + return + } + + if localName.equals("outline") { + if itemStack.count > 1 { + itemStack.removeLast() + } + } + } +}