1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
|
import Foundation
/// Fetches and parses man.sr.ht wiki pages over plain HTTP (no auth required).
struct ManPage: Sendable {
let url: URL
let title: String
let contentHTML: String
}
struct ManPageService {
static let baseURL = URL(string: "https://man.sr.ht")!
static let pagesBaseURL = URL(string: "https://srht.site/")!
/// Fetches a man.sr.ht page and extracts the article content.
/// Uses an unauthenticated URLSession because man.sr.ht pages are public.
static func fetch(url: URL) async throws -> ManPage {
guard isTrustedDocumentationURL(url) else {
throw URLError(.badURL)
}
var request = URLRequest(url: url)
request.setValue(Bundle.main.hutchUserAgent, forHTTPHeaderField: "User-Agent")
let (data, response) = try await URLSession.shared.data(for: request)
if let http = response as? HTTPURLResponse,
!(200...299).contains(http.statusCode) {
throw URLError(.badServerResponse)
}
guard let html = String(data: data, encoding: .utf8) else {
throw URLError(.cannotDecodeContentData)
}
return ManPage(
url: url,
title: extractTitle(from: html, fallbackURL: url),
contentHTML: sanitizeContentHTML(extractContent(from: html))
)
}
static func isTrustedDocumentationURL(_ url: URL) -> Bool {
guard url.scheme?.localizedCaseInsensitiveCompare("https") == .orderedSame,
let host = url.host?.lowercased() else {
return false
}
return host == "man.sr.ht"
|| host.hasSuffix(".man.sr.ht")
|| host == "srht.site"
}
private static func extractTitle(from html: String, fallbackURL: URL) -> String {
if let headerHTML = substring(
in: html,
startingAtFirstOccurrenceOf: #"<div class="header-tabbed">"#
),
let h2Contents = firstMatch(in: headerHTML, pattern: #"<h2\b[^>]*>(.*?)</h2>"#) {
let title = stripHTML(from: h2Contents).trimmingCharacters(in: .whitespacesAndNewlines)
if !title.isEmpty {
return title
}
}
if let titleContents = firstMatch(in: html, pattern: #"<title\b[^>]*>(.*?)</title>"#) {
let rawTitle = stripHTML(from: titleContents).trimmingCharacters(in: .whitespacesAndNewlines)
let suffix = " - man.sr.ht"
let normalizedTitle: String
if rawTitle.hasSuffix(suffix) {
normalizedTitle = String(rawTitle.dropLast(suffix.count))
} else {
normalizedTitle = rawTitle
}
if !normalizedTitle.isEmpty {
return normalizedTitle
}
}
let lastComponent = fallbackURL.pathComponents.last { $0 != "/" } ?? ""
return lastComponent.isEmpty ? fallbackURL.absoluteString : lastComponent
}
private static func extractContent(from html: String) -> String {
if let content = extractDivBlock(from: html, className: "markdown"), !content.isEmpty {
return content
}
if let content = extractArticleBlock(from: html, className: "content"), !content.isEmpty {
return content
}
if let content = extractDivBlock(from: html, className: "content"), !content.isEmpty {
return content
}
return ""
}
private static func sanitizeContentHTML(_ html: String) -> String {
html.replacingOccurrences(
of: ###"<a\b[^>]*aria-hidden="true"[^>]*href="#[^"]*"[^>]*>\s*#\s*</a>"###,
with: "",
options: [.regularExpression, .caseInsensitive]
)
}
private static func extractArticleBlock(from html: String, className: String) -> String? {
extractElementBlock(from: html, elementName: "article", className: className)
}
private static func extractDivBlock(from html: String, className: String) -> String? {
extractElementBlock(from: html, elementName: "div", className: className)
}
private static func extractElementBlock(
from html: String,
elementName: String,
className: String
) -> String? {
guard let startRange = html.range(of: #"<\#(elementName) class="\#(className)""#) else {
return nil
}
let characters = Array(html)
var index = html.distance(from: html.startIndex, to: startRange.lowerBound)
var depth = 0
var foundOpeningDiv = false
while index < characters.count {
guard characters[index] == "<" else {
index += 1
continue
}
if hasPrefix("</\(elementName)", at: index, in: characters) {
if foundOpeningDiv {
depth -= 1
if depth == 0 {
let closeEnd = endOfTag(startingAt: index, in: characters)
return String(characters[html.distance(from: html.startIndex, to: startRange.lowerBound)..<closeEnd])
}
}
index += 1
continue
}
if hasPrefix("<\(elementName)", at: index, in: characters) {
if !isSelfClosingTag(startingAt: index, in: characters) {
depth += 1
foundOpeningDiv = true
}
index += 1
continue
}
index += 1
}
return nil
}
private static func firstMatch(in text: String, pattern: String) -> String? {
guard let regex = try? NSRegularExpression(
pattern: pattern,
options: [.caseInsensitive, .dotMatchesLineSeparators]
) else {
return nil
}
let range = NSRange(text.startIndex..., in: text)
guard let match = regex.firstMatch(in: text, range: range),
match.numberOfRanges > 1,
let captureRange = Range(match.range(at: 1), in: text) else {
return nil
}
return String(text[captureRange])
}
private static func substring(in text: String, startingAtFirstOccurrenceOf needle: String) -> String? {
guard let range = text.range(of: needle) else {
return nil
}
return String(text[range.lowerBound...])
}
private static func stripHTML(from text: String) -> String {
let noTags = text.replacingOccurrences(
of: #"<[^>]+>"#,
with: "",
options: .regularExpression
)
return decodeHTMLEntities(noTags)
}
private static func hasPrefix(_ prefix: String, at index: Int, in characters: [Character]) -> Bool {
guard index + prefix.count <= characters.count else { return false }
return String(characters[index..<(index + prefix.count)]).lowercased() == prefix
}
private static func isSelfClosingTag(startingAt index: Int, in characters: [Character]) -> Bool {
let tagEnd = endOfTag(startingAt: index, in: characters)
guard tagEnd > index else { return false }
let tagContents = String(characters[index..<tagEnd])
return tagContents.contains("/>")
}
private static func endOfTag(startingAt index: Int, in characters: [Character]) -> Int {
var current = index
while current < characters.count {
if characters[current] == ">" {
return current + 1
}
current += 1
}
return characters.count
}
}
|