-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathWebContentExtractor.swift
More file actions
227 lines (192 loc) · 7.77 KB
/
WebContentExtractor.swift
File metadata and controls
227 lines (192 loc) · 7.77 KB
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
219
220
221
222
223
224
225
226
227
import WebKit
import Logger
import Preferences
public class WebContentFetcher: NSObject, WKNavigationDelegate {
private var webView: WKWebView?
private var loadingTimer: Timer?
private static let converter = HTMLToMarkdownConverter()
private var completion: ((Result<String, Error>) -> Void)?
private struct Config {
static let timeout: TimeInterval = 30.0
static let contentLoadDelay: TimeInterval = 2.0
}
public enum WebContentError: Error, LocalizedError {
case invalidURL(String)
case timeout
case noContent
case navigationFailed(Error)
case javascriptError(Error)
public var errorDescription: String? {
switch self {
case .invalidURL(let url): "Invalid URL: \(url)"
case .timeout: "Request timed out"
case .noContent: "No content found"
case .navigationFailed(let error): "Navigation failed: \(error.localizedDescription)"
case .javascriptError(let error): "JavaScript execution error: \(error.localizedDescription)"
}
}
}
// MARK: - Initialization
public override init() {
super.init()
setupWebView()
}
deinit {
cleanup()
}
// MARK: - Public Methods
public func fetchContent(from urlString: String, completion: @escaping (Result<String, Error>) -> Void) {
guard let url = URL(string: urlString) else {
completion(.failure(WebContentError.invalidURL(urlString)))
return
}
DispatchQueue.main.async { [weak self] in
self?.completion = completion
self?.setupTimeout()
self?.loadContent(from: url)
}
}
public static func fetchContentAsync(from urlString: String) async throws -> String {
try await withCheckedThrowingContinuation { continuation in
let fetcher = WebContentFetcher()
fetcher.fetchContent(from: urlString) { result in
withExtendedLifetime(fetcher) {
continuation.resume(with: result)
}
}
}
}
public static func fetchMultipleContentAsync(from urls: [String]) async -> [String] {
var results: [String] = []
for url in urls {
do {
let content = try await fetchContentAsync(from: url)
results.append("Successfully fetched content from \(url): \(content)")
} catch {
Logger.client.error("Failed to fetch content from \(url): \(error.localizedDescription)")
results.append("Failed to fetch content from \(url) with error: \(error.localizedDescription)")
}
}
return results
}
// MARK: - Private Methods
private func setupWebView() {
let configuration = WKWebViewConfiguration()
let dataSource = WKWebsiteDataStore.nonPersistent()
if #available(macOS 14.0, *) {
configureProxy(for: dataSource)
}
configuration.websiteDataStore = dataSource
webView = WKWebView(frame: .zero, configuration: configuration)
webView?.navigationDelegate = self
}
@available(macOS 14.0, *)
private func configureProxy(for dataSource: WKWebsiteDataStore) {
let proxyURL = UserDefaults.shared.value(for: \.gitHubCopilotProxyUrl)
guard let url = URL(string: proxyURL),
let host = url.host,
let port = url.port,
let proxyPort = NWEndpoint.Port(port.description) else { return }
let tlsOptions = NWProtocolTLS.Options()
let useStrictSSL = UserDefaults.shared.value(for: \.gitHubCopilotUseStrictSSL)
if !useStrictSSL {
let secOptions = tlsOptions.securityProtocolOptions
sec_protocol_options_set_verify_block(secOptions, { _, _, completion in
completion(true)
}, .main)
}
let httpProxy = ProxyConfiguration(
httpCONNECTProxy: NWEndpoint.hostPort(
host: NWEndpoint.Host(host),
port: proxyPort
),
tlsOptions: tlsOptions
)
httpProxy.applyCredential(
username: UserDefaults.shared.value(for: \.gitHubCopilotProxyUsername),
password: UserDefaults.shared.value(for: \.gitHubCopilotProxyPassword)
)
dataSource.proxyConfigurations = [httpProxy]
}
private func cleanup() {
loadingTimer?.invalidate()
loadingTimer = nil
webView?.navigationDelegate = nil
webView?.stopLoading()
webView = nil
}
private func setupTimeout() {
loadingTimer?.invalidate()
loadingTimer = Timer.scheduledTimer(withTimeInterval: Config.timeout, repeats: false) { [weak self] _ in
DispatchQueue.main.async {
Logger.client.error("Request timed out")
self?.completeWithError(WebContentError.timeout)
}
}
}
private func loadContent(from url: URL) {
if webView == nil {
setupWebView()
}
guard let webView = webView else {
completeWithError(WebContentError.navigationFailed(NSError(domain: "WebView creation failed", code: -1)))
return
}
let request = URLRequest(
url: url,
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: Config.timeout
)
webView.load(request)
}
private func processHTML(_ html: String) {
do {
let cleanedText = try Self.converter.convertToMarkdown(from: html)
completeWithSuccess(cleanedText)
} catch {
Logger.client.error("SwiftSoup parsing error: \(error.localizedDescription)")
completeWithError(error)
}
}
private func completeWithSuccess(_ content: String) {
completion?(.success(content))
completion = nil
}
private func completeWithError(_ error: Error) {
completion?(.failure(error))
completion = nil
}
// MARK: - WKNavigationDelegate
public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
loadingTimer?.invalidate()
DispatchQueue.main.asyncAfter(deadline: .now() + Config.contentLoadDelay) {
webView.evaluateJavaScript("document.body.innerHTML") { [weak self] result, error in
DispatchQueue.main.async {
if let error = error {
Logger.client.error("JavaScript execution error: \(error.localizedDescription)")
self?.completeWithError(WebContentError.javascriptError(error))
return
}
if let html = result as? String, !html.isEmpty {
self?.processHTML(html)
} else {
self?.completeWithError(WebContentError.noContent)
}
}
}
}
}
public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
handleNavigationFailure(error)
}
public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
handleNavigationFailure(error)
}
private func handleNavigationFailure(_ error: Error) {
loadingTimer?.invalidate()
DispatchQueue.main.async {
Logger.client.error("Navigation failed: \(error.localizedDescription)")
self.completeWithError(WebContentError.navigationFailed(error))
}
}
}